17adc3a2bSChandler Carruth //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
27adc3a2bSChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67adc3a2bSChandler Carruth //
77adc3a2bSChandler Carruth //===----------------------------------------------------------------------===//
87adc3a2bSChandler Carruth //
97adc3a2bSChandler Carruth // This simple pass provides alias and mod/ref information for global values
107adc3a2bSChandler Carruth // that do not have their address taken, and keeps track of whether functions
117adc3a2bSChandler Carruth // read or write memory (are "pure").  For this simple (but very common) case,
127adc3a2bSChandler Carruth // we can provide pretty accurate and useful information.
137adc3a2bSChandler Carruth //
147adc3a2bSChandler Carruth //===----------------------------------------------------------------------===//
157adc3a2bSChandler Carruth 
167adc3a2bSChandler Carruth #include "llvm/Analysis/GlobalsModRef.h"
177adc3a2bSChandler Carruth #include "llvm/ADT/SCCIterator.h"
187adc3a2bSChandler Carruth #include "llvm/ADT/SmallPtrSet.h"
197adc3a2bSChandler Carruth #include "llvm/ADT/Statistic.h"
208c2082e1SSimon Pilgrim #include "llvm/Analysis/CallGraph.h"
217adc3a2bSChandler Carruth #include "llvm/Analysis/MemoryBuiltins.h"
227b560d40SChandler Carruth #include "llvm/Analysis/TargetLibraryInfo.h"
237adc3a2bSChandler Carruth #include "llvm/Analysis/ValueTracking.h"
247adc3a2bSChandler Carruth #include "llvm/IR/InstIterator.h"
257adc3a2bSChandler Carruth #include "llvm/IR/Instructions.h"
267adc3a2bSChandler Carruth #include "llvm/IR/IntrinsicInst.h"
277adc3a2bSChandler Carruth #include "llvm/IR/Module.h"
284fc7c55fSArthur Eubanks #include "llvm/IR/PassManager.h"
2905da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
307adc3a2bSChandler Carruth #include "llvm/Pass.h"
317adc3a2bSChandler Carruth #include "llvm/Support/CommandLine.h"
328c2082e1SSimon Pilgrim 
337adc3a2bSChandler Carruth using namespace llvm;
347adc3a2bSChandler Carruth 
357adc3a2bSChandler Carruth #define DEBUG_TYPE "globalsmodref-aa"
367adc3a2bSChandler Carruth 
377adc3a2bSChandler Carruth STATISTIC(NumNonAddrTakenGlobalVars,
387adc3a2bSChandler Carruth           "Number of global vars without address taken");
397adc3a2bSChandler Carruth STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
407adc3a2bSChandler Carruth STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
417adc3a2bSChandler Carruth STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
427adc3a2bSChandler Carruth STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
437adc3a2bSChandler Carruth 
447adc3a2bSChandler Carruth // An option to enable unsafe alias results from the GlobalsModRef analysis.
457adc3a2bSChandler Carruth // When enabled, GlobalsModRef will provide no-alias results which in extremely
467adc3a2bSChandler Carruth // rare cases may not be conservatively correct. In particular, in the face of
47000400caSJay Foad // transforms which cause asymmetry between how effective getUnderlyingObject
487adc3a2bSChandler Carruth // is for two pointers, it may produce incorrect results.
497adc3a2bSChandler Carruth //
507adc3a2bSChandler Carruth // These unsafe results have been returned by GMR for many years without
517adc3a2bSChandler Carruth // causing significant issues in the wild and so we provide a mechanism to
527adc3a2bSChandler Carruth // re-enable them for users of LLVM that have a particular performance
537adc3a2bSChandler Carruth // sensitivity and no known issues. The option also makes it easy to evaluate
547adc3a2bSChandler Carruth // the performance impact of these results.
557adc3a2bSChandler Carruth static cl::opt<bool> EnableUnsafeGlobalsModRefAliasResults(
567adc3a2bSChandler Carruth     "enable-unsafe-globalsmodref-alias-results", cl::init(false), cl::Hidden);
577adc3a2bSChandler Carruth 
587adc3a2bSChandler Carruth /// The mod/ref information collected for a particular function.
597adc3a2bSChandler Carruth ///
607adc3a2bSChandler Carruth /// We collect information about mod/ref behavior of a function here, both in
617adc3a2bSChandler Carruth /// general and as pertains to specific globals. We only have this detailed
627adc3a2bSChandler Carruth /// information when we know *something* useful about the behavior. If we
637adc3a2bSChandler Carruth /// saturate to fully general mod/ref, we remove the info for the function.
647b560d40SChandler Carruth class GlobalsAAResult::FunctionInfo {
657adc3a2bSChandler Carruth   typedef SmallDenseMap<const GlobalValue *, ModRefInfo, 16> GlobalInfoMapType;
667adc3a2bSChandler Carruth 
677adc3a2bSChandler Carruth   /// Build a wrapper struct that has 8-byte alignment. All heap allocations
687adc3a2bSChandler Carruth   /// should provide this much alignment at least, but this makes it clear we
697adc3a2bSChandler Carruth   /// specifically rely on this amount of alignment.
70a8301fceSFangrui Song   struct alignas(8) AlignedMap {
713a3cb929SKazu Hirata     AlignedMap() = default;
723a3cb929SKazu Hirata     AlignedMap(const AlignedMap &Arg) = default;
737adc3a2bSChandler Carruth     GlobalInfoMapType Map;
747adc3a2bSChandler Carruth   };
757adc3a2bSChandler Carruth 
767adc3a2bSChandler Carruth   /// Pointer traits for our aligned map.
777adc3a2bSChandler Carruth   struct AlignedMapPointerTraits {
getAsVoidPointerGlobalsAAResult::FunctionInfo::AlignedMapPointerTraits787adc3a2bSChandler Carruth     static inline void *getAsVoidPointer(AlignedMap *P) { return P; }
getFromVoidPointerGlobalsAAResult::FunctionInfo::AlignedMapPointerTraits797adc3a2bSChandler Carruth     static inline AlignedMap *getFromVoidPointer(void *P) {
807adc3a2bSChandler Carruth       return (AlignedMap *)P;
817adc3a2bSChandler Carruth     }
8265eb74e9SDavid Blaikie     static constexpr int NumLowBitsAvailable = 3;
83b2505005SBenjamin Kramer     static_assert(alignof(AlignedMap) >= (1 << NumLowBitsAvailable),
847adc3a2bSChandler Carruth                   "AlignedMap insufficiently aligned to have enough low bits.");
857adc3a2bSChandler Carruth   };
867adc3a2bSChandler Carruth 
877adc3a2bSChandler Carruth   /// The bit that flags that this function may read any global. This is
887adc3a2bSChandler Carruth   /// chosen to mix together with ModRefInfo bits.
8963d2250aSAlina Sbirlea   /// FIXME: This assumes ModRefInfo lattice will remain 4 bits!
9050db8a20SAlina Sbirlea   /// It overlaps with ModRefInfo::Must bit!
9150db8a20SAlina Sbirlea   /// FunctionInfo.getModRefInfo() masks out everything except ModRef so
9250db8a20SAlina Sbirlea   /// this remains correct, but the Must info is lost.
937adc3a2bSChandler Carruth   enum { MayReadAnyGlobal = 4 };
947adc3a2bSChandler Carruth 
957adc3a2bSChandler Carruth   /// Checks to document the invariants of the bit packing here.
9650db8a20SAlina Sbirlea   static_assert((MayReadAnyGlobal & static_cast<int>(ModRefInfo::MustModRef)) ==
9750db8a20SAlina Sbirlea                     0,
987adc3a2bSChandler Carruth                 "ModRef and the MayReadAnyGlobal flag bits overlap.");
9950db8a20SAlina Sbirlea   static_assert(((MayReadAnyGlobal |
10050db8a20SAlina Sbirlea                   static_cast<int>(ModRefInfo::MustModRef)) >>
1017adc3a2bSChandler Carruth                  AlignedMapPointerTraits::NumLowBitsAvailable) == 0,
1027adc3a2bSChandler Carruth                 "Insufficient low bits to store our flag and ModRef info.");
1037adc3a2bSChandler Carruth 
1047adc3a2bSChandler Carruth public:
1053a3cb929SKazu Hirata   FunctionInfo() = default;
~FunctionInfo()1067adc3a2bSChandler Carruth   ~FunctionInfo() {
1077adc3a2bSChandler Carruth     delete Info.getPointer();
1087adc3a2bSChandler Carruth   }
1097adc3a2bSChandler Carruth   // Spell out the copy ond move constructors and assignment operators to get
1107adc3a2bSChandler Carruth   // deep copy semantics and correct move semantics in the face of the
1117adc3a2bSChandler Carruth   // pointer-int pair.
FunctionInfo(const FunctionInfo & Arg)1127adc3a2bSChandler Carruth   FunctionInfo(const FunctionInfo &Arg)
1137adc3a2bSChandler Carruth       : Info(nullptr, Arg.Info.getInt()) {
1147adc3a2bSChandler Carruth     if (const auto *ArgPtr = Arg.Info.getPointer())
1157adc3a2bSChandler Carruth       Info.setPointer(new AlignedMap(*ArgPtr));
1167adc3a2bSChandler Carruth   }
FunctionInfo(FunctionInfo && Arg)1177adc3a2bSChandler Carruth   FunctionInfo(FunctionInfo &&Arg)
1187adc3a2bSChandler Carruth       : Info(Arg.Info.getPointer(), Arg.Info.getInt()) {
1197adc3a2bSChandler Carruth     Arg.Info.setPointerAndInt(nullptr, 0);
1207adc3a2bSChandler Carruth   }
operator =(const FunctionInfo & RHS)1217adc3a2bSChandler Carruth   FunctionInfo &operator=(const FunctionInfo &RHS) {
1227adc3a2bSChandler Carruth     delete Info.getPointer();
1237adc3a2bSChandler Carruth     Info.setPointerAndInt(nullptr, RHS.Info.getInt());
1247adc3a2bSChandler Carruth     if (const auto *RHSPtr = RHS.Info.getPointer())
1257adc3a2bSChandler Carruth       Info.setPointer(new AlignedMap(*RHSPtr));
1267adc3a2bSChandler Carruth     return *this;
1277adc3a2bSChandler Carruth   }
operator =(FunctionInfo && RHS)1287adc3a2bSChandler Carruth   FunctionInfo &operator=(FunctionInfo &&RHS) {
1297adc3a2bSChandler Carruth     delete Info.getPointer();
1307adc3a2bSChandler Carruth     Info.setPointerAndInt(RHS.Info.getPointer(), RHS.Info.getInt());
1317adc3a2bSChandler Carruth     RHS.Info.setPointerAndInt(nullptr, 0);
1327adc3a2bSChandler Carruth     return *this;
1337adc3a2bSChandler Carruth   }
1347adc3a2bSChandler Carruth 
13550db8a20SAlina Sbirlea   /// This method clears MayReadAnyGlobal bit added by GlobalsAAResult to return
13650db8a20SAlina Sbirlea   /// the corresponding ModRefInfo. It must align in functionality with
13750db8a20SAlina Sbirlea   /// clearMust().
globalClearMayReadAnyGlobal(int I) const13850db8a20SAlina Sbirlea   ModRefInfo globalClearMayReadAnyGlobal(int I) const {
13950db8a20SAlina Sbirlea     return ModRefInfo((I & static_cast<int>(ModRefInfo::ModRef)) |
14050db8a20SAlina Sbirlea                       static_cast<int>(ModRefInfo::NoModRef));
14150db8a20SAlina Sbirlea   }
14250db8a20SAlina Sbirlea 
1437adc3a2bSChandler Carruth   /// Returns the \c ModRefInfo info for this function.
getModRefInfo() const1447adc3a2bSChandler Carruth   ModRefInfo getModRefInfo() const {
14550db8a20SAlina Sbirlea     return globalClearMayReadAnyGlobal(Info.getInt());
1467adc3a2bSChandler Carruth   }
1477adc3a2bSChandler Carruth 
1487adc3a2bSChandler Carruth   /// Adds new \c ModRefInfo for this function to its state.
addModRefInfo(ModRefInfo NewMRI)1497adc3a2bSChandler Carruth   void addModRefInfo(ModRefInfo NewMRI) {
15050db8a20SAlina Sbirlea     Info.setInt(Info.getInt() | static_cast<int>(setMust(NewMRI)));
1517adc3a2bSChandler Carruth   }
1527adc3a2bSChandler Carruth 
1537adc3a2bSChandler Carruth   /// Returns whether this function may read any global variable, and we don't
1547adc3a2bSChandler Carruth   /// know which global.
mayReadAnyGlobal() const1557adc3a2bSChandler Carruth   bool mayReadAnyGlobal() const { return Info.getInt() & MayReadAnyGlobal; }
1567adc3a2bSChandler Carruth 
1577adc3a2bSChandler Carruth   /// Sets this function as potentially reading from any global.
setMayReadAnyGlobal()1587adc3a2bSChandler Carruth   void setMayReadAnyGlobal() { Info.setInt(Info.getInt() | MayReadAnyGlobal); }
1597adc3a2bSChandler Carruth 
1607adc3a2bSChandler Carruth   /// Returns the \c ModRefInfo info for this function w.r.t. a particular
1617adc3a2bSChandler Carruth   /// global, which may be more precise than the general information above.
getModRefInfoForGlobal(const GlobalValue & GV) const1627adc3a2bSChandler Carruth   ModRefInfo getModRefInfoForGlobal(const GlobalValue &GV) const {
163193429f0SAlina Sbirlea     ModRefInfo GlobalMRI =
164193429f0SAlina Sbirlea         mayReadAnyGlobal() ? ModRefInfo::Ref : ModRefInfo::NoModRef;
1657adc3a2bSChandler Carruth     if (AlignedMap *P = Info.getPointer()) {
1667adc3a2bSChandler Carruth       auto I = P->Map.find(&GV);
1677adc3a2bSChandler Carruth       if (I != P->Map.end())
168d6037ebeSAlina Sbirlea         GlobalMRI = unionModRef(GlobalMRI, I->second);
1697adc3a2bSChandler Carruth     }
1707adc3a2bSChandler Carruth     return GlobalMRI;
1717adc3a2bSChandler Carruth   }
1727adc3a2bSChandler Carruth 
1737adc3a2bSChandler Carruth   /// Add mod/ref info from another function into ours, saturating towards
174193429f0SAlina Sbirlea   /// ModRef.
addFunctionInfo(const FunctionInfo & FI)1757adc3a2bSChandler Carruth   void addFunctionInfo(const FunctionInfo &FI) {
1767adc3a2bSChandler Carruth     addModRefInfo(FI.getModRefInfo());
1777adc3a2bSChandler Carruth 
1787adc3a2bSChandler Carruth     if (FI.mayReadAnyGlobal())
1797adc3a2bSChandler Carruth       setMayReadAnyGlobal();
1807adc3a2bSChandler Carruth 
1817adc3a2bSChandler Carruth     if (AlignedMap *P = FI.Info.getPointer())
1827adc3a2bSChandler Carruth       for (const auto &G : P->Map)
1837adc3a2bSChandler Carruth         addModRefInfoForGlobal(*G.first, G.second);
1847adc3a2bSChandler Carruth   }
1857adc3a2bSChandler Carruth 
addModRefInfoForGlobal(const GlobalValue & GV,ModRefInfo NewMRI)1867adc3a2bSChandler Carruth   void addModRefInfoForGlobal(const GlobalValue &GV, ModRefInfo NewMRI) {
1877adc3a2bSChandler Carruth     AlignedMap *P = Info.getPointer();
1887adc3a2bSChandler Carruth     if (!P) {
1897adc3a2bSChandler Carruth       P = new AlignedMap();
1907adc3a2bSChandler Carruth       Info.setPointer(P);
1917adc3a2bSChandler Carruth     }
1927adc3a2bSChandler Carruth     auto &GlobalMRI = P->Map[&GV];
193d6037ebeSAlina Sbirlea     GlobalMRI = unionModRef(GlobalMRI, NewMRI);
1947adc3a2bSChandler Carruth   }
1957adc3a2bSChandler Carruth 
1967adc3a2bSChandler Carruth   /// Clear a global's ModRef info. Should be used when a global is being
1977adc3a2bSChandler Carruth   /// deleted.
eraseModRefInfoForGlobal(const GlobalValue & GV)1987adc3a2bSChandler Carruth   void eraseModRefInfoForGlobal(const GlobalValue &GV) {
1997adc3a2bSChandler Carruth     if (AlignedMap *P = Info.getPointer())
2007adc3a2bSChandler Carruth       P->Map.erase(&GV);
2017adc3a2bSChandler Carruth   }
2027adc3a2bSChandler Carruth 
2037adc3a2bSChandler Carruth private:
2047adc3a2bSChandler Carruth   /// All of the information is encoded into a single pointer, with a three bit
2057adc3a2bSChandler Carruth   /// integer in the low three bits. The high bit provides a flag for when this
2067adc3a2bSChandler Carruth   /// function may read any global. The low two bits are the ModRefInfo. And
2077adc3a2bSChandler Carruth   /// the pointer, when non-null, points to a map from GlobalValue to
2087adc3a2bSChandler Carruth   /// ModRefInfo specific to that GlobalValue.
2097adc3a2bSChandler Carruth   PointerIntPair<AlignedMap *, 3, unsigned, AlignedMapPointerTraits> Info;
2107adc3a2bSChandler Carruth };
2117adc3a2bSChandler Carruth 
deleted()2127b560d40SChandler Carruth void GlobalsAAResult::DeletionCallbackHandle::deleted() {
2137adc3a2bSChandler Carruth   Value *V = getValPtr();
2147adc3a2bSChandler Carruth   if (auto *F = dyn_cast<Function>(V))
21598800d9cSNAKAMURA Takumi     GAR->FunctionInfos.erase(F);
2167adc3a2bSChandler Carruth 
2177adc3a2bSChandler Carruth   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
21898800d9cSNAKAMURA Takumi     if (GAR->NonAddressTakenGlobals.erase(GV)) {
2197adc3a2bSChandler Carruth       // This global might be an indirect global.  If so, remove it and
2207adc3a2bSChandler Carruth       // remove any AllocRelatedValues for it.
22198800d9cSNAKAMURA Takumi       if (GAR->IndirectGlobals.erase(GV)) {
2227adc3a2bSChandler Carruth         // Remove any entries in AllocsForIndirectGlobals for this global.
22398800d9cSNAKAMURA Takumi         for (auto I = GAR->AllocsForIndirectGlobals.begin(),
22498800d9cSNAKAMURA Takumi                   E = GAR->AllocsForIndirectGlobals.end();
2257adc3a2bSChandler Carruth              I != E; ++I)
2267adc3a2bSChandler Carruth           if (I->second == GV)
22798800d9cSNAKAMURA Takumi             GAR->AllocsForIndirectGlobals.erase(I);
2287adc3a2bSChandler Carruth       }
2297adc3a2bSChandler Carruth 
2307adc3a2bSChandler Carruth       // Scan the function info we have collected and remove this global
2317adc3a2bSChandler Carruth       // from all of them.
23298800d9cSNAKAMURA Takumi       for (auto &FIPair : GAR->FunctionInfos)
2337adc3a2bSChandler Carruth         FIPair.second.eraseModRefInfoForGlobal(*GV);
2347adc3a2bSChandler Carruth     }
2357adc3a2bSChandler Carruth   }
2367adc3a2bSChandler Carruth 
2377adc3a2bSChandler Carruth   // If this is an allocation related to an indirect global, remove it.
23898800d9cSNAKAMURA Takumi   GAR->AllocsForIndirectGlobals.erase(V);
2397adc3a2bSChandler Carruth 
2407adc3a2bSChandler Carruth   // And clear out the handle.
2417adc3a2bSChandler Carruth   setValPtr(nullptr);
24298800d9cSNAKAMURA Takumi   GAR->Handles.erase(I);
2437adc3a2bSChandler Carruth   // This object is now destroyed!
2447adc3a2bSChandler Carruth }
2457adc3a2bSChandler Carruth 
getModRefBehavior(const Function * F)2467b560d40SChandler Carruth FunctionModRefBehavior GlobalsAAResult::getModRefBehavior(const Function *F) {
2477adc3a2bSChandler Carruth   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
2487adc3a2bSChandler Carruth 
2497adc3a2bSChandler Carruth   if (FunctionInfo *FI = getFunctionInfo(F)) {
25063d2250aSAlina Sbirlea     if (!isModOrRefSet(FI->getModRefInfo()))
2517adc3a2bSChandler Carruth       Min = FMRB_DoesNotAccessMemory;
25263d2250aSAlina Sbirlea     else if (!isModSet(FI->getModRefInfo()))
2537adc3a2bSChandler Carruth       Min = FMRB_OnlyReadsMemory;
2547adc3a2bSChandler Carruth   }
2557adc3a2bSChandler Carruth 
2567b560d40SChandler Carruth   return FunctionModRefBehavior(AAResultBase::getModRefBehavior(F) & Min);
2577adc3a2bSChandler Carruth }
2587adc3a2bSChandler Carruth 
2597adc3a2bSChandler Carruth /// Returns the function info for the function, or null if we don't have
2607adc3a2bSChandler Carruth /// anything useful to say about it.
2617b560d40SChandler Carruth GlobalsAAResult::FunctionInfo *
getFunctionInfo(const Function * F)2627b560d40SChandler Carruth GlobalsAAResult::getFunctionInfo(const Function *F) {
2637adc3a2bSChandler Carruth   auto I = FunctionInfos.find(F);
2647adc3a2bSChandler Carruth   if (I != FunctionInfos.end())
2657adc3a2bSChandler Carruth     return &I->second;
2667adc3a2bSChandler Carruth   return nullptr;
2677adc3a2bSChandler Carruth }
2687adc3a2bSChandler Carruth 
2697adc3a2bSChandler Carruth /// AnalyzeGlobals - Scan through the users of all of the internal
2707adc3a2bSChandler Carruth /// GlobalValue's in the program.  If none of them have their "address taken"
2717adc3a2bSChandler Carruth /// (really, their address passed to something nontrivial), record this fact,
2727adc3a2bSChandler Carruth /// and record the functions that they are used directly in.
AnalyzeGlobals(Module & M)2737b560d40SChandler Carruth void GlobalsAAResult::AnalyzeGlobals(Module &M) {
274b30f2f51SMatthias Braun   SmallPtrSet<Function *, 32> TrackedFunctions;
2757adc3a2bSChandler Carruth   for (Function &F : M)
276db69f1b2SAlina Sbirlea     if (F.hasLocalLinkage()) {
2777adc3a2bSChandler Carruth       if (!AnalyzeUsesOfPointer(&F)) {
2787adc3a2bSChandler Carruth         // Remember that we are tracking this global.
2797adc3a2bSChandler Carruth         NonAddressTakenGlobals.insert(&F);
2807adc3a2bSChandler Carruth         TrackedFunctions.insert(&F);
2817adc3a2bSChandler Carruth         Handles.emplace_front(*this, &F);
2827adc3a2bSChandler Carruth         Handles.front().I = Handles.begin();
2837adc3a2bSChandler Carruth         ++NumNonAddrTakenFunctions;
284db69f1b2SAlina Sbirlea       } else
285db69f1b2SAlina Sbirlea         UnknownFunctionsWithLocalLinkage = true;
2867adc3a2bSChandler Carruth     }
2877adc3a2bSChandler Carruth 
288b30f2f51SMatthias Braun   SmallPtrSet<Function *, 16> Readers, Writers;
2897adc3a2bSChandler Carruth   for (GlobalVariable &GV : M.globals())
2907adc3a2bSChandler Carruth     if (GV.hasLocalLinkage()) {
2917adc3a2bSChandler Carruth       if (!AnalyzeUsesOfPointer(&GV, &Readers,
2927adc3a2bSChandler Carruth                                 GV.isConstant() ? nullptr : &Writers)) {
2937adc3a2bSChandler Carruth         // Remember that we are tracking this global, and the mod/ref fns
2947adc3a2bSChandler Carruth         NonAddressTakenGlobals.insert(&GV);
2957adc3a2bSChandler Carruth         Handles.emplace_front(*this, &GV);
2967adc3a2bSChandler Carruth         Handles.front().I = Handles.begin();
2977adc3a2bSChandler Carruth 
2987adc3a2bSChandler Carruth         for (Function *Reader : Readers) {
2997adc3a2bSChandler Carruth           if (TrackedFunctions.insert(Reader).second) {
3007adc3a2bSChandler Carruth             Handles.emplace_front(*this, Reader);
3017adc3a2bSChandler Carruth             Handles.front().I = Handles.begin();
3027adc3a2bSChandler Carruth           }
303193429f0SAlina Sbirlea           FunctionInfos[Reader].addModRefInfoForGlobal(GV, ModRefInfo::Ref);
3047adc3a2bSChandler Carruth         }
3057adc3a2bSChandler Carruth 
3067adc3a2bSChandler Carruth         if (!GV.isConstant()) // No need to keep track of writers to constants
3077adc3a2bSChandler Carruth           for (Function *Writer : Writers) {
3087adc3a2bSChandler Carruth             if (TrackedFunctions.insert(Writer).second) {
3097adc3a2bSChandler Carruth               Handles.emplace_front(*this, Writer);
3107adc3a2bSChandler Carruth               Handles.front().I = Handles.begin();
3117adc3a2bSChandler Carruth             }
312193429f0SAlina Sbirlea             FunctionInfos[Writer].addModRefInfoForGlobal(GV, ModRefInfo::Mod);
3137adc3a2bSChandler Carruth           }
3147adc3a2bSChandler Carruth         ++NumNonAddrTakenGlobalVars;
3157adc3a2bSChandler Carruth 
3167adc3a2bSChandler Carruth         // If this global holds a pointer type, see if it is an indirect global.
3175f6eaac6SManuel Jacob         if (GV.getValueType()->isPointerTy() &&
3187adc3a2bSChandler Carruth             AnalyzeIndirectGlobalMemory(&GV))
3197adc3a2bSChandler Carruth           ++NumIndirectGlobalVars;
3207adc3a2bSChandler Carruth       }
3217adc3a2bSChandler Carruth       Readers.clear();
3227adc3a2bSChandler Carruth       Writers.clear();
3237adc3a2bSChandler Carruth     }
3247adc3a2bSChandler Carruth }
3257adc3a2bSChandler Carruth 
3267adc3a2bSChandler Carruth /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
3277adc3a2bSChandler Carruth /// If this is used by anything complex (i.e., the address escapes), return
3287adc3a2bSChandler Carruth /// true.  Also, while we are at it, keep track of those functions that read and
3297adc3a2bSChandler Carruth /// write to the value.
3307adc3a2bSChandler Carruth ///
3317adc3a2bSChandler Carruth /// If OkayStoreDest is non-null, stores into this global are allowed.
AnalyzeUsesOfPointer(Value * V,SmallPtrSetImpl<Function * > * Readers,SmallPtrSetImpl<Function * > * Writers,GlobalValue * OkayStoreDest)3327b560d40SChandler Carruth bool GlobalsAAResult::AnalyzeUsesOfPointer(Value *V,
3337adc3a2bSChandler Carruth                                            SmallPtrSetImpl<Function *> *Readers,
3347adc3a2bSChandler Carruth                                            SmallPtrSetImpl<Function *> *Writers,
3357adc3a2bSChandler Carruth                                            GlobalValue *OkayStoreDest) {
3367adc3a2bSChandler Carruth   if (!V->getType()->isPointerTy())
3377adc3a2bSChandler Carruth     return true;
3387adc3a2bSChandler Carruth 
3397adc3a2bSChandler Carruth   for (Use &U : V->uses()) {
3407adc3a2bSChandler Carruth     User *I = U.getUser();
3417adc3a2bSChandler Carruth     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3427adc3a2bSChandler Carruth       if (Readers)
3437adc3a2bSChandler Carruth         Readers->insert(LI->getParent()->getParent());
3447adc3a2bSChandler Carruth     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3457adc3a2bSChandler Carruth       if (V == SI->getOperand(1)) {
3467adc3a2bSChandler Carruth         if (Writers)
3477adc3a2bSChandler Carruth           Writers->insert(SI->getParent()->getParent());
3487adc3a2bSChandler Carruth       } else if (SI->getOperand(1) != OkayStoreDest) {
3497adc3a2bSChandler Carruth         return true; // Storing the pointer
3507adc3a2bSChandler Carruth       }
3517adc3a2bSChandler Carruth     } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
3527adc3a2bSChandler Carruth       if (AnalyzeUsesOfPointer(I, Readers, Writers))
3537adc3a2bSChandler Carruth         return true;
354fa5d31f8SMichael Liao     } else if (Operator::getOpcode(I) == Instruction::BitCast ||
355fa5d31f8SMichael Liao                Operator::getOpcode(I) == Instruction::AddrSpaceCast) {
3567adc3a2bSChandler Carruth       if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
3577adc3a2bSChandler Carruth         return true;
358363ac683SChandler Carruth     } else if (auto *Call = dyn_cast<CallBase>(I)) {
3597adc3a2bSChandler Carruth       // Make sure that this is just the function being called, not that it is
3607adc3a2bSChandler Carruth       // passing into the function.
361363ac683SChandler Carruth       if (Call->isDataOperand(&U)) {
3627adc3a2bSChandler Carruth         // Detect calls to free.
3639c27b59cSTeresa Johnson         if (Call->isArgOperand(&U) &&
364*c81dff3cSNikita Popov             getFreedOperand(Call, &GetTLI(*Call->getFunction())) == U) {
3657adc3a2bSChandler Carruth           if (Writers)
366363ac683SChandler Carruth             Writers->insert(Call->getParent()->getParent());
3677adc3a2bSChandler Carruth         } else {
3687adc3a2bSChandler Carruth           return true; // Argument of an unknown call.
3697adc3a2bSChandler Carruth         }
3707adc3a2bSChandler Carruth       }
3717adc3a2bSChandler Carruth     } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
3727adc3a2bSChandler Carruth       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
3737adc3a2bSChandler Carruth         return true; // Allow comparison against null.
37474bed9d7SEli Friedman     } else if (Constant *C = dyn_cast<Constant>(I)) {
375c5b72620SEli Friedman       // Ignore constants which don't have any live uses.
376c5b72620SEli Friedman       if (isa<GlobalValue>(C) || C->isConstantUsed())
377c5b72620SEli Friedman         return true;
3787adc3a2bSChandler Carruth     } else {
3797adc3a2bSChandler Carruth       return true;
3807adc3a2bSChandler Carruth     }
3817adc3a2bSChandler Carruth   }
3827adc3a2bSChandler Carruth 
3837adc3a2bSChandler Carruth   return false;
3847adc3a2bSChandler Carruth }
3857adc3a2bSChandler Carruth 
3867adc3a2bSChandler Carruth /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
3877adc3a2bSChandler Carruth /// which holds a pointer type.  See if the global always points to non-aliased
388e838949bSPhilip Reames /// heap memory: that is, all initializers of the globals store a value known
389e838949bSPhilip Reames /// to be obtained via a noalias return function call which have no other use.
3907adc3a2bSChandler Carruth /// Further, all loads out of GV must directly use the memory, not store the
3917adc3a2bSChandler Carruth /// pointer somewhere.  If this is true, we consider the memory pointed to by
3927adc3a2bSChandler Carruth /// GV to be owned by GV and can disambiguate other pointers from it.
AnalyzeIndirectGlobalMemory(GlobalVariable * GV)393c67dec69SJames Molloy bool GlobalsAAResult::AnalyzeIndirectGlobalMemory(GlobalVariable *GV) {
3947adc3a2bSChandler Carruth   // Keep track of values related to the allocation of the memory, f.e. the
395e838949bSPhilip Reames   // value produced by the noalias call and any casts.
3967adc3a2bSChandler Carruth   std::vector<Value *> AllocRelatedValues;
3977adc3a2bSChandler Carruth 
398c67dec69SJames Molloy   // If the initializer is a valid pointer, bail.
399c67dec69SJames Molloy   if (Constant *C = GV->getInitializer())
400c67dec69SJames Molloy     if (!C->isNullValue())
401c67dec69SJames Molloy       return false;
402c67dec69SJames Molloy 
4037adc3a2bSChandler Carruth   // Walk the user list of the global.  If we find anything other than a direct
4047adc3a2bSChandler Carruth   // load or store, bail out.
4057adc3a2bSChandler Carruth   for (User *U : GV->users()) {
4067adc3a2bSChandler Carruth     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
4077adc3a2bSChandler Carruth       // The pointer loaded from the global can only be used in simple ways:
4087adc3a2bSChandler Carruth       // we allow addressing of it and loading storing to it.  We do *not* allow
4097adc3a2bSChandler Carruth       // storing the loaded pointer somewhere else or passing to a function.
4107adc3a2bSChandler Carruth       if (AnalyzeUsesOfPointer(LI))
4117adc3a2bSChandler Carruth         return false; // Loaded pointer escapes.
4127adc3a2bSChandler Carruth       // TODO: Could try some IP mod/ref of the loaded pointer.
4137adc3a2bSChandler Carruth     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
4147adc3a2bSChandler Carruth       // Storing the global itself.
4157adc3a2bSChandler Carruth       if (SI->getOperand(0) == GV)
4167adc3a2bSChandler Carruth         return false;
4177adc3a2bSChandler Carruth 
4187adc3a2bSChandler Carruth       // If storing the null pointer, ignore it.
4197adc3a2bSChandler Carruth       if (isa<ConstantPointerNull>(SI->getOperand(0)))
4207adc3a2bSChandler Carruth         continue;
4217adc3a2bSChandler Carruth 
4227adc3a2bSChandler Carruth       // Check the value being stored.
423b0eb40caSVitaly Buka       Value *Ptr = getUnderlyingObject(SI->getOperand(0));
4247adc3a2bSChandler Carruth 
425e838949bSPhilip Reames       if (!isNoAliasCall(Ptr))
4267adc3a2bSChandler Carruth         return false; // Too hard to analyze.
4277adc3a2bSChandler Carruth 
4287adc3a2bSChandler Carruth       // Analyze all uses of the allocation.  If any of them are used in a
4297adc3a2bSChandler Carruth       // non-simple way (e.g. stored to another global) bail out.
4307adc3a2bSChandler Carruth       if (AnalyzeUsesOfPointer(Ptr, /*Readers*/ nullptr, /*Writers*/ nullptr,
4317adc3a2bSChandler Carruth                                GV))
4327adc3a2bSChandler Carruth         return false; // Loaded pointer escapes.
4337adc3a2bSChandler Carruth 
4347adc3a2bSChandler Carruth       // Remember that this allocation is related to the indirect global.
4357adc3a2bSChandler Carruth       AllocRelatedValues.push_back(Ptr);
4367adc3a2bSChandler Carruth     } else {
4377adc3a2bSChandler Carruth       // Something complex, bail out.
4387adc3a2bSChandler Carruth       return false;
4397adc3a2bSChandler Carruth     }
4407adc3a2bSChandler Carruth   }
4417adc3a2bSChandler Carruth 
4427adc3a2bSChandler Carruth   // Okay, this is an indirect global.  Remember all of the allocations for
4437adc3a2bSChandler Carruth   // this global in AllocsForIndirectGlobals.
4447adc3a2bSChandler Carruth   while (!AllocRelatedValues.empty()) {
4457adc3a2bSChandler Carruth     AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
4467adc3a2bSChandler Carruth     Handles.emplace_front(*this, AllocRelatedValues.back());
4477adc3a2bSChandler Carruth     Handles.front().I = Handles.begin();
4487adc3a2bSChandler Carruth     AllocRelatedValues.pop_back();
4497adc3a2bSChandler Carruth   }
4507adc3a2bSChandler Carruth   IndirectGlobals.insert(GV);
4517adc3a2bSChandler Carruth   Handles.emplace_front(*this, GV);
4527adc3a2bSChandler Carruth   Handles.front().I = Handles.begin();
4537adc3a2bSChandler Carruth   return true;
4547adc3a2bSChandler Carruth }
4557adc3a2bSChandler Carruth 
CollectSCCMembership(CallGraph & CG)456eb46641cSJames Molloy void GlobalsAAResult::CollectSCCMembership(CallGraph &CG) {
457eb46641cSJames Molloy   // We do a bottom-up SCC traversal of the call graph.  In other words, we
458eb46641cSJames Molloy   // visit all callees before callers (leaf-first).
459eb46641cSJames Molloy   unsigned SCCID = 0;
460eb46641cSJames Molloy   for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
461eb46641cSJames Molloy     const std::vector<CallGraphNode *> &SCC = *I;
462eb46641cSJames Molloy     assert(!SCC.empty() && "SCC with no functions?");
463eb46641cSJames Molloy 
464eb46641cSJames Molloy     for (auto *CGN : SCC)
465eb46641cSJames Molloy       if (Function *F = CGN->getFunction())
466eb46641cSJames Molloy         FunctionToSCCMap[F] = SCCID;
467eb46641cSJames Molloy     ++SCCID;
468eb46641cSJames Molloy   }
469eb46641cSJames Molloy }
470eb46641cSJames Molloy 
4717adc3a2bSChandler Carruth /// AnalyzeCallGraph - At this point, we know the functions where globals are
4727adc3a2bSChandler Carruth /// immediately stored to and read from.  Propagate this information up the call
4737adc3a2bSChandler Carruth /// graph to all callers and compute the mod/ref info for all memory for each
4747adc3a2bSChandler Carruth /// function.
AnalyzeCallGraph(CallGraph & CG,Module & M)4757b560d40SChandler Carruth void GlobalsAAResult::AnalyzeCallGraph(CallGraph &CG, Module &M) {
4767adc3a2bSChandler Carruth   // We do a bottom-up SCC traversal of the call graph.  In other words, we
4777adc3a2bSChandler Carruth   // visit all callees before callers (leaf-first).
4787adc3a2bSChandler Carruth   for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
4797adc3a2bSChandler Carruth     const std::vector<CallGraphNode *> &SCC = *I;
4807adc3a2bSChandler Carruth     assert(!SCC.empty() && "SCC with no functions?");
4817adc3a2bSChandler Carruth 
482c662b501SDavid Blaikie     Function *F = SCC[0]->getFunction();
483c662b501SDavid Blaikie 
4847a9b7888SDavid Blaikie     if (!F || !F->isDefinitionExact()) {
4855ce32728SSanjoy Das       // Calls externally or not exact - can't say anything useful. Remove any
4865ce32728SSanjoy Das       // existing function records (may have been created when scanning
4875ce32728SSanjoy Das       // globals).
4887adc3a2bSChandler Carruth       for (auto *Node : SCC)
4897adc3a2bSChandler Carruth         FunctionInfos.erase(Node->getFunction());
4907adc3a2bSChandler Carruth       continue;
4917adc3a2bSChandler Carruth     }
4927adc3a2bSChandler Carruth 
493c662b501SDavid Blaikie     FunctionInfo &FI = FunctionInfos[F];
494196a9fabSChandler Carruth     Handles.emplace_front(*this, F);
495196a9fabSChandler Carruth     Handles.front().I = Handles.begin();
4967adc3a2bSChandler Carruth     bool KnowNothing = false;
4977adc3a2bSChandler Carruth 
4989dc7da3fSJohannes Doerfert     // Intrinsics, like any other synchronizing function, can make effects
4999dc7da3fSJohannes Doerfert     // of other threads visible. Without nosync we know nothing really.
5009dc7da3fSJohannes Doerfert     // Similarly, if `nocallback` is missing the function, or intrinsic,
5019dc7da3fSJohannes Doerfert     // can call into the module arbitrarily. If both are set the function
5029dc7da3fSJohannes Doerfert     // has an effect but will not interact with accesses of internal
5039dc7da3fSJohannes Doerfert     // globals inside the module. We are conservative here for optnone
5049dc7da3fSJohannes Doerfert     // functions, might not be necessary.
5059dc7da3fSJohannes Doerfert     auto MaySyncOrCallIntoModule = [](const Function &F) {
5069dc7da3fSJohannes Doerfert       return !F.isDeclaration() || !F.hasNoSync() ||
5079dc7da3fSJohannes Doerfert              !F.hasFnAttribute(Attribute::NoCallback);
5089dc7da3fSJohannes Doerfert     };
5099dc7da3fSJohannes Doerfert 
5107adc3a2bSChandler Carruth     // Collect the mod/ref properties due to called functions.  We only compute
5117adc3a2bSChandler Carruth     // one mod-ref set.
5127adc3a2bSChandler Carruth     for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
5137adc3a2bSChandler Carruth       if (!F) {
5147adc3a2bSChandler Carruth         KnowNothing = true;
5157adc3a2bSChandler Carruth         break;
5167adc3a2bSChandler Carruth       }
5177adc3a2bSChandler Carruth 
51885bd3978SEvandro Menezes       if (F->isDeclaration() || F->hasOptNone()) {
5197adc3a2bSChandler Carruth         // Try to get mod/ref behaviour from function attributes.
520457cc4dbSAmaury Sechet         if (F->doesNotAccessMemory()) {
5217adc3a2bSChandler Carruth           // Can't do better than that!
5227adc3a2bSChandler Carruth         } else if (F->onlyReadsMemory()) {
523193429f0SAlina Sbirlea           FI.addModRefInfo(ModRefInfo::Ref);
5249dc7da3fSJohannes Doerfert           if (!F->onlyAccessesArgMemory() && MaySyncOrCallIntoModule(*F))
5257adc3a2bSChandler Carruth             // This function might call back into the module and read a global -
5267adc3a2bSChandler Carruth             // consider every global as possibly being read by this function.
5277adc3a2bSChandler Carruth             FI.setMayReadAnyGlobal();
5287adc3a2bSChandler Carruth         } else {
529193429f0SAlina Sbirlea           FI.addModRefInfo(ModRefInfo::ModRef);
530db69f1b2SAlina Sbirlea           if (!F->onlyAccessesArgMemory())
531db69f1b2SAlina Sbirlea             FI.setMayReadAnyGlobal();
5329dc7da3fSJohannes Doerfert           if (MaySyncOrCallIntoModule(*F)) {
533db69f1b2SAlina Sbirlea             KnowNothing = true;
534db69f1b2SAlina Sbirlea             break;
535db69f1b2SAlina Sbirlea           }
5367adc3a2bSChandler Carruth         }
5377adc3a2bSChandler Carruth         continue;
5387adc3a2bSChandler Carruth       }
5397adc3a2bSChandler Carruth 
5407adc3a2bSChandler Carruth       for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
5417adc3a2bSChandler Carruth            CI != E && !KnowNothing; ++CI)
5427adc3a2bSChandler Carruth         if (Function *Callee = CI->second->getFunction()) {
5437adc3a2bSChandler Carruth           if (FunctionInfo *CalleeFI = getFunctionInfo(Callee)) {
5447adc3a2bSChandler Carruth             // Propagate function effect up.
5457adc3a2bSChandler Carruth             FI.addFunctionInfo(*CalleeFI);
5467adc3a2bSChandler Carruth           } else {
5477adc3a2bSChandler Carruth             // Can't say anything about it.  However, if it is inside our SCC,
5487adc3a2bSChandler Carruth             // then nothing needs to be done.
5497adc3a2bSChandler Carruth             CallGraphNode *CalleeNode = CG[Callee];
5500d955d0bSDavid Majnemer             if (!is_contained(SCC, CalleeNode))
5517adc3a2bSChandler Carruth               KnowNothing = true;
5527adc3a2bSChandler Carruth           }
5537adc3a2bSChandler Carruth         } else {
5547adc3a2bSChandler Carruth           KnowNothing = true;
5557adc3a2bSChandler Carruth         }
5567adc3a2bSChandler Carruth     }
5577adc3a2bSChandler Carruth 
5587adc3a2bSChandler Carruth     // If we can't say anything useful about this SCC, remove all SCC functions
5597adc3a2bSChandler Carruth     // from the FunctionInfos map.
5607adc3a2bSChandler Carruth     if (KnowNothing) {
5617adc3a2bSChandler Carruth       for (auto *Node : SCC)
5627adc3a2bSChandler Carruth         FunctionInfos.erase(Node->getFunction());
5637adc3a2bSChandler Carruth       continue;
5647adc3a2bSChandler Carruth     }
5657adc3a2bSChandler Carruth 
5667adc3a2bSChandler Carruth     // Scan the function bodies for explicit loads or stores.
5677adc3a2bSChandler Carruth     for (auto *Node : SCC) {
56863d2250aSAlina Sbirlea       if (isModAndRefSet(FI.getModRefInfo()))
5697adc3a2bSChandler Carruth         break; // The mod/ref lattice saturates here.
570c662b501SDavid Blaikie 
571c662b501SDavid Blaikie       // Don't prove any properties based on the implementation of an optnone
5727a9b7888SDavid Blaikie       // function. Function attributes were already used as a best approximation
5737a9b7888SDavid Blaikie       // above.
57485bd3978SEvandro Menezes       if (Node->getFunction()->hasOptNone())
575c662b501SDavid Blaikie         continue;
576c662b501SDavid Blaikie 
5777adc3a2bSChandler Carruth       for (Instruction &I : instructions(Node->getFunction())) {
57863d2250aSAlina Sbirlea         if (isModAndRefSet(FI.getModRefInfo()))
5797adc3a2bSChandler Carruth           break; // The mod/ref lattice saturates here.
5807adc3a2bSChandler Carruth 
5817adc3a2bSChandler Carruth         // We handle calls specially because the graph-relevant aspects are
5827adc3a2bSChandler Carruth         // handled above.
583363ac683SChandler Carruth         if (auto *Call = dyn_cast<CallBase>(&I)) {
584ed63fcb2SNikita Popov           if (Function *Callee = Call->getCalledFunction()) {
5857adc3a2bSChandler Carruth             // The callgraph doesn't include intrinsic calls.
5867adc3a2bSChandler Carruth             if (Callee->isIntrinsic()) {
587363ac683SChandler Carruth               if (isa<DbgInfoIntrinsic>(Call))
5884653b1a4SMikael Holmen                 // Don't let dbg intrinsics affect alias info.
5894653b1a4SMikael Holmen                 continue;
5904653b1a4SMikael Holmen 
5917adc3a2bSChandler Carruth               FunctionModRefBehavior Behaviour =
5927b560d40SChandler Carruth                   AAResultBase::getModRefBehavior(Callee);
593d6037ebeSAlina Sbirlea               FI.addModRefInfo(createModRefInfo(Behaviour));
5947adc3a2bSChandler Carruth             }
5957adc3a2bSChandler Carruth           }
5967adc3a2bSChandler Carruth           continue;
5977adc3a2bSChandler Carruth         }
5987adc3a2bSChandler Carruth 
5997adc3a2bSChandler Carruth         // All non-call instructions we use the primary predicates for whether
60002a2bb2fSHiroshi Inoue         // they read or write memory.
6017adc3a2bSChandler Carruth         if (I.mayReadFromMemory())
602193429f0SAlina Sbirlea           FI.addModRefInfo(ModRefInfo::Ref);
6037adc3a2bSChandler Carruth         if (I.mayWriteToMemory())
604193429f0SAlina Sbirlea           FI.addModRefInfo(ModRefInfo::Mod);
6057adc3a2bSChandler Carruth       }
6067adc3a2bSChandler Carruth     }
6077adc3a2bSChandler Carruth 
60863d2250aSAlina Sbirlea     if (!isModSet(FI.getModRefInfo()))
6097adc3a2bSChandler Carruth       ++NumReadMemFunctions;
61063d2250aSAlina Sbirlea     if (!isModOrRefSet(FI.getModRefInfo()))
6117adc3a2bSChandler Carruth       ++NumNoMemFunctions;
6127adc3a2bSChandler Carruth 
6137adc3a2bSChandler Carruth     // Finally, now that we know the full effect on this SCC, clone the
6147adc3a2bSChandler Carruth     // information to each function in the SCC.
61517379c4eSJames Molloy     // FI is a reference into FunctionInfos, so copy it now so that it doesn't
61617379c4eSJames Molloy     // get invalidated if DenseMap decides to re-hash.
61717379c4eSJames Molloy     FunctionInfo CachedFI = FI;
6187adc3a2bSChandler Carruth     for (unsigned i = 1, e = SCC.size(); i != e; ++i)
61917379c4eSJames Molloy       FunctionInfos[SCC[i]->getFunction()] = CachedFI;
6207adc3a2bSChandler Carruth   }
6217adc3a2bSChandler Carruth }
6227adc3a2bSChandler Carruth 
6235b2a732fSJames Molloy // GV is a non-escaping global. V is a pointer address that has been loaded from.
6245b2a732fSJames Molloy // If we can prove that V must escape, we can conclude that a load from V cannot
6255b2a732fSJames Molloy // alias GV.
isNonEscapingGlobalNoAliasWithLoad(const GlobalValue * GV,const Value * V,int & Depth,const DataLayout & DL)6265b2a732fSJames Molloy static bool isNonEscapingGlobalNoAliasWithLoad(const GlobalValue *GV,
6275b2a732fSJames Molloy                                                const Value *V,
6285b2a732fSJames Molloy                                                int &Depth,
6295b2a732fSJames Molloy                                                const DataLayout &DL) {
6305b2a732fSJames Molloy   SmallPtrSet<const Value *, 8> Visited;
6315b2a732fSJames Molloy   SmallVector<const Value *, 8> Inputs;
6325b2a732fSJames Molloy   Visited.insert(V);
6335b2a732fSJames Molloy   Inputs.push_back(V);
6345b2a732fSJames Molloy   do {
6355b2a732fSJames Molloy     const Value *Input = Inputs.pop_back_val();
6365b2a732fSJames Molloy 
6375b2a732fSJames Molloy     if (isa<GlobalValue>(Input) || isa<Argument>(Input) || isa<CallInst>(Input) ||
6385b2a732fSJames Molloy         isa<InvokeInst>(Input))
6395b2a732fSJames Molloy       // Arguments to functions or returns from functions are inherently
6405b2a732fSJames Molloy       // escaping, so we can immediately classify those as not aliasing any
6415b2a732fSJames Molloy       // non-addr-taken globals.
6425b2a732fSJames Molloy       //
6435b2a732fSJames Molloy       // (Transitive) loads from a global are also safe - if this aliased
6445b2a732fSJames Molloy       // another global, its address would escape, so no alias.
6455b2a732fSJames Molloy       continue;
6465b2a732fSJames Molloy 
6475b2a732fSJames Molloy     // Recurse through a limited number of selects, loads and PHIs. This is an
6485b2a732fSJames Molloy     // arbitrary depth of 4, lower numbers could be used to fix compile time
6495b2a732fSJames Molloy     // issues if needed, but this is generally expected to be only be important
6505b2a732fSJames Molloy     // for small depths.
6515b2a732fSJames Molloy     if (++Depth > 4)
6525b2a732fSJames Molloy       return false;
6535b2a732fSJames Molloy 
6545b2a732fSJames Molloy     if (auto *LI = dyn_cast<LoadInst>(Input)) {
655b0eb40caSVitaly Buka       Inputs.push_back(getUnderlyingObject(LI->getPointerOperand()));
6565b2a732fSJames Molloy       continue;
6575b2a732fSJames Molloy     }
6585b2a732fSJames Molloy     if (auto *SI = dyn_cast<SelectInst>(Input)) {
659b0eb40caSVitaly Buka       const Value *LHS = getUnderlyingObject(SI->getTrueValue());
660b0eb40caSVitaly Buka       const Value *RHS = getUnderlyingObject(SI->getFalseValue());
6615b2a732fSJames Molloy       if (Visited.insert(LHS).second)
6625b2a732fSJames Molloy         Inputs.push_back(LHS);
6635b2a732fSJames Molloy       if (Visited.insert(RHS).second)
6645b2a732fSJames Molloy         Inputs.push_back(RHS);
6655b2a732fSJames Molloy       continue;
6665b2a732fSJames Molloy     }
6675b2a732fSJames Molloy     if (auto *PN = dyn_cast<PHINode>(Input)) {
6685b2a732fSJames Molloy       for (const Value *Op : PN->incoming_values()) {
669b0eb40caSVitaly Buka         Op = getUnderlyingObject(Op);
6705b2a732fSJames Molloy         if (Visited.insert(Op).second)
6715b2a732fSJames Molloy           Inputs.push_back(Op);
6725b2a732fSJames Molloy       }
6735b2a732fSJames Molloy       continue;
6745b2a732fSJames Molloy     }
6755b2a732fSJames Molloy 
6765b2a732fSJames Molloy     return false;
6775b2a732fSJames Molloy   } while (!Inputs.empty());
6785b2a732fSJames Molloy 
6795b2a732fSJames Molloy   // All inputs were known to be no-alias.
6805b2a732fSJames Molloy   return true;
6815b2a732fSJames Molloy }
6825b2a732fSJames Molloy 
6837adc3a2bSChandler Carruth // There are particular cases where we can conclude no-alias between
6847adc3a2bSChandler Carruth // a non-addr-taken global and some other underlying object. Specifically,
6857adc3a2bSChandler Carruth // a non-addr-taken global is known to not be escaped from any function. It is
6867adc3a2bSChandler Carruth // also incorrect for a transformation to introduce an escape of a global in
6877adc3a2bSChandler Carruth // a way that is observable when it was not there previously. One function
6887adc3a2bSChandler Carruth // being transformed to introduce an escape which could possibly be observed
6897adc3a2bSChandler Carruth // (via loading from a global or the return value for example) within another
6907adc3a2bSChandler Carruth // function is never safe. If the observation is made through non-atomic
6917adc3a2bSChandler Carruth // operations on different threads, it is a data-race and UB. If the
6927adc3a2bSChandler Carruth // observation is well defined, by being observed the transformation would have
6937adc3a2bSChandler Carruth // changed program behavior by introducing the observed escape, making it an
6947adc3a2bSChandler Carruth // invalid transform.
6957adc3a2bSChandler Carruth //
6967adc3a2bSChandler Carruth // This property does require that transformations which *temporarily* escape
6977adc3a2bSChandler Carruth // a global that was not previously escaped, prior to restoring it, cannot rely
6987adc3a2bSChandler Carruth // on the results of GMR::alias. This seems a reasonable restriction, although
6997adc3a2bSChandler Carruth // currently there is no way to enforce it. There is also no realistic
7007adc3a2bSChandler Carruth // optimization pass that would make this mistake. The closest example is
7017adc3a2bSChandler Carruth // a transformation pass which does reg2mem of SSA values but stores them into
7027adc3a2bSChandler Carruth // global variables temporarily before restoring the global variable's value.
7037adc3a2bSChandler Carruth // This could be useful to expose "benign" races for example. However, it seems
7047adc3a2bSChandler Carruth // reasonable to require that a pass which introduces escapes of global
7057adc3a2bSChandler Carruth // variables in this way to either not trust AA results while the escape is
7067adc3a2bSChandler Carruth // active, or to be forced to operate as a module pass that cannot co-exist
7077adc3a2bSChandler Carruth // with an alias analysis such as GMR.
isNonEscapingGlobalNoAlias(const GlobalValue * GV,const Value * V)7087b560d40SChandler Carruth bool GlobalsAAResult::isNonEscapingGlobalNoAlias(const GlobalValue *GV,
7097adc3a2bSChandler Carruth                                                  const Value *V) {
7107adc3a2bSChandler Carruth   // In order to know that the underlying object cannot alias the
7117adc3a2bSChandler Carruth   // non-addr-taken global, we must know that it would have to be an escape.
7127adc3a2bSChandler Carruth   // Thus if the underlying object is a function argument, a load from
7137adc3a2bSChandler Carruth   // a global, or the return of a function, it cannot alias. We can also
7147adc3a2bSChandler Carruth   // recurse through PHI nodes and select nodes provided all of their inputs
7157adc3a2bSChandler Carruth   // resolve to one of these known-escaping roots.
7167adc3a2bSChandler Carruth   SmallPtrSet<const Value *, 8> Visited;
7177adc3a2bSChandler Carruth   SmallVector<const Value *, 8> Inputs;
7187adc3a2bSChandler Carruth   Visited.insert(V);
7197adc3a2bSChandler Carruth   Inputs.push_back(V);
7207adc3a2bSChandler Carruth   int Depth = 0;
7217adc3a2bSChandler Carruth   do {
7227adc3a2bSChandler Carruth     const Value *Input = Inputs.pop_back_val();
7237adc3a2bSChandler Carruth 
7247adc3a2bSChandler Carruth     if (auto *InputGV = dyn_cast<GlobalValue>(Input)) {
7257adc3a2bSChandler Carruth       // If one input is the very global we're querying against, then we can't
7267adc3a2bSChandler Carruth       // conclude no-alias.
7277adc3a2bSChandler Carruth       if (InputGV == GV)
7287adc3a2bSChandler Carruth         return false;
7297adc3a2bSChandler Carruth 
7307adc3a2bSChandler Carruth       // Distinct GlobalVariables never alias, unless overriden or zero-sized.
7317adc3a2bSChandler Carruth       // FIXME: The condition can be refined, but be conservative for now.
7327adc3a2bSChandler Carruth       auto *GVar = dyn_cast<GlobalVariable>(GV);
7337adc3a2bSChandler Carruth       auto *InputGVar = dyn_cast<GlobalVariable>(InputGV);
7347adc3a2bSChandler Carruth       if (GVar && InputGVar &&
7357adc3a2bSChandler Carruth           !GVar->isDeclaration() && !InputGVar->isDeclaration() &&
7365ce32728SSanjoy Das           !GVar->isInterposable() && !InputGVar->isInterposable()) {
7377adc3a2bSChandler Carruth         Type *GVType = GVar->getInitializer()->getType();
7387adc3a2bSChandler Carruth         Type *InputGVType = InputGVar->getInitializer()->getType();
7397adc3a2bSChandler Carruth         if (GVType->isSized() && InputGVType->isSized() &&
7407b560d40SChandler Carruth             (DL.getTypeAllocSize(GVType) > 0) &&
7417b560d40SChandler Carruth             (DL.getTypeAllocSize(InputGVType) > 0))
7427adc3a2bSChandler Carruth           continue;
7437adc3a2bSChandler Carruth       }
7447adc3a2bSChandler Carruth 
7457adc3a2bSChandler Carruth       // Conservatively return false, even though we could be smarter
7467adc3a2bSChandler Carruth       // (e.g. look through GlobalAliases).
7477adc3a2bSChandler Carruth       return false;
7487adc3a2bSChandler Carruth     }
7497adc3a2bSChandler Carruth 
7507adc3a2bSChandler Carruth     if (isa<Argument>(Input) || isa<CallInst>(Input) ||
7517adc3a2bSChandler Carruth         isa<InvokeInst>(Input)) {
7527adc3a2bSChandler Carruth       // Arguments to functions or returns from functions are inherently
7537adc3a2bSChandler Carruth       // escaping, so we can immediately classify those as not aliasing any
7547adc3a2bSChandler Carruth       // non-addr-taken globals.
7557adc3a2bSChandler Carruth       continue;
7567adc3a2bSChandler Carruth     }
7577adc3a2bSChandler Carruth 
7585b2a732fSJames Molloy     // Recurse through a limited number of selects, loads and PHIs. This is an
7597adc3a2bSChandler Carruth     // arbitrary depth of 4, lower numbers could be used to fix compile time
7607adc3a2bSChandler Carruth     // issues if needed, but this is generally expected to be only be important
7617adc3a2bSChandler Carruth     // for small depths.
7627adc3a2bSChandler Carruth     if (++Depth > 4)
7637adc3a2bSChandler Carruth       return false;
7645b2a732fSJames Molloy 
7655b2a732fSJames Molloy     if (auto *LI = dyn_cast<LoadInst>(Input)) {
7665b2a732fSJames Molloy       // A pointer loaded from a global would have been captured, and we know
7675b2a732fSJames Molloy       // that the global is non-escaping, so no alias.
768b0eb40caSVitaly Buka       const Value *Ptr = getUnderlyingObject(LI->getPointerOperand());
7695b2a732fSJames Molloy       if (isNonEscapingGlobalNoAliasWithLoad(GV, Ptr, Depth, DL))
7705b2a732fSJames Molloy         // The load does not alias with GV.
7715b2a732fSJames Molloy         continue;
7725b2a732fSJames Molloy       // Otherwise, a load could come from anywhere, so bail.
7735b2a732fSJames Molloy       return false;
7745b2a732fSJames Molloy     }
7757adc3a2bSChandler Carruth     if (auto *SI = dyn_cast<SelectInst>(Input)) {
776b0eb40caSVitaly Buka       const Value *LHS = getUnderlyingObject(SI->getTrueValue());
777b0eb40caSVitaly Buka       const Value *RHS = getUnderlyingObject(SI->getFalseValue());
7787adc3a2bSChandler Carruth       if (Visited.insert(LHS).second)
7797adc3a2bSChandler Carruth         Inputs.push_back(LHS);
7807adc3a2bSChandler Carruth       if (Visited.insert(RHS).second)
7817adc3a2bSChandler Carruth         Inputs.push_back(RHS);
7827adc3a2bSChandler Carruth       continue;
7837adc3a2bSChandler Carruth     }
7847adc3a2bSChandler Carruth     if (auto *PN = dyn_cast<PHINode>(Input)) {
7857adc3a2bSChandler Carruth       for (const Value *Op : PN->incoming_values()) {
786b0eb40caSVitaly Buka         Op = getUnderlyingObject(Op);
7877adc3a2bSChandler Carruth         if (Visited.insert(Op).second)
7887adc3a2bSChandler Carruth           Inputs.push_back(Op);
7897adc3a2bSChandler Carruth       }
7907adc3a2bSChandler Carruth       continue;
7917adc3a2bSChandler Carruth     }
7927adc3a2bSChandler Carruth 
7937adc3a2bSChandler Carruth     // FIXME: It would be good to handle other obvious no-alias cases here, but
79402a2bb2fSHiroshi Inoue     // it isn't clear how to do so reasonably without building a small version
7957b560d40SChandler Carruth     // of BasicAA into this code. We could recurse into AAResultBase::alias
7967adc3a2bSChandler Carruth     // here but that seems likely to go poorly as we're inside the
79702a2bb2fSHiroshi Inoue     // implementation of such a query. Until then, just conservatively return
7987adc3a2bSChandler Carruth     // false.
7997adc3a2bSChandler Carruth     return false;
8007adc3a2bSChandler Carruth   } while (!Inputs.empty());
8017adc3a2bSChandler Carruth 
8027adc3a2bSChandler Carruth   // If all the inputs to V were definitively no-alias, then V is no-alias.
8037adc3a2bSChandler Carruth   return true;
8047adc3a2bSChandler Carruth }
8057adc3a2bSChandler Carruth 
invalidate(Module &,const PreservedAnalyses & PA,ModuleAnalysisManager::Invalidator &)8065cc99d05SAlina Sbirlea bool GlobalsAAResult::invalidate(Module &, const PreservedAnalyses &PA,
8075cc99d05SAlina Sbirlea                                  ModuleAnalysisManager::Invalidator &) {
8085cc99d05SAlina Sbirlea   // Check whether the analysis has been explicitly invalidated. Otherwise, it's
8095cc99d05SAlina Sbirlea   // stateless and remains preserved.
8105cc99d05SAlina Sbirlea   auto PAC = PA.getChecker<GlobalsAA>();
8115cc99d05SAlina Sbirlea   return !PAC.preservedWhenStateless();
8125cc99d05SAlina Sbirlea }
8135cc99d05SAlina Sbirlea 
8147adc3a2bSChandler Carruth /// alias - If one of the pointers is to a global that we are tracking, and the
8157adc3a2bSChandler Carruth /// other is some random pointer, we know there cannot be an alias, because the
8167adc3a2bSChandler Carruth /// address of the global isn't taken.
alias(const MemoryLocation & LocA,const MemoryLocation & LocB,AAQueryInfo & AAQI)8177b560d40SChandler Carruth AliasResult GlobalsAAResult::alias(const MemoryLocation &LocA,
818bfc779e4SAlina Sbirlea                                    const MemoryLocation &LocB,
819bfc779e4SAlina Sbirlea                                    AAQueryInfo &AAQI) {
8207adc3a2bSChandler Carruth   // Get the base object these pointers point to.
8210b84afa5SNikita Popov   const Value *UV1 =
82270e3c9a8SNikita Popov       getUnderlyingObject(LocA.Ptr->stripPointerCastsForAliasAnalysis());
8230b84afa5SNikita Popov   const Value *UV2 =
82470e3c9a8SNikita Popov       getUnderlyingObject(LocB.Ptr->stripPointerCastsForAliasAnalysis());
8257adc3a2bSChandler Carruth 
8267adc3a2bSChandler Carruth   // If either of the underlying values is a global, they may be non-addr-taken
8277adc3a2bSChandler Carruth   // globals, which we can answer queries about.
8287adc3a2bSChandler Carruth   const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
8297adc3a2bSChandler Carruth   const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
8307adc3a2bSChandler Carruth   if (GV1 || GV2) {
8317adc3a2bSChandler Carruth     // If the global's address is taken, pretend we don't know it's a pointer to
8327adc3a2bSChandler Carruth     // the global.
8337adc3a2bSChandler Carruth     if (GV1 && !NonAddressTakenGlobals.count(GV1))
8347adc3a2bSChandler Carruth       GV1 = nullptr;
8357adc3a2bSChandler Carruth     if (GV2 && !NonAddressTakenGlobals.count(GV2))
8367adc3a2bSChandler Carruth       GV2 = nullptr;
8377adc3a2bSChandler Carruth 
8387adc3a2bSChandler Carruth     // If the two pointers are derived from two different non-addr-taken
8397adc3a2bSChandler Carruth     // globals we know these can't alias.
8407adc3a2bSChandler Carruth     if (GV1 && GV2 && GV1 != GV2)
841d0660797Sdfukalov       return AliasResult::NoAlias;
8427adc3a2bSChandler Carruth 
8437adc3a2bSChandler Carruth     // If one is and the other isn't, it isn't strictly safe but we can fake
8447adc3a2bSChandler Carruth     // this result if necessary for performance. This does not appear to be
8457adc3a2bSChandler Carruth     // a common problem in practice.
8467adc3a2bSChandler Carruth     if (EnableUnsafeGlobalsModRefAliasResults)
8477adc3a2bSChandler Carruth       if ((GV1 || GV2) && GV1 != GV2)
848d0660797Sdfukalov         return AliasResult::NoAlias;
8497adc3a2bSChandler Carruth 
8507adc3a2bSChandler Carruth     // Check for a special case where a non-escaping global can be used to
8517adc3a2bSChandler Carruth     // conclude no-alias.
8527adc3a2bSChandler Carruth     if ((GV1 || GV2) && GV1 != GV2) {
8537adc3a2bSChandler Carruth       const GlobalValue *GV = GV1 ? GV1 : GV2;
8547adc3a2bSChandler Carruth       const Value *UV = GV1 ? UV2 : UV1;
8557adc3a2bSChandler Carruth       if (isNonEscapingGlobalNoAlias(GV, UV))
856d0660797Sdfukalov         return AliasResult::NoAlias;
8577adc3a2bSChandler Carruth     }
8587adc3a2bSChandler Carruth 
8597adc3a2bSChandler Carruth     // Otherwise if they are both derived from the same addr-taken global, we
8607adc3a2bSChandler Carruth     // can't know the two accesses don't overlap.
8617adc3a2bSChandler Carruth   }
8627adc3a2bSChandler Carruth 
8637adc3a2bSChandler Carruth   // These pointers may be based on the memory owned by an indirect global.  If
8647adc3a2bSChandler Carruth   // so, we may be able to handle this.  First check to see if the base pointer
8657adc3a2bSChandler Carruth   // is a direct load from an indirect global.
8667adc3a2bSChandler Carruth   GV1 = GV2 = nullptr;
8677adc3a2bSChandler Carruth   if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
8687adc3a2bSChandler Carruth     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
8697adc3a2bSChandler Carruth       if (IndirectGlobals.count(GV))
8707adc3a2bSChandler Carruth         GV1 = GV;
8717adc3a2bSChandler Carruth   if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
8727adc3a2bSChandler Carruth     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
8737adc3a2bSChandler Carruth       if (IndirectGlobals.count(GV))
8747adc3a2bSChandler Carruth         GV2 = GV;
8757adc3a2bSChandler Carruth 
8767adc3a2bSChandler Carruth   // These pointers may also be from an allocation for the indirect global.  If
8777adc3a2bSChandler Carruth   // so, also handle them.
8787adc3a2bSChandler Carruth   if (!GV1)
8797adc3a2bSChandler Carruth     GV1 = AllocsForIndirectGlobals.lookup(UV1);
8807adc3a2bSChandler Carruth   if (!GV2)
8817adc3a2bSChandler Carruth     GV2 = AllocsForIndirectGlobals.lookup(UV2);
8827adc3a2bSChandler Carruth 
8837adc3a2bSChandler Carruth   // Now that we know whether the two pointers are related to indirect globals,
8847adc3a2bSChandler Carruth   // use this to disambiguate the pointers. If the pointers are based on
8857adc3a2bSChandler Carruth   // different indirect globals they cannot alias.
8867adc3a2bSChandler Carruth   if (GV1 && GV2 && GV1 != GV2)
887d0660797Sdfukalov     return AliasResult::NoAlias;
8887adc3a2bSChandler Carruth 
8897adc3a2bSChandler Carruth   // If one is based on an indirect global and the other isn't, it isn't
8907adc3a2bSChandler Carruth   // strictly safe but we can fake this result if necessary for performance.
8917adc3a2bSChandler Carruth   // This does not appear to be a common problem in practice.
8927adc3a2bSChandler Carruth   if (EnableUnsafeGlobalsModRefAliasResults)
8937adc3a2bSChandler Carruth     if ((GV1 || GV2) && GV1 != GV2)
894d0660797Sdfukalov       return AliasResult::NoAlias;
8957adc3a2bSChandler Carruth 
896bfc779e4SAlina Sbirlea   return AAResultBase::alias(LocA, LocB, AAQI);
8977adc3a2bSChandler Carruth }
8987adc3a2bSChandler Carruth 
getModRefInfoForArgument(const CallBase * Call,const GlobalValue * GV,AAQueryInfo & AAQI)899363ac683SChandler Carruth ModRefInfo GlobalsAAResult::getModRefInfoForArgument(const CallBase *Call,
900bfc779e4SAlina Sbirlea                                                      const GlobalValue *GV,
901bfc779e4SAlina Sbirlea                                                      AAQueryInfo &AAQI) {
902363ac683SChandler Carruth   if (Call->doesNotAccessMemory())
903193429f0SAlina Sbirlea     return ModRefInfo::NoModRef;
904193429f0SAlina Sbirlea   ModRefInfo ConservativeResult =
905363ac683SChandler Carruth       Call->onlyReadsMemory() ? ModRefInfo::Ref : ModRefInfo::ModRef;
906eb46641cSJames Molloy 
907eb46641cSJames Molloy   // Iterate through all the arguments to the called function. If any argument
908eb46641cSJames Molloy   // is based on GV, return the conservative result.
909601b3a13SKazu Hirata   for (const auto &A : Call->args()) {
91071e8c6f2SBjorn Pettersson     SmallVector<const Value*, 4> Objects;
911b0eb40caSVitaly Buka     getUnderlyingObjects(A, Objects);
912eb46641cSJames Molloy 
913eb46641cSJames Molloy     // All objects must be identified.
9140a16c228SDavid Majnemer     if (!all_of(Objects, isIdentifiedObject) &&
91568befd70SVaivaswatha Nagaraj         // Try ::alias to see if all objects are known not to alias GV.
91671e8c6f2SBjorn Pettersson         !all_of(Objects, [&](const Value *V) {
9174df8efceSNikita Popov           return this->alias(MemoryLocation::getBeforeOrAfter(V),
9184df8efceSNikita Popov                              MemoryLocation::getBeforeOrAfter(GV),
919d0660797Sdfukalov                              AAQI) == AliasResult::NoAlias;
92068befd70SVaivaswatha Nagaraj         }))
921eb46641cSJames Molloy       return ConservativeResult;
922eb46641cSJames Molloy 
9230a16c228SDavid Majnemer     if (is_contained(Objects, GV))
924eb46641cSJames Molloy       return ConservativeResult;
925eb46641cSJames Molloy   }
926eb46641cSJames Molloy 
927eb46641cSJames Molloy   // We identified all objects in the argument list, and none of them were GV.
928193429f0SAlina Sbirlea   return ModRefInfo::NoModRef;
929eb46641cSJames Molloy }
930eb46641cSJames Molloy 
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc,AAQueryInfo & AAQI)931363ac683SChandler Carruth ModRefInfo GlobalsAAResult::getModRefInfo(const CallBase *Call,
932bfc779e4SAlina Sbirlea                                           const MemoryLocation &Loc,
933bfc779e4SAlina Sbirlea                                           AAQueryInfo &AAQI) {
934193429f0SAlina Sbirlea   ModRefInfo Known = ModRefInfo::ModRef;
9357adc3a2bSChandler Carruth 
9367adc3a2bSChandler Carruth   // If we are asking for mod/ref info of a direct call with a pointer to a
9377adc3a2bSChandler Carruth   // global we are tracking, return information if we have it.
9387adc3a2bSChandler Carruth   if (const GlobalValue *GV =
939b0eb40caSVitaly Buka           dyn_cast<GlobalValue>(getUnderlyingObject(Loc.Ptr)))
940db69f1b2SAlina Sbirlea     // If GV is internal to this IR and there is no function with local linkage
941db69f1b2SAlina Sbirlea     // that has had their address taken, keep looking for a tighter ModRefInfo.
942db69f1b2SAlina Sbirlea     if (GV->hasLocalLinkage() && !UnknownFunctionsWithLocalLinkage)
943363ac683SChandler Carruth       if (const Function *F = Call->getCalledFunction())
9447adc3a2bSChandler Carruth         if (NonAddressTakenGlobals.count(GV))
9457adc3a2bSChandler Carruth           if (const FunctionInfo *FI = getFunctionInfo(F))
94663d2250aSAlina Sbirlea             Known = unionModRef(FI->getModRefInfoForGlobal(*GV),
947bfc779e4SAlina Sbirlea                                 getModRefInfoForArgument(Call, GV, AAQI));
9487adc3a2bSChandler Carruth 
94963d2250aSAlina Sbirlea   if (!isModOrRefSet(Known))
950193429f0SAlina Sbirlea     return ModRefInfo::NoModRef; // No need to query other mod/ref analyses
951bfc779e4SAlina Sbirlea   return intersectModRef(Known, AAResultBase::getModRefInfo(Call, Loc, AAQI));
9527b560d40SChandler Carruth }
9537b560d40SChandler Carruth 
GlobalsAAResult(const DataLayout & DL,std::function<const TargetLibraryInfo & (Function & F)> GetTLI)9549c27b59cSTeresa Johnson GlobalsAAResult::GlobalsAAResult(
9559c27b59cSTeresa Johnson     const DataLayout &DL,
9569c27b59cSTeresa Johnson     std::function<const TargetLibraryInfo &(Function &F)> GetTLI)
957b932bdf5SKazu Hirata     : DL(DL), GetTLI(std::move(GetTLI)) {}
9587b560d40SChandler Carruth 
GlobalsAAResult(GlobalsAAResult && Arg)9597b560d40SChandler Carruth GlobalsAAResult::GlobalsAAResult(GlobalsAAResult &&Arg)
9609c27b59cSTeresa Johnson     : AAResultBase(std::move(Arg)), DL(Arg.DL), GetTLI(std::move(Arg.GetTLI)),
9611a296ec6SNAKAMURA Takumi       NonAddressTakenGlobals(std::move(Arg.NonAddressTakenGlobals)),
9621a296ec6SNAKAMURA Takumi       IndirectGlobals(std::move(Arg.IndirectGlobals)),
9631a296ec6SNAKAMURA Takumi       AllocsForIndirectGlobals(std::move(Arg.AllocsForIndirectGlobals)),
9641a296ec6SNAKAMURA Takumi       FunctionInfos(std::move(Arg.FunctionInfos)),
96598800d9cSNAKAMURA Takumi       Handles(std::move(Arg.Handles)) {
96698800d9cSNAKAMURA Takumi   // Update the parent for each DeletionCallbackHandle.
96798800d9cSNAKAMURA Takumi   for (auto &H : Handles) {
96898800d9cSNAKAMURA Takumi     assert(H.GAR == &Arg);
96998800d9cSNAKAMURA Takumi     H.GAR = this;
97098800d9cSNAKAMURA Takumi   }
97198800d9cSNAKAMURA Takumi }
9727b560d40SChandler Carruth 
9733a3cb929SKazu Hirata GlobalsAAResult::~GlobalsAAResult() = default;
97445a9c203SChandler Carruth 
analyzeModule(Module & M,std::function<const TargetLibraryInfo & (Function & F)> GetTLI,CallGraph & CG)9759c27b59cSTeresa Johnson /*static*/ GlobalsAAResult GlobalsAAResult::analyzeModule(
9769c27b59cSTeresa Johnson     Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
9777b560d40SChandler Carruth     CallGraph &CG) {
9789c27b59cSTeresa Johnson   GlobalsAAResult Result(M.getDataLayout(), GetTLI);
9797b560d40SChandler Carruth 
980eb46641cSJames Molloy   // Discover which functions aren't recursive, to feed into AnalyzeGlobals.
981eb46641cSJames Molloy   Result.CollectSCCMembership(CG);
982eb46641cSJames Molloy 
9837b560d40SChandler Carruth   // Find non-addr taken globals.
9847b560d40SChandler Carruth   Result.AnalyzeGlobals(M);
9857b560d40SChandler Carruth 
9867b560d40SChandler Carruth   // Propagate on CG.
9877b560d40SChandler Carruth   Result.AnalyzeCallGraph(CG, M);
9887b560d40SChandler Carruth 
9897b560d40SChandler Carruth   return Result;
9907b560d40SChandler Carruth }
9917b560d40SChandler Carruth 
992dab4eae2SChandler Carruth AnalysisKey GlobalsAA::Key;
993b4faf13cSChandler Carruth 
run(Module & M,ModuleAnalysisManager & AM)994fd03ac6aSSean Silva GlobalsAAResult GlobalsAA::run(Module &M, ModuleAnalysisManager &AM) {
9959c27b59cSTeresa Johnson   FunctionAnalysisManager &FAM =
9969c27b59cSTeresa Johnson       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
9979c27b59cSTeresa Johnson   auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
9989c27b59cSTeresa Johnson     return FAM.getResult<TargetLibraryAnalysis>(F);
9999c27b59cSTeresa Johnson   };
10009c27b59cSTeresa Johnson   return GlobalsAAResult::analyzeModule(M, GetTLI,
1001b47f8010SChandler Carruth                                         AM.getResult<CallGraphAnalysis>(M));
10027b560d40SChandler Carruth }
10037b560d40SChandler Carruth 
run(Module & M,ModuleAnalysisManager & AM)10044fc7c55fSArthur Eubanks PreservedAnalyses RecomputeGlobalsAAPass::run(Module &M,
10054fc7c55fSArthur Eubanks                                               ModuleAnalysisManager &AM) {
10064fc7c55fSArthur Eubanks   if (auto *G = AM.getCachedResult<GlobalsAA>(M)) {
10074fc7c55fSArthur Eubanks     auto &CG = AM.getResult<CallGraphAnalysis>(M);
10084fc7c55fSArthur Eubanks     G->NonAddressTakenGlobals.clear();
10094fc7c55fSArthur Eubanks     G->UnknownFunctionsWithLocalLinkage = false;
10104fc7c55fSArthur Eubanks     G->IndirectGlobals.clear();
10114fc7c55fSArthur Eubanks     G->AllocsForIndirectGlobals.clear();
10124fc7c55fSArthur Eubanks     G->FunctionInfos.clear();
10134fc7c55fSArthur Eubanks     G->FunctionToSCCMap.clear();
10144fc7c55fSArthur Eubanks     G->Handles.clear();
10154fc7c55fSArthur Eubanks     G->CollectSCCMembership(CG);
10164fc7c55fSArthur Eubanks     G->AnalyzeGlobals(M);
10174fc7c55fSArthur Eubanks     G->AnalyzeCallGraph(CG, M);
10184fc7c55fSArthur Eubanks   }
10194fc7c55fSArthur Eubanks   return PreservedAnalyses::all();
10204fc7c55fSArthur Eubanks }
10214fc7c55fSArthur Eubanks 
10227b560d40SChandler Carruth char GlobalsAAWrapperPass::ID = 0;
10237b560d40SChandler Carruth INITIALIZE_PASS_BEGIN(GlobalsAAWrapperPass, "globals-aa",
10247b560d40SChandler Carruth                       "Globals Alias Analysis", false, true)
INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)10257b560d40SChandler Carruth INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
10267b560d40SChandler Carruth INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10277b560d40SChandler Carruth INITIALIZE_PASS_END(GlobalsAAWrapperPass, "globals-aa",
10287b560d40SChandler Carruth                     "Globals Alias Analysis", false, true)
10297b560d40SChandler Carruth 
10307b560d40SChandler Carruth ModulePass *llvm::createGlobalsAAWrapperPass() {
10317b560d40SChandler Carruth   return new GlobalsAAWrapperPass();
10327b560d40SChandler Carruth }
10337b560d40SChandler Carruth 
GlobalsAAWrapperPass()10347b560d40SChandler Carruth GlobalsAAWrapperPass::GlobalsAAWrapperPass() : ModulePass(ID) {
10357b560d40SChandler Carruth   initializeGlobalsAAWrapperPassPass(*PassRegistry::getPassRegistry());
10367b560d40SChandler Carruth }
10377b560d40SChandler Carruth 
runOnModule(Module & M)10387b560d40SChandler Carruth bool GlobalsAAWrapperPass::runOnModule(Module &M) {
10399c27b59cSTeresa Johnson   auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
10409c27b59cSTeresa Johnson     return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
10419c27b59cSTeresa Johnson   };
10427b560d40SChandler Carruth   Result.reset(new GlobalsAAResult(GlobalsAAResult::analyzeModule(
10439c27b59cSTeresa Johnson       M, GetTLI, getAnalysis<CallGraphWrapperPass>().getCallGraph())));
10447b560d40SChandler Carruth   return false;
10457b560d40SChandler Carruth }
10467b560d40SChandler Carruth 
doFinalization(Module & M)10477b560d40SChandler Carruth bool GlobalsAAWrapperPass::doFinalization(Module &M) {
10487b560d40SChandler Carruth   Result.reset();
10497b560d40SChandler Carruth   return false;
10507b560d40SChandler Carruth }
10517b560d40SChandler Carruth 
getAnalysisUsage(AnalysisUsage & AU) const10527b560d40SChandler Carruth void GlobalsAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10537b560d40SChandler Carruth   AU.setPreservesAll();
10547b560d40SChandler Carruth   AU.addRequired<CallGraphWrapperPass>();
10557b560d40SChandler Carruth   AU.addRequired<TargetLibraryInfoWrapperPass>();
10567adc3a2bSChandler Carruth }
1057