17330f729Sjoerg //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This simple pass provides alias and mod/ref information for global values
107330f729Sjoerg // that do not have their address taken, and keeps track of whether functions
117330f729Sjoerg // read or write memory (are "pure"). For this simple (but very common) case,
127330f729Sjoerg // we can provide pretty accurate and useful information.
137330f729Sjoerg //
147330f729Sjoerg //===----------------------------------------------------------------------===//
157330f729Sjoerg
167330f729Sjoerg #include "llvm/Analysis/GlobalsModRef.h"
177330f729Sjoerg #include "llvm/ADT/SCCIterator.h"
187330f729Sjoerg #include "llvm/ADT/SmallPtrSet.h"
197330f729Sjoerg #include "llvm/ADT/Statistic.h"
20*82d56013Sjoerg #include "llvm/Analysis/CallGraph.h"
217330f729Sjoerg #include "llvm/Analysis/MemoryBuiltins.h"
227330f729Sjoerg #include "llvm/Analysis/TargetLibraryInfo.h"
237330f729Sjoerg #include "llvm/Analysis/ValueTracking.h"
247330f729Sjoerg #include "llvm/IR/DerivedTypes.h"
257330f729Sjoerg #include "llvm/IR/InstIterator.h"
267330f729Sjoerg #include "llvm/IR/Instructions.h"
277330f729Sjoerg #include "llvm/IR/IntrinsicInst.h"
287330f729Sjoerg #include "llvm/IR/Module.h"
29*82d56013Sjoerg #include "llvm/InitializePasses.h"
307330f729Sjoerg #include "llvm/Pass.h"
317330f729Sjoerg #include "llvm/Support/CommandLine.h"
32*82d56013Sjoerg
337330f729Sjoerg using namespace llvm;
347330f729Sjoerg
357330f729Sjoerg #define DEBUG_TYPE "globalsmodref-aa"
367330f729Sjoerg
377330f729Sjoerg STATISTIC(NumNonAddrTakenGlobalVars,
387330f729Sjoerg "Number of global vars without address taken");
397330f729Sjoerg STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
407330f729Sjoerg STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
417330f729Sjoerg STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
427330f729Sjoerg STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
437330f729Sjoerg
447330f729Sjoerg // An option to enable unsafe alias results from the GlobalsModRef analysis.
457330f729Sjoerg // When enabled, GlobalsModRef will provide no-alias results which in extremely
467330f729Sjoerg // rare cases may not be conservatively correct. In particular, in the face of
47*82d56013Sjoerg // transforms which cause asymmetry between how effective getUnderlyingObject
487330f729Sjoerg // is for two pointers, it may produce incorrect results.
497330f729Sjoerg //
507330f729Sjoerg // These unsafe results have been returned by GMR for many years without
517330f729Sjoerg // causing significant issues in the wild and so we provide a mechanism to
527330f729Sjoerg // re-enable them for users of LLVM that have a particular performance
537330f729Sjoerg // sensitivity and no known issues. The option also makes it easy to evaluate
547330f729Sjoerg // the performance impact of these results.
557330f729Sjoerg static cl::opt<bool> EnableUnsafeGlobalsModRefAliasResults(
567330f729Sjoerg "enable-unsafe-globalsmodref-alias-results", cl::init(false), cl::Hidden);
577330f729Sjoerg
587330f729Sjoerg /// The mod/ref information collected for a particular function.
597330f729Sjoerg ///
607330f729Sjoerg /// We collect information about mod/ref behavior of a function here, both in
617330f729Sjoerg /// general and as pertains to specific globals. We only have this detailed
627330f729Sjoerg /// information when we know *something* useful about the behavior. If we
637330f729Sjoerg /// saturate to fully general mod/ref, we remove the info for the function.
647330f729Sjoerg class GlobalsAAResult::FunctionInfo {
657330f729Sjoerg typedef SmallDenseMap<const GlobalValue *, ModRefInfo, 16> GlobalInfoMapType;
667330f729Sjoerg
677330f729Sjoerg /// Build a wrapper struct that has 8-byte alignment. All heap allocations
687330f729Sjoerg /// should provide this much alignment at least, but this makes it clear we
697330f729Sjoerg /// specifically rely on this amount of alignment.
707330f729Sjoerg struct alignas(8) AlignedMap {
AlignedMapGlobalsAAResult::FunctionInfo::AlignedMap717330f729Sjoerg AlignedMap() {}
AlignedMapGlobalsAAResult::FunctionInfo::AlignedMap727330f729Sjoerg AlignedMap(const AlignedMap &Arg) : Map(Arg.Map) {}
737330f729Sjoerg GlobalInfoMapType Map;
747330f729Sjoerg };
757330f729Sjoerg
767330f729Sjoerg /// Pointer traits for our aligned map.
777330f729Sjoerg struct AlignedMapPointerTraits {
getAsVoidPointerGlobalsAAResult::FunctionInfo::AlignedMapPointerTraits787330f729Sjoerg static inline void *getAsVoidPointer(AlignedMap *P) { return P; }
getFromVoidPointerGlobalsAAResult::FunctionInfo::AlignedMapPointerTraits797330f729Sjoerg static inline AlignedMap *getFromVoidPointer(void *P) {
807330f729Sjoerg return (AlignedMap *)P;
817330f729Sjoerg }
82*82d56013Sjoerg static constexpr int NumLowBitsAvailable = 3;
837330f729Sjoerg static_assert(alignof(AlignedMap) >= (1 << NumLowBitsAvailable),
847330f729Sjoerg "AlignedMap insufficiently aligned to have enough low bits.");
857330f729Sjoerg };
867330f729Sjoerg
877330f729Sjoerg /// The bit that flags that this function may read any global. This is
887330f729Sjoerg /// chosen to mix together with ModRefInfo bits.
897330f729Sjoerg /// FIXME: This assumes ModRefInfo lattice will remain 4 bits!
907330f729Sjoerg /// It overlaps with ModRefInfo::Must bit!
917330f729Sjoerg /// FunctionInfo.getModRefInfo() masks out everything except ModRef so
927330f729Sjoerg /// this remains correct, but the Must info is lost.
937330f729Sjoerg enum { MayReadAnyGlobal = 4 };
947330f729Sjoerg
957330f729Sjoerg /// Checks to document the invariants of the bit packing here.
967330f729Sjoerg static_assert((MayReadAnyGlobal & static_cast<int>(ModRefInfo::MustModRef)) ==
977330f729Sjoerg 0,
987330f729Sjoerg "ModRef and the MayReadAnyGlobal flag bits overlap.");
997330f729Sjoerg static_assert(((MayReadAnyGlobal |
1007330f729Sjoerg static_cast<int>(ModRefInfo::MustModRef)) >>
1017330f729Sjoerg AlignedMapPointerTraits::NumLowBitsAvailable) == 0,
1027330f729Sjoerg "Insufficient low bits to store our flag and ModRef info.");
1037330f729Sjoerg
1047330f729Sjoerg public:
FunctionInfo()1057330f729Sjoerg FunctionInfo() : Info() {}
~FunctionInfo()1067330f729Sjoerg ~FunctionInfo() {
1077330f729Sjoerg delete Info.getPointer();
1087330f729Sjoerg }
1097330f729Sjoerg // Spell out the copy ond move constructors and assignment operators to get
1107330f729Sjoerg // deep copy semantics and correct move semantics in the face of the
1117330f729Sjoerg // pointer-int pair.
FunctionInfo(const FunctionInfo & Arg)1127330f729Sjoerg FunctionInfo(const FunctionInfo &Arg)
1137330f729Sjoerg : Info(nullptr, Arg.Info.getInt()) {
1147330f729Sjoerg if (const auto *ArgPtr = Arg.Info.getPointer())
1157330f729Sjoerg Info.setPointer(new AlignedMap(*ArgPtr));
1167330f729Sjoerg }
FunctionInfo(FunctionInfo && Arg)1177330f729Sjoerg FunctionInfo(FunctionInfo &&Arg)
1187330f729Sjoerg : Info(Arg.Info.getPointer(), Arg.Info.getInt()) {
1197330f729Sjoerg Arg.Info.setPointerAndInt(nullptr, 0);
1207330f729Sjoerg }
operator =(const FunctionInfo & RHS)1217330f729Sjoerg FunctionInfo &operator=(const FunctionInfo &RHS) {
1227330f729Sjoerg delete Info.getPointer();
1237330f729Sjoerg Info.setPointerAndInt(nullptr, RHS.Info.getInt());
1247330f729Sjoerg if (const auto *RHSPtr = RHS.Info.getPointer())
1257330f729Sjoerg Info.setPointer(new AlignedMap(*RHSPtr));
1267330f729Sjoerg return *this;
1277330f729Sjoerg }
operator =(FunctionInfo && RHS)1287330f729Sjoerg FunctionInfo &operator=(FunctionInfo &&RHS) {
1297330f729Sjoerg delete Info.getPointer();
1307330f729Sjoerg Info.setPointerAndInt(RHS.Info.getPointer(), RHS.Info.getInt());
1317330f729Sjoerg RHS.Info.setPointerAndInt(nullptr, 0);
1327330f729Sjoerg return *this;
1337330f729Sjoerg }
1347330f729Sjoerg
1357330f729Sjoerg /// This method clears MayReadAnyGlobal bit added by GlobalsAAResult to return
1367330f729Sjoerg /// the corresponding ModRefInfo. It must align in functionality with
1377330f729Sjoerg /// clearMust().
globalClearMayReadAnyGlobal(int I) const1387330f729Sjoerg ModRefInfo globalClearMayReadAnyGlobal(int I) const {
1397330f729Sjoerg return ModRefInfo((I & static_cast<int>(ModRefInfo::ModRef)) |
1407330f729Sjoerg static_cast<int>(ModRefInfo::NoModRef));
1417330f729Sjoerg }
1427330f729Sjoerg
1437330f729Sjoerg /// Returns the \c ModRefInfo info for this function.
getModRefInfo() const1447330f729Sjoerg ModRefInfo getModRefInfo() const {
1457330f729Sjoerg return globalClearMayReadAnyGlobal(Info.getInt());
1467330f729Sjoerg }
1477330f729Sjoerg
1487330f729Sjoerg /// Adds new \c ModRefInfo for this function to its state.
addModRefInfo(ModRefInfo NewMRI)1497330f729Sjoerg void addModRefInfo(ModRefInfo NewMRI) {
1507330f729Sjoerg Info.setInt(Info.getInt() | static_cast<int>(setMust(NewMRI)));
1517330f729Sjoerg }
1527330f729Sjoerg
1537330f729Sjoerg /// Returns whether this function may read any global variable, and we don't
1547330f729Sjoerg /// know which global.
mayReadAnyGlobal() const1557330f729Sjoerg bool mayReadAnyGlobal() const { return Info.getInt() & MayReadAnyGlobal; }
1567330f729Sjoerg
1577330f729Sjoerg /// Sets this function as potentially reading from any global.
setMayReadAnyGlobal()1587330f729Sjoerg void setMayReadAnyGlobal() { Info.setInt(Info.getInt() | MayReadAnyGlobal); }
1597330f729Sjoerg
1607330f729Sjoerg /// Returns the \c ModRefInfo info for this function w.r.t. a particular
1617330f729Sjoerg /// global, which may be more precise than the general information above.
getModRefInfoForGlobal(const GlobalValue & GV) const1627330f729Sjoerg ModRefInfo getModRefInfoForGlobal(const GlobalValue &GV) const {
1637330f729Sjoerg ModRefInfo GlobalMRI =
1647330f729Sjoerg mayReadAnyGlobal() ? ModRefInfo::Ref : ModRefInfo::NoModRef;
1657330f729Sjoerg if (AlignedMap *P = Info.getPointer()) {
1667330f729Sjoerg auto I = P->Map.find(&GV);
1677330f729Sjoerg if (I != P->Map.end())
1687330f729Sjoerg GlobalMRI = unionModRef(GlobalMRI, I->second);
1697330f729Sjoerg }
1707330f729Sjoerg return GlobalMRI;
1717330f729Sjoerg }
1727330f729Sjoerg
1737330f729Sjoerg /// Add mod/ref info from another function into ours, saturating towards
1747330f729Sjoerg /// ModRef.
addFunctionInfo(const FunctionInfo & FI)1757330f729Sjoerg void addFunctionInfo(const FunctionInfo &FI) {
1767330f729Sjoerg addModRefInfo(FI.getModRefInfo());
1777330f729Sjoerg
1787330f729Sjoerg if (FI.mayReadAnyGlobal())
1797330f729Sjoerg setMayReadAnyGlobal();
1807330f729Sjoerg
1817330f729Sjoerg if (AlignedMap *P = FI.Info.getPointer())
1827330f729Sjoerg for (const auto &G : P->Map)
1837330f729Sjoerg addModRefInfoForGlobal(*G.first, G.second);
1847330f729Sjoerg }
1857330f729Sjoerg
addModRefInfoForGlobal(const GlobalValue & GV,ModRefInfo NewMRI)1867330f729Sjoerg void addModRefInfoForGlobal(const GlobalValue &GV, ModRefInfo NewMRI) {
1877330f729Sjoerg AlignedMap *P = Info.getPointer();
1887330f729Sjoerg if (!P) {
1897330f729Sjoerg P = new AlignedMap();
1907330f729Sjoerg Info.setPointer(P);
1917330f729Sjoerg }
1927330f729Sjoerg auto &GlobalMRI = P->Map[&GV];
1937330f729Sjoerg GlobalMRI = unionModRef(GlobalMRI, NewMRI);
1947330f729Sjoerg }
1957330f729Sjoerg
1967330f729Sjoerg /// Clear a global's ModRef info. Should be used when a global is being
1977330f729Sjoerg /// deleted.
eraseModRefInfoForGlobal(const GlobalValue & GV)1987330f729Sjoerg void eraseModRefInfoForGlobal(const GlobalValue &GV) {
1997330f729Sjoerg if (AlignedMap *P = Info.getPointer())
2007330f729Sjoerg P->Map.erase(&GV);
2017330f729Sjoerg }
2027330f729Sjoerg
2037330f729Sjoerg private:
2047330f729Sjoerg /// All of the information is encoded into a single pointer, with a three bit
2057330f729Sjoerg /// integer in the low three bits. The high bit provides a flag for when this
2067330f729Sjoerg /// function may read any global. The low two bits are the ModRefInfo. And
2077330f729Sjoerg /// the pointer, when non-null, points to a map from GlobalValue to
2087330f729Sjoerg /// ModRefInfo specific to that GlobalValue.
2097330f729Sjoerg PointerIntPair<AlignedMap *, 3, unsigned, AlignedMapPointerTraits> Info;
2107330f729Sjoerg };
2117330f729Sjoerg
deleted()2127330f729Sjoerg void GlobalsAAResult::DeletionCallbackHandle::deleted() {
2137330f729Sjoerg Value *V = getValPtr();
2147330f729Sjoerg if (auto *F = dyn_cast<Function>(V))
2157330f729Sjoerg GAR->FunctionInfos.erase(F);
2167330f729Sjoerg
2177330f729Sjoerg if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2187330f729Sjoerg if (GAR->NonAddressTakenGlobals.erase(GV)) {
2197330f729Sjoerg // This global might be an indirect global. If so, remove it and
2207330f729Sjoerg // remove any AllocRelatedValues for it.
2217330f729Sjoerg if (GAR->IndirectGlobals.erase(GV)) {
2227330f729Sjoerg // Remove any entries in AllocsForIndirectGlobals for this global.
2237330f729Sjoerg for (auto I = GAR->AllocsForIndirectGlobals.begin(),
2247330f729Sjoerg E = GAR->AllocsForIndirectGlobals.end();
2257330f729Sjoerg I != E; ++I)
2267330f729Sjoerg if (I->second == GV)
2277330f729Sjoerg GAR->AllocsForIndirectGlobals.erase(I);
2287330f729Sjoerg }
2297330f729Sjoerg
2307330f729Sjoerg // Scan the function info we have collected and remove this global
2317330f729Sjoerg // from all of them.
2327330f729Sjoerg for (auto &FIPair : GAR->FunctionInfos)
2337330f729Sjoerg FIPair.second.eraseModRefInfoForGlobal(*GV);
2347330f729Sjoerg }
2357330f729Sjoerg }
2367330f729Sjoerg
2377330f729Sjoerg // If this is an allocation related to an indirect global, remove it.
2387330f729Sjoerg GAR->AllocsForIndirectGlobals.erase(V);
2397330f729Sjoerg
2407330f729Sjoerg // And clear out the handle.
2417330f729Sjoerg setValPtr(nullptr);
2427330f729Sjoerg GAR->Handles.erase(I);
2437330f729Sjoerg // This object is now destroyed!
2447330f729Sjoerg }
2457330f729Sjoerg
getModRefBehavior(const Function * F)2467330f729Sjoerg FunctionModRefBehavior GlobalsAAResult::getModRefBehavior(const Function *F) {
2477330f729Sjoerg FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
2487330f729Sjoerg
2497330f729Sjoerg if (FunctionInfo *FI = getFunctionInfo(F)) {
2507330f729Sjoerg if (!isModOrRefSet(FI->getModRefInfo()))
2517330f729Sjoerg Min = FMRB_DoesNotAccessMemory;
2527330f729Sjoerg else if (!isModSet(FI->getModRefInfo()))
2537330f729Sjoerg Min = FMRB_OnlyReadsMemory;
2547330f729Sjoerg }
2557330f729Sjoerg
2567330f729Sjoerg return FunctionModRefBehavior(AAResultBase::getModRefBehavior(F) & Min);
2577330f729Sjoerg }
2587330f729Sjoerg
2597330f729Sjoerg FunctionModRefBehavior
getModRefBehavior(const CallBase * Call)2607330f729Sjoerg GlobalsAAResult::getModRefBehavior(const CallBase *Call) {
2617330f729Sjoerg FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
2627330f729Sjoerg
2637330f729Sjoerg if (!Call->hasOperandBundles())
2647330f729Sjoerg if (const Function *F = Call->getCalledFunction())
2657330f729Sjoerg if (FunctionInfo *FI = getFunctionInfo(F)) {
2667330f729Sjoerg if (!isModOrRefSet(FI->getModRefInfo()))
2677330f729Sjoerg Min = FMRB_DoesNotAccessMemory;
2687330f729Sjoerg else if (!isModSet(FI->getModRefInfo()))
2697330f729Sjoerg Min = FMRB_OnlyReadsMemory;
2707330f729Sjoerg }
2717330f729Sjoerg
2727330f729Sjoerg return FunctionModRefBehavior(AAResultBase::getModRefBehavior(Call) & Min);
2737330f729Sjoerg }
2747330f729Sjoerg
2757330f729Sjoerg /// Returns the function info for the function, or null if we don't have
2767330f729Sjoerg /// anything useful to say about it.
2777330f729Sjoerg GlobalsAAResult::FunctionInfo *
getFunctionInfo(const Function * F)2787330f729Sjoerg GlobalsAAResult::getFunctionInfo(const Function *F) {
2797330f729Sjoerg auto I = FunctionInfos.find(F);
2807330f729Sjoerg if (I != FunctionInfos.end())
2817330f729Sjoerg return &I->second;
2827330f729Sjoerg return nullptr;
2837330f729Sjoerg }
2847330f729Sjoerg
2857330f729Sjoerg /// AnalyzeGlobals - Scan through the users of all of the internal
2867330f729Sjoerg /// GlobalValue's in the program. If none of them have their "address taken"
2877330f729Sjoerg /// (really, their address passed to something nontrivial), record this fact,
2887330f729Sjoerg /// and record the functions that they are used directly in.
AnalyzeGlobals(Module & M)2897330f729Sjoerg void GlobalsAAResult::AnalyzeGlobals(Module &M) {
2907330f729Sjoerg SmallPtrSet<Function *, 32> TrackedFunctions;
2917330f729Sjoerg for (Function &F : M)
292*82d56013Sjoerg if (F.hasLocalLinkage()) {
2937330f729Sjoerg if (!AnalyzeUsesOfPointer(&F)) {
2947330f729Sjoerg // Remember that we are tracking this global.
2957330f729Sjoerg NonAddressTakenGlobals.insert(&F);
2967330f729Sjoerg TrackedFunctions.insert(&F);
2977330f729Sjoerg Handles.emplace_front(*this, &F);
2987330f729Sjoerg Handles.front().I = Handles.begin();
2997330f729Sjoerg ++NumNonAddrTakenFunctions;
300*82d56013Sjoerg } else
301*82d56013Sjoerg UnknownFunctionsWithLocalLinkage = true;
3027330f729Sjoerg }
3037330f729Sjoerg
3047330f729Sjoerg SmallPtrSet<Function *, 16> Readers, Writers;
3057330f729Sjoerg for (GlobalVariable &GV : M.globals())
3067330f729Sjoerg if (GV.hasLocalLinkage()) {
3077330f729Sjoerg if (!AnalyzeUsesOfPointer(&GV, &Readers,
3087330f729Sjoerg GV.isConstant() ? nullptr : &Writers)) {
3097330f729Sjoerg // Remember that we are tracking this global, and the mod/ref fns
3107330f729Sjoerg NonAddressTakenGlobals.insert(&GV);
3117330f729Sjoerg Handles.emplace_front(*this, &GV);
3127330f729Sjoerg Handles.front().I = Handles.begin();
3137330f729Sjoerg
3147330f729Sjoerg for (Function *Reader : Readers) {
3157330f729Sjoerg if (TrackedFunctions.insert(Reader).second) {
3167330f729Sjoerg Handles.emplace_front(*this, Reader);
3177330f729Sjoerg Handles.front().I = Handles.begin();
3187330f729Sjoerg }
3197330f729Sjoerg FunctionInfos[Reader].addModRefInfoForGlobal(GV, ModRefInfo::Ref);
3207330f729Sjoerg }
3217330f729Sjoerg
3227330f729Sjoerg if (!GV.isConstant()) // No need to keep track of writers to constants
3237330f729Sjoerg for (Function *Writer : Writers) {
3247330f729Sjoerg if (TrackedFunctions.insert(Writer).second) {
3257330f729Sjoerg Handles.emplace_front(*this, Writer);
3267330f729Sjoerg Handles.front().I = Handles.begin();
3277330f729Sjoerg }
3287330f729Sjoerg FunctionInfos[Writer].addModRefInfoForGlobal(GV, ModRefInfo::Mod);
3297330f729Sjoerg }
3307330f729Sjoerg ++NumNonAddrTakenGlobalVars;
3317330f729Sjoerg
3327330f729Sjoerg // If this global holds a pointer type, see if it is an indirect global.
3337330f729Sjoerg if (GV.getValueType()->isPointerTy() &&
3347330f729Sjoerg AnalyzeIndirectGlobalMemory(&GV))
3357330f729Sjoerg ++NumIndirectGlobalVars;
3367330f729Sjoerg }
3377330f729Sjoerg Readers.clear();
3387330f729Sjoerg Writers.clear();
3397330f729Sjoerg }
3407330f729Sjoerg }
3417330f729Sjoerg
3427330f729Sjoerg /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
3437330f729Sjoerg /// If this is used by anything complex (i.e., the address escapes), return
3447330f729Sjoerg /// true. Also, while we are at it, keep track of those functions that read and
3457330f729Sjoerg /// write to the value.
3467330f729Sjoerg ///
3477330f729Sjoerg /// If OkayStoreDest is non-null, stores into this global are allowed.
AnalyzeUsesOfPointer(Value * V,SmallPtrSetImpl<Function * > * Readers,SmallPtrSetImpl<Function * > * Writers,GlobalValue * OkayStoreDest)3487330f729Sjoerg bool GlobalsAAResult::AnalyzeUsesOfPointer(Value *V,
3497330f729Sjoerg SmallPtrSetImpl<Function *> *Readers,
3507330f729Sjoerg SmallPtrSetImpl<Function *> *Writers,
3517330f729Sjoerg GlobalValue *OkayStoreDest) {
3527330f729Sjoerg if (!V->getType()->isPointerTy())
3537330f729Sjoerg return true;
3547330f729Sjoerg
3557330f729Sjoerg for (Use &U : V->uses()) {
3567330f729Sjoerg User *I = U.getUser();
3577330f729Sjoerg if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3587330f729Sjoerg if (Readers)
3597330f729Sjoerg Readers->insert(LI->getParent()->getParent());
3607330f729Sjoerg } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3617330f729Sjoerg if (V == SI->getOperand(1)) {
3627330f729Sjoerg if (Writers)
3637330f729Sjoerg Writers->insert(SI->getParent()->getParent());
3647330f729Sjoerg } else if (SI->getOperand(1) != OkayStoreDest) {
3657330f729Sjoerg return true; // Storing the pointer
3667330f729Sjoerg }
3677330f729Sjoerg } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {
3687330f729Sjoerg if (AnalyzeUsesOfPointer(I, Readers, Writers))
3697330f729Sjoerg return true;
370*82d56013Sjoerg } else if (Operator::getOpcode(I) == Instruction::BitCast ||
371*82d56013Sjoerg Operator::getOpcode(I) == Instruction::AddrSpaceCast) {
3727330f729Sjoerg if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest))
3737330f729Sjoerg return true;
3747330f729Sjoerg } else if (auto *Call = dyn_cast<CallBase>(I)) {
3757330f729Sjoerg // Make sure that this is just the function being called, not that it is
3767330f729Sjoerg // passing into the function.
3777330f729Sjoerg if (Call->isDataOperand(&U)) {
3787330f729Sjoerg // Detect calls to free.
3797330f729Sjoerg if (Call->isArgOperand(&U) &&
3807330f729Sjoerg isFreeCall(I, &GetTLI(*Call->getFunction()))) {
3817330f729Sjoerg if (Writers)
3827330f729Sjoerg Writers->insert(Call->getParent()->getParent());
3837330f729Sjoerg } else {
3847330f729Sjoerg return true; // Argument of an unknown call.
3857330f729Sjoerg }
3867330f729Sjoerg }
3877330f729Sjoerg } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
3887330f729Sjoerg if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
3897330f729Sjoerg return true; // Allow comparison against null.
3907330f729Sjoerg } else if (Constant *C = dyn_cast<Constant>(I)) {
3917330f729Sjoerg // Ignore constants which don't have any live uses.
3927330f729Sjoerg if (isa<GlobalValue>(C) || C->isConstantUsed())
3937330f729Sjoerg return true;
3947330f729Sjoerg } else {
3957330f729Sjoerg return true;
3967330f729Sjoerg }
3977330f729Sjoerg }
3987330f729Sjoerg
3997330f729Sjoerg return false;
4007330f729Sjoerg }
4017330f729Sjoerg
4027330f729Sjoerg /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
4037330f729Sjoerg /// which holds a pointer type. See if the global always points to non-aliased
4047330f729Sjoerg /// heap memory: that is, all initializers of the globals are allocations, and
4057330f729Sjoerg /// those allocations have no use other than initialization of the global.
4067330f729Sjoerg /// Further, all loads out of GV must directly use the memory, not store the
4077330f729Sjoerg /// pointer somewhere. If this is true, we consider the memory pointed to by
4087330f729Sjoerg /// GV to be owned by GV and can disambiguate other pointers from it.
AnalyzeIndirectGlobalMemory(GlobalVariable * GV)4097330f729Sjoerg bool GlobalsAAResult::AnalyzeIndirectGlobalMemory(GlobalVariable *GV) {
4107330f729Sjoerg // Keep track of values related to the allocation of the memory, f.e. the
4117330f729Sjoerg // value produced by the malloc call and any casts.
4127330f729Sjoerg std::vector<Value *> AllocRelatedValues;
4137330f729Sjoerg
4147330f729Sjoerg // If the initializer is a valid pointer, bail.
4157330f729Sjoerg if (Constant *C = GV->getInitializer())
4167330f729Sjoerg if (!C->isNullValue())
4177330f729Sjoerg return false;
4187330f729Sjoerg
4197330f729Sjoerg // Walk the user list of the global. If we find anything other than a direct
4207330f729Sjoerg // load or store, bail out.
4217330f729Sjoerg for (User *U : GV->users()) {
4227330f729Sjoerg if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
4237330f729Sjoerg // The pointer loaded from the global can only be used in simple ways:
4247330f729Sjoerg // we allow addressing of it and loading storing to it. We do *not* allow
4257330f729Sjoerg // storing the loaded pointer somewhere else or passing to a function.
4267330f729Sjoerg if (AnalyzeUsesOfPointer(LI))
4277330f729Sjoerg return false; // Loaded pointer escapes.
4287330f729Sjoerg // TODO: Could try some IP mod/ref of the loaded pointer.
4297330f729Sjoerg } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
4307330f729Sjoerg // Storing the global itself.
4317330f729Sjoerg if (SI->getOperand(0) == GV)
4327330f729Sjoerg return false;
4337330f729Sjoerg
4347330f729Sjoerg // If storing the null pointer, ignore it.
4357330f729Sjoerg if (isa<ConstantPointerNull>(SI->getOperand(0)))
4367330f729Sjoerg continue;
4377330f729Sjoerg
4387330f729Sjoerg // Check the value being stored.
439*82d56013Sjoerg Value *Ptr = getUnderlyingObject(SI->getOperand(0));
4407330f729Sjoerg
4417330f729Sjoerg if (!isAllocLikeFn(Ptr, &GetTLI(*SI->getFunction())))
4427330f729Sjoerg return false; // Too hard to analyze.
4437330f729Sjoerg
4447330f729Sjoerg // Analyze all uses of the allocation. If any of them are used in a
4457330f729Sjoerg // non-simple way (e.g. stored to another global) bail out.
4467330f729Sjoerg if (AnalyzeUsesOfPointer(Ptr, /*Readers*/ nullptr, /*Writers*/ nullptr,
4477330f729Sjoerg GV))
4487330f729Sjoerg return false; // Loaded pointer escapes.
4497330f729Sjoerg
4507330f729Sjoerg // Remember that this allocation is related to the indirect global.
4517330f729Sjoerg AllocRelatedValues.push_back(Ptr);
4527330f729Sjoerg } else {
4537330f729Sjoerg // Something complex, bail out.
4547330f729Sjoerg return false;
4557330f729Sjoerg }
4567330f729Sjoerg }
4577330f729Sjoerg
4587330f729Sjoerg // Okay, this is an indirect global. Remember all of the allocations for
4597330f729Sjoerg // this global in AllocsForIndirectGlobals.
4607330f729Sjoerg while (!AllocRelatedValues.empty()) {
4617330f729Sjoerg AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
4627330f729Sjoerg Handles.emplace_front(*this, AllocRelatedValues.back());
4637330f729Sjoerg Handles.front().I = Handles.begin();
4647330f729Sjoerg AllocRelatedValues.pop_back();
4657330f729Sjoerg }
4667330f729Sjoerg IndirectGlobals.insert(GV);
4677330f729Sjoerg Handles.emplace_front(*this, GV);
4687330f729Sjoerg Handles.front().I = Handles.begin();
4697330f729Sjoerg return true;
4707330f729Sjoerg }
4717330f729Sjoerg
CollectSCCMembership(CallGraph & CG)4727330f729Sjoerg void GlobalsAAResult::CollectSCCMembership(CallGraph &CG) {
4737330f729Sjoerg // We do a bottom-up SCC traversal of the call graph. In other words, we
4747330f729Sjoerg // visit all callees before callers (leaf-first).
4757330f729Sjoerg unsigned SCCID = 0;
4767330f729Sjoerg for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
4777330f729Sjoerg const std::vector<CallGraphNode *> &SCC = *I;
4787330f729Sjoerg assert(!SCC.empty() && "SCC with no functions?");
4797330f729Sjoerg
4807330f729Sjoerg for (auto *CGN : SCC)
4817330f729Sjoerg if (Function *F = CGN->getFunction())
4827330f729Sjoerg FunctionToSCCMap[F] = SCCID;
4837330f729Sjoerg ++SCCID;
4847330f729Sjoerg }
4857330f729Sjoerg }
4867330f729Sjoerg
4877330f729Sjoerg /// AnalyzeCallGraph - At this point, we know the functions where globals are
4887330f729Sjoerg /// immediately stored to and read from. Propagate this information up the call
4897330f729Sjoerg /// graph to all callers and compute the mod/ref info for all memory for each
4907330f729Sjoerg /// function.
AnalyzeCallGraph(CallGraph & CG,Module & M)4917330f729Sjoerg void GlobalsAAResult::AnalyzeCallGraph(CallGraph &CG, Module &M) {
4927330f729Sjoerg // We do a bottom-up SCC traversal of the call graph. In other words, we
4937330f729Sjoerg // visit all callees before callers (leaf-first).
4947330f729Sjoerg for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
4957330f729Sjoerg const std::vector<CallGraphNode *> &SCC = *I;
4967330f729Sjoerg assert(!SCC.empty() && "SCC with no functions?");
4977330f729Sjoerg
4987330f729Sjoerg Function *F = SCC[0]->getFunction();
4997330f729Sjoerg
5007330f729Sjoerg if (!F || !F->isDefinitionExact()) {
5017330f729Sjoerg // Calls externally or not exact - can't say anything useful. Remove any
5027330f729Sjoerg // existing function records (may have been created when scanning
5037330f729Sjoerg // globals).
5047330f729Sjoerg for (auto *Node : SCC)
5057330f729Sjoerg FunctionInfos.erase(Node->getFunction());
5067330f729Sjoerg continue;
5077330f729Sjoerg }
5087330f729Sjoerg
5097330f729Sjoerg FunctionInfo &FI = FunctionInfos[F];
5107330f729Sjoerg Handles.emplace_front(*this, F);
5117330f729Sjoerg Handles.front().I = Handles.begin();
5127330f729Sjoerg bool KnowNothing = false;
5137330f729Sjoerg
5147330f729Sjoerg // Collect the mod/ref properties due to called functions. We only compute
5157330f729Sjoerg // one mod-ref set.
5167330f729Sjoerg for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
5177330f729Sjoerg if (!F) {
5187330f729Sjoerg KnowNothing = true;
5197330f729Sjoerg break;
5207330f729Sjoerg }
5217330f729Sjoerg
5227330f729Sjoerg if (F->isDeclaration() || F->hasOptNone()) {
5237330f729Sjoerg // Try to get mod/ref behaviour from function attributes.
5247330f729Sjoerg if (F->doesNotAccessMemory()) {
5257330f729Sjoerg // Can't do better than that!
5267330f729Sjoerg } else if (F->onlyReadsMemory()) {
5277330f729Sjoerg FI.addModRefInfo(ModRefInfo::Ref);
5287330f729Sjoerg if (!F->isIntrinsic() && !F->onlyAccessesArgMemory())
5297330f729Sjoerg // This function might call back into the module and read a global -
5307330f729Sjoerg // consider every global as possibly being read by this function.
5317330f729Sjoerg FI.setMayReadAnyGlobal();
5327330f729Sjoerg } else {
5337330f729Sjoerg FI.addModRefInfo(ModRefInfo::ModRef);
534*82d56013Sjoerg if (!F->onlyAccessesArgMemory())
535*82d56013Sjoerg FI.setMayReadAnyGlobal();
536*82d56013Sjoerg if (!F->isIntrinsic()) {
537*82d56013Sjoerg KnowNothing = true;
538*82d56013Sjoerg break;
539*82d56013Sjoerg }
5407330f729Sjoerg }
5417330f729Sjoerg continue;
5427330f729Sjoerg }
5437330f729Sjoerg
5447330f729Sjoerg for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
5457330f729Sjoerg CI != E && !KnowNothing; ++CI)
5467330f729Sjoerg if (Function *Callee = CI->second->getFunction()) {
5477330f729Sjoerg if (FunctionInfo *CalleeFI = getFunctionInfo(Callee)) {
5487330f729Sjoerg // Propagate function effect up.
5497330f729Sjoerg FI.addFunctionInfo(*CalleeFI);
5507330f729Sjoerg } else {
5517330f729Sjoerg // Can't say anything about it. However, if it is inside our SCC,
5527330f729Sjoerg // then nothing needs to be done.
5537330f729Sjoerg CallGraphNode *CalleeNode = CG[Callee];
5547330f729Sjoerg if (!is_contained(SCC, CalleeNode))
5557330f729Sjoerg KnowNothing = true;
5567330f729Sjoerg }
5577330f729Sjoerg } else {
5587330f729Sjoerg KnowNothing = true;
5597330f729Sjoerg }
5607330f729Sjoerg }
5617330f729Sjoerg
5627330f729Sjoerg // If we can't say anything useful about this SCC, remove all SCC functions
5637330f729Sjoerg // from the FunctionInfos map.
5647330f729Sjoerg if (KnowNothing) {
5657330f729Sjoerg for (auto *Node : SCC)
5667330f729Sjoerg FunctionInfos.erase(Node->getFunction());
5677330f729Sjoerg continue;
5687330f729Sjoerg }
5697330f729Sjoerg
5707330f729Sjoerg // Scan the function bodies for explicit loads or stores.
5717330f729Sjoerg for (auto *Node : SCC) {
5727330f729Sjoerg if (isModAndRefSet(FI.getModRefInfo()))
5737330f729Sjoerg break; // The mod/ref lattice saturates here.
5747330f729Sjoerg
5757330f729Sjoerg // Don't prove any properties based on the implementation of an optnone
5767330f729Sjoerg // function. Function attributes were already used as a best approximation
5777330f729Sjoerg // above.
5787330f729Sjoerg if (Node->getFunction()->hasOptNone())
5797330f729Sjoerg continue;
5807330f729Sjoerg
5817330f729Sjoerg for (Instruction &I : instructions(Node->getFunction())) {
5827330f729Sjoerg if (isModAndRefSet(FI.getModRefInfo()))
5837330f729Sjoerg break; // The mod/ref lattice saturates here.
5847330f729Sjoerg
5857330f729Sjoerg // We handle calls specially because the graph-relevant aspects are
5867330f729Sjoerg // handled above.
5877330f729Sjoerg if (auto *Call = dyn_cast<CallBase>(&I)) {
5887330f729Sjoerg auto &TLI = GetTLI(*Node->getFunction());
5897330f729Sjoerg if (isAllocationFn(Call, &TLI) || isFreeCall(Call, &TLI)) {
5907330f729Sjoerg // FIXME: It is completely unclear why this is necessary and not
5917330f729Sjoerg // handled by the above graph code.
5927330f729Sjoerg FI.addModRefInfo(ModRefInfo::ModRef);
5937330f729Sjoerg } else if (Function *Callee = Call->getCalledFunction()) {
5947330f729Sjoerg // The callgraph doesn't include intrinsic calls.
5957330f729Sjoerg if (Callee->isIntrinsic()) {
5967330f729Sjoerg if (isa<DbgInfoIntrinsic>(Call))
5977330f729Sjoerg // Don't let dbg intrinsics affect alias info.
5987330f729Sjoerg continue;
5997330f729Sjoerg
6007330f729Sjoerg FunctionModRefBehavior Behaviour =
6017330f729Sjoerg AAResultBase::getModRefBehavior(Callee);
6027330f729Sjoerg FI.addModRefInfo(createModRefInfo(Behaviour));
6037330f729Sjoerg }
6047330f729Sjoerg }
6057330f729Sjoerg continue;
6067330f729Sjoerg }
6077330f729Sjoerg
6087330f729Sjoerg // All non-call instructions we use the primary predicates for whether
6097330f729Sjoerg // they read or write memory.
6107330f729Sjoerg if (I.mayReadFromMemory())
6117330f729Sjoerg FI.addModRefInfo(ModRefInfo::Ref);
6127330f729Sjoerg if (I.mayWriteToMemory())
6137330f729Sjoerg FI.addModRefInfo(ModRefInfo::Mod);
6147330f729Sjoerg }
6157330f729Sjoerg }
6167330f729Sjoerg
6177330f729Sjoerg if (!isModSet(FI.getModRefInfo()))
6187330f729Sjoerg ++NumReadMemFunctions;
6197330f729Sjoerg if (!isModOrRefSet(FI.getModRefInfo()))
6207330f729Sjoerg ++NumNoMemFunctions;
6217330f729Sjoerg
6227330f729Sjoerg // Finally, now that we know the full effect on this SCC, clone the
6237330f729Sjoerg // information to each function in the SCC.
6247330f729Sjoerg // FI is a reference into FunctionInfos, so copy it now so that it doesn't
6257330f729Sjoerg // get invalidated if DenseMap decides to re-hash.
6267330f729Sjoerg FunctionInfo CachedFI = FI;
6277330f729Sjoerg for (unsigned i = 1, e = SCC.size(); i != e; ++i)
6287330f729Sjoerg FunctionInfos[SCC[i]->getFunction()] = CachedFI;
6297330f729Sjoerg }
6307330f729Sjoerg }
6317330f729Sjoerg
6327330f729Sjoerg // GV is a non-escaping global. V is a pointer address that has been loaded from.
6337330f729Sjoerg // If we can prove that V must escape, we can conclude that a load from V cannot
6347330f729Sjoerg // alias GV.
isNonEscapingGlobalNoAliasWithLoad(const GlobalValue * GV,const Value * V,int & Depth,const DataLayout & DL)6357330f729Sjoerg static bool isNonEscapingGlobalNoAliasWithLoad(const GlobalValue *GV,
6367330f729Sjoerg const Value *V,
6377330f729Sjoerg int &Depth,
6387330f729Sjoerg const DataLayout &DL) {
6397330f729Sjoerg SmallPtrSet<const Value *, 8> Visited;
6407330f729Sjoerg SmallVector<const Value *, 8> Inputs;
6417330f729Sjoerg Visited.insert(V);
6427330f729Sjoerg Inputs.push_back(V);
6437330f729Sjoerg do {
6447330f729Sjoerg const Value *Input = Inputs.pop_back_val();
6457330f729Sjoerg
6467330f729Sjoerg if (isa<GlobalValue>(Input) || isa<Argument>(Input) || isa<CallInst>(Input) ||
6477330f729Sjoerg isa<InvokeInst>(Input))
6487330f729Sjoerg // Arguments to functions or returns from functions are inherently
6497330f729Sjoerg // escaping, so we can immediately classify those as not aliasing any
6507330f729Sjoerg // non-addr-taken globals.
6517330f729Sjoerg //
6527330f729Sjoerg // (Transitive) loads from a global are also safe - if this aliased
6537330f729Sjoerg // another global, its address would escape, so no alias.
6547330f729Sjoerg continue;
6557330f729Sjoerg
6567330f729Sjoerg // Recurse through a limited number of selects, loads and PHIs. This is an
6577330f729Sjoerg // arbitrary depth of 4, lower numbers could be used to fix compile time
6587330f729Sjoerg // issues if needed, but this is generally expected to be only be important
6597330f729Sjoerg // for small depths.
6607330f729Sjoerg if (++Depth > 4)
6617330f729Sjoerg return false;
6627330f729Sjoerg
6637330f729Sjoerg if (auto *LI = dyn_cast<LoadInst>(Input)) {
664*82d56013Sjoerg Inputs.push_back(getUnderlyingObject(LI->getPointerOperand()));
6657330f729Sjoerg continue;
6667330f729Sjoerg }
6677330f729Sjoerg if (auto *SI = dyn_cast<SelectInst>(Input)) {
668*82d56013Sjoerg const Value *LHS = getUnderlyingObject(SI->getTrueValue());
669*82d56013Sjoerg const Value *RHS = getUnderlyingObject(SI->getFalseValue());
6707330f729Sjoerg if (Visited.insert(LHS).second)
6717330f729Sjoerg Inputs.push_back(LHS);
6727330f729Sjoerg if (Visited.insert(RHS).second)
6737330f729Sjoerg Inputs.push_back(RHS);
6747330f729Sjoerg continue;
6757330f729Sjoerg }
6767330f729Sjoerg if (auto *PN = dyn_cast<PHINode>(Input)) {
6777330f729Sjoerg for (const Value *Op : PN->incoming_values()) {
678*82d56013Sjoerg Op = getUnderlyingObject(Op);
6797330f729Sjoerg if (Visited.insert(Op).second)
6807330f729Sjoerg Inputs.push_back(Op);
6817330f729Sjoerg }
6827330f729Sjoerg continue;
6837330f729Sjoerg }
6847330f729Sjoerg
6857330f729Sjoerg return false;
6867330f729Sjoerg } while (!Inputs.empty());
6877330f729Sjoerg
6887330f729Sjoerg // All inputs were known to be no-alias.
6897330f729Sjoerg return true;
6907330f729Sjoerg }
6917330f729Sjoerg
6927330f729Sjoerg // There are particular cases where we can conclude no-alias between
6937330f729Sjoerg // a non-addr-taken global and some other underlying object. Specifically,
6947330f729Sjoerg // a non-addr-taken global is known to not be escaped from any function. It is
6957330f729Sjoerg // also incorrect for a transformation to introduce an escape of a global in
6967330f729Sjoerg // a way that is observable when it was not there previously. One function
6977330f729Sjoerg // being transformed to introduce an escape which could possibly be observed
6987330f729Sjoerg // (via loading from a global or the return value for example) within another
6997330f729Sjoerg // function is never safe. If the observation is made through non-atomic
7007330f729Sjoerg // operations on different threads, it is a data-race and UB. If the
7017330f729Sjoerg // observation is well defined, by being observed the transformation would have
7027330f729Sjoerg // changed program behavior by introducing the observed escape, making it an
7037330f729Sjoerg // invalid transform.
7047330f729Sjoerg //
7057330f729Sjoerg // This property does require that transformations which *temporarily* escape
7067330f729Sjoerg // a global that was not previously escaped, prior to restoring it, cannot rely
7077330f729Sjoerg // on the results of GMR::alias. This seems a reasonable restriction, although
7087330f729Sjoerg // currently there is no way to enforce it. There is also no realistic
7097330f729Sjoerg // optimization pass that would make this mistake. The closest example is
7107330f729Sjoerg // a transformation pass which does reg2mem of SSA values but stores them into
7117330f729Sjoerg // global variables temporarily before restoring the global variable's value.
7127330f729Sjoerg // This could be useful to expose "benign" races for example. However, it seems
7137330f729Sjoerg // reasonable to require that a pass which introduces escapes of global
7147330f729Sjoerg // variables in this way to either not trust AA results while the escape is
7157330f729Sjoerg // active, or to be forced to operate as a module pass that cannot co-exist
7167330f729Sjoerg // with an alias analysis such as GMR.
isNonEscapingGlobalNoAlias(const GlobalValue * GV,const Value * V)7177330f729Sjoerg bool GlobalsAAResult::isNonEscapingGlobalNoAlias(const GlobalValue *GV,
7187330f729Sjoerg const Value *V) {
7197330f729Sjoerg // In order to know that the underlying object cannot alias the
7207330f729Sjoerg // non-addr-taken global, we must know that it would have to be an escape.
7217330f729Sjoerg // Thus if the underlying object is a function argument, a load from
7227330f729Sjoerg // a global, or the return of a function, it cannot alias. We can also
7237330f729Sjoerg // recurse through PHI nodes and select nodes provided all of their inputs
7247330f729Sjoerg // resolve to one of these known-escaping roots.
7257330f729Sjoerg SmallPtrSet<const Value *, 8> Visited;
7267330f729Sjoerg SmallVector<const Value *, 8> Inputs;
7277330f729Sjoerg Visited.insert(V);
7287330f729Sjoerg Inputs.push_back(V);
7297330f729Sjoerg int Depth = 0;
7307330f729Sjoerg do {
7317330f729Sjoerg const Value *Input = Inputs.pop_back_val();
7327330f729Sjoerg
7337330f729Sjoerg if (auto *InputGV = dyn_cast<GlobalValue>(Input)) {
7347330f729Sjoerg // If one input is the very global we're querying against, then we can't
7357330f729Sjoerg // conclude no-alias.
7367330f729Sjoerg if (InputGV == GV)
7377330f729Sjoerg return false;
7387330f729Sjoerg
7397330f729Sjoerg // Distinct GlobalVariables never alias, unless overriden or zero-sized.
7407330f729Sjoerg // FIXME: The condition can be refined, but be conservative for now.
7417330f729Sjoerg auto *GVar = dyn_cast<GlobalVariable>(GV);
7427330f729Sjoerg auto *InputGVar = dyn_cast<GlobalVariable>(InputGV);
7437330f729Sjoerg if (GVar && InputGVar &&
7447330f729Sjoerg !GVar->isDeclaration() && !InputGVar->isDeclaration() &&
7457330f729Sjoerg !GVar->isInterposable() && !InputGVar->isInterposable()) {
7467330f729Sjoerg Type *GVType = GVar->getInitializer()->getType();
7477330f729Sjoerg Type *InputGVType = InputGVar->getInitializer()->getType();
7487330f729Sjoerg if (GVType->isSized() && InputGVType->isSized() &&
7497330f729Sjoerg (DL.getTypeAllocSize(GVType) > 0) &&
7507330f729Sjoerg (DL.getTypeAllocSize(InputGVType) > 0))
7517330f729Sjoerg continue;
7527330f729Sjoerg }
7537330f729Sjoerg
7547330f729Sjoerg // Conservatively return false, even though we could be smarter
7557330f729Sjoerg // (e.g. look through GlobalAliases).
7567330f729Sjoerg return false;
7577330f729Sjoerg }
7587330f729Sjoerg
7597330f729Sjoerg if (isa<Argument>(Input) || isa<CallInst>(Input) ||
7607330f729Sjoerg isa<InvokeInst>(Input)) {
7617330f729Sjoerg // Arguments to functions or returns from functions are inherently
7627330f729Sjoerg // escaping, so we can immediately classify those as not aliasing any
7637330f729Sjoerg // non-addr-taken globals.
7647330f729Sjoerg continue;
7657330f729Sjoerg }
7667330f729Sjoerg
7677330f729Sjoerg // Recurse through a limited number of selects, loads and PHIs. This is an
7687330f729Sjoerg // arbitrary depth of 4, lower numbers could be used to fix compile time
7697330f729Sjoerg // issues if needed, but this is generally expected to be only be important
7707330f729Sjoerg // for small depths.
7717330f729Sjoerg if (++Depth > 4)
7727330f729Sjoerg return false;
7737330f729Sjoerg
7747330f729Sjoerg if (auto *LI = dyn_cast<LoadInst>(Input)) {
7757330f729Sjoerg // A pointer loaded from a global would have been captured, and we know
7767330f729Sjoerg // that the global is non-escaping, so no alias.
777*82d56013Sjoerg const Value *Ptr = getUnderlyingObject(LI->getPointerOperand());
7787330f729Sjoerg if (isNonEscapingGlobalNoAliasWithLoad(GV, Ptr, Depth, DL))
7797330f729Sjoerg // The load does not alias with GV.
7807330f729Sjoerg continue;
7817330f729Sjoerg // Otherwise, a load could come from anywhere, so bail.
7827330f729Sjoerg return false;
7837330f729Sjoerg }
7847330f729Sjoerg if (auto *SI = dyn_cast<SelectInst>(Input)) {
785*82d56013Sjoerg const Value *LHS = getUnderlyingObject(SI->getTrueValue());
786*82d56013Sjoerg const Value *RHS = getUnderlyingObject(SI->getFalseValue());
7877330f729Sjoerg if (Visited.insert(LHS).second)
7887330f729Sjoerg Inputs.push_back(LHS);
7897330f729Sjoerg if (Visited.insert(RHS).second)
7907330f729Sjoerg Inputs.push_back(RHS);
7917330f729Sjoerg continue;
7927330f729Sjoerg }
7937330f729Sjoerg if (auto *PN = dyn_cast<PHINode>(Input)) {
7947330f729Sjoerg for (const Value *Op : PN->incoming_values()) {
795*82d56013Sjoerg Op = getUnderlyingObject(Op);
7967330f729Sjoerg if (Visited.insert(Op).second)
7977330f729Sjoerg Inputs.push_back(Op);
7987330f729Sjoerg }
7997330f729Sjoerg continue;
8007330f729Sjoerg }
8017330f729Sjoerg
8027330f729Sjoerg // FIXME: It would be good to handle other obvious no-alias cases here, but
8037330f729Sjoerg // it isn't clear how to do so reasonably without building a small version
8047330f729Sjoerg // of BasicAA into this code. We could recurse into AAResultBase::alias
8057330f729Sjoerg // here but that seems likely to go poorly as we're inside the
8067330f729Sjoerg // implementation of such a query. Until then, just conservatively return
8077330f729Sjoerg // false.
8087330f729Sjoerg return false;
8097330f729Sjoerg } while (!Inputs.empty());
8107330f729Sjoerg
8117330f729Sjoerg // If all the inputs to V were definitively no-alias, then V is no-alias.
8127330f729Sjoerg return true;
8137330f729Sjoerg }
8147330f729Sjoerg
invalidate(Module &,const PreservedAnalyses & PA,ModuleAnalysisManager::Invalidator &)815*82d56013Sjoerg bool GlobalsAAResult::invalidate(Module &, const PreservedAnalyses &PA,
816*82d56013Sjoerg ModuleAnalysisManager::Invalidator &) {
817*82d56013Sjoerg // Check whether the analysis has been explicitly invalidated. Otherwise, it's
818*82d56013Sjoerg // stateless and remains preserved.
819*82d56013Sjoerg auto PAC = PA.getChecker<GlobalsAA>();
820*82d56013Sjoerg return !PAC.preservedWhenStateless();
821*82d56013Sjoerg }
822*82d56013Sjoerg
8237330f729Sjoerg /// alias - If one of the pointers is to a global that we are tracking, and the
8247330f729Sjoerg /// other is some random pointer, we know there cannot be an alias, because the
8257330f729Sjoerg /// address of the global isn't taken.
alias(const MemoryLocation & LocA,const MemoryLocation & LocB,AAQueryInfo & AAQI)8267330f729Sjoerg AliasResult GlobalsAAResult::alias(const MemoryLocation &LocA,
8277330f729Sjoerg const MemoryLocation &LocB,
8287330f729Sjoerg AAQueryInfo &AAQI) {
8297330f729Sjoerg // Get the base object these pointers point to.
830*82d56013Sjoerg const Value *UV1 =
831*82d56013Sjoerg getUnderlyingObject(LocA.Ptr->stripPointerCastsForAliasAnalysis());
832*82d56013Sjoerg const Value *UV2 =
833*82d56013Sjoerg getUnderlyingObject(LocB.Ptr->stripPointerCastsForAliasAnalysis());
8347330f729Sjoerg
8357330f729Sjoerg // If either of the underlying values is a global, they may be non-addr-taken
8367330f729Sjoerg // globals, which we can answer queries about.
8377330f729Sjoerg const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
8387330f729Sjoerg const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
8397330f729Sjoerg if (GV1 || GV2) {
8407330f729Sjoerg // If the global's address is taken, pretend we don't know it's a pointer to
8417330f729Sjoerg // the global.
8427330f729Sjoerg if (GV1 && !NonAddressTakenGlobals.count(GV1))
8437330f729Sjoerg GV1 = nullptr;
8447330f729Sjoerg if (GV2 && !NonAddressTakenGlobals.count(GV2))
8457330f729Sjoerg GV2 = nullptr;
8467330f729Sjoerg
8477330f729Sjoerg // If the two pointers are derived from two different non-addr-taken
8487330f729Sjoerg // globals we know these can't alias.
8497330f729Sjoerg if (GV1 && GV2 && GV1 != GV2)
850*82d56013Sjoerg return AliasResult::NoAlias;
8517330f729Sjoerg
8527330f729Sjoerg // If one is and the other isn't, it isn't strictly safe but we can fake
8537330f729Sjoerg // this result if necessary for performance. This does not appear to be
8547330f729Sjoerg // a common problem in practice.
8557330f729Sjoerg if (EnableUnsafeGlobalsModRefAliasResults)
8567330f729Sjoerg if ((GV1 || GV2) && GV1 != GV2)
857*82d56013Sjoerg return AliasResult::NoAlias;
8587330f729Sjoerg
8597330f729Sjoerg // Check for a special case where a non-escaping global can be used to
8607330f729Sjoerg // conclude no-alias.
8617330f729Sjoerg if ((GV1 || GV2) && GV1 != GV2) {
8627330f729Sjoerg const GlobalValue *GV = GV1 ? GV1 : GV2;
8637330f729Sjoerg const Value *UV = GV1 ? UV2 : UV1;
8647330f729Sjoerg if (isNonEscapingGlobalNoAlias(GV, UV))
865*82d56013Sjoerg return AliasResult::NoAlias;
8667330f729Sjoerg }
8677330f729Sjoerg
8687330f729Sjoerg // Otherwise if they are both derived from the same addr-taken global, we
8697330f729Sjoerg // can't know the two accesses don't overlap.
8707330f729Sjoerg }
8717330f729Sjoerg
8727330f729Sjoerg // These pointers may be based on the memory owned by an indirect global. If
8737330f729Sjoerg // so, we may be able to handle this. First check to see if the base pointer
8747330f729Sjoerg // is a direct load from an indirect global.
8757330f729Sjoerg GV1 = GV2 = nullptr;
8767330f729Sjoerg if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
8777330f729Sjoerg if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
8787330f729Sjoerg if (IndirectGlobals.count(GV))
8797330f729Sjoerg GV1 = GV;
8807330f729Sjoerg if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
8817330f729Sjoerg if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
8827330f729Sjoerg if (IndirectGlobals.count(GV))
8837330f729Sjoerg GV2 = GV;
8847330f729Sjoerg
8857330f729Sjoerg // These pointers may also be from an allocation for the indirect global. If
8867330f729Sjoerg // so, also handle them.
8877330f729Sjoerg if (!GV1)
8887330f729Sjoerg GV1 = AllocsForIndirectGlobals.lookup(UV1);
8897330f729Sjoerg if (!GV2)
8907330f729Sjoerg GV2 = AllocsForIndirectGlobals.lookup(UV2);
8917330f729Sjoerg
8927330f729Sjoerg // Now that we know whether the two pointers are related to indirect globals,
8937330f729Sjoerg // use this to disambiguate the pointers. If the pointers are based on
8947330f729Sjoerg // different indirect globals they cannot alias.
8957330f729Sjoerg if (GV1 && GV2 && GV1 != GV2)
896*82d56013Sjoerg return AliasResult::NoAlias;
8977330f729Sjoerg
8987330f729Sjoerg // If one is based on an indirect global and the other isn't, it isn't
8997330f729Sjoerg // strictly safe but we can fake this result if necessary for performance.
9007330f729Sjoerg // This does not appear to be a common problem in practice.
9017330f729Sjoerg if (EnableUnsafeGlobalsModRefAliasResults)
9027330f729Sjoerg if ((GV1 || GV2) && GV1 != GV2)
903*82d56013Sjoerg return AliasResult::NoAlias;
9047330f729Sjoerg
9057330f729Sjoerg return AAResultBase::alias(LocA, LocB, AAQI);
9067330f729Sjoerg }
9077330f729Sjoerg
getModRefInfoForArgument(const CallBase * Call,const GlobalValue * GV,AAQueryInfo & AAQI)9087330f729Sjoerg ModRefInfo GlobalsAAResult::getModRefInfoForArgument(const CallBase *Call,
9097330f729Sjoerg const GlobalValue *GV,
9107330f729Sjoerg AAQueryInfo &AAQI) {
9117330f729Sjoerg if (Call->doesNotAccessMemory())
9127330f729Sjoerg return ModRefInfo::NoModRef;
9137330f729Sjoerg ModRefInfo ConservativeResult =
9147330f729Sjoerg Call->onlyReadsMemory() ? ModRefInfo::Ref : ModRefInfo::ModRef;
9157330f729Sjoerg
9167330f729Sjoerg // Iterate through all the arguments to the called function. If any argument
9177330f729Sjoerg // is based on GV, return the conservative result.
9187330f729Sjoerg for (auto &A : Call->args()) {
9197330f729Sjoerg SmallVector<const Value*, 4> Objects;
920*82d56013Sjoerg getUnderlyingObjects(A, Objects);
9217330f729Sjoerg
9227330f729Sjoerg // All objects must be identified.
9237330f729Sjoerg if (!all_of(Objects, isIdentifiedObject) &&
9247330f729Sjoerg // Try ::alias to see if all objects are known not to alias GV.
9257330f729Sjoerg !all_of(Objects, [&](const Value *V) {
926*82d56013Sjoerg return this->alias(MemoryLocation::getBeforeOrAfter(V),
927*82d56013Sjoerg MemoryLocation::getBeforeOrAfter(GV),
928*82d56013Sjoerg AAQI) == AliasResult::NoAlias;
9297330f729Sjoerg }))
9307330f729Sjoerg return ConservativeResult;
9317330f729Sjoerg
9327330f729Sjoerg if (is_contained(Objects, GV))
9337330f729Sjoerg return ConservativeResult;
9347330f729Sjoerg }
9357330f729Sjoerg
9367330f729Sjoerg // We identified all objects in the argument list, and none of them were GV.
9377330f729Sjoerg return ModRefInfo::NoModRef;
9387330f729Sjoerg }
9397330f729Sjoerg
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc,AAQueryInfo & AAQI)9407330f729Sjoerg ModRefInfo GlobalsAAResult::getModRefInfo(const CallBase *Call,
9417330f729Sjoerg const MemoryLocation &Loc,
9427330f729Sjoerg AAQueryInfo &AAQI) {
9437330f729Sjoerg ModRefInfo Known = ModRefInfo::ModRef;
9447330f729Sjoerg
9457330f729Sjoerg // If we are asking for mod/ref info of a direct call with a pointer to a
9467330f729Sjoerg // global we are tracking, return information if we have it.
9477330f729Sjoerg if (const GlobalValue *GV =
948*82d56013Sjoerg dyn_cast<GlobalValue>(getUnderlyingObject(Loc.Ptr)))
949*82d56013Sjoerg // If GV is internal to this IR and there is no function with local linkage
950*82d56013Sjoerg // that has had their address taken, keep looking for a tighter ModRefInfo.
951*82d56013Sjoerg if (GV->hasLocalLinkage() && !UnknownFunctionsWithLocalLinkage)
9527330f729Sjoerg if (const Function *F = Call->getCalledFunction())
9537330f729Sjoerg if (NonAddressTakenGlobals.count(GV))
9547330f729Sjoerg if (const FunctionInfo *FI = getFunctionInfo(F))
9557330f729Sjoerg Known = unionModRef(FI->getModRefInfoForGlobal(*GV),
9567330f729Sjoerg getModRefInfoForArgument(Call, GV, AAQI));
9577330f729Sjoerg
9587330f729Sjoerg if (!isModOrRefSet(Known))
9597330f729Sjoerg return ModRefInfo::NoModRef; // No need to query other mod/ref analyses
9607330f729Sjoerg return intersectModRef(Known, AAResultBase::getModRefInfo(Call, Loc, AAQI));
9617330f729Sjoerg }
9627330f729Sjoerg
GlobalsAAResult(const DataLayout & DL,std::function<const TargetLibraryInfo & (Function & F)> GetTLI)9637330f729Sjoerg GlobalsAAResult::GlobalsAAResult(
9647330f729Sjoerg const DataLayout &DL,
9657330f729Sjoerg std::function<const TargetLibraryInfo &(Function &F)> GetTLI)
9667330f729Sjoerg : AAResultBase(), DL(DL), GetTLI(std::move(GetTLI)) {}
9677330f729Sjoerg
GlobalsAAResult(GlobalsAAResult && Arg)9687330f729Sjoerg GlobalsAAResult::GlobalsAAResult(GlobalsAAResult &&Arg)
9697330f729Sjoerg : AAResultBase(std::move(Arg)), DL(Arg.DL), GetTLI(std::move(Arg.GetTLI)),
9707330f729Sjoerg NonAddressTakenGlobals(std::move(Arg.NonAddressTakenGlobals)),
9717330f729Sjoerg IndirectGlobals(std::move(Arg.IndirectGlobals)),
9727330f729Sjoerg AllocsForIndirectGlobals(std::move(Arg.AllocsForIndirectGlobals)),
9737330f729Sjoerg FunctionInfos(std::move(Arg.FunctionInfos)),
9747330f729Sjoerg Handles(std::move(Arg.Handles)) {
9757330f729Sjoerg // Update the parent for each DeletionCallbackHandle.
9767330f729Sjoerg for (auto &H : Handles) {
9777330f729Sjoerg assert(H.GAR == &Arg);
9787330f729Sjoerg H.GAR = this;
9797330f729Sjoerg }
9807330f729Sjoerg }
9817330f729Sjoerg
~GlobalsAAResult()9827330f729Sjoerg GlobalsAAResult::~GlobalsAAResult() {}
9837330f729Sjoerg
analyzeModule(Module & M,std::function<const TargetLibraryInfo & (Function & F)> GetTLI,CallGraph & CG)9847330f729Sjoerg /*static*/ GlobalsAAResult GlobalsAAResult::analyzeModule(
9857330f729Sjoerg Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
9867330f729Sjoerg CallGraph &CG) {
9877330f729Sjoerg GlobalsAAResult Result(M.getDataLayout(), GetTLI);
9887330f729Sjoerg
9897330f729Sjoerg // Discover which functions aren't recursive, to feed into AnalyzeGlobals.
9907330f729Sjoerg Result.CollectSCCMembership(CG);
9917330f729Sjoerg
9927330f729Sjoerg // Find non-addr taken globals.
9937330f729Sjoerg Result.AnalyzeGlobals(M);
9947330f729Sjoerg
9957330f729Sjoerg // Propagate on CG.
9967330f729Sjoerg Result.AnalyzeCallGraph(CG, M);
9977330f729Sjoerg
9987330f729Sjoerg return Result;
9997330f729Sjoerg }
10007330f729Sjoerg
10017330f729Sjoerg AnalysisKey GlobalsAA::Key;
10027330f729Sjoerg
run(Module & M,ModuleAnalysisManager & AM)10037330f729Sjoerg GlobalsAAResult GlobalsAA::run(Module &M, ModuleAnalysisManager &AM) {
10047330f729Sjoerg FunctionAnalysisManager &FAM =
10057330f729Sjoerg AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
10067330f729Sjoerg auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
10077330f729Sjoerg return FAM.getResult<TargetLibraryAnalysis>(F);
10087330f729Sjoerg };
10097330f729Sjoerg return GlobalsAAResult::analyzeModule(M, GetTLI,
10107330f729Sjoerg AM.getResult<CallGraphAnalysis>(M));
10117330f729Sjoerg }
10127330f729Sjoerg
10137330f729Sjoerg char GlobalsAAWrapperPass::ID = 0;
10147330f729Sjoerg INITIALIZE_PASS_BEGIN(GlobalsAAWrapperPass, "globals-aa",
10157330f729Sjoerg "Globals Alias Analysis", false, true)
INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)10167330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
10177330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10187330f729Sjoerg INITIALIZE_PASS_END(GlobalsAAWrapperPass, "globals-aa",
10197330f729Sjoerg "Globals Alias Analysis", false, true)
10207330f729Sjoerg
10217330f729Sjoerg ModulePass *llvm::createGlobalsAAWrapperPass() {
10227330f729Sjoerg return new GlobalsAAWrapperPass();
10237330f729Sjoerg }
10247330f729Sjoerg
GlobalsAAWrapperPass()10257330f729Sjoerg GlobalsAAWrapperPass::GlobalsAAWrapperPass() : ModulePass(ID) {
10267330f729Sjoerg initializeGlobalsAAWrapperPassPass(*PassRegistry::getPassRegistry());
10277330f729Sjoerg }
10287330f729Sjoerg
runOnModule(Module & M)10297330f729Sjoerg bool GlobalsAAWrapperPass::runOnModule(Module &M) {
10307330f729Sjoerg auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
10317330f729Sjoerg return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
10327330f729Sjoerg };
10337330f729Sjoerg Result.reset(new GlobalsAAResult(GlobalsAAResult::analyzeModule(
10347330f729Sjoerg M, GetTLI, getAnalysis<CallGraphWrapperPass>().getCallGraph())));
10357330f729Sjoerg return false;
10367330f729Sjoerg }
10377330f729Sjoerg
doFinalization(Module & M)10387330f729Sjoerg bool GlobalsAAWrapperPass::doFinalization(Module &M) {
10397330f729Sjoerg Result.reset();
10407330f729Sjoerg return false;
10417330f729Sjoerg }
10427330f729Sjoerg
getAnalysisUsage(AnalysisUsage & AU) const10437330f729Sjoerg void GlobalsAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10447330f729Sjoerg AU.setPreservesAll();
10457330f729Sjoerg AU.addRequired<CallGraphWrapperPass>();
10467330f729Sjoerg AU.addRequired<TargetLibraryInfoWrapperPass>();
10477330f729Sjoerg }
1048