e6c7a6a9df35148236622718437ef3abaea059d3
[oota-llvm.git] / lib / Analysis / IPA / GlobalsModRef.cpp
1 //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
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 simple pass provides alias and mod/ref information for global values
11 // that do not have their address taken, and keeps track of whether functions
12 // read or write memory (are "pure").  For this simple (but very common) case,
13 // we can provide pretty accurate and useful information.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/ADT/SCCIterator.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/CallGraph.h"
22 #include "llvm/Analysis/MemoryBuiltins.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/InstIterator.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/CommandLine.h"
32 #include <set>
33 using namespace llvm;
34
35 #define DEBUG_TYPE "globalsmodref-aa"
36
37 STATISTIC(NumNonAddrTakenGlobalVars,
38           "Number of global vars without address taken");
39 STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
40 STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
41 STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
42 STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
43
44 // An option to enable unsafe alias results from the GlobalsModRef analysis.
45 // When enabled, GlobalsModRef will provide no-alias results which in extremely
46 // rare cases may not be conservatively correct. In particular, in the face of
47 // transforms which cause assymetry between how effective GetUnderlyingObject
48 // is for two pointers, it may produce incorrect results.
49 //
50 // These unsafe results have been returned by GMR for many years without
51 // causing significant issues in the wild and so we provide a mechanism to
52 // re-enable them for users of LLVM that have a particular performance
53 // sensitivity and no known issues. The option also makes it easy to evaluate
54 // the performance impact of these results.
55 static cl::opt<bool> EnableUnsafeGlobalsModRefAliasResults(
56     "enable-unsafe-globalsmodref-alias-results", cl::init(false), cl::Hidden);
57
58 namespace {
59 /// FunctionRecord - One instance of this structure is stored for every
60 /// function in the program.  Later, the entries for these functions are
61 /// removed if the function is found to call an external function (in which
62 /// case we know nothing about it.
63 struct FunctionRecord {
64   /// GlobalInfo - Maintain mod/ref info for all of the globals without
65   /// addresses taken that are read or written (transitively) by this
66   /// function.
67   std::map<const GlobalValue *, unsigned> GlobalInfo;
68
69   /// MayReadAnyGlobal - May read global variables, but it is not known which.
70   bool MayReadAnyGlobal;
71
72   unsigned getInfoForGlobal(const GlobalValue *GV) const {
73     unsigned Effect = MayReadAnyGlobal ? AliasAnalysis::Ref : 0;
74     std::map<const GlobalValue *, unsigned>::const_iterator I =
75         GlobalInfo.find(GV);
76     if (I != GlobalInfo.end())
77       Effect |= I->second;
78     return Effect;
79   }
80
81   /// FunctionEffect - Capture whether or not this function reads or writes to
82   /// ANY memory.  If not, we can do a lot of aggressive analysis on it.
83   unsigned FunctionEffect;
84
85   FunctionRecord() : MayReadAnyGlobal(false), FunctionEffect(0) {}
86 };
87
88 /// GlobalsModRef - The actual analysis pass.
89 class GlobalsModRef : public ModulePass, public AliasAnalysis {
90   /// NonAddressTakenGlobals - The globals that do not have their addresses
91   /// taken.
92   std::set<const GlobalValue *> NonAddressTakenGlobals;
93
94   /// IndirectGlobals - The memory pointed to by this global is known to be
95   /// 'owned' by the global.
96   std::set<const GlobalValue *> IndirectGlobals;
97
98   /// AllocsForIndirectGlobals - If an instruction allocates memory for an
99   /// indirect global, this map indicates which one.
100   std::map<const Value *, const GlobalValue *> AllocsForIndirectGlobals;
101
102   /// FunctionInfo - For each function, keep track of what globals are
103   /// modified or read.
104   std::map<const Function *, FunctionRecord> FunctionInfo;
105
106 public:
107   static char ID;
108   GlobalsModRef() : ModulePass(ID) {
109     initializeGlobalsModRefPass(*PassRegistry::getPassRegistry());
110   }
111
112   bool runOnModule(Module &M) override {
113     InitializeAliasAnalysis(this, &M.getDataLayout());
114
115     // Find non-addr taken globals.
116     AnalyzeGlobals(M);
117
118     // Propagate on CG.
119     AnalyzeCallGraph(getAnalysis<CallGraphWrapperPass>().getCallGraph(), M);
120     return false;
121   }
122
123   void getAnalysisUsage(AnalysisUsage &AU) const override {
124     AliasAnalysis::getAnalysisUsage(AU);
125     AU.addRequired<CallGraphWrapperPass>();
126     AU.setPreservesAll(); // Does not transform code
127   }
128
129   //------------------------------------------------
130   // Implement the AliasAnalysis API
131   //
132   AliasResult alias(const MemoryLocation &LocA,
133                     const MemoryLocation &LocB) override;
134   ModRefResult getModRefInfo(ImmutableCallSite CS,
135                              const MemoryLocation &Loc) override;
136   ModRefResult getModRefInfo(ImmutableCallSite CS1,
137                              ImmutableCallSite CS2) override {
138     return AliasAnalysis::getModRefInfo(CS1, CS2);
139   }
140
141   /// getModRefBehavior - Return the behavior of the specified function if
142   /// called from the specified call site.  The call site may be null in which
143   /// case the most generic behavior of this function should be returned.
144   ModRefBehavior getModRefBehavior(const Function *F) override {
145     ModRefBehavior Min = UnknownModRefBehavior;
146
147     if (FunctionRecord *FR = getFunctionInfo(F)) {
148       if (FR->FunctionEffect == 0)
149         Min = DoesNotAccessMemory;
150       else if ((FR->FunctionEffect & Mod) == 0)
151         Min = OnlyReadsMemory;
152     }
153
154     return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
155   }
156
157   /// getModRefBehavior - Return the behavior of the specified function if
158   /// called from the specified call site.  The call site may be null in which
159   /// case the most generic behavior of this function should be returned.
160   ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override {
161     ModRefBehavior Min = UnknownModRefBehavior;
162
163     if (const Function *F = CS.getCalledFunction())
164       if (FunctionRecord *FR = getFunctionInfo(F)) {
165         if (FR->FunctionEffect == 0)
166           Min = DoesNotAccessMemory;
167         else if ((FR->FunctionEffect & Mod) == 0)
168           Min = OnlyReadsMemory;
169       }
170
171     return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
172   }
173
174   void deleteValue(Value *V) override;
175   void addEscapingUse(Use &U) override;
176
177   /// getAdjustedAnalysisPointer - This method is used when a pass implements
178   /// an analysis interface through multiple inheritance.  If needed, it
179   /// should override this to adjust the this pointer as needed for the
180   /// specified pass info.
181   void *getAdjustedAnalysisPointer(AnalysisID PI) override {
182     if (PI == &AliasAnalysis::ID)
183       return (AliasAnalysis *)this;
184     return this;
185   }
186
187 private:
188   /// getFunctionInfo - Return the function info for the function, or null if
189   /// we don't have anything useful to say about it.
190   FunctionRecord *getFunctionInfo(const Function *F) {
191     std::map<const Function *, FunctionRecord>::iterator I =
192         FunctionInfo.find(F);
193     if (I != FunctionInfo.end())
194       return &I->second;
195     return nullptr;
196   }
197
198   void AnalyzeGlobals(Module &M);
199   void AnalyzeCallGraph(CallGraph &CG, Module &M);
200   bool AnalyzeUsesOfPointer(Value *V, std::vector<Function *> &Readers,
201                             std::vector<Function *> &Writers,
202                             GlobalValue *OkayStoreDest = nullptr);
203   bool AnalyzeIndirectGlobalMemory(GlobalValue *GV);
204 };
205 }
206
207 char GlobalsModRef::ID = 0;
208 INITIALIZE_AG_PASS_BEGIN(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
209                          "Simple mod/ref analysis for globals", false, true,
210                          false)
211 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
212 INITIALIZE_AG_PASS_END(GlobalsModRef, AliasAnalysis, "globalsmodref-aa",
213                        "Simple mod/ref analysis for globals", false, true,
214                        false)
215
216 Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
217
218 /// AnalyzeGlobals - Scan through the users of all of the internal
219 /// GlobalValue's in the program.  If none of them have their "address taken"
220 /// (really, their address passed to something nontrivial), record this fact,
221 /// and record the functions that they are used directly in.
222 void GlobalsModRef::AnalyzeGlobals(Module &M) {
223   std::vector<Function *> Readers, Writers;
224   for (Function &F : M)
225     if (F.hasLocalLinkage()) {
226       if (!AnalyzeUsesOfPointer(&F, Readers, Writers)) {
227         // Remember that we are tracking this global.
228         NonAddressTakenGlobals.insert(&F);
229         ++NumNonAddrTakenFunctions;
230       }
231       Readers.clear();
232       Writers.clear();
233     }
234
235   for (GlobalVariable &GV : M.globals())
236     if (GV.hasLocalLinkage()) {
237       if (!AnalyzeUsesOfPointer(&GV, Readers, Writers)) {
238         // Remember that we are tracking this global, and the mod/ref fns
239         NonAddressTakenGlobals.insert(&GV);
240
241         for (Function *Reader : Readers)
242           FunctionInfo[Reader].GlobalInfo[&GV] |= Ref;
243
244         if (!GV.isConstant()) // No need to keep track of writers to constants
245           for (Function *Writer : Writers)
246             FunctionInfo[Writer].GlobalInfo[&GV] |= Mod;
247         ++NumNonAddrTakenGlobalVars;
248
249         // If this global holds a pointer type, see if it is an indirect global.
250         if (GV.getType()->getElementType()->isPointerTy() &&
251             AnalyzeIndirectGlobalMemory(&GV))
252           ++NumIndirectGlobalVars;
253       }
254       Readers.clear();
255       Writers.clear();
256     }
257 }
258
259 /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
260 /// If this is used by anything complex (i.e., the address escapes), return
261 /// true.  Also, while we are at it, keep track of those functions that read and
262 /// write to the value.
263 ///
264 /// If OkayStoreDest is non-null, stores into this global are allowed.
265 bool GlobalsModRef::AnalyzeUsesOfPointer(Value *V,
266                                          std::vector<Function *> &Readers,
267                                          std::vector<Function *> &Writers,
268                                          GlobalValue *OkayStoreDest) {
269   if (!V->getType()->isPointerTy())
270     return true;
271
272   for (Use &U : V->uses()) {
273     User *I = U.getUser();
274     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
275       Readers.push_back(LI->getParent()->getParent());
276     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
277       if (V == SI->getOperand(1)) {
278         Writers.push_back(SI->getParent()->getParent());
279       } else if (SI->getOperand(1) != OkayStoreDest) {
280         return true; // Storing the pointer
281       }
282     } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
283       if (AnalyzeUsesOfPointer(I, Readers, Writers))
284         return true;
285     } else if (Operator::getOpcode(I) == Instruction::BitCast) {
286       if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
287         return true;
288     } else if (auto CS = CallSite(I)) {
289       // Make sure that this is just the function being called, not that it is
290       // passing into the function.
291       if (!CS.isCallee(&U)) {
292         // Detect calls to free.
293         if (isFreeCall(I, TLI))
294           Writers.push_back(CS->getParent()->getParent());
295         else
296           return true; // Argument of an unknown call.
297       }
298     } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
299       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
300         return true; // Allow comparison against null.
301     } else {
302       return true;
303     }
304   }
305
306   return false;
307 }
308
309 /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
310 /// which holds a pointer type.  See if the global always points to non-aliased
311 /// heap memory: that is, all initializers of the globals are allocations, and
312 /// those allocations have no use other than initialization of the global.
313 /// Further, all loads out of GV must directly use the memory, not store the
314 /// pointer somewhere.  If this is true, we consider the memory pointed to by
315 /// GV to be owned by GV and can disambiguate other pointers from it.
316 bool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
317   // Keep track of values related to the allocation of the memory, f.e. the
318   // value produced by the malloc call and any casts.
319   std::vector<Value *> AllocRelatedValues;
320
321   // Walk the user list of the global.  If we find anything other than a direct
322   // load or store, bail out.
323   for (User *U : GV->users()) {
324     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
325       // The pointer loaded from the global can only be used in simple ways:
326       // we allow addressing of it and loading storing to it.  We do *not* allow
327       // storing the loaded pointer somewhere else or passing to a function.
328       std::vector<Function *> ReadersWriters;
329       if (AnalyzeUsesOfPointer(LI, ReadersWriters, ReadersWriters))
330         return false; // Loaded pointer escapes.
331       // TODO: Could try some IP mod/ref of the loaded pointer.
332     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
333       // Storing the global itself.
334       if (SI->getOperand(0) == GV)
335         return false;
336
337       // If storing the null pointer, ignore it.
338       if (isa<ConstantPointerNull>(SI->getOperand(0)))
339         continue;
340
341       // Check the value being stored.
342       Value *Ptr = GetUnderlyingObject(SI->getOperand(0),
343                                        GV->getParent()->getDataLayout());
344
345       if (!isAllocLikeFn(Ptr, TLI))
346         return false; // Too hard to analyze.
347
348       // Analyze all uses of the allocation.  If any of them are used in a
349       // non-simple way (e.g. stored to another global) bail out.
350       std::vector<Function *> ReadersWriters;
351       if (AnalyzeUsesOfPointer(Ptr, ReadersWriters, ReadersWriters, GV))
352         return false; // Loaded pointer escapes.
353
354       // Remember that this allocation is related to the indirect global.
355       AllocRelatedValues.push_back(Ptr);
356     } else {
357       // Something complex, bail out.
358       return false;
359     }
360   }
361
362   // Okay, this is an indirect global.  Remember all of the allocations for
363   // this global in AllocsForIndirectGlobals.
364   while (!AllocRelatedValues.empty()) {
365     AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
366     AllocRelatedValues.pop_back();
367   }
368   IndirectGlobals.insert(GV);
369   return true;
370 }
371
372 /// AnalyzeCallGraph - At this point, we know the functions where globals are
373 /// immediately stored to and read from.  Propagate this information up the call
374 /// graph to all callers and compute the mod/ref info for all memory for each
375 /// function.
376 void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
377   // We do a bottom-up SCC traversal of the call graph.  In other words, we
378   // visit all callees before callers (leaf-first).
379   for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
380     const std::vector<CallGraphNode *> &SCC = *I;
381     assert(!SCC.empty() && "SCC with no functions?");
382
383     if (!SCC[0]->getFunction()) {
384       // Calls externally - can't say anything useful.  Remove any existing
385       // function records (may have been created when scanning globals).
386       for (auto *Node : SCC)
387         FunctionInfo.erase(Node->getFunction());
388       continue;
389     }
390
391     FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
392
393     bool KnowNothing = false;
394     unsigned FunctionEffect = 0;
395
396     // Collect the mod/ref properties due to called functions.  We only compute
397     // one mod-ref set.
398     for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
399       Function *F = SCC[i]->getFunction();
400       if (!F) {
401         KnowNothing = true;
402         break;
403       }
404
405       if (F->isDeclaration()) {
406         // Try to get mod/ref behaviour from function attributes.
407         if (F->doesNotAccessMemory()) {
408           // Can't do better than that!
409         } else if (F->onlyReadsMemory()) {
410           FunctionEffect |= Ref;
411           if (!F->isIntrinsic())
412             // This function might call back into the module and read a global -
413             // consider every global as possibly being read by this function.
414             FR.MayReadAnyGlobal = true;
415         } else {
416           FunctionEffect |= ModRef;
417           // Can't say anything useful unless it's an intrinsic - they don't
418           // read or write global variables of the kind considered here.
419           KnowNothing = !F->isIntrinsic();
420         }
421         continue;
422       }
423
424       for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
425            CI != E && !KnowNothing; ++CI)
426         if (Function *Callee = CI->second->getFunction()) {
427           if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
428             // Propagate function effect up.
429             FunctionEffect |= CalleeFR->FunctionEffect;
430
431             // Incorporate callee's effects on globals into our info.
432             for (const auto &G : CalleeFR->GlobalInfo)
433               FR.GlobalInfo[G.first] |= G.second;
434             FR.MayReadAnyGlobal |= CalleeFR->MayReadAnyGlobal;
435           } else {
436             // Can't say anything about it.  However, if it is inside our SCC,
437             // then nothing needs to be done.
438             CallGraphNode *CalleeNode = CG[Callee];
439             if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end())
440               KnowNothing = true;
441           }
442         } else {
443           KnowNothing = true;
444         }
445     }
446
447     // If we can't say anything useful about this SCC, remove all SCC functions
448     // from the FunctionInfo map.
449     if (KnowNothing) {
450       for (auto *Node : SCC)
451         FunctionInfo.erase(Node->getFunction());
452       continue;
453     }
454
455     // Scan the function bodies for explicit loads or stores.
456     for (auto *Node : SCC) {
457       if (FunctionEffect == ModRef)
458         break; // The mod/ref lattice saturates here.
459       for (Instruction &I : inst_range(Node->getFunction())) {
460         if (FunctionEffect == ModRef)
461           break; // The mod/ref lattice saturates here.
462
463         // We handle calls specially because the graph-relevant aspects are
464         // handled above.
465         if (auto CS = CallSite(&I)) {
466           if (isAllocationFn(&I, TLI) || isFreeCall(&I, TLI)) {
467             // FIXME: It is completely unclear why this is necessary and not
468             // handled by the above graph code.
469             FunctionEffect |= ModRef;
470           } else if (Function *Callee = CS.getCalledFunction()) {
471             // The callgraph doesn't include intrinsic calls.
472             if (Callee->isIntrinsic()) {
473               ModRefBehavior Behaviour =
474                   AliasAnalysis::getModRefBehavior(Callee);
475               FunctionEffect |= (Behaviour & ModRef);
476             }
477           }
478           continue;
479         }
480
481         // All non-call instructions we use the primary predicates for whether
482         // thay read or write memory.
483         if (I.mayReadFromMemory())
484           FunctionEffect |= Ref;
485         if (I.mayWriteToMemory())
486           FunctionEffect |= Mod;
487       }
488     }
489
490     if ((FunctionEffect & Mod) == 0)
491       ++NumReadMemFunctions;
492     if (FunctionEffect == 0)
493       ++NumNoMemFunctions;
494     FR.FunctionEffect = FunctionEffect;
495
496     // Finally, now that we know the full effect on this SCC, clone the
497     // information to each function in the SCC.
498     for (unsigned i = 1, e = SCC.size(); i != e; ++i)
499       FunctionInfo[SCC[i]->getFunction()] = FR;
500   }
501 }
502
503 /// alias - If one of the pointers is to a global that we are tracking, and the
504 /// other is some random pointer, we know there cannot be an alias, because the
505 /// address of the global isn't taken.
506 AliasResult GlobalsModRef::alias(const MemoryLocation &LocA,
507                                  const MemoryLocation &LocB) {
508   // Get the base object these pointers point to.
509   const Value *UV1 = GetUnderlyingObject(LocA.Ptr, *DL);
510   const Value *UV2 = GetUnderlyingObject(LocB.Ptr, *DL);
511
512   // If either of the underlying values is a global, they may be non-addr-taken
513   // globals, which we can answer queries about.
514   const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
515   const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
516   if (GV1 || GV2) {
517     // If the global's address is taken, pretend we don't know it's a pointer to
518     // the global.
519     if (GV1 && !NonAddressTakenGlobals.count(GV1))
520       GV1 = nullptr;
521     if (GV2 && !NonAddressTakenGlobals.count(GV2))
522       GV2 = nullptr;
523
524     // If the two pointers are derived from two different non-addr-taken
525     // globals we know these can't alias.
526     if (GV1 && GV2 && GV1 != GV2)
527       return NoAlias;
528
529     // If one is and the other isn't, it isn't strictly safe but we can fake
530     // this result if necessary for performance. This does not appear to be
531     // a common problem in practice.
532     if (EnableUnsafeGlobalsModRefAliasResults)
533       if ((GV1 || GV2) && GV1 != GV2)
534         return NoAlias;
535
536     // Otherwise if they are both derived from the same addr-taken global, we
537     // can't know the two accesses don't overlap.
538   }
539
540   // These pointers may be based on the memory owned by an indirect global.  If
541   // so, we may be able to handle this.  First check to see if the base pointer
542   // is a direct load from an indirect global.
543   GV1 = GV2 = nullptr;
544   if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
545     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
546       if (IndirectGlobals.count(GV))
547         GV1 = GV;
548   if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
549     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
550       if (IndirectGlobals.count(GV))
551         GV2 = GV;
552
553   // These pointers may also be from an allocation for the indirect global.  If
554   // so, also handle them.
555   if (AllocsForIndirectGlobals.count(UV1))
556     GV1 = AllocsForIndirectGlobals[UV1];
557   if (AllocsForIndirectGlobals.count(UV2))
558     GV2 = AllocsForIndirectGlobals[UV2];
559
560   // Now that we know whether the two pointers are related to indirect globals,
561   // use this to disambiguate the pointers. If the pointers are based on
562   // different indirect globals they cannot alias.
563   if (GV1 && GV2 && GV1 != GV2)
564     return NoAlias;
565
566   // If one is based on an indirect global and the other isn't, it isn't
567   // strictly safe but we can fake this result if necessary for performance.
568   // This does not appear to be a common problem in practice.
569   if (EnableUnsafeGlobalsModRefAliasResults)
570     if ((GV1 || GV2) && GV1 != GV2)
571       return NoAlias;
572
573   return AliasAnalysis::alias(LocA, LocB);
574 }
575
576 AliasAnalysis::ModRefResult
577 GlobalsModRef::getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc) {
578   unsigned Known = ModRef;
579
580   // If we are asking for mod/ref info of a direct call with a pointer to a
581   // global we are tracking, return information if we have it.
582   const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
583   if (const GlobalValue *GV =
584           dyn_cast<GlobalValue>(GetUnderlyingObject(Loc.Ptr, DL)))
585     if (GV->hasLocalLinkage())
586       if (const Function *F = CS.getCalledFunction())
587         if (NonAddressTakenGlobals.count(GV))
588           if (const FunctionRecord *FR = getFunctionInfo(F))
589             Known = FR->getInfoForGlobal(GV);
590
591   if (Known == NoModRef)
592     return NoModRef; // No need to query other mod/ref analyses
593   return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, Loc));
594 }
595
596 //===----------------------------------------------------------------------===//
597 // Methods to update the analysis as a result of the client transformation.
598 //
599 void GlobalsModRef::deleteValue(Value *V) {
600   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
601     if (NonAddressTakenGlobals.erase(GV)) {
602       // This global might be an indirect global.  If so, remove it and remove
603       // any AllocRelatedValues for it.
604       if (IndirectGlobals.erase(GV)) {
605         // Remove any entries in AllocsForIndirectGlobals for this global.
606         for (std::map<const Value *, const GlobalValue *>::iterator
607                  I = AllocsForIndirectGlobals.begin(),
608                  E = AllocsForIndirectGlobals.end();
609              I != E;) {
610           if (I->second == GV) {
611             AllocsForIndirectGlobals.erase(I++);
612           } else {
613             ++I;
614           }
615         }
616       }
617     }
618   }
619
620   // Otherwise, if this is an allocation related to an indirect global, remove
621   // it.
622   AllocsForIndirectGlobals.erase(V);
623
624   AliasAnalysis::deleteValue(V);
625 }
626
627 void GlobalsModRef::addEscapingUse(Use &U) {
628   // For the purposes of this analysis, it is conservatively correct to treat
629   // a newly escaping value equivalently to a deleted one.  We could perhaps
630   // be more precise by processing the new use and attempting to update our
631   // saved analysis results to accommodate it.
632   deleteValue(U);
633
634   AliasAnalysis::addEscapingUse(U);
635 }