GlobalsModRef.cpp revision 218893
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"
27218893Sdim#include "llvm/Analysis/ValueTracking.h"
28193323Sed#include "llvm/Support/CommandLine.h"
29193323Sed#include "llvm/Support/InstIterator.h"
30193323Sed#include "llvm/ADT/Statistic.h"
31193323Sed#include "llvm/ADT/SCCIterator.h"
32193323Sed#include <set>
33193323Sedusing namespace llvm;
34193323Sed
35193323SedSTATISTIC(NumNonAddrTakenGlobalVars,
36193323Sed          "Number of global vars without address taken");
37193323SedSTATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
38193323SedSTATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
39193323SedSTATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
40193323SedSTATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
41193323Sed
42193323Sednamespace {
43193323Sed  /// FunctionRecord - One instance of this structure is stored for every
44193323Sed  /// function in the program.  Later, the entries for these functions are
45193323Sed  /// removed if the function is found to call an external function (in which
46193323Sed  /// case we know nothing about it.
47198892Srdivacky  struct FunctionRecord {
48193323Sed    /// GlobalInfo - Maintain mod/ref info for all of the globals without
49193323Sed    /// addresses taken that are read or written (transitively) by this
50193323Sed    /// function.
51212904Sdim    std::map<const GlobalValue*, unsigned> GlobalInfo;
52193323Sed
53193323Sed    /// MayReadAnyGlobal - May read global variables, but it is not known which.
54193323Sed    bool MayReadAnyGlobal;
55193323Sed
56212904Sdim    unsigned getInfoForGlobal(const GlobalValue *GV) const {
57193323Sed      unsigned Effect = MayReadAnyGlobal ? AliasAnalysis::Ref : 0;
58212904Sdim      std::map<const GlobalValue*, unsigned>::const_iterator I =
59212904Sdim        GlobalInfo.find(GV);
60193323Sed      if (I != GlobalInfo.end())
61193323Sed        Effect |= I->second;
62193323Sed      return Effect;
63193323Sed    }
64193323Sed
65193323Sed    /// FunctionEffect - Capture whether or not this function reads or writes to
66193323Sed    /// ANY memory.  If not, we can do a lot of aggressive analysis on it.
67193323Sed    unsigned FunctionEffect;
68193323Sed
69193323Sed    FunctionRecord() : MayReadAnyGlobal (false), FunctionEffect(0) {}
70193323Sed  };
71193323Sed
72193323Sed  /// GlobalsModRef - The actual analysis pass.
73198892Srdivacky  class GlobalsModRef : public ModulePass, public AliasAnalysis {
74193323Sed    /// NonAddressTakenGlobals - The globals that do not have their addresses
75193323Sed    /// taken.
76212904Sdim    std::set<const GlobalValue*> NonAddressTakenGlobals;
77193323Sed
78193323Sed    /// IndirectGlobals - The memory pointed to by this global is known to be
79193323Sed    /// 'owned' by the global.
80212904Sdim    std::set<const GlobalValue*> IndirectGlobals;
81193323Sed
82193323Sed    /// AllocsForIndirectGlobals - If an instruction allocates memory for an
83193323Sed    /// indirect global, this map indicates which one.
84212904Sdim    std::map<const Value*, const GlobalValue*> AllocsForIndirectGlobals;
85193323Sed
86193323Sed    /// FunctionInfo - For each function, keep track of what globals are
87193323Sed    /// modified or read.
88212904Sdim    std::map<const Function*, FunctionRecord> FunctionInfo;
89193323Sed
90193323Sed  public:
91193323Sed    static char ID;
92218893Sdim    GlobalsModRef() : ModulePass(ID) {
93218893Sdim      initializeGlobalsModRefPass(*PassRegistry::getPassRegistry());
94218893Sdim    }
95193323Sed
96193323Sed    bool runOnModule(Module &M) {
97193323Sed      InitializeAliasAnalysis(this);                 // set up super class
98193323Sed      AnalyzeGlobals(M);                          // find non-addr taken globals
99193323Sed      AnalyzeCallGraph(getAnalysis<CallGraph>(), M); // Propagate on CG
100193323Sed      return false;
101193323Sed    }
102193323Sed
103193323Sed    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
104193323Sed      AliasAnalysis::getAnalysisUsage(AU);
105193323Sed      AU.addRequired<CallGraph>();
106193323Sed      AU.setPreservesAll();                         // Does not transform code
107193323Sed    }
108193323Sed
109193323Sed    //------------------------------------------------
110193323Sed    // Implement the AliasAnalysis API
111193323Sed    //
112218893Sdim    AliasResult alias(const Location &LocA, const Location &LocB);
113212904Sdim    ModRefResult getModRefInfo(ImmutableCallSite CS,
114218893Sdim                               const Location &Loc);
115212904Sdim    ModRefResult getModRefInfo(ImmutableCallSite CS1,
116212904Sdim                               ImmutableCallSite CS2) {
117212904Sdim      return AliasAnalysis::getModRefInfo(CS1, CS2);
118193323Sed    }
119193323Sed
120193323Sed    /// getModRefBehavior - Return the behavior of the specified function if
121193323Sed    /// called from the specified call site.  The call site may be null in which
122193323Sed    /// case the most generic behavior of this function should be returned.
123212904Sdim    ModRefBehavior getModRefBehavior(const Function *F) {
124218893Sdim      ModRefBehavior Min = UnknownModRefBehavior;
125218893Sdim
126193323Sed      if (FunctionRecord *FR = getFunctionInfo(F)) {
127193323Sed        if (FR->FunctionEffect == 0)
128218893Sdim          Min = DoesNotAccessMemory;
129193323Sed        else if ((FR->FunctionEffect & Mod) == 0)
130218893Sdim          Min = OnlyReadsMemory;
131193323Sed      }
132218893Sdim
133218893Sdim      return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
134193323Sed    }
135193323Sed
136193323Sed    /// getModRefBehavior - Return the behavior of the specified function if
137193323Sed    /// called from the specified call site.  The call site may be null in which
138193323Sed    /// case the most generic behavior of this function should be returned.
139212904Sdim    ModRefBehavior getModRefBehavior(ImmutableCallSite CS) {
140218893Sdim      ModRefBehavior Min = UnknownModRefBehavior;
141218893Sdim
142218893Sdim      if (const Function* F = CS.getCalledFunction())
143218893Sdim        if (FunctionRecord *FR = getFunctionInfo(F)) {
144218893Sdim          if (FR->FunctionEffect == 0)
145218893Sdim            Min = DoesNotAccessMemory;
146218893Sdim          else if ((FR->FunctionEffect & Mod) == 0)
147218893Sdim            Min = OnlyReadsMemory;
148218893Sdim        }
149218893Sdim
150218893Sdim      return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
151193323Sed    }
152193323Sed
153193323Sed    virtual void deleteValue(Value *V);
154193323Sed    virtual void copyValue(Value *From, Value *To);
155218893Sdim    virtual void addEscapingUse(Use &U);
156193323Sed
157202878Srdivacky    /// getAdjustedAnalysisPointer - This method is used when a pass implements
158202878Srdivacky    /// an analysis interface through multiple inheritance.  If needed, it
159202878Srdivacky    /// should override this to adjust the this pointer as needed for the
160202878Srdivacky    /// specified pass info.
161212904Sdim    virtual void *getAdjustedAnalysisPointer(AnalysisID PI) {
162212904Sdim      if (PI == &AliasAnalysis::ID)
163202878Srdivacky        return (AliasAnalysis*)this;
164202878Srdivacky      return this;
165202878Srdivacky    }
166202878Srdivacky
167193323Sed  private:
168193323Sed    /// getFunctionInfo - Return the function info for the function, or null if
169193323Sed    /// we don't have anything useful to say about it.
170212904Sdim    FunctionRecord *getFunctionInfo(const Function *F) {
171212904Sdim      std::map<const Function*, FunctionRecord>::iterator I =
172212904Sdim        FunctionInfo.find(F);
173193323Sed      if (I != FunctionInfo.end())
174193323Sed        return &I->second;
175193323Sed      return 0;
176193323Sed    }
177193323Sed
178193323Sed    void AnalyzeGlobals(Module &M);
179193323Sed    void AnalyzeCallGraph(CallGraph &CG, Module &M);
180193323Sed    bool AnalyzeUsesOfPointer(Value *V, std::vector<Function*> &Readers,
181193323Sed                              std::vector<Function*> &Writers,
182193323Sed                              GlobalValue *OkayStoreDest = 0);
183193323Sed    bool AnalyzeIndirectGlobalMemory(GlobalValue *GV);
184193323Sed  };
185193323Sed}
186193323Sed
187193323Sedchar GlobalsModRef::ID = 0;
188218893SdimINITIALIZE_AG_PASS_BEGIN(GlobalsModRef, AliasAnalysis,
189212904Sdim                "globalsmodref-aa", "Simple mod/ref analysis for globals",
190218893Sdim                false, true, false)
191218893SdimINITIALIZE_AG_DEPENDENCY(CallGraph)
192218893SdimINITIALIZE_AG_PASS_END(GlobalsModRef, AliasAnalysis,
193218893Sdim                "globalsmodref-aa", "Simple mod/ref analysis for globals",
194218893Sdim                false, true, false)
195193323Sed
196193323SedPass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
197193323Sed
198193323Sed/// AnalyzeGlobals - Scan through the users of all of the internal
199193323Sed/// GlobalValue's in the program.  If none of them have their "address taken"
200193323Sed/// (really, their address passed to something nontrivial), record this fact,
201193323Sed/// and record the functions that they are used directly in.
202193323Sedvoid GlobalsModRef::AnalyzeGlobals(Module &M) {
203193323Sed  std::vector<Function*> Readers, Writers;
204193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
205193323Sed    if (I->hasLocalLinkage()) {
206193323Sed      if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
207193323Sed        // Remember that we are tracking this global.
208193323Sed        NonAddressTakenGlobals.insert(I);
209193323Sed        ++NumNonAddrTakenFunctions;
210193323Sed      }
211193323Sed      Readers.clear(); Writers.clear();
212193323Sed    }
213193323Sed
214193323Sed  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
215193323Sed       I != E; ++I)
216193323Sed    if (I->hasLocalLinkage()) {
217193323Sed      if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
218193323Sed        // Remember that we are tracking this global, and the mod/ref fns
219193323Sed        NonAddressTakenGlobals.insert(I);
220193323Sed
221193323Sed        for (unsigned i = 0, e = Readers.size(); i != e; ++i)
222193323Sed          FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
223193323Sed
224193323Sed        if (!I->isConstant())  // No need to keep track of writers to constants
225193323Sed          for (unsigned i = 0, e = Writers.size(); i != e; ++i)
226193323Sed            FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
227193323Sed        ++NumNonAddrTakenGlobalVars;
228193323Sed
229193323Sed        // If this global holds a pointer type, see if it is an indirect global.
230204642Srdivacky        if (I->getType()->getElementType()->isPointerTy() &&
231193323Sed            AnalyzeIndirectGlobalMemory(I))
232193323Sed          ++NumIndirectGlobalVars;
233193323Sed      }
234193323Sed      Readers.clear(); Writers.clear();
235193323Sed    }
236193323Sed}
237193323Sed
238193323Sed/// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
239193323Sed/// If this is used by anything complex (i.e., the address escapes), return
240193323Sed/// true.  Also, while we are at it, keep track of those functions that read and
241193323Sed/// write to the value.
242193323Sed///
243193323Sed/// If OkayStoreDest is non-null, stores into this global are allowed.
244193323Sedbool GlobalsModRef::AnalyzeUsesOfPointer(Value *V,
245193323Sed                                         std::vector<Function*> &Readers,
246193323Sed                                         std::vector<Function*> &Writers,
247193323Sed                                         GlobalValue *OkayStoreDest) {
248204642Srdivacky  if (!V->getType()->isPointerTy()) return true;
249193323Sed
250210299Sed  for (Value::use_iterator UI = V->use_begin(), E=V->use_end(); UI != E; ++UI) {
251210299Sed    User *U = *UI;
252210299Sed    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
253193323Sed      Readers.push_back(LI->getParent()->getParent());
254210299Sed    } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
255193323Sed      if (V == SI->getOperand(1)) {
256193323Sed        Writers.push_back(SI->getParent()->getParent());
257193323Sed      } else if (SI->getOperand(1) != OkayStoreDest) {
258193323Sed        return true;  // Storing the pointer
259193323Sed      }
260210299Sed    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
261193323Sed      if (AnalyzeUsesOfPointer(GEP, Readers, Writers)) return true;
262210299Sed    } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
263198090Srdivacky      if (AnalyzeUsesOfPointer(BCI, Readers, Writers, OkayStoreDest))
264198090Srdivacky        return true;
265210299Sed    } else if (isFreeCall(U)) {
266210299Sed      Writers.push_back(cast<Instruction>(U)->getParent()->getParent());
267210299Sed    } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
268193323Sed      // Make sure that this is just the function being called, not that it is
269193323Sed      // passing into the function.
270210299Sed      for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
271210299Sed        if (CI->getArgOperand(i) == V) return true;
272210299Sed    } else if (InvokeInst *II = dyn_cast<InvokeInst>(U)) {
273193323Sed      // Make sure that this is just the function being called, not that it is
274193323Sed      // passing into the function.
275210299Sed      for (unsigned i = 0, e = II->getNumArgOperands(); i != e; ++i)
276210299Sed        if (II->getArgOperand(i) == V) return true;
277210299Sed    } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
278193323Sed      if (CE->getOpcode() == Instruction::GetElementPtr ||
279193323Sed          CE->getOpcode() == Instruction::BitCast) {
280193323Sed        if (AnalyzeUsesOfPointer(CE, Readers, Writers))
281193323Sed          return true;
282193323Sed      } else {
283193323Sed        return true;
284193323Sed      }
285210299Sed    } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(U)) {
286193323Sed      if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
287193323Sed        return true;  // Allow comparison against null.
288193323Sed    } else {
289193323Sed      return true;
290193323Sed    }
291210299Sed  }
292210299Sed
293193323Sed  return false;
294193323Sed}
295193323Sed
296193323Sed/// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
297193323Sed/// which holds a pointer type.  See if the global always points to non-aliased
298193323Sed/// heap memory: that is, all initializers of the globals are allocations, and
299193323Sed/// those allocations have no use other than initialization of the global.
300193323Sed/// Further, all loads out of GV must directly use the memory, not store the
301193323Sed/// pointer somewhere.  If this is true, we consider the memory pointed to by
302193323Sed/// GV to be owned by GV and can disambiguate other pointers from it.
303193323Sedbool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
304193323Sed  // Keep track of values related to the allocation of the memory, f.e. the
305193323Sed  // value produced by the malloc call and any casts.
306193323Sed  std::vector<Value*> AllocRelatedValues;
307193323Sed
308193323Sed  // Walk the user list of the global.  If we find anything other than a direct
309193323Sed  // load or store, bail out.
310193323Sed  for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
311210299Sed    User *U = *I;
312210299Sed    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
313193323Sed      // The pointer loaded from the global can only be used in simple ways:
314193323Sed      // we allow addressing of it and loading storing to it.  We do *not* allow
315193323Sed      // storing the loaded pointer somewhere else or passing to a function.
316193323Sed      std::vector<Function*> ReadersWriters;
317193323Sed      if (AnalyzeUsesOfPointer(LI, ReadersWriters, ReadersWriters))
318193323Sed        return false;  // Loaded pointer escapes.
319193323Sed      // TODO: Could try some IP mod/ref of the loaded pointer.
320210299Sed    } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
321193323Sed      // Storing the global itself.
322193323Sed      if (SI->getOperand(0) == GV) return false;
323193323Sed
324193323Sed      // If storing the null pointer, ignore it.
325193323Sed      if (isa<ConstantPointerNull>(SI->getOperand(0)))
326193323Sed        continue;
327193323Sed
328193323Sed      // Check the value being stored.
329218893Sdim      Value *Ptr = GetUnderlyingObject(SI->getOperand(0));
330193323Sed
331198396Srdivacky      if (isMalloc(Ptr)) {
332193323Sed        // Okay, easy case.
333193323Sed      } else if (CallInst *CI = dyn_cast<CallInst>(Ptr)) {
334193323Sed        Function *F = CI->getCalledFunction();
335193323Sed        if (!F || !F->isDeclaration()) return false;     // Too hard to analyze.
336193323Sed        if (F->getName() != "calloc") return false;   // Not calloc.
337193323Sed      } else {
338193323Sed        return false;  // Too hard to analyze.
339193323Sed      }
340193323Sed
341193323Sed      // Analyze all uses of the allocation.  If any of them are used in a
342193323Sed      // non-simple way (e.g. stored to another global) bail out.
343193323Sed      std::vector<Function*> ReadersWriters;
344193323Sed      if (AnalyzeUsesOfPointer(Ptr, ReadersWriters, ReadersWriters, GV))
345193323Sed        return false;  // Loaded pointer escapes.
346193323Sed
347193323Sed      // Remember that this allocation is related to the indirect global.
348193323Sed      AllocRelatedValues.push_back(Ptr);
349193323Sed    } else {
350193323Sed      // Something complex, bail out.
351193323Sed      return false;
352193323Sed    }
353193323Sed  }
354193323Sed
355193323Sed  // Okay, this is an indirect global.  Remember all of the allocations for
356193323Sed  // this global in AllocsForIndirectGlobals.
357193323Sed  while (!AllocRelatedValues.empty()) {
358193323Sed    AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
359193323Sed    AllocRelatedValues.pop_back();
360193323Sed  }
361193323Sed  IndirectGlobals.insert(GV);
362193323Sed  return true;
363193323Sed}
364193323Sed
365193323Sed/// AnalyzeCallGraph - At this point, we know the functions where globals are
366193323Sed/// immediately stored to and read from.  Propagate this information up the call
367193323Sed/// graph to all callers and compute the mod/ref info for all memory for each
368193323Sed/// function.
369193323Sedvoid GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
370193323Sed  // We do a bottom-up SCC traversal of the call graph.  In other words, we
371193323Sed  // visit all callees before callers (leaf-first).
372193323Sed  for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I != E;
373193323Sed       ++I) {
374193323Sed    std::vector<CallGraphNode *> &SCC = *I;
375193323Sed    assert(!SCC.empty() && "SCC with no functions?");
376193323Sed
377193323Sed    if (!SCC[0]->getFunction()) {
378193323Sed      // Calls externally - can't say anything useful.  Remove any existing
379193323Sed      // function records (may have been created when scanning globals).
380193323Sed      for (unsigned i = 0, e = SCC.size(); i != e; ++i)
381193323Sed        FunctionInfo.erase(SCC[i]->getFunction());
382193323Sed      continue;
383193323Sed    }
384193323Sed
385193323Sed    FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
386193323Sed
387193323Sed    bool KnowNothing = false;
388193323Sed    unsigned FunctionEffect = 0;
389193323Sed
390193323Sed    // Collect the mod/ref properties due to called functions.  We only compute
391193323Sed    // one mod-ref set.
392193323Sed    for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
393193323Sed      Function *F = SCC[i]->getFunction();
394193323Sed      if (!F) {
395193323Sed        KnowNothing = true;
396193323Sed        break;
397193323Sed      }
398193323Sed
399193323Sed      if (F->isDeclaration()) {
400193323Sed        // Try to get mod/ref behaviour from function attributes.
401193323Sed        if (F->doesNotAccessMemory()) {
402193323Sed          // Can't do better than that!
403193323Sed        } else if (F->onlyReadsMemory()) {
404193323Sed          FunctionEffect |= Ref;
405193323Sed          if (!F->isIntrinsic())
406193323Sed            // This function might call back into the module and read a global -
407193323Sed            // consider every global as possibly being read by this function.
408193323Sed            FR.MayReadAnyGlobal = true;
409193323Sed        } else {
410193323Sed          FunctionEffect |= ModRef;
411193323Sed          // Can't say anything useful unless it's an intrinsic - they don't
412193323Sed          // read or write global variables of the kind considered here.
413193323Sed          KnowNothing = !F->isIntrinsic();
414193323Sed        }
415193323Sed        continue;
416193323Sed      }
417193323Sed
418193323Sed      for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
419193323Sed           CI != E && !KnowNothing; ++CI)
420193323Sed        if (Function *Callee = CI->second->getFunction()) {
421193323Sed          if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
422193323Sed            // Propagate function effect up.
423193323Sed            FunctionEffect |= CalleeFR->FunctionEffect;
424193323Sed
425193323Sed            // Incorporate callee's effects on globals into our info.
426212904Sdim            for (std::map<const GlobalValue*, unsigned>::iterator GI =
427193323Sed                   CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end();
428193323Sed                 GI != E; ++GI)
429193323Sed              FR.GlobalInfo[GI->first] |= GI->second;
430193323Sed            FR.MayReadAnyGlobal |= CalleeFR->MayReadAnyGlobal;
431193323Sed          } else {
432193323Sed            // Can't say anything about it.  However, if it is inside our SCC,
433193323Sed            // then nothing needs to be done.
434193323Sed            CallGraphNode *CalleeNode = CG[Callee];
435193323Sed            if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end())
436193323Sed              KnowNothing = true;
437193323Sed          }
438193323Sed        } else {
439193323Sed          KnowNothing = true;
440193323Sed        }
441193323Sed    }
442193323Sed
443193323Sed    // If we can't say anything useful about this SCC, remove all SCC functions
444193323Sed    // from the FunctionInfo map.
445193323Sed    if (KnowNothing) {
446193323Sed      for (unsigned i = 0, e = SCC.size(); i != e; ++i)
447193323Sed        FunctionInfo.erase(SCC[i]->getFunction());
448193323Sed      continue;
449193323Sed    }
450193323Sed
451193323Sed    // Scan the function bodies for explicit loads or stores.
452193323Sed    for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i)
453193323Sed      for (inst_iterator II = inst_begin(SCC[i]->getFunction()),
454193323Sed             E = inst_end(SCC[i]->getFunction());
455193323Sed           II != E && FunctionEffect != ModRef; ++II)
456193323Sed        if (isa<LoadInst>(*II)) {
457193323Sed          FunctionEffect |= Ref;
458193323Sed          if (cast<LoadInst>(*II).isVolatile())
459193323Sed            // Volatile loads may have side-effects, so mark them as writing
460193323Sed            // memory (for example, a flag inside the processor).
461193323Sed            FunctionEffect |= Mod;
462193323Sed        } else if (isa<StoreInst>(*II)) {
463193323Sed          FunctionEffect |= Mod;
464193323Sed          if (cast<StoreInst>(*II).isVolatile())
465193323Sed            // Treat volatile stores as reading memory somewhere.
466193323Sed            FunctionEffect |= Ref;
467198892Srdivacky        } else if (isMalloc(&cast<Instruction>(*II)) ||
468198892Srdivacky                   isFreeCall(&cast<Instruction>(*II))) {
469193323Sed          FunctionEffect |= ModRef;
470193323Sed        }
471193323Sed
472193323Sed    if ((FunctionEffect & Mod) == 0)
473193323Sed      ++NumReadMemFunctions;
474193323Sed    if (FunctionEffect == 0)
475193323Sed      ++NumNoMemFunctions;
476193323Sed    FR.FunctionEffect = FunctionEffect;
477193323Sed
478193323Sed    // Finally, now that we know the full effect on this SCC, clone the
479193323Sed    // information to each function in the SCC.
480193323Sed    for (unsigned i = 1, e = SCC.size(); i != e; ++i)
481193323Sed      FunctionInfo[SCC[i]->getFunction()] = FR;
482193323Sed  }
483193323Sed}
484193323Sed
485193323Sed
486193323Sed
487193323Sed/// alias - If one of the pointers is to a global that we are tracking, and the
488193323Sed/// other is some random pointer, we know there cannot be an alias, because the
489193323Sed/// address of the global isn't taken.
490193323SedAliasAnalysis::AliasResult
491218893SdimGlobalsModRef::alias(const Location &LocA,
492218893Sdim                     const Location &LocB) {
493193323Sed  // Get the base object these pointers point to.
494218893Sdim  const Value *UV1 = GetUnderlyingObject(LocA.Ptr);
495218893Sdim  const Value *UV2 = GetUnderlyingObject(LocB.Ptr);
496193323Sed
497193323Sed  // If either of the underlying values is a global, they may be non-addr-taken
498193323Sed  // globals, which we can answer queries about.
499212904Sdim  const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
500212904Sdim  const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
501193323Sed  if (GV1 || GV2) {
502193323Sed    // If the global's address is taken, pretend we don't know it's a pointer to
503193323Sed    // the global.
504193323Sed    if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0;
505193323Sed    if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0;
506193323Sed
507203954Srdivacky    // If the two pointers are derived from two different non-addr-taken
508193323Sed    // globals, or if one is and the other isn't, we know these can't alias.
509193323Sed    if ((GV1 || GV2) && GV1 != GV2)
510193323Sed      return NoAlias;
511193323Sed
512193323Sed    // Otherwise if they are both derived from the same addr-taken global, we
513193323Sed    // can't know the two accesses don't overlap.
514193323Sed  }
515193323Sed
516193323Sed  // These pointers may be based on the memory owned by an indirect global.  If
517193323Sed  // so, we may be able to handle this.  First check to see if the base pointer
518193323Sed  // is a direct load from an indirect global.
519193323Sed  GV1 = GV2 = 0;
520212904Sdim  if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
521193323Sed    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
522193323Sed      if (IndirectGlobals.count(GV))
523193323Sed        GV1 = GV;
524212904Sdim  if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
525212904Sdim    if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
526193323Sed      if (IndirectGlobals.count(GV))
527193323Sed        GV2 = GV;
528193323Sed
529193323Sed  // These pointers may also be from an allocation for the indirect global.  If
530193323Sed  // so, also handle them.
531193323Sed  if (AllocsForIndirectGlobals.count(UV1))
532193323Sed    GV1 = AllocsForIndirectGlobals[UV1];
533193323Sed  if (AllocsForIndirectGlobals.count(UV2))
534193323Sed    GV2 = AllocsForIndirectGlobals[UV2];
535193323Sed
536193323Sed  // Now that we know whether the two pointers are related to indirect globals,
537193323Sed  // use this to disambiguate the pointers.  If either pointer is based on an
538193323Sed  // indirect global and if they are not both based on the same indirect global,
539193323Sed  // they cannot alias.
540193323Sed  if ((GV1 || GV2) && GV1 != GV2)
541193323Sed    return NoAlias;
542193323Sed
543218893Sdim  return AliasAnalysis::alias(LocA, LocB);
544193323Sed}
545193323Sed
546193323SedAliasAnalysis::ModRefResult
547212904SdimGlobalsModRef::getModRefInfo(ImmutableCallSite CS,
548218893Sdim                             const Location &Loc) {
549193323Sed  unsigned Known = ModRef;
550193323Sed
551193323Sed  // If we are asking for mod/ref info of a direct call with a pointer to a
552193323Sed  // global we are tracking, return information if we have it.
553218893Sdim  if (const GlobalValue *GV =
554218893Sdim        dyn_cast<GlobalValue>(GetUnderlyingObject(Loc.Ptr)))
555193323Sed    if (GV->hasLocalLinkage())
556212904Sdim      if (const Function *F = CS.getCalledFunction())
557193323Sed        if (NonAddressTakenGlobals.count(GV))
558212904Sdim          if (const FunctionRecord *FR = getFunctionInfo(F))
559193323Sed            Known = FR->getInfoForGlobal(GV);
560193323Sed
561193323Sed  if (Known == NoModRef)
562193323Sed    return NoModRef; // No need to query other mod/ref analyses
563218893Sdim  return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, Loc));
564193323Sed}
565193323Sed
566193323Sed
567193323Sed//===----------------------------------------------------------------------===//
568193323Sed// Methods to update the analysis as a result of the client transformation.
569193323Sed//
570193323Sedvoid GlobalsModRef::deleteValue(Value *V) {
571193323Sed  if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
572193323Sed    if (NonAddressTakenGlobals.erase(GV)) {
573193323Sed      // This global might be an indirect global.  If so, remove it and remove
574193323Sed      // any AllocRelatedValues for it.
575193323Sed      if (IndirectGlobals.erase(GV)) {
576193323Sed        // Remove any entries in AllocsForIndirectGlobals for this global.
577212904Sdim        for (std::map<const Value*, const GlobalValue*>::iterator
578193323Sed             I = AllocsForIndirectGlobals.begin(),
579193323Sed             E = AllocsForIndirectGlobals.end(); I != E; ) {
580193323Sed          if (I->second == GV) {
581193323Sed            AllocsForIndirectGlobals.erase(I++);
582193323Sed          } else {
583193323Sed            ++I;
584193323Sed          }
585193323Sed        }
586193323Sed      }
587193323Sed    }
588193323Sed  }
589193323Sed
590193323Sed  // Otherwise, if this is an allocation related to an indirect global, remove
591193323Sed  // it.
592193323Sed  AllocsForIndirectGlobals.erase(V);
593193323Sed
594193323Sed  AliasAnalysis::deleteValue(V);
595193323Sed}
596193323Sed
597193323Sedvoid GlobalsModRef::copyValue(Value *From, Value *To) {
598193323Sed  AliasAnalysis::copyValue(From, To);
599193323Sed}
600218893Sdim
601218893Sdimvoid GlobalsModRef::addEscapingUse(Use &U) {
602218893Sdim  // For the purposes of this analysis, it is conservatively correct to treat
603218893Sdim  // a newly escaping value equivalently to a deleted one.  We could perhaps
604218893Sdim  // be more precise by processing the new use and attempting to update our
605218893Sdim  // saved analysis results to accomodate it.
606218893Sdim  deleteValue(U);
607218893Sdim
608218893Sdim  AliasAnalysis::addEscapingUse(U);
609218893Sdim}
610