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/GlobalsModRef.h"
18 #include "llvm/ADT/SCCIterator.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/MemoryBuiltins.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/InstIterator.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CommandLine.h"
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "globalsmodref-aa"
34 
35 STATISTIC(NumNonAddrTakenGlobalVars,
36           "Number of global vars without address taken");
37 STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
38 STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
39 STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
40 STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
41 
42 // An option to enable unsafe alias results from the GlobalsModRef analysis.
43 // When enabled, GlobalsModRef will provide no-alias results which in extremely
44 // rare cases may not be conservatively correct. In particular, in the face of
45 // transforms which cause assymetry between how effective GetUnderlyingObject
46 // is for two pointers, it may produce incorrect results.
47 //
48 // These unsafe results have been returned by GMR for many years without
49 // causing significant issues in the wild and so we provide a mechanism to
50 // re-enable them for users of LLVM that have a particular performance
51 // sensitivity and no known issues. The option also makes it easy to evaluate
52 // the performance impact of these results.
53 static cl::opt<bool> EnableUnsafeGlobalsModRefAliasResults(
54     "enable-unsafe-globalsmodref-alias-results", cl::init(false), cl::Hidden);
55 
56 /// The mod/ref information collected for a particular function.
57 ///
58 /// We collect information about mod/ref behavior of a function here, both in
59 /// general and as pertains to specific globals. We only have this detailed
60 /// information when we know *something* useful about the behavior. If we
61 /// saturate to fully general mod/ref, we remove the info for the function.
62 class GlobalsAAResult::FunctionInfo {
63   typedef SmallDenseMap<const GlobalValue *, ModRefInfo, 16> GlobalInfoMapType;
64 
65   /// Build a wrapper struct that has 8-byte alignment. All heap allocations
66   /// should provide this much alignment at least, but this makes it clear we
67   /// specifically rely on this amount of alignment.
68   struct LLVM_ALIGNAS(8) AlignedMap {
69     AlignedMap() {}
70     AlignedMap(const AlignedMap &Arg) : Map(Arg.Map) {}
71     GlobalInfoMapType Map;
72   };
73 
74   /// Pointer traits for our aligned map.
75   struct AlignedMapPointerTraits {
76     static inline void *getAsVoidPointer(AlignedMap *P) { return P; }
77     static inline AlignedMap *getFromVoidPointer(void *P) {
78       return (AlignedMap *)P;
79     }
80     enum { NumLowBitsAvailable = 3 };
81     static_assert(alignof(AlignedMap) >= (1 << NumLowBitsAvailable),
82                   "AlignedMap insufficiently aligned to have enough low bits.");
83   };
84 
85   /// The bit that flags that this function may read any global. This is
86   /// chosen to mix together with ModRefInfo bits.
87   /// FIXME: This assumes ModRefInfo lattice will remain 4 bits!
88   enum { MayReadAnyGlobal = 4 };
89 
90   /// Checks to document the invariants of the bit packing here.
91   static_assert((MayReadAnyGlobal & static_cast<int>(ModRefInfo::ModRef)) == 0,
92                 "ModRef and the MayReadAnyGlobal flag bits overlap.");
93   static_assert(((MayReadAnyGlobal | static_cast<int>(ModRefInfo::ModRef)) >>
94                  AlignedMapPointerTraits::NumLowBitsAvailable) == 0,
95                 "Insufficient low bits to store our flag and ModRef info.");
96 
97 public:
98   FunctionInfo() : Info() {}
99   ~FunctionInfo() {
100     delete Info.getPointer();
101   }
102   // Spell out the copy ond move constructors and assignment operators to get
103   // deep copy semantics and correct move semantics in the face of the
104   // pointer-int pair.
105   FunctionInfo(const FunctionInfo &Arg)
106       : Info(nullptr, Arg.Info.getInt()) {
107     if (const auto *ArgPtr = Arg.Info.getPointer())
108       Info.setPointer(new AlignedMap(*ArgPtr));
109   }
110   FunctionInfo(FunctionInfo &&Arg)
111       : Info(Arg.Info.getPointer(), Arg.Info.getInt()) {
112     Arg.Info.setPointerAndInt(nullptr, 0);
113   }
114   FunctionInfo &operator=(const FunctionInfo &RHS) {
115     delete Info.getPointer();
116     Info.setPointerAndInt(nullptr, RHS.Info.getInt());
117     if (const auto *RHSPtr = RHS.Info.getPointer())
118       Info.setPointer(new AlignedMap(*RHSPtr));
119     return *this;
120   }
121   FunctionInfo &operator=(FunctionInfo &&RHS) {
122     delete Info.getPointer();
123     Info.setPointerAndInt(RHS.Info.getPointer(), RHS.Info.getInt());
124     RHS.Info.setPointerAndInt(nullptr, 0);
125     return *this;
126   }
127 
128   /// Returns the \c ModRefInfo info for this function.
129   ModRefInfo getModRefInfo() const {
130     return ModRefInfo(Info.getInt() & static_cast<int>(ModRefInfo::ModRef));
131   }
132 
133   /// Adds new \c ModRefInfo for this function to its state.
134   void addModRefInfo(ModRefInfo NewMRI) {
135     Info.setInt(Info.getInt() | static_cast<int>(NewMRI));
136   }
137 
138   /// Returns whether this function may read any global variable, and we don't
139   /// know which global.
140   bool mayReadAnyGlobal() const { return Info.getInt() & MayReadAnyGlobal; }
141 
142   /// Sets this function as potentially reading from any global.
143   void setMayReadAnyGlobal() { Info.setInt(Info.getInt() | MayReadAnyGlobal); }
144 
145   /// Returns the \c ModRefInfo info for this function w.r.t. a particular
146   /// global, which may be more precise than the general information above.
147   ModRefInfo getModRefInfoForGlobal(const GlobalValue &GV) const {
148     ModRefInfo GlobalMRI =
149         mayReadAnyGlobal() ? ModRefInfo::Ref : ModRefInfo::NoModRef;
150     if (AlignedMap *P = Info.getPointer()) {
151       auto I = P->Map.find(&GV);
152       if (I != P->Map.end())
153         GlobalMRI = unionModRef(GlobalMRI, I->second);
154     }
155     return GlobalMRI;
156   }
157 
158   /// Add mod/ref info from another function into ours, saturating towards
159   /// ModRef.
160   void addFunctionInfo(const FunctionInfo &FI) {
161     addModRefInfo(FI.getModRefInfo());
162 
163     if (FI.mayReadAnyGlobal())
164       setMayReadAnyGlobal();
165 
166     if (AlignedMap *P = FI.Info.getPointer())
167       for (const auto &G : P->Map)
168         addModRefInfoForGlobal(*G.first, G.second);
169   }
170 
171   void addModRefInfoForGlobal(const GlobalValue &GV, ModRefInfo NewMRI) {
172     AlignedMap *P = Info.getPointer();
173     if (!P) {
174       P = new AlignedMap();
175       Info.setPointer(P);
176     }
177     auto &GlobalMRI = P->Map[&GV];
178     GlobalMRI = unionModRef(GlobalMRI, NewMRI);
179   }
180 
181   /// Clear a global's ModRef info. Should be used when a global is being
182   /// deleted.
183   void eraseModRefInfoForGlobal(const GlobalValue &GV) {
184     if (AlignedMap *P = Info.getPointer())
185       P->Map.erase(&GV);
186   }
187 
188 private:
189   /// All of the information is encoded into a single pointer, with a three bit
190   /// integer in the low three bits. The high bit provides a flag for when this
191   /// function may read any global. The low two bits are the ModRefInfo. And
192   /// the pointer, when non-null, points to a map from GlobalValue to
193   /// ModRefInfo specific to that GlobalValue.
194   PointerIntPair<AlignedMap *, 3, unsigned, AlignedMapPointerTraits> Info;
195 };
196 
197 void GlobalsAAResult::DeletionCallbackHandle::deleted() {
198   Value *V = getValPtr();
199   if (auto *F = dyn_cast<Function>(V))
200     GAR->FunctionInfos.erase(F);
201 
202   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
203     if (GAR->NonAddressTakenGlobals.erase(GV)) {
204       // This global might be an indirect global.  If so, remove it and
205       // remove any AllocRelatedValues for it.
206       if (GAR->IndirectGlobals.erase(GV)) {
207         // Remove any entries in AllocsForIndirectGlobals for this global.
208         for (auto I = GAR->AllocsForIndirectGlobals.begin(),
209                   E = GAR->AllocsForIndirectGlobals.end();
210              I != E; ++I)
211           if (I->second == GV)
212             GAR->AllocsForIndirectGlobals.erase(I);
213       }
214 
215       // Scan the function info we have collected and remove this global
216       // from all of them.
217       for (auto &FIPair : GAR->FunctionInfos)
218         FIPair.second.eraseModRefInfoForGlobal(*GV);
219     }
220   }
221 
222   // If this is an allocation related to an indirect global, remove it.
223   GAR->AllocsForIndirectGlobals.erase(V);
224 
225   // And clear out the handle.
226   setValPtr(nullptr);
227   GAR->Handles.erase(I);
228   // This object is now destroyed!
229 }
230 
231 FunctionModRefBehavior GlobalsAAResult::getModRefBehavior(const Function *F) {
232   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
233 
234   if (FunctionInfo *FI = getFunctionInfo(F)) {
235     if (!isModOrRefSet(FI->getModRefInfo()))
236       Min = FMRB_DoesNotAccessMemory;
237     else if (!isModSet(FI->getModRefInfo()))
238       Min = FMRB_OnlyReadsMemory;
239   }
240 
241   return FunctionModRefBehavior(AAResultBase::getModRefBehavior(F) & Min);
242 }
243 
244 FunctionModRefBehavior
245 GlobalsAAResult::getModRefBehavior(ImmutableCallSite CS) {
246   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
247 
248   if (!CS.hasOperandBundles())
249     if (const Function *F = CS.getCalledFunction())
250       if (FunctionInfo *FI = getFunctionInfo(F)) {
251         if (!isModOrRefSet(FI->getModRefInfo()))
252           Min = FMRB_DoesNotAccessMemory;
253         else if (!isModSet(FI->getModRefInfo()))
254           Min = FMRB_OnlyReadsMemory;
255       }
256 
257   return FunctionModRefBehavior(AAResultBase::getModRefBehavior(CS) & Min);
258 }
259 
260 /// Returns the function info for the function, or null if we don't have
261 /// anything useful to say about it.
262 GlobalsAAResult::FunctionInfo *
263 GlobalsAAResult::getFunctionInfo(const Function *F) {
264   auto I = FunctionInfos.find(F);
265   if (I != FunctionInfos.end())
266     return &I->second;
267   return nullptr;
268 }
269 
270 /// AnalyzeGlobals - Scan through the users of all of the internal
271 /// GlobalValue's in the program.  If none of them have their "address taken"
272 /// (really, their address passed to something nontrivial), record this fact,
273 /// and record the functions that they are used directly in.
274 void GlobalsAAResult::AnalyzeGlobals(Module &M) {
275   SmallPtrSet<Function *, 32> TrackedFunctions;
276   for (Function &F : M)
277     if (F.hasLocalLinkage())
278       if (!AnalyzeUsesOfPointer(&F)) {
279         // Remember that we are tracking this global.
280         NonAddressTakenGlobals.insert(&F);
281         TrackedFunctions.insert(&F);
282         Handles.emplace_front(*this, &F);
283         Handles.front().I = Handles.begin();
284         ++NumNonAddrTakenFunctions;
285       }
286 
287   SmallPtrSet<Function *, 16> Readers, Writers;
288   for (GlobalVariable &GV : M.globals())
289     if (GV.hasLocalLinkage()) {
290       if (!AnalyzeUsesOfPointer(&GV, &Readers,
291                                 GV.isConstant() ? nullptr : &Writers)) {
292         // Remember that we are tracking this global, and the mod/ref fns
293         NonAddressTakenGlobals.insert(&GV);
294         Handles.emplace_front(*this, &GV);
295         Handles.front().I = Handles.begin();
296 
297         for (Function *Reader : Readers) {
298           if (TrackedFunctions.insert(Reader).second) {
299             Handles.emplace_front(*this, Reader);
300             Handles.front().I = Handles.begin();
301           }
302           FunctionInfos[Reader].addModRefInfoForGlobal(GV, ModRefInfo::Ref);
303         }
304 
305         if (!GV.isConstant()) // No need to keep track of writers to constants
306           for (Function *Writer : Writers) {
307             if (TrackedFunctions.insert(Writer).second) {
308               Handles.emplace_front(*this, Writer);
309               Handles.front().I = Handles.begin();
310             }
311             FunctionInfos[Writer].addModRefInfoForGlobal(GV, ModRefInfo::Mod);
312           }
313         ++NumNonAddrTakenGlobalVars;
314 
315         // If this global holds a pointer type, see if it is an indirect global.
316         if (GV.getValueType()->isPointerTy() &&
317             AnalyzeIndirectGlobalMemory(&GV))
318           ++NumIndirectGlobalVars;
319       }
320       Readers.clear();
321       Writers.clear();
322     }
323 }
324 
325 /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
326 /// If this is used by anything complex (i.e., the address escapes), return
327 /// true.  Also, while we are at it, keep track of those functions that read and
328 /// write to the value.
329 ///
330 /// If OkayStoreDest is non-null, stores into this global are allowed.
331 bool GlobalsAAResult::AnalyzeUsesOfPointer(Value *V,
332                                            SmallPtrSetImpl<Function *> *Readers,
333                                            SmallPtrSetImpl<Function *> *Writers,
334                                            GlobalValue *OkayStoreDest) {
335   if (!V->getType()->isPointerTy())
336     return true;
337 
338   for (Use &U : V->uses()) {
339     User *I = U.getUser();
340     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
341       if (Readers)
342         Readers->insert(LI->getParent()->getParent());
343     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
344       if (V == SI->getOperand(1)) {
345         if (Writers)
346           Writers->insert(SI->getParent()->getParent());
347       } else if (SI->getOperand(1) != OkayStoreDest) {
348         return true; // Storing the pointer
349       }
350     } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
351       if (AnalyzeUsesOfPointer(I, Readers, Writers))
352         return true;
353     } else if (Operator::getOpcode(I) == Instruction::BitCast) {
354       if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
355         return true;
356     } else if (auto CS = CallSite(I)) {
357       // Make sure that this is just the function being called, not that it is
358       // passing into the function.
359       if (CS.isDataOperand(&U)) {
360         // Detect calls to free.
361         if (CS.isArgOperand(&U) && isFreeCall(I, &TLI)) {
362           if (Writers)
363             Writers->insert(CS->getParent()->getParent());
364         } else {
365           return true; // Argument of an unknown call.
366         }
367       }
368     } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
369       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
370         return true; // Allow comparison against null.
371     } else if (Constant *C = dyn_cast<Constant>(I)) {
372       // Ignore constants which don't have any live uses.
373       if (isa<GlobalValue>(C) || C->isConstantUsed())
374         return true;
375     } else {
376       return true;
377     }
378   }
379 
380   return false;
381 }
382 
383 /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
384 /// which holds a pointer type.  See if the global always points to non-aliased
385 /// heap memory: that is, all initializers of the globals are allocations, and
386 /// those allocations have no use other than initialization of the global.
387 /// Further, all loads out of GV must directly use the memory, not store the
388 /// pointer somewhere.  If this is true, we consider the memory pointed to by
389 /// GV to be owned by GV and can disambiguate other pointers from it.
390 bool GlobalsAAResult::AnalyzeIndirectGlobalMemory(GlobalVariable *GV) {
391   // Keep track of values related to the allocation of the memory, f.e. the
392   // value produced by the malloc call and any casts.
393   std::vector<Value *> AllocRelatedValues;
394 
395   // If the initializer is a valid pointer, bail.
396   if (Constant *C = GV->getInitializer())
397     if (!C->isNullValue())
398       return false;
399 
400   // Walk the user list of the global.  If we find anything other than a direct
401   // load or store, bail out.
402   for (User *U : GV->users()) {
403     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
404       // The pointer loaded from the global can only be used in simple ways:
405       // we allow addressing of it and loading storing to it.  We do *not* allow
406       // storing the loaded pointer somewhere else or passing to a function.
407       if (AnalyzeUsesOfPointer(LI))
408         return false; // Loaded pointer escapes.
409       // TODO: Could try some IP mod/ref of the loaded pointer.
410     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
411       // Storing the global itself.
412       if (SI->getOperand(0) == GV)
413         return false;
414 
415       // If storing the null pointer, ignore it.
416       if (isa<ConstantPointerNull>(SI->getOperand(0)))
417         continue;
418 
419       // Check the value being stored.
420       Value *Ptr = GetUnderlyingObject(SI->getOperand(0),
421                                        GV->getParent()->getDataLayout());
422 
423       if (!isAllocLikeFn(Ptr, &TLI))
424         return false; // Too hard to analyze.
425 
426       // Analyze all uses of the allocation.  If any of them are used in a
427       // non-simple way (e.g. stored to another global) bail out.
428       if (AnalyzeUsesOfPointer(Ptr, /*Readers*/ nullptr, /*Writers*/ nullptr,
429                                GV))
430         return false; // Loaded pointer escapes.
431 
432       // Remember that this allocation is related to the indirect global.
433       AllocRelatedValues.push_back(Ptr);
434     } else {
435       // Something complex, bail out.
436       return false;
437     }
438   }
439 
440   // Okay, this is an indirect global.  Remember all of the allocations for
441   // this global in AllocsForIndirectGlobals.
442   while (!AllocRelatedValues.empty()) {
443     AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
444     Handles.emplace_front(*this, AllocRelatedValues.back());
445     Handles.front().I = Handles.begin();
446     AllocRelatedValues.pop_back();
447   }
448   IndirectGlobals.insert(GV);
449   Handles.emplace_front(*this, GV);
450   Handles.front().I = Handles.begin();
451   return true;
452 }
453 
454 void GlobalsAAResult::CollectSCCMembership(CallGraph &CG) {
455   // We do a bottom-up SCC traversal of the call graph.  In other words, we
456   // visit all callees before callers (leaf-first).
457   unsigned SCCID = 0;
458   for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
459     const std::vector<CallGraphNode *> &SCC = *I;
460     assert(!SCC.empty() && "SCC with no functions?");
461 
462     for (auto *CGN : SCC)
463       if (Function *F = CGN->getFunction())
464         FunctionToSCCMap[F] = SCCID;
465     ++SCCID;
466   }
467 }
468 
469 /// AnalyzeCallGraph - At this point, we know the functions where globals are
470 /// immediately stored to and read from.  Propagate this information up the call
471 /// graph to all callers and compute the mod/ref info for all memory for each
472 /// function.
473 void GlobalsAAResult::AnalyzeCallGraph(CallGraph &CG, Module &M) {
474   // We do a bottom-up SCC traversal of the call graph.  In other words, we
475   // visit all callees before callers (leaf-first).
476   for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
477     const std::vector<CallGraphNode *> &SCC = *I;
478     assert(!SCC.empty() && "SCC with no functions?");
479 
480     Function *F = SCC[0]->getFunction();
481 
482     if (!F || !F->isDefinitionExact()) {
483       // Calls externally or not exact - can't say anything useful. Remove any
484       // existing function records (may have been created when scanning
485       // globals).
486       for (auto *Node : SCC)
487         FunctionInfos.erase(Node->getFunction());
488       continue;
489     }
490 
491     FunctionInfo &FI = FunctionInfos[F];
492     bool KnowNothing = false;
493 
494     // Collect the mod/ref properties due to called functions.  We only compute
495     // one mod-ref set.
496     for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
497       if (!F) {
498         KnowNothing = true;
499         break;
500       }
501 
502       if (F->isDeclaration() || F->hasFnAttribute(Attribute::OptimizeNone)) {
503         // Try to get mod/ref behaviour from function attributes.
504         if (F->doesNotAccessMemory()) {
505           // Can't do better than that!
506         } else if (F->onlyReadsMemory()) {
507           FI.addModRefInfo(ModRefInfo::Ref);
508           if (!F->isIntrinsic() && !F->onlyAccessesArgMemory())
509             // This function might call back into the module and read a global -
510             // consider every global as possibly being read by this function.
511             FI.setMayReadAnyGlobal();
512         } else {
513           FI.addModRefInfo(ModRefInfo::ModRef);
514           // Can't say anything useful unless it's an intrinsic - they don't
515           // read or write global variables of the kind considered here.
516           KnowNothing = !F->isIntrinsic();
517         }
518         continue;
519       }
520 
521       for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
522            CI != E && !KnowNothing; ++CI)
523         if (Function *Callee = CI->second->getFunction()) {
524           if (FunctionInfo *CalleeFI = getFunctionInfo(Callee)) {
525             // Propagate function effect up.
526             FI.addFunctionInfo(*CalleeFI);
527           } else {
528             // Can't say anything about it.  However, if it is inside our SCC,
529             // then nothing needs to be done.
530             CallGraphNode *CalleeNode = CG[Callee];
531             if (!is_contained(SCC, CalleeNode))
532               KnowNothing = true;
533           }
534         } else {
535           KnowNothing = true;
536         }
537     }
538 
539     // If we can't say anything useful about this SCC, remove all SCC functions
540     // from the FunctionInfos map.
541     if (KnowNothing) {
542       for (auto *Node : SCC)
543         FunctionInfos.erase(Node->getFunction());
544       continue;
545     }
546 
547     // Scan the function bodies for explicit loads or stores.
548     for (auto *Node : SCC) {
549       if (isModAndRefSet(FI.getModRefInfo()))
550         break; // The mod/ref lattice saturates here.
551 
552       // Don't prove any properties based on the implementation of an optnone
553       // function. Function attributes were already used as a best approximation
554       // above.
555       if (Node->getFunction()->hasFnAttribute(Attribute::OptimizeNone))
556         continue;
557 
558       for (Instruction &I : instructions(Node->getFunction())) {
559         if (isModAndRefSet(FI.getModRefInfo()))
560           break; // The mod/ref lattice saturates here.
561 
562         // We handle calls specially because the graph-relevant aspects are
563         // handled above.
564         if (auto CS = CallSite(&I)) {
565           if (isAllocationFn(&I, &TLI) || isFreeCall(&I, &TLI)) {
566             // FIXME: It is completely unclear why this is necessary and not
567             // handled by the above graph code.
568             FI.addModRefInfo(ModRefInfo::ModRef);
569           } else if (Function *Callee = CS.getCalledFunction()) {
570             // The callgraph doesn't include intrinsic calls.
571             if (Callee->isIntrinsic()) {
572               FunctionModRefBehavior Behaviour =
573                   AAResultBase::getModRefBehavior(Callee);
574               FI.addModRefInfo(createModRefInfo(Behaviour));
575             }
576           }
577           continue;
578         }
579 
580         // All non-call instructions we use the primary predicates for whether
581         // thay read or write memory.
582         if (I.mayReadFromMemory())
583           FI.addModRefInfo(ModRefInfo::Ref);
584         if (I.mayWriteToMemory())
585           FI.addModRefInfo(ModRefInfo::Mod);
586       }
587     }
588 
589     if (!isModSet(FI.getModRefInfo()))
590       ++NumReadMemFunctions;
591     if (!isModOrRefSet(FI.getModRefInfo()))
592       ++NumNoMemFunctions;
593 
594     // Finally, now that we know the full effect on this SCC, clone the
595     // information to each function in the SCC.
596     // FI is a reference into FunctionInfos, so copy it now so that it doesn't
597     // get invalidated if DenseMap decides to re-hash.
598     FunctionInfo CachedFI = FI;
599     for (unsigned i = 1, e = SCC.size(); i != e; ++i)
600       FunctionInfos[SCC[i]->getFunction()] = CachedFI;
601   }
602 }
603 
604 // GV is a non-escaping global. V is a pointer address that has been loaded from.
605 // If we can prove that V must escape, we can conclude that a load from V cannot
606 // alias GV.
607 static bool isNonEscapingGlobalNoAliasWithLoad(const GlobalValue *GV,
608                                                const Value *V,
609                                                int &Depth,
610                                                const DataLayout &DL) {
611   SmallPtrSet<const Value *, 8> Visited;
612   SmallVector<const Value *, 8> Inputs;
613   Visited.insert(V);
614   Inputs.push_back(V);
615   do {
616     const Value *Input = Inputs.pop_back_val();
617 
618     if (isa<GlobalValue>(Input) || isa<Argument>(Input) || isa<CallInst>(Input) ||
619         isa<InvokeInst>(Input))
620       // Arguments to functions or returns from functions are inherently
621       // escaping, so we can immediately classify those as not aliasing any
622       // non-addr-taken globals.
623       //
624       // (Transitive) loads from a global are also safe - if this aliased
625       // another global, its address would escape, so no alias.
626       continue;
627 
628     // Recurse through a limited number of selects, loads and PHIs. This is an
629     // arbitrary depth of 4, lower numbers could be used to fix compile time
630     // issues if needed, but this is generally expected to be only be important
631     // for small depths.
632     if (++Depth > 4)
633       return false;
634 
635     if (auto *LI = dyn_cast<LoadInst>(Input)) {
636       Inputs.push_back(GetUnderlyingObject(LI->getPointerOperand(), DL));
637       continue;
638     }
639     if (auto *SI = dyn_cast<SelectInst>(Input)) {
640       const Value *LHS = GetUnderlyingObject(SI->getTrueValue(), DL);
641       const Value *RHS = GetUnderlyingObject(SI->getFalseValue(), DL);
642       if (Visited.insert(LHS).second)
643         Inputs.push_back(LHS);
644       if (Visited.insert(RHS).second)
645         Inputs.push_back(RHS);
646       continue;
647     }
648     if (auto *PN = dyn_cast<PHINode>(Input)) {
649       for (const Value *Op : PN->incoming_values()) {
650         Op = GetUnderlyingObject(Op, DL);
651         if (Visited.insert(Op).second)
652           Inputs.push_back(Op);
653       }
654       continue;
655     }
656 
657     return false;
658   } while (!Inputs.empty());
659 
660   // All inputs were known to be no-alias.
661   return true;
662 }
663 
664 // There are particular cases where we can conclude no-alias between
665 // a non-addr-taken global and some other underlying object. Specifically,
666 // a non-addr-taken global is known to not be escaped from any function. It is
667 // also incorrect for a transformation to introduce an escape of a global in
668 // a way that is observable when it was not there previously. One function
669 // being transformed to introduce an escape which could possibly be observed
670 // (via loading from a global or the return value for example) within another
671 // function is never safe. If the observation is made through non-atomic
672 // operations on different threads, it is a data-race and UB. If the
673 // observation is well defined, by being observed the transformation would have
674 // changed program behavior by introducing the observed escape, making it an
675 // invalid transform.
676 //
677 // This property does require that transformations which *temporarily* escape
678 // a global that was not previously escaped, prior to restoring it, cannot rely
679 // on the results of GMR::alias. This seems a reasonable restriction, although
680 // currently there is no way to enforce it. There is also no realistic
681 // optimization pass that would make this mistake. The closest example is
682 // a transformation pass which does reg2mem of SSA values but stores them into
683 // global variables temporarily before restoring the global variable's value.
684 // This could be useful to expose "benign" races for example. However, it seems
685 // reasonable to require that a pass which introduces escapes of global
686 // variables in this way to either not trust AA results while the escape is
687 // active, or to be forced to operate as a module pass that cannot co-exist
688 // with an alias analysis such as GMR.
689 bool GlobalsAAResult::isNonEscapingGlobalNoAlias(const GlobalValue *GV,
690                                                  const Value *V) {
691   // In order to know that the underlying object cannot alias the
692   // non-addr-taken global, we must know that it would have to be an escape.
693   // Thus if the underlying object is a function argument, a load from
694   // a global, or the return of a function, it cannot alias. We can also
695   // recurse through PHI nodes and select nodes provided all of their inputs
696   // resolve to one of these known-escaping roots.
697   SmallPtrSet<const Value *, 8> Visited;
698   SmallVector<const Value *, 8> Inputs;
699   Visited.insert(V);
700   Inputs.push_back(V);
701   int Depth = 0;
702   do {
703     const Value *Input = Inputs.pop_back_val();
704 
705     if (auto *InputGV = dyn_cast<GlobalValue>(Input)) {
706       // If one input is the very global we're querying against, then we can't
707       // conclude no-alias.
708       if (InputGV == GV)
709         return false;
710 
711       // Distinct GlobalVariables never alias, unless overriden or zero-sized.
712       // FIXME: The condition can be refined, but be conservative for now.
713       auto *GVar = dyn_cast<GlobalVariable>(GV);
714       auto *InputGVar = dyn_cast<GlobalVariable>(InputGV);
715       if (GVar && InputGVar &&
716           !GVar->isDeclaration() && !InputGVar->isDeclaration() &&
717           !GVar->isInterposable() && !InputGVar->isInterposable()) {
718         Type *GVType = GVar->getInitializer()->getType();
719         Type *InputGVType = InputGVar->getInitializer()->getType();
720         if (GVType->isSized() && InputGVType->isSized() &&
721             (DL.getTypeAllocSize(GVType) > 0) &&
722             (DL.getTypeAllocSize(InputGVType) > 0))
723           continue;
724       }
725 
726       // Conservatively return false, even though we could be smarter
727       // (e.g. look through GlobalAliases).
728       return false;
729     }
730 
731     if (isa<Argument>(Input) || isa<CallInst>(Input) ||
732         isa<InvokeInst>(Input)) {
733       // Arguments to functions or returns from functions are inherently
734       // escaping, so we can immediately classify those as not aliasing any
735       // non-addr-taken globals.
736       continue;
737     }
738 
739     // Recurse through a limited number of selects, loads and PHIs. This is an
740     // arbitrary depth of 4, lower numbers could be used to fix compile time
741     // issues if needed, but this is generally expected to be only be important
742     // for small depths.
743     if (++Depth > 4)
744       return false;
745 
746     if (auto *LI = dyn_cast<LoadInst>(Input)) {
747       // A pointer loaded from a global would have been captured, and we know
748       // that the global is non-escaping, so no alias.
749       const Value *Ptr = GetUnderlyingObject(LI->getPointerOperand(), DL);
750       if (isNonEscapingGlobalNoAliasWithLoad(GV, Ptr, Depth, DL))
751         // The load does not alias with GV.
752         continue;
753       // Otherwise, a load could come from anywhere, so bail.
754       return false;
755     }
756     if (auto *SI = dyn_cast<SelectInst>(Input)) {
757       const Value *LHS = GetUnderlyingObject(SI->getTrueValue(), DL);
758       const Value *RHS = GetUnderlyingObject(SI->getFalseValue(), DL);
759       if (Visited.insert(LHS).second)
760         Inputs.push_back(LHS);
761       if (Visited.insert(RHS).second)
762         Inputs.push_back(RHS);
763       continue;
764     }
765     if (auto *PN = dyn_cast<PHINode>(Input)) {
766       for (const Value *Op : PN->incoming_values()) {
767         Op = GetUnderlyingObject(Op, DL);
768         if (Visited.insert(Op).second)
769           Inputs.push_back(Op);
770       }
771       continue;
772     }
773 
774     // FIXME: It would be good to handle other obvious no-alias cases here, but
775     // it isn't clear how to do so reasonbly without building a small version
776     // of BasicAA into this code. We could recurse into AAResultBase::alias
777     // here but that seems likely to go poorly as we're inside the
778     // implementation of such a query. Until then, just conservatievly retun
779     // false.
780     return false;
781   } while (!Inputs.empty());
782 
783   // If all the inputs to V were definitively no-alias, then V is no-alias.
784   return true;
785 }
786 
787 /// alias - If one of the pointers is to a global that we are tracking, and the
788 /// other is some random pointer, we know there cannot be an alias, because the
789 /// address of the global isn't taken.
790 AliasResult GlobalsAAResult::alias(const MemoryLocation &LocA,
791                                    const MemoryLocation &LocB) {
792   // Get the base object these pointers point to.
793   const Value *UV1 = GetUnderlyingObject(LocA.Ptr, DL);
794   const Value *UV2 = GetUnderlyingObject(LocB.Ptr, DL);
795 
796   // If either of the underlying values is a global, they may be non-addr-taken
797   // globals, which we can answer queries about.
798   const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
799   const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
800   if (GV1 || GV2) {
801     // If the global's address is taken, pretend we don't know it's a pointer to
802     // the global.
803     if (GV1 && !NonAddressTakenGlobals.count(GV1))
804       GV1 = nullptr;
805     if (GV2 && !NonAddressTakenGlobals.count(GV2))
806       GV2 = nullptr;
807 
808     // If the two pointers are derived from two different non-addr-taken
809     // globals we know these can't alias.
810     if (GV1 && GV2 && GV1 != GV2)
811       return NoAlias;
812 
813     // If one is and the other isn't, it isn't strictly safe but we can fake
814     // this result if necessary for performance. This does not appear to be
815     // a common problem in practice.
816     if (EnableUnsafeGlobalsModRefAliasResults)
817       if ((GV1 || GV2) && GV1 != GV2)
818         return NoAlias;
819 
820     // Check for a special case where a non-escaping global can be used to
821     // conclude no-alias.
822     if ((GV1 || GV2) && GV1 != GV2) {
823       const GlobalValue *GV = GV1 ? GV1 : GV2;
824       const Value *UV = GV1 ? UV2 : UV1;
825       if (isNonEscapingGlobalNoAlias(GV, UV))
826         return NoAlias;
827     }
828 
829     // Otherwise if they are both derived from the same addr-taken global, we
830     // can't know the two accesses don't overlap.
831   }
832 
833   // These pointers may be based on the memory owned by an indirect global.  If
834   // so, we may be able to handle this.  First check to see if the base pointer
835   // is a direct load from an indirect global.
836   GV1 = GV2 = nullptr;
837   if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
838     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
839       if (IndirectGlobals.count(GV))
840         GV1 = GV;
841   if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
842     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
843       if (IndirectGlobals.count(GV))
844         GV2 = GV;
845 
846   // These pointers may also be from an allocation for the indirect global.  If
847   // so, also handle them.
848   if (!GV1)
849     GV1 = AllocsForIndirectGlobals.lookup(UV1);
850   if (!GV2)
851     GV2 = AllocsForIndirectGlobals.lookup(UV2);
852 
853   // Now that we know whether the two pointers are related to indirect globals,
854   // use this to disambiguate the pointers. If the pointers are based on
855   // different indirect globals they cannot alias.
856   if (GV1 && GV2 && GV1 != GV2)
857     return NoAlias;
858 
859   // If one is based on an indirect global and the other isn't, it isn't
860   // strictly safe but we can fake this result if necessary for performance.
861   // This does not appear to be a common problem in practice.
862   if (EnableUnsafeGlobalsModRefAliasResults)
863     if ((GV1 || GV2) && GV1 != GV2)
864       return NoAlias;
865 
866   return AAResultBase::alias(LocA, LocB);
867 }
868 
869 ModRefInfo GlobalsAAResult::getModRefInfoForArgument(ImmutableCallSite CS,
870                                                      const GlobalValue *GV) {
871   if (CS.doesNotAccessMemory())
872     return ModRefInfo::NoModRef;
873   ModRefInfo ConservativeResult =
874       CS.onlyReadsMemory() ? ModRefInfo::Ref : ModRefInfo::ModRef;
875 
876   // Iterate through all the arguments to the called function. If any argument
877   // is based on GV, return the conservative result.
878   for (auto &A : CS.args()) {
879     SmallVector<Value*, 4> Objects;
880     GetUnderlyingObjects(A, Objects, DL);
881 
882     // All objects must be identified.
883     if (!all_of(Objects, isIdentifiedObject) &&
884         // Try ::alias to see if all objects are known not to alias GV.
885         !all_of(Objects, [&](Value *V) {
886           return this->alias(MemoryLocation(V), MemoryLocation(GV)) == NoAlias;
887         }))
888       return ConservativeResult;
889 
890     if (is_contained(Objects, GV))
891       return ConservativeResult;
892   }
893 
894   // We identified all objects in the argument list, and none of them were GV.
895   return ModRefInfo::NoModRef;
896 }
897 
898 ModRefInfo GlobalsAAResult::getModRefInfo(ImmutableCallSite CS,
899                                           const MemoryLocation &Loc) {
900   ModRefInfo Known = ModRefInfo::ModRef;
901 
902   // If we are asking for mod/ref info of a direct call with a pointer to a
903   // global we are tracking, return information if we have it.
904   if (const GlobalValue *GV =
905           dyn_cast<GlobalValue>(GetUnderlyingObject(Loc.Ptr, DL)))
906     if (GV->hasLocalLinkage())
907       if (const Function *F = CS.getCalledFunction())
908         if (NonAddressTakenGlobals.count(GV))
909           if (const FunctionInfo *FI = getFunctionInfo(F))
910             Known = unionModRef(FI->getModRefInfoForGlobal(*GV),
911                                 getModRefInfoForArgument(CS, GV));
912 
913   if (!isModOrRefSet(Known))
914     return ModRefInfo::NoModRef; // No need to query other mod/ref analyses
915   return intersectModRef(Known, AAResultBase::getModRefInfo(CS, Loc));
916 }
917 
918 GlobalsAAResult::GlobalsAAResult(const DataLayout &DL,
919                                  const TargetLibraryInfo &TLI)
920     : AAResultBase(), DL(DL), TLI(TLI) {}
921 
922 GlobalsAAResult::GlobalsAAResult(GlobalsAAResult &&Arg)
923     : AAResultBase(std::move(Arg)), DL(Arg.DL), TLI(Arg.TLI),
924       NonAddressTakenGlobals(std::move(Arg.NonAddressTakenGlobals)),
925       IndirectGlobals(std::move(Arg.IndirectGlobals)),
926       AllocsForIndirectGlobals(std::move(Arg.AllocsForIndirectGlobals)),
927       FunctionInfos(std::move(Arg.FunctionInfos)),
928       Handles(std::move(Arg.Handles)) {
929   // Update the parent for each DeletionCallbackHandle.
930   for (auto &H : Handles) {
931     assert(H.GAR == &Arg);
932     H.GAR = this;
933   }
934 }
935 
936 GlobalsAAResult::~GlobalsAAResult() {}
937 
938 /*static*/ GlobalsAAResult
939 GlobalsAAResult::analyzeModule(Module &M, const TargetLibraryInfo &TLI,
940                                CallGraph &CG) {
941   GlobalsAAResult Result(M.getDataLayout(), TLI);
942 
943   // Discover which functions aren't recursive, to feed into AnalyzeGlobals.
944   Result.CollectSCCMembership(CG);
945 
946   // Find non-addr taken globals.
947   Result.AnalyzeGlobals(M);
948 
949   // Propagate on CG.
950   Result.AnalyzeCallGraph(CG, M);
951 
952   return Result;
953 }
954 
955 AnalysisKey GlobalsAA::Key;
956 
957 GlobalsAAResult GlobalsAA::run(Module &M, ModuleAnalysisManager &AM) {
958   return GlobalsAAResult::analyzeModule(M,
959                                         AM.getResult<TargetLibraryAnalysis>(M),
960                                         AM.getResult<CallGraphAnalysis>(M));
961 }
962 
963 char GlobalsAAWrapperPass::ID = 0;
964 INITIALIZE_PASS_BEGIN(GlobalsAAWrapperPass, "globals-aa",
965                       "Globals Alias Analysis", false, true)
966 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
967 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
968 INITIALIZE_PASS_END(GlobalsAAWrapperPass, "globals-aa",
969                     "Globals Alias Analysis", false, true)
970 
971 ModulePass *llvm::createGlobalsAAWrapperPass() {
972   return new GlobalsAAWrapperPass();
973 }
974 
975 GlobalsAAWrapperPass::GlobalsAAWrapperPass() : ModulePass(ID) {
976   initializeGlobalsAAWrapperPassPass(*PassRegistry::getPassRegistry());
977 }
978 
979 bool GlobalsAAWrapperPass::runOnModule(Module &M) {
980   Result.reset(new GlobalsAAResult(GlobalsAAResult::analyzeModule(
981       M, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
982       getAnalysis<CallGraphWrapperPass>().getCallGraph())));
983   return false;
984 }
985 
986 bool GlobalsAAWrapperPass::doFinalization(Module &M) {
987   Result.reset();
988   return false;
989 }
990 
991 void GlobalsAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
992   AU.setPreservesAll();
993   AU.addRequired<CallGraphWrapperPass>();
994   AU.addRequired<TargetLibraryInfoWrapperPass>();
995 }
996