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