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