xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/ModuleSummaryAnalysis.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
10b57cec5SDimitry Andric //===- ModuleSummaryAnalysis.cpp - Module summary index builder -----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass builds a ModuleSummaryIndex object for the module, to be written
100b57cec5SDimitry Andric // to bitcode or LLVM assembly.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/Analysis/ModuleSummaryAnalysis.h"
150b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
160b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
170b57cec5SDimitry Andric #include "llvm/ADT/MapVector.h"
180b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
220b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
27bdd1243dSDimitry Andric #include "llvm/Analysis/MemoryProfileInfo.h"
280b57cec5SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
295ffd83dbSDimitry Andric #include "llvm/Analysis/StackSafetyAnalysis.h"
300b57cec5SDimitry Andric #include "llvm/Analysis/TypeMetadataUtils.h"
310b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
320b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
330b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
340b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
350b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
360b57cec5SDimitry Andric #include "llvm/IR/Function.h"
370b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
380b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
390b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
400b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
410b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
420b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
430b57cec5SDimitry Andric #include "llvm/IR/Module.h"
440b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
450b57cec5SDimitry Andric #include "llvm/IR/Use.h"
460b57cec5SDimitry Andric #include "llvm/IR/User.h"
47480093f4SDimitry Andric #include "llvm/InitializePasses.h"
480b57cec5SDimitry Andric #include "llvm/Object/ModuleSymbolTable.h"
490b57cec5SDimitry Andric #include "llvm/Object/SymbolicFile.h"
500b57cec5SDimitry Andric #include "llvm/Pass.h"
510b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
520b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
53fe6060f1SDimitry Andric #include "llvm/Support/FileSystem.h"
540b57cec5SDimitry Andric #include <algorithm>
550b57cec5SDimitry Andric #include <cassert>
560b57cec5SDimitry Andric #include <cstdint>
570b57cec5SDimitry Andric #include <vector>
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric using namespace llvm;
60bdd1243dSDimitry Andric using namespace llvm::memprof;
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric #define DEBUG_TYPE "module-summary-analysis"
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric // Option to force edges cold which will block importing when the
650b57cec5SDimitry Andric // -import-cold-multiplier is set to 0. Useful for debugging.
66bdd1243dSDimitry Andric namespace llvm {
670b57cec5SDimitry Andric FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold =
680b57cec5SDimitry Andric     FunctionSummary::FSHT_None;
69bdd1243dSDimitry Andric } // namespace llvm
70bdd1243dSDimitry Andric 
71bdd1243dSDimitry Andric static cl::opt<FunctionSummary::ForceSummaryHotnessType, true> FSEC(
720b57cec5SDimitry Andric     "force-summary-edges-cold", cl::Hidden, cl::location(ForceSummaryEdgesCold),
730b57cec5SDimitry Andric     cl::desc("Force all edges in the function summary to cold"),
740b57cec5SDimitry Andric     cl::values(clEnumValN(FunctionSummary::FSHT_None, "none", "None."),
750b57cec5SDimitry Andric                clEnumValN(FunctionSummary::FSHT_AllNonCritical,
760b57cec5SDimitry Andric                           "all-non-critical", "All non-critical edges."),
770b57cec5SDimitry Andric                clEnumValN(FunctionSummary::FSHT_All, "all", "All edges.")));
780b57cec5SDimitry Andric 
79bdd1243dSDimitry Andric static cl::opt<std::string> ModuleSummaryDotFile(
80bdd1243dSDimitry Andric     "module-summary-dot-file", cl::Hidden, cl::value_desc("filename"),
81bdd1243dSDimitry Andric     cl::desc("File to emit dot graph of new summary into"));
820b57cec5SDimitry Andric 
83*06c3fb27SDimitry Andric extern cl::opt<bool> ScalePartialSampleProfileWorkingSetSize;
84*06c3fb27SDimitry Andric 
850b57cec5SDimitry Andric // Walk through the operands of a given User via worklist iteration and populate
860b57cec5SDimitry Andric // the set of GlobalValue references encountered. Invoked either on an
870b57cec5SDimitry Andric // Instruction or a GlobalVariable (which walks its initializer).
880b57cec5SDimitry Andric // Return true if any of the operands contains blockaddress. This is important
890b57cec5SDimitry Andric // to know when computing summary for global var, because if global variable
900b57cec5SDimitry Andric // references basic block address we can't import it separately from function
910b57cec5SDimitry Andric // containing that basic block. For simplicity we currently don't import such
920b57cec5SDimitry Andric // global vars at all. When importing function we aren't interested if any
930b57cec5SDimitry Andric // instruction in it takes an address of any basic block, because instruction
940b57cec5SDimitry Andric // can only take an address of basic block located in the same function.
950b57cec5SDimitry Andric static bool findRefEdges(ModuleSummaryIndex &Index, const User *CurUser,
960b57cec5SDimitry Andric                          SetVector<ValueInfo> &RefEdges,
970b57cec5SDimitry Andric                          SmallPtrSet<const User *, 8> &Visited) {
980b57cec5SDimitry Andric   bool HasBlockAddress = false;
990b57cec5SDimitry Andric   SmallVector<const User *, 32> Worklist;
100fe6060f1SDimitry Andric   if (Visited.insert(CurUser).second)
1010b57cec5SDimitry Andric     Worklist.push_back(CurUser);
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric   while (!Worklist.empty()) {
1040b57cec5SDimitry Andric     const User *U = Worklist.pop_back_val();
1055ffd83dbSDimitry Andric     const auto *CB = dyn_cast<CallBase>(U);
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric     for (const auto &OI : U->operands()) {
1080b57cec5SDimitry Andric       const User *Operand = dyn_cast<User>(OI);
1090b57cec5SDimitry Andric       if (!Operand)
1100b57cec5SDimitry Andric         continue;
1110b57cec5SDimitry Andric       if (isa<BlockAddress>(Operand)) {
1120b57cec5SDimitry Andric         HasBlockAddress = true;
1130b57cec5SDimitry Andric         continue;
1140b57cec5SDimitry Andric       }
1150b57cec5SDimitry Andric       if (auto *GV = dyn_cast<GlobalValue>(Operand)) {
1160b57cec5SDimitry Andric         // We have a reference to a global value. This should be added to
1170b57cec5SDimitry Andric         // the reference set unless it is a callee. Callees are handled
1180b57cec5SDimitry Andric         // specially by WriteFunction and are added to a separate list.
1195ffd83dbSDimitry Andric         if (!(CB && CB->isCallee(&OI)))
1200b57cec5SDimitry Andric           RefEdges.insert(Index.getOrInsertValueInfo(GV));
1210b57cec5SDimitry Andric         continue;
1220b57cec5SDimitry Andric       }
123fe6060f1SDimitry Andric       if (Visited.insert(Operand).second)
1240b57cec5SDimitry Andric         Worklist.push_back(Operand);
1250b57cec5SDimitry Andric     }
1260b57cec5SDimitry Andric   }
1270b57cec5SDimitry Andric   return HasBlockAddress;
1280b57cec5SDimitry Andric }
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric static CalleeInfo::HotnessType getHotness(uint64_t ProfileCount,
1310b57cec5SDimitry Andric                                           ProfileSummaryInfo *PSI) {
1320b57cec5SDimitry Andric   if (!PSI)
1330b57cec5SDimitry Andric     return CalleeInfo::HotnessType::Unknown;
1340b57cec5SDimitry Andric   if (PSI->isHotCount(ProfileCount))
1350b57cec5SDimitry Andric     return CalleeInfo::HotnessType::Hot;
1360b57cec5SDimitry Andric   if (PSI->isColdCount(ProfileCount))
1370b57cec5SDimitry Andric     return CalleeInfo::HotnessType::Cold;
1380b57cec5SDimitry Andric   return CalleeInfo::HotnessType::None;
1390b57cec5SDimitry Andric }
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric static bool isNonRenamableLocal(const GlobalValue &GV) {
1420b57cec5SDimitry Andric   return GV.hasSection() && GV.hasLocalLinkage();
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric /// Determine whether this call has all constant integer arguments (excluding
1460b57cec5SDimitry Andric /// "this") and summarize it to VCalls or ConstVCalls as appropriate.
1470b57cec5SDimitry Andric static void addVCallToSet(DevirtCallSite Call, GlobalValue::GUID Guid,
1480b57cec5SDimitry Andric                           SetVector<FunctionSummary::VFuncId> &VCalls,
1490b57cec5SDimitry Andric                           SetVector<FunctionSummary::ConstVCall> &ConstVCalls) {
1500b57cec5SDimitry Andric   std::vector<uint64_t> Args;
1510b57cec5SDimitry Andric   // Start from the second argument to skip the "this" pointer.
152e8d8bef9SDimitry Andric   for (auto &Arg : drop_begin(Call.CB.args())) {
1530b57cec5SDimitry Andric     auto *CI = dyn_cast<ConstantInt>(Arg);
1540b57cec5SDimitry Andric     if (!CI || CI->getBitWidth() > 64) {
1550b57cec5SDimitry Andric       VCalls.insert({Guid, Call.Offset});
1560b57cec5SDimitry Andric       return;
1570b57cec5SDimitry Andric     }
1580b57cec5SDimitry Andric     Args.push_back(CI->getZExtValue());
1590b57cec5SDimitry Andric   }
1600b57cec5SDimitry Andric   ConstVCalls.insert({{Guid, Call.Offset}, std::move(Args)});
1610b57cec5SDimitry Andric }
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric /// If this intrinsic call requires that we add information to the function
1640b57cec5SDimitry Andric /// summary, do so via the non-constant reference arguments.
1650b57cec5SDimitry Andric static void addIntrinsicToSummary(
1660b57cec5SDimitry Andric     const CallInst *CI, SetVector<GlobalValue::GUID> &TypeTests,
1670b57cec5SDimitry Andric     SetVector<FunctionSummary::VFuncId> &TypeTestAssumeVCalls,
1680b57cec5SDimitry Andric     SetVector<FunctionSummary::VFuncId> &TypeCheckedLoadVCalls,
1690b57cec5SDimitry Andric     SetVector<FunctionSummary::ConstVCall> &TypeTestAssumeConstVCalls,
1700b57cec5SDimitry Andric     SetVector<FunctionSummary::ConstVCall> &TypeCheckedLoadConstVCalls,
1710b57cec5SDimitry Andric     DominatorTree &DT) {
1720b57cec5SDimitry Andric   switch (CI->getCalledFunction()->getIntrinsicID()) {
173972a253aSDimitry Andric   case Intrinsic::type_test:
174972a253aSDimitry Andric   case Intrinsic::public_type_test: {
1750b57cec5SDimitry Andric     auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(1));
1760b57cec5SDimitry Andric     auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
1770b57cec5SDimitry Andric     if (!TypeId)
1780b57cec5SDimitry Andric       break;
1790b57cec5SDimitry Andric     GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric     // Produce a summary from type.test intrinsics. We only summarize type.test
1820b57cec5SDimitry Andric     // intrinsics that are used other than by an llvm.assume intrinsic.
1830b57cec5SDimitry Andric     // Intrinsics that are assumed are relevant only to the devirtualization
1840b57cec5SDimitry Andric     // pass, not the type test lowering pass.
1850b57cec5SDimitry Andric     bool HasNonAssumeUses = llvm::any_of(CI->uses(), [](const Use &CIU) {
186fe6060f1SDimitry Andric       return !isa<AssumeInst>(CIU.getUser());
1870b57cec5SDimitry Andric     });
1880b57cec5SDimitry Andric     if (HasNonAssumeUses)
1890b57cec5SDimitry Andric       TypeTests.insert(Guid);
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric     SmallVector<DevirtCallSite, 4> DevirtCalls;
1920b57cec5SDimitry Andric     SmallVector<CallInst *, 4> Assumes;
1930b57cec5SDimitry Andric     findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
1940b57cec5SDimitry Andric     for (auto &Call : DevirtCalls)
1950b57cec5SDimitry Andric       addVCallToSet(Call, Guid, TypeTestAssumeVCalls,
1960b57cec5SDimitry Andric                     TypeTestAssumeConstVCalls);
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric     break;
1990b57cec5SDimitry Andric   }
2000b57cec5SDimitry Andric 
201*06c3fb27SDimitry Andric   case Intrinsic::type_checked_load_relative:
2020b57cec5SDimitry Andric   case Intrinsic::type_checked_load: {
2030b57cec5SDimitry Andric     auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(2));
2040b57cec5SDimitry Andric     auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
2050b57cec5SDimitry Andric     if (!TypeId)
2060b57cec5SDimitry Andric       break;
2070b57cec5SDimitry Andric     GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric     SmallVector<DevirtCallSite, 4> DevirtCalls;
2100b57cec5SDimitry Andric     SmallVector<Instruction *, 4> LoadedPtrs;
2110b57cec5SDimitry Andric     SmallVector<Instruction *, 4> Preds;
2120b57cec5SDimitry Andric     bool HasNonCallUses = false;
2130b57cec5SDimitry Andric     findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
2140b57cec5SDimitry Andric                                                HasNonCallUses, CI, DT);
2150b57cec5SDimitry Andric     // Any non-call uses of the result of llvm.type.checked.load will
2160b57cec5SDimitry Andric     // prevent us from optimizing away the llvm.type.test.
2170b57cec5SDimitry Andric     if (HasNonCallUses)
2180b57cec5SDimitry Andric       TypeTests.insert(Guid);
2190b57cec5SDimitry Andric     for (auto &Call : DevirtCalls)
2200b57cec5SDimitry Andric       addVCallToSet(Call, Guid, TypeCheckedLoadVCalls,
2210b57cec5SDimitry Andric                     TypeCheckedLoadConstVCalls);
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric     break;
2240b57cec5SDimitry Andric   }
2250b57cec5SDimitry Andric   default:
2260b57cec5SDimitry Andric     break;
2270b57cec5SDimitry Andric   }
2280b57cec5SDimitry Andric }
2290b57cec5SDimitry Andric 
2300b57cec5SDimitry Andric static bool isNonVolatileLoad(const Instruction *I) {
2310b57cec5SDimitry Andric   if (const auto *LI = dyn_cast<LoadInst>(I))
2320b57cec5SDimitry Andric     return !LI->isVolatile();
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric   return false;
2350b57cec5SDimitry Andric }
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric static bool isNonVolatileStore(const Instruction *I) {
2380b57cec5SDimitry Andric   if (const auto *SI = dyn_cast<StoreInst>(I))
2390b57cec5SDimitry Andric     return !SI->isVolatile();
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric   return false;
2420b57cec5SDimitry Andric }
2430b57cec5SDimitry Andric 
2440eae32dcSDimitry Andric // Returns true if the function definition must be unreachable.
2450eae32dcSDimitry Andric //
2460eae32dcSDimitry Andric // Note if this helper function returns true, `F` is guaranteed
2470eae32dcSDimitry Andric // to be unreachable; if it returns false, `F` might still
2480eae32dcSDimitry Andric // be unreachable but not covered by this helper function.
2490eae32dcSDimitry Andric static bool mustBeUnreachableFunction(const Function &F) {
2500eae32dcSDimitry Andric   // A function must be unreachable if its entry block ends with an
2510eae32dcSDimitry Andric   // 'unreachable'.
2520eae32dcSDimitry Andric   assert(!F.isDeclaration());
2530eae32dcSDimitry Andric   return isa<UnreachableInst>(F.getEntryBlock().getTerminator());
2540eae32dcSDimitry Andric }
2550eae32dcSDimitry Andric 
2565ffd83dbSDimitry Andric static void computeFunctionSummary(
2575ffd83dbSDimitry Andric     ModuleSummaryIndex &Index, const Module &M, const Function &F,
2585ffd83dbSDimitry Andric     BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, DominatorTree &DT,
2595ffd83dbSDimitry Andric     bool HasLocalsInUsedOrAsm, DenseSet<GlobalValue::GUID> &CantBePromoted,
2605ffd83dbSDimitry Andric     bool IsThinLTO,
2615ffd83dbSDimitry Andric     std::function<const StackSafetyInfo *(const Function &F)> GetSSICallback) {
2620b57cec5SDimitry Andric   // Summary not currently supported for anonymous functions, they should
2630b57cec5SDimitry Andric   // have been named.
2640b57cec5SDimitry Andric   assert(F.hasName());
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric   unsigned NumInsts = 0;
2670b57cec5SDimitry Andric   // Map from callee ValueId to profile count. Used to accumulate profile
2680b57cec5SDimitry Andric   // counts for all static calls to a given callee.
269*06c3fb27SDimitry Andric   MapVector<ValueInfo, CalleeInfo, DenseMap<ValueInfo, unsigned>,
270*06c3fb27SDimitry Andric             std::vector<std::pair<ValueInfo, CalleeInfo>>>
271*06c3fb27SDimitry Andric       CallGraphEdges;
2720b57cec5SDimitry Andric   SetVector<ValueInfo> RefEdges, LoadRefEdges, StoreRefEdges;
2730b57cec5SDimitry Andric   SetVector<GlobalValue::GUID> TypeTests;
2740b57cec5SDimitry Andric   SetVector<FunctionSummary::VFuncId> TypeTestAssumeVCalls,
2750b57cec5SDimitry Andric       TypeCheckedLoadVCalls;
2760b57cec5SDimitry Andric   SetVector<FunctionSummary::ConstVCall> TypeTestAssumeConstVCalls,
2770b57cec5SDimitry Andric       TypeCheckedLoadConstVCalls;
2780b57cec5SDimitry Andric   ICallPromotionAnalysis ICallAnalysis;
2790b57cec5SDimitry Andric   SmallPtrSet<const User *, 8> Visited;
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   // Add personality function, prefix data and prologue data to function's ref
2820b57cec5SDimitry Andric   // list.
2830b57cec5SDimitry Andric   findRefEdges(Index, &F, RefEdges, Visited);
2840b57cec5SDimitry Andric   std::vector<const Instruction *> NonVolatileLoads;
2850b57cec5SDimitry Andric   std::vector<const Instruction *> NonVolatileStores;
2860b57cec5SDimitry Andric 
287bdd1243dSDimitry Andric   std::vector<CallsiteInfo> Callsites;
288bdd1243dSDimitry Andric   std::vector<AllocInfo> Allocs;
289bdd1243dSDimitry Andric 
290*06c3fb27SDimitry Andric #ifndef NDEBUG
291*06c3fb27SDimitry Andric   DenseSet<const CallBase *> CallsThatMayHaveMemprofSummary;
292*06c3fb27SDimitry Andric #endif
293*06c3fb27SDimitry Andric 
2940b57cec5SDimitry Andric   bool HasInlineAsmMaybeReferencingInternal = false;
295349cc55cSDimitry Andric   bool HasIndirBranchToBlockAddress = false;
296349cc55cSDimitry Andric   bool HasUnknownCall = false;
297349cc55cSDimitry Andric   bool MayThrow = false;
298349cc55cSDimitry Andric   for (const BasicBlock &BB : F) {
299349cc55cSDimitry Andric     // We don't allow inlining of function with indirect branch to blockaddress.
300349cc55cSDimitry Andric     // If the blockaddress escapes the function, e.g., via a global variable,
301349cc55cSDimitry Andric     // inlining may lead to an invalid cross-function reference. So we shouldn't
302349cc55cSDimitry Andric     // import such function either.
303349cc55cSDimitry Andric     if (BB.hasAddressTaken()) {
304349cc55cSDimitry Andric       for (User *U : BlockAddress::get(const_cast<BasicBlock *>(&BB))->users())
305349cc55cSDimitry Andric         if (!isa<CallBrInst>(*U)) {
306349cc55cSDimitry Andric           HasIndirBranchToBlockAddress = true;
307349cc55cSDimitry Andric           break;
308349cc55cSDimitry Andric         }
309349cc55cSDimitry Andric     }
310349cc55cSDimitry Andric 
3110b57cec5SDimitry Andric     for (const Instruction &I : BB) {
312349cc55cSDimitry Andric       if (I.isDebugOrPseudoInst())
3130b57cec5SDimitry Andric         continue;
3140b57cec5SDimitry Andric       ++NumInsts;
315349cc55cSDimitry Andric 
3160b57cec5SDimitry Andric       // Regular LTO module doesn't participate in ThinLTO import,
3170b57cec5SDimitry Andric       // so no reference from it can be read/writeonly, since this
3180b57cec5SDimitry Andric       // would require importing variable as local copy
3190b57cec5SDimitry Andric       if (IsThinLTO) {
3200b57cec5SDimitry Andric         if (isNonVolatileLoad(&I)) {
3210b57cec5SDimitry Andric           // Postpone processing of non-volatile load instructions
3220b57cec5SDimitry Andric           // See comments below
3230b57cec5SDimitry Andric           Visited.insert(&I);
3240b57cec5SDimitry Andric           NonVolatileLoads.push_back(&I);
3250b57cec5SDimitry Andric           continue;
3260b57cec5SDimitry Andric         } else if (isNonVolatileStore(&I)) {
3270b57cec5SDimitry Andric           Visited.insert(&I);
3280b57cec5SDimitry Andric           NonVolatileStores.push_back(&I);
3290b57cec5SDimitry Andric           // All references from second operand of store (destination address)
3300b57cec5SDimitry Andric           // can be considered write-only if they're not referenced by any
3310b57cec5SDimitry Andric           // non-store instruction. References from first operand of store
3320b57cec5SDimitry Andric           // (stored value) can't be treated either as read- or as write-only
3330b57cec5SDimitry Andric           // so we add them to RefEdges as we do with all other instructions
3340b57cec5SDimitry Andric           // except non-volatile load.
3350b57cec5SDimitry Andric           Value *Stored = I.getOperand(0);
3360b57cec5SDimitry Andric           if (auto *GV = dyn_cast<GlobalValue>(Stored))
3370b57cec5SDimitry Andric             // findRefEdges will try to examine GV operands, so instead
3380b57cec5SDimitry Andric             // of calling it we should add GV to RefEdges directly.
3390b57cec5SDimitry Andric             RefEdges.insert(Index.getOrInsertValueInfo(GV));
3400b57cec5SDimitry Andric           else if (auto *U = dyn_cast<User>(Stored))
3410b57cec5SDimitry Andric             findRefEdges(Index, U, RefEdges, Visited);
3420b57cec5SDimitry Andric           continue;
3430b57cec5SDimitry Andric         }
3440b57cec5SDimitry Andric       }
3450b57cec5SDimitry Andric       findRefEdges(Index, &I, RefEdges, Visited);
3465ffd83dbSDimitry Andric       const auto *CB = dyn_cast<CallBase>(&I);
347349cc55cSDimitry Andric       if (!CB) {
348349cc55cSDimitry Andric         if (I.mayThrow())
349349cc55cSDimitry Andric           MayThrow = true;
3500b57cec5SDimitry Andric         continue;
351349cc55cSDimitry Andric       }
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric       const auto *CI = dyn_cast<CallInst>(&I);
3540b57cec5SDimitry Andric       // Since we don't know exactly which local values are referenced in inline
3550b57cec5SDimitry Andric       // assembly, conservatively mark the function as possibly referencing
3560b57cec5SDimitry Andric       // a local value from inline assembly to ensure we don't export a
3570b57cec5SDimitry Andric       // reference (which would require renaming and promotion of the
3580b57cec5SDimitry Andric       // referenced value).
3590b57cec5SDimitry Andric       if (HasLocalsInUsedOrAsm && CI && CI->isInlineAsm())
3600b57cec5SDimitry Andric         HasInlineAsmMaybeReferencingInternal = true;
3610b57cec5SDimitry Andric 
3625ffd83dbSDimitry Andric       auto *CalledValue = CB->getCalledOperand();
3635ffd83dbSDimitry Andric       auto *CalledFunction = CB->getCalledFunction();
3640b57cec5SDimitry Andric       if (CalledValue && !CalledFunction) {
3658bcb0991SDimitry Andric         CalledValue = CalledValue->stripPointerCasts();
3660b57cec5SDimitry Andric         // Stripping pointer casts can reveal a called function.
3670b57cec5SDimitry Andric         CalledFunction = dyn_cast<Function>(CalledValue);
3680b57cec5SDimitry Andric       }
3690b57cec5SDimitry Andric       // Check if this is an alias to a function. If so, get the
3700b57cec5SDimitry Andric       // called aliasee for the checks below.
3710b57cec5SDimitry Andric       if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
3720b57cec5SDimitry Andric         assert(!CalledFunction && "Expected null called function in callsite for alias");
373349cc55cSDimitry Andric         CalledFunction = dyn_cast<Function>(GA->getAliaseeObject());
3740b57cec5SDimitry Andric       }
3750b57cec5SDimitry Andric       // Check if this is a direct call to a known function or a known
3760b57cec5SDimitry Andric       // intrinsic, or an indirect call with profile data.
3770b57cec5SDimitry Andric       if (CalledFunction) {
3780b57cec5SDimitry Andric         if (CI && CalledFunction->isIntrinsic()) {
3790b57cec5SDimitry Andric           addIntrinsicToSummary(
3800b57cec5SDimitry Andric               CI, TypeTests, TypeTestAssumeVCalls, TypeCheckedLoadVCalls,
3810b57cec5SDimitry Andric               TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls, DT);
3820b57cec5SDimitry Andric           continue;
3830b57cec5SDimitry Andric         }
3840b57cec5SDimitry Andric         // We should have named any anonymous globals
3850b57cec5SDimitry Andric         assert(CalledFunction->hasName());
3865ffd83dbSDimitry Andric         auto ScaledCount = PSI->getProfileCount(*CB, BFI);
38781ad6265SDimitry Andric         auto Hotness = ScaledCount ? getHotness(*ScaledCount, PSI)
3880b57cec5SDimitry Andric                                    : CalleeInfo::HotnessType::Unknown;
3890b57cec5SDimitry Andric         if (ForceSummaryEdgesCold != FunctionSummary::FSHT_None)
3900b57cec5SDimitry Andric           Hotness = CalleeInfo::HotnessType::Cold;
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric         // Use the original CalledValue, in case it was an alias. We want
3930b57cec5SDimitry Andric         // to record the call edge to the alias in that case. Eventually
3940b57cec5SDimitry Andric         // an alias summary will be created to associate the alias and
3950b57cec5SDimitry Andric         // aliasee.
3960b57cec5SDimitry Andric         auto &ValueInfo = CallGraphEdges[Index.getOrInsertValueInfo(
3970b57cec5SDimitry Andric             cast<GlobalValue>(CalledValue))];
3980b57cec5SDimitry Andric         ValueInfo.updateHotness(Hotness);
3990b57cec5SDimitry Andric         // Add the relative block frequency to CalleeInfo if there is no profile
4000b57cec5SDimitry Andric         // information.
4010b57cec5SDimitry Andric         if (BFI != nullptr && Hotness == CalleeInfo::HotnessType::Unknown) {
4020b57cec5SDimitry Andric           uint64_t BBFreq = BFI->getBlockFreq(&BB).getFrequency();
4030b57cec5SDimitry Andric           uint64_t EntryFreq = BFI->getEntryFreq();
4040b57cec5SDimitry Andric           ValueInfo.updateRelBlockFreq(BBFreq, EntryFreq);
4050b57cec5SDimitry Andric         }
4060b57cec5SDimitry Andric       } else {
407349cc55cSDimitry Andric         HasUnknownCall = true;
4080b57cec5SDimitry Andric         // Skip inline assembly calls.
4090b57cec5SDimitry Andric         if (CI && CI->isInlineAsm())
4100b57cec5SDimitry Andric           continue;
4110b57cec5SDimitry Andric         // Skip direct calls.
4120b57cec5SDimitry Andric         if (!CalledValue || isa<Constant>(CalledValue))
4130b57cec5SDimitry Andric           continue;
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric         // Check if the instruction has a callees metadata. If so, add callees
4160b57cec5SDimitry Andric         // to CallGraphEdges to reflect the references from the metadata, and
4170b57cec5SDimitry Andric         // to enable importing for subsequent indirect call promotion and
4180b57cec5SDimitry Andric         // inlining.
4190b57cec5SDimitry Andric         if (auto *MD = I.getMetadata(LLVMContext::MD_callees)) {
420fcaf7f86SDimitry Andric           for (const auto &Op : MD->operands()) {
4210b57cec5SDimitry Andric             Function *Callee = mdconst::extract_or_null<Function>(Op);
4220b57cec5SDimitry Andric             if (Callee)
4230b57cec5SDimitry Andric               CallGraphEdges[Index.getOrInsertValueInfo(Callee)];
4240b57cec5SDimitry Andric           }
4250b57cec5SDimitry Andric         }
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric         uint32_t NumVals, NumCandidates;
4280b57cec5SDimitry Andric         uint64_t TotalCount;
4290b57cec5SDimitry Andric         auto CandidateProfileData =
4300b57cec5SDimitry Andric             ICallAnalysis.getPromotionCandidatesForInstruction(
4310b57cec5SDimitry Andric                 &I, NumVals, TotalCount, NumCandidates);
432fcaf7f86SDimitry Andric         for (const auto &Candidate : CandidateProfileData)
4330b57cec5SDimitry Andric           CallGraphEdges[Index.getOrInsertValueInfo(Candidate.Value)]
4340b57cec5SDimitry Andric               .updateHotness(getHotness(Candidate.Count, PSI));
4350b57cec5SDimitry Andric       }
436bdd1243dSDimitry Andric 
437*06c3fb27SDimitry Andric       // Summarize memprof related metadata. This is only needed for ThinLTO.
438*06c3fb27SDimitry Andric       if (!IsThinLTO)
439*06c3fb27SDimitry Andric         continue;
440*06c3fb27SDimitry Andric 
441bdd1243dSDimitry Andric       // TODO: Skip indirect calls for now. Need to handle these better, likely
442bdd1243dSDimitry Andric       // by creating multiple Callsites, one per target, then speculatively
443bdd1243dSDimitry Andric       // devirtualize while applying clone info in the ThinLTO backends. This
444bdd1243dSDimitry Andric       // will also be important because we will have a different set of clone
445bdd1243dSDimitry Andric       // versions per target. This handling needs to match that in the ThinLTO
446bdd1243dSDimitry Andric       // backend so we handle things consistently for matching of callsite
447bdd1243dSDimitry Andric       // summaries to instructions.
448bdd1243dSDimitry Andric       if (!CalledFunction)
449bdd1243dSDimitry Andric         continue;
450bdd1243dSDimitry Andric 
451*06c3fb27SDimitry Andric       // Ensure we keep this analysis in sync with the handling in the ThinLTO
452*06c3fb27SDimitry Andric       // backend (see MemProfContextDisambiguation::applyImport). Save this call
453*06c3fb27SDimitry Andric       // so that we can skip it in checking the reverse case later.
454*06c3fb27SDimitry Andric       assert(mayHaveMemprofSummary(CB));
455*06c3fb27SDimitry Andric #ifndef NDEBUG
456*06c3fb27SDimitry Andric       CallsThatMayHaveMemprofSummary.insert(CB);
457*06c3fb27SDimitry Andric #endif
458*06c3fb27SDimitry Andric 
459bdd1243dSDimitry Andric       // Compute the list of stack ids first (so we can trim them from the stack
460bdd1243dSDimitry Andric       // ids on any MIBs).
461bdd1243dSDimitry Andric       CallStack<MDNode, MDNode::op_iterator> InstCallsite(
462bdd1243dSDimitry Andric           I.getMetadata(LLVMContext::MD_callsite));
463bdd1243dSDimitry Andric       auto *MemProfMD = I.getMetadata(LLVMContext::MD_memprof);
464bdd1243dSDimitry Andric       if (MemProfMD) {
465bdd1243dSDimitry Andric         std::vector<MIBInfo> MIBs;
466bdd1243dSDimitry Andric         for (auto &MDOp : MemProfMD->operands()) {
467bdd1243dSDimitry Andric           auto *MIBMD = cast<const MDNode>(MDOp);
468bdd1243dSDimitry Andric           MDNode *StackNode = getMIBStackNode(MIBMD);
469bdd1243dSDimitry Andric           assert(StackNode);
470bdd1243dSDimitry Andric           SmallVector<unsigned> StackIdIndices;
471bdd1243dSDimitry Andric           CallStack<MDNode, MDNode::op_iterator> StackContext(StackNode);
472bdd1243dSDimitry Andric           // Collapse out any on the allocation call (inlining).
473bdd1243dSDimitry Andric           for (auto ContextIter =
474bdd1243dSDimitry Andric                    StackContext.beginAfterSharedPrefix(InstCallsite);
475bdd1243dSDimitry Andric                ContextIter != StackContext.end(); ++ContextIter) {
476bdd1243dSDimitry Andric             unsigned StackIdIdx = Index.addOrGetStackIdIndex(*ContextIter);
477bdd1243dSDimitry Andric             // If this is a direct recursion, simply skip the duplicate
478bdd1243dSDimitry Andric             // entries. If this is mutual recursion, handling is left to
479bdd1243dSDimitry Andric             // the LTO link analysis client.
480bdd1243dSDimitry Andric             if (StackIdIndices.empty() || StackIdIndices.back() != StackIdIdx)
481bdd1243dSDimitry Andric               StackIdIndices.push_back(StackIdIdx);
482bdd1243dSDimitry Andric           }
483bdd1243dSDimitry Andric           MIBs.push_back(
484bdd1243dSDimitry Andric               MIBInfo(getMIBAllocType(MIBMD), std::move(StackIdIndices)));
485bdd1243dSDimitry Andric         }
486bdd1243dSDimitry Andric         Allocs.push_back(AllocInfo(std::move(MIBs)));
487bdd1243dSDimitry Andric       } else if (!InstCallsite.empty()) {
488bdd1243dSDimitry Andric         SmallVector<unsigned> StackIdIndices;
489bdd1243dSDimitry Andric         for (auto StackId : InstCallsite)
490bdd1243dSDimitry Andric           StackIdIndices.push_back(Index.addOrGetStackIdIndex(StackId));
491bdd1243dSDimitry Andric         // Use the original CalledValue, in case it was an alias. We want
492bdd1243dSDimitry Andric         // to record the call edge to the alias in that case. Eventually
493bdd1243dSDimitry Andric         // an alias summary will be created to associate the alias and
494bdd1243dSDimitry Andric         // aliasee.
495bdd1243dSDimitry Andric         auto CalleeValueInfo =
496bdd1243dSDimitry Andric             Index.getOrInsertValueInfo(cast<GlobalValue>(CalledValue));
497bdd1243dSDimitry Andric         Callsites.push_back({CalleeValueInfo, StackIdIndices});
498bdd1243dSDimitry Andric       }
4990b57cec5SDimitry Andric     }
500349cc55cSDimitry Andric   }
501*06c3fb27SDimitry Andric 
502*06c3fb27SDimitry Andric   if (PSI->hasPartialSampleProfile() && ScalePartialSampleProfileWorkingSetSize)
5035ffd83dbSDimitry Andric     Index.addBlockCount(F.size());
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric   std::vector<ValueInfo> Refs;
5060b57cec5SDimitry Andric   if (IsThinLTO) {
5070b57cec5SDimitry Andric     auto AddRefEdges = [&](const std::vector<const Instruction *> &Instrs,
5080b57cec5SDimitry Andric                            SetVector<ValueInfo> &Edges,
5090b57cec5SDimitry Andric                            SmallPtrSet<const User *, 8> &Cache) {
5100b57cec5SDimitry Andric       for (const auto *I : Instrs) {
5110b57cec5SDimitry Andric         Cache.erase(I);
5120b57cec5SDimitry Andric         findRefEdges(Index, I, Edges, Cache);
5130b57cec5SDimitry Andric       }
5140b57cec5SDimitry Andric     };
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric     // By now we processed all instructions in a function, except
5170b57cec5SDimitry Andric     // non-volatile loads and non-volatile value stores. Let's find
5180b57cec5SDimitry Andric     // ref edges for both of instruction sets
5190b57cec5SDimitry Andric     AddRefEdges(NonVolatileLoads, LoadRefEdges, Visited);
5200b57cec5SDimitry Andric     // We can add some values to the Visited set when processing load
5210b57cec5SDimitry Andric     // instructions which are also used by stores in NonVolatileStores.
5220b57cec5SDimitry Andric     // For example this can happen if we have following code:
5230b57cec5SDimitry Andric     //
5240b57cec5SDimitry Andric     // store %Derived* @foo, %Derived** bitcast (%Base** @bar to %Derived**)
5250b57cec5SDimitry Andric     // %42 = load %Derived*, %Derived** bitcast (%Base** @bar to %Derived**)
5260b57cec5SDimitry Andric     //
5270b57cec5SDimitry Andric     // After processing loads we'll add bitcast to the Visited set, and if
5280b57cec5SDimitry Andric     // we use the same set while processing stores, we'll never see store
5290b57cec5SDimitry Andric     // to @bar and @bar will be mistakenly treated as readonly.
5300b57cec5SDimitry Andric     SmallPtrSet<const llvm::User *, 8> StoreCache;
5310b57cec5SDimitry Andric     AddRefEdges(NonVolatileStores, StoreRefEdges, StoreCache);
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric     // If both load and store instruction reference the same variable
5340b57cec5SDimitry Andric     // we won't be able to optimize it. Add all such reference edges
5350b57cec5SDimitry Andric     // to RefEdges set.
536fcaf7f86SDimitry Andric     for (const auto &VI : StoreRefEdges)
5370b57cec5SDimitry Andric       if (LoadRefEdges.remove(VI))
5380b57cec5SDimitry Andric         RefEdges.insert(VI);
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric     unsigned RefCnt = RefEdges.size();
5410b57cec5SDimitry Andric     // All new reference edges inserted in two loops below are either
5420b57cec5SDimitry Andric     // read or write only. They will be grouped in the end of RefEdges
5430b57cec5SDimitry Andric     // vector, so we can use a single integer value to identify them.
544fcaf7f86SDimitry Andric     for (const auto &VI : LoadRefEdges)
5450b57cec5SDimitry Andric       RefEdges.insert(VI);
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric     unsigned FirstWORef = RefEdges.size();
548fcaf7f86SDimitry Andric     for (const auto &VI : StoreRefEdges)
5490b57cec5SDimitry Andric       RefEdges.insert(VI);
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric     Refs = RefEdges.takeVector();
5520b57cec5SDimitry Andric     for (; RefCnt < FirstWORef; ++RefCnt)
5530b57cec5SDimitry Andric       Refs[RefCnt].setReadOnly();
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric     for (; RefCnt < Refs.size(); ++RefCnt)
5560b57cec5SDimitry Andric       Refs[RefCnt].setWriteOnly();
5570b57cec5SDimitry Andric   } else {
5580b57cec5SDimitry Andric     Refs = RefEdges.takeVector();
5590b57cec5SDimitry Andric   }
5600b57cec5SDimitry Andric   // Explicit add hot edges to enforce importing for designated GUIDs for
5610b57cec5SDimitry Andric   // sample PGO, to enable the same inlines as the profiled optimized binary.
5620b57cec5SDimitry Andric   for (auto &I : F.getImportGUIDs())
5630b57cec5SDimitry Andric     CallGraphEdges[Index.getOrInsertValueInfo(I)].updateHotness(
5640b57cec5SDimitry Andric         ForceSummaryEdgesCold == FunctionSummary::FSHT_All
5650b57cec5SDimitry Andric             ? CalleeInfo::HotnessType::Cold
5660b57cec5SDimitry Andric             : CalleeInfo::HotnessType::Critical);
5670b57cec5SDimitry Andric 
568*06c3fb27SDimitry Andric #ifndef NDEBUG
569*06c3fb27SDimitry Andric   // Make sure that all calls we decided could not have memprof summaries get a
570*06c3fb27SDimitry Andric   // false value for mayHaveMemprofSummary, to ensure that this handling remains
571*06c3fb27SDimitry Andric   // in sync with the ThinLTO backend handling.
572*06c3fb27SDimitry Andric   if (IsThinLTO) {
573*06c3fb27SDimitry Andric     for (const BasicBlock &BB : F) {
574*06c3fb27SDimitry Andric       for (const Instruction &I : BB) {
575*06c3fb27SDimitry Andric         const auto *CB = dyn_cast<CallBase>(&I);
576*06c3fb27SDimitry Andric         if (!CB)
577*06c3fb27SDimitry Andric           continue;
578*06c3fb27SDimitry Andric         // We already checked these above.
579*06c3fb27SDimitry Andric         if (CallsThatMayHaveMemprofSummary.count(CB))
580*06c3fb27SDimitry Andric           continue;
581*06c3fb27SDimitry Andric         assert(!mayHaveMemprofSummary(CB));
582*06c3fb27SDimitry Andric       }
583*06c3fb27SDimitry Andric     }
584*06c3fb27SDimitry Andric   }
585*06c3fb27SDimitry Andric #endif
586*06c3fb27SDimitry Andric 
5870b57cec5SDimitry Andric   bool NonRenamableLocal = isNonRenamableLocal(F);
588349cc55cSDimitry Andric   bool NotEligibleForImport = NonRenamableLocal ||
589349cc55cSDimitry Andric                               HasInlineAsmMaybeReferencingInternal ||
590349cc55cSDimitry Andric                               HasIndirBranchToBlockAddress;
591fe6060f1SDimitry Andric   GlobalValueSummary::GVFlags Flags(
592fe6060f1SDimitry Andric       F.getLinkage(), F.getVisibility(), NotEligibleForImport,
59381ad6265SDimitry Andric       /* Live = */ false, F.isDSOLocal(), F.canBeOmittedFromSymbolTable());
5940b57cec5SDimitry Andric   FunctionSummary::FFlags FunFlags{
595bdd1243dSDimitry Andric       F.doesNotAccessMemory(), F.onlyReadsMemory() && !F.doesNotAccessMemory(),
5960b57cec5SDimitry Andric       F.hasFnAttribute(Attribute::NoRecurse), F.returnDoesNotAlias(),
5970b57cec5SDimitry Andric       // FIXME: refactor this to use the same code that inliner is using.
5980b57cec5SDimitry Andric       // Don't try to import functions with noinline attribute.
599349cc55cSDimitry Andric       F.getAttributes().hasFnAttr(Attribute::NoInline),
600349cc55cSDimitry Andric       F.hasFnAttribute(Attribute::AlwaysInline),
6010eae32dcSDimitry Andric       F.hasFnAttribute(Attribute::NoUnwind), MayThrow, HasUnknownCall,
6020eae32dcSDimitry Andric       mustBeUnreachableFunction(F)};
6035ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> ParamAccesses;
6045ffd83dbSDimitry Andric   if (auto *SSI = GetSSICallback(F))
605e8d8bef9SDimitry Andric     ParamAccesses = SSI->getParamAccesses(Index);
6068bcb0991SDimitry Andric   auto FuncSummary = std::make_unique<FunctionSummary>(
6070b57cec5SDimitry Andric       Flags, NumInsts, FunFlags, /*EntryCount=*/0, std::move(Refs),
6080b57cec5SDimitry Andric       CallGraphEdges.takeVector(), TypeTests.takeVector(),
6090b57cec5SDimitry Andric       TypeTestAssumeVCalls.takeVector(), TypeCheckedLoadVCalls.takeVector(),
6100b57cec5SDimitry Andric       TypeTestAssumeConstVCalls.takeVector(),
611bdd1243dSDimitry Andric       TypeCheckedLoadConstVCalls.takeVector(), std::move(ParamAccesses),
612bdd1243dSDimitry Andric       std::move(Callsites), std::move(Allocs));
6130b57cec5SDimitry Andric   if (NonRenamableLocal)
6140b57cec5SDimitry Andric     CantBePromoted.insert(F.getGUID());
6150b57cec5SDimitry Andric   Index.addGlobalValueSummary(F, std::move(FuncSummary));
6160b57cec5SDimitry Andric }
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric /// Find function pointers referenced within the given vtable initializer
6190b57cec5SDimitry Andric /// (or subset of an initializer) \p I. The starting offset of \p I within
6200b57cec5SDimitry Andric /// the vtable initializer is \p StartingOffset. Any discovered function
6210b57cec5SDimitry Andric /// pointers are added to \p VTableFuncs along with their cumulative offset
6220b57cec5SDimitry Andric /// within the initializer.
6230b57cec5SDimitry Andric static void findFuncPointers(const Constant *I, uint64_t StartingOffset,
6240b57cec5SDimitry Andric                              const Module &M, ModuleSummaryIndex &Index,
6250b57cec5SDimitry Andric                              VTableFuncList &VTableFuncs) {
6260b57cec5SDimitry Andric   // First check if this is a function pointer.
6270b57cec5SDimitry Andric   if (I->getType()->isPointerTy()) {
628*06c3fb27SDimitry Andric     auto C = I->stripPointerCasts();
629*06c3fb27SDimitry Andric     auto A = dyn_cast<GlobalAlias>(C);
630*06c3fb27SDimitry Andric     if (isa<Function>(C) || (A && isa<Function>(A->getAliasee()))) {
631*06c3fb27SDimitry Andric       auto GV = dyn_cast<GlobalValue>(C);
632*06c3fb27SDimitry Andric       assert(GV);
6330b57cec5SDimitry Andric       // We can disregard __cxa_pure_virtual as a possible call target, as
6340b57cec5SDimitry Andric       // calls to pure virtuals are UB.
635*06c3fb27SDimitry Andric       if (GV && GV->getName() != "__cxa_pure_virtual")
636*06c3fb27SDimitry Andric         VTableFuncs.push_back({Index.getOrInsertValueInfo(GV), StartingOffset});
6370b57cec5SDimitry Andric       return;
6380b57cec5SDimitry Andric     }
639*06c3fb27SDimitry Andric   }
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   // Walk through the elements in the constant struct or array and recursively
6420b57cec5SDimitry Andric   // look for virtual function pointers.
6430b57cec5SDimitry Andric   const DataLayout &DL = M.getDataLayout();
6440b57cec5SDimitry Andric   if (auto *C = dyn_cast<ConstantStruct>(I)) {
6450b57cec5SDimitry Andric     StructType *STy = dyn_cast<StructType>(C->getType());
6460b57cec5SDimitry Andric     assert(STy);
6470b57cec5SDimitry Andric     const StructLayout *SL = DL.getStructLayout(C->getType());
6480b57cec5SDimitry Andric 
649fe6060f1SDimitry Andric     for (auto EI : llvm::enumerate(STy->elements())) {
650fe6060f1SDimitry Andric       auto Offset = SL->getElementOffset(EI.index());
6510b57cec5SDimitry Andric       unsigned Op = SL->getElementContainingOffset(Offset);
6520b57cec5SDimitry Andric       findFuncPointers(cast<Constant>(I->getOperand(Op)),
6530b57cec5SDimitry Andric                        StartingOffset + Offset, M, Index, VTableFuncs);
6540b57cec5SDimitry Andric     }
6550b57cec5SDimitry Andric   } else if (auto *C = dyn_cast<ConstantArray>(I)) {
6560b57cec5SDimitry Andric     ArrayType *ATy = C->getType();
6570b57cec5SDimitry Andric     Type *EltTy = ATy->getElementType();
6580b57cec5SDimitry Andric     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
6590b57cec5SDimitry Andric     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
6600b57cec5SDimitry Andric       findFuncPointers(cast<Constant>(I->getOperand(i)),
6610b57cec5SDimitry Andric                        StartingOffset + i * EltSize, M, Index, VTableFuncs);
6620b57cec5SDimitry Andric     }
6630b57cec5SDimitry Andric   }
6640b57cec5SDimitry Andric }
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric // Identify the function pointers referenced by vtable definition \p V.
6670b57cec5SDimitry Andric static void computeVTableFuncs(ModuleSummaryIndex &Index,
6680b57cec5SDimitry Andric                                const GlobalVariable &V, const Module &M,
6690b57cec5SDimitry Andric                                VTableFuncList &VTableFuncs) {
6700b57cec5SDimitry Andric   if (!V.isConstant())
6710b57cec5SDimitry Andric     return;
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric   findFuncPointers(V.getInitializer(), /*StartingOffset=*/0, M, Index,
6740b57cec5SDimitry Andric                    VTableFuncs);
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric #ifndef NDEBUG
6770b57cec5SDimitry Andric   // Validate that the VTableFuncs list is ordered by offset.
6780b57cec5SDimitry Andric   uint64_t PrevOffset = 0;
6790b57cec5SDimitry Andric   for (auto &P : VTableFuncs) {
6800b57cec5SDimitry Andric     // The findVFuncPointers traversal should have encountered the
6810b57cec5SDimitry Andric     // functions in offset order. We need to use ">=" since PrevOffset
6820b57cec5SDimitry Andric     // starts at 0.
6830b57cec5SDimitry Andric     assert(P.VTableOffset >= PrevOffset);
6840b57cec5SDimitry Andric     PrevOffset = P.VTableOffset;
6850b57cec5SDimitry Andric   }
6860b57cec5SDimitry Andric #endif
6870b57cec5SDimitry Andric }
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric /// Record vtable definition \p V for each type metadata it references.
6900b57cec5SDimitry Andric static void
6910b57cec5SDimitry Andric recordTypeIdCompatibleVtableReferences(ModuleSummaryIndex &Index,
6920b57cec5SDimitry Andric                                        const GlobalVariable &V,
6930b57cec5SDimitry Andric                                        SmallVectorImpl<MDNode *> &Types) {
6940b57cec5SDimitry Andric   for (MDNode *Type : Types) {
6950b57cec5SDimitry Andric     auto TypeID = Type->getOperand(1).get();
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric     uint64_t Offset =
6980b57cec5SDimitry Andric         cast<ConstantInt>(
6990b57cec5SDimitry Andric             cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
7000b57cec5SDimitry Andric             ->getZExtValue();
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric     if (auto *TypeId = dyn_cast<MDString>(TypeID))
7030b57cec5SDimitry Andric       Index.getOrInsertTypeIdCompatibleVtableSummary(TypeId->getString())
7040b57cec5SDimitry Andric           .push_back({Offset, Index.getOrInsertValueInfo(&V)});
7050b57cec5SDimitry Andric   }
7060b57cec5SDimitry Andric }
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric static void computeVariableSummary(ModuleSummaryIndex &Index,
7090b57cec5SDimitry Andric                                    const GlobalVariable &V,
7100b57cec5SDimitry Andric                                    DenseSet<GlobalValue::GUID> &CantBePromoted,
7110b57cec5SDimitry Andric                                    const Module &M,
7120b57cec5SDimitry Andric                                    SmallVectorImpl<MDNode *> &Types) {
7130b57cec5SDimitry Andric   SetVector<ValueInfo> RefEdges;
7140b57cec5SDimitry Andric   SmallPtrSet<const User *, 8> Visited;
7150b57cec5SDimitry Andric   bool HasBlockAddress = findRefEdges(Index, &V, RefEdges, Visited);
7160b57cec5SDimitry Andric   bool NonRenamableLocal = isNonRenamableLocal(V);
717fe6060f1SDimitry Andric   GlobalValueSummary::GVFlags Flags(
718fe6060f1SDimitry Andric       V.getLinkage(), V.getVisibility(), NonRenamableLocal,
71981ad6265SDimitry Andric       /* Live = */ false, V.isDSOLocal(), V.canBeOmittedFromSymbolTable());
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   VTableFuncList VTableFuncs;
7220b57cec5SDimitry Andric   // If splitting is not enabled, then we compute the summary information
7230b57cec5SDimitry Andric   // necessary for index-based whole program devirtualization.
7240b57cec5SDimitry Andric   if (!Index.enableSplitLTOUnit()) {
7250b57cec5SDimitry Andric     Types.clear();
7260b57cec5SDimitry Andric     V.getMetadata(LLVMContext::MD_type, Types);
7270b57cec5SDimitry Andric     if (!Types.empty()) {
7280b57cec5SDimitry Andric       // Identify the function pointers referenced by this vtable definition.
7290b57cec5SDimitry Andric       computeVTableFuncs(Index, V, M, VTableFuncs);
7300b57cec5SDimitry Andric 
7310b57cec5SDimitry Andric       // Record this vtable definition for each type metadata it references.
7320b57cec5SDimitry Andric       recordTypeIdCompatibleVtableReferences(Index, V, Types);
7330b57cec5SDimitry Andric     }
7340b57cec5SDimitry Andric   }
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric   // Don't mark variables we won't be able to internalize as read/write-only.
7370b57cec5SDimitry Andric   bool CanBeInternalized =
7380b57cec5SDimitry Andric       !V.hasComdat() && !V.hasAppendingLinkage() && !V.isInterposable() &&
7390b57cec5SDimitry Andric       !V.hasAvailableExternallyLinkage() && !V.hasDLLExportStorageClass();
7405ffd83dbSDimitry Andric   bool Constant = V.isConstant();
7415ffd83dbSDimitry Andric   GlobalVarSummary::GVarFlags VarFlags(CanBeInternalized,
7425ffd83dbSDimitry Andric                                        Constant ? false : CanBeInternalized,
7435ffd83dbSDimitry Andric                                        Constant, V.getVCallVisibility());
7448bcb0991SDimitry Andric   auto GVarSummary = std::make_unique<GlobalVarSummary>(Flags, VarFlags,
7450b57cec5SDimitry Andric                                                          RefEdges.takeVector());
7460b57cec5SDimitry Andric   if (NonRenamableLocal)
7470b57cec5SDimitry Andric     CantBePromoted.insert(V.getGUID());
7480b57cec5SDimitry Andric   if (HasBlockAddress)
7490b57cec5SDimitry Andric     GVarSummary->setNotEligibleToImport();
7500b57cec5SDimitry Andric   if (!VTableFuncs.empty())
7510b57cec5SDimitry Andric     GVarSummary->setVTableFuncs(VTableFuncs);
7520b57cec5SDimitry Andric   Index.addGlobalValueSummary(V, std::move(GVarSummary));
7530b57cec5SDimitry Andric }
7540b57cec5SDimitry Andric 
755fcaf7f86SDimitry Andric static void computeAliasSummary(ModuleSummaryIndex &Index, const GlobalAlias &A,
7560b57cec5SDimitry Andric                                 DenseSet<GlobalValue::GUID> &CantBePromoted) {
757fcaf7f86SDimitry Andric   // Skip summary for indirect function aliases as summary for aliasee will not
758fcaf7f86SDimitry Andric   // be emitted.
759fcaf7f86SDimitry Andric   const GlobalObject *Aliasee = A.getAliaseeObject();
760fcaf7f86SDimitry Andric   if (isa<GlobalIFunc>(Aliasee))
761fcaf7f86SDimitry Andric     return;
7620b57cec5SDimitry Andric   bool NonRenamableLocal = isNonRenamableLocal(A);
763fe6060f1SDimitry Andric   GlobalValueSummary::GVFlags Flags(
764fe6060f1SDimitry Andric       A.getLinkage(), A.getVisibility(), NonRenamableLocal,
76581ad6265SDimitry Andric       /* Live = */ false, A.isDSOLocal(), A.canBeOmittedFromSymbolTable());
7668bcb0991SDimitry Andric   auto AS = std::make_unique<AliasSummary>(Flags);
7670b57cec5SDimitry Andric   auto AliaseeVI = Index.getValueInfo(Aliasee->getGUID());
7680b57cec5SDimitry Andric   assert(AliaseeVI && "Alias expects aliasee summary to be available");
7690b57cec5SDimitry Andric   assert(AliaseeVI.getSummaryList().size() == 1 &&
7700b57cec5SDimitry Andric          "Expected a single entry per aliasee in per-module index");
7710b57cec5SDimitry Andric   AS->setAliasee(AliaseeVI, AliaseeVI.getSummaryList()[0].get());
7720b57cec5SDimitry Andric   if (NonRenamableLocal)
7730b57cec5SDimitry Andric     CantBePromoted.insert(A.getGUID());
7740b57cec5SDimitry Andric   Index.addGlobalValueSummary(A, std::move(AS));
7750b57cec5SDimitry Andric }
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric // Set LiveRoot flag on entries matching the given value name.
7780b57cec5SDimitry Andric static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) {
7790b57cec5SDimitry Andric   if (ValueInfo VI = Index.getValueInfo(GlobalValue::getGUID(Name)))
780fcaf7f86SDimitry Andric     for (const auto &Summary : VI.getSummaryList())
7810b57cec5SDimitry Andric       Summary->setLive(true);
7820b57cec5SDimitry Andric }
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric ModuleSummaryIndex llvm::buildModuleSummaryIndex(
7850b57cec5SDimitry Andric     const Module &M,
7860b57cec5SDimitry Andric     std::function<BlockFrequencyInfo *(const Function &F)> GetBFICallback,
7875ffd83dbSDimitry Andric     ProfileSummaryInfo *PSI,
7885ffd83dbSDimitry Andric     std::function<const StackSafetyInfo *(const Function &F)> GetSSICallback) {
7890b57cec5SDimitry Andric   assert(PSI);
7900b57cec5SDimitry Andric   bool EnableSplitLTOUnit = false;
791*06c3fb27SDimitry Andric   bool UnifiedLTO = false;
7920b57cec5SDimitry Andric   if (auto *MD = mdconst::extract_or_null<ConstantInt>(
7930b57cec5SDimitry Andric           M.getModuleFlag("EnableSplitLTOUnit")))
7940b57cec5SDimitry Andric     EnableSplitLTOUnit = MD->getZExtValue();
795*06c3fb27SDimitry Andric   if (auto *MD =
796*06c3fb27SDimitry Andric           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("UnifiedLTO")))
797*06c3fb27SDimitry Andric     UnifiedLTO = MD->getZExtValue();
798*06c3fb27SDimitry Andric   ModuleSummaryIndex Index(/*HaveGVs=*/true, EnableSplitLTOUnit, UnifiedLTO);
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric   // Identify the local values in the llvm.used and llvm.compiler.used sets,
8010b57cec5SDimitry Andric   // which should not be exported as they would then require renaming and
8020b57cec5SDimitry Andric   // promotion, but we may have opaque uses e.g. in inline asm. We collect them
8030b57cec5SDimitry Andric   // here because we use this information to mark functions containing inline
8040b57cec5SDimitry Andric   // assembly calls as not importable.
805fe6060f1SDimitry Andric   SmallPtrSet<GlobalValue *, 4> LocalsUsed;
806fe6060f1SDimitry Andric   SmallVector<GlobalValue *, 4> Used;
8070b57cec5SDimitry Andric   // First collect those in the llvm.used set.
808fe6060f1SDimitry Andric   collectUsedGlobalVariables(M, Used, /*CompilerUsed=*/false);
8090b57cec5SDimitry Andric   // Next collect those in the llvm.compiler.used set.
810fe6060f1SDimitry Andric   collectUsedGlobalVariables(M, Used, /*CompilerUsed=*/true);
8110b57cec5SDimitry Andric   DenseSet<GlobalValue::GUID> CantBePromoted;
8120b57cec5SDimitry Andric   for (auto *V : Used) {
8130b57cec5SDimitry Andric     if (V->hasLocalLinkage()) {
8140b57cec5SDimitry Andric       LocalsUsed.insert(V);
8150b57cec5SDimitry Andric       CantBePromoted.insert(V->getGUID());
8160b57cec5SDimitry Andric     }
8170b57cec5SDimitry Andric   }
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   bool HasLocalInlineAsmSymbol = false;
8200b57cec5SDimitry Andric   if (!M.getModuleInlineAsm().empty()) {
8210b57cec5SDimitry Andric     // Collect the local values defined by module level asm, and set up
8220b57cec5SDimitry Andric     // summaries for these symbols so that they can be marked as NoRename,
8230b57cec5SDimitry Andric     // to prevent export of any use of them in regular IR that would require
8240b57cec5SDimitry Andric     // renaming within the module level asm. Note we don't need to create a
8250b57cec5SDimitry Andric     // summary for weak or global defs, as they don't need to be flagged as
8260b57cec5SDimitry Andric     // NoRename, and defs in module level asm can't be imported anyway.
8270b57cec5SDimitry Andric     // Also, any values used but not defined within module level asm should
8280b57cec5SDimitry Andric     // be listed on the llvm.used or llvm.compiler.used global and marked as
8290b57cec5SDimitry Andric     // referenced from there.
8300b57cec5SDimitry Andric     ModuleSymbolTable::CollectAsmSymbols(
8310b57cec5SDimitry Andric         M, [&](StringRef Name, object::BasicSymbolRef::Flags Flags) {
8320b57cec5SDimitry Andric           // Symbols not marked as Weak or Global are local definitions.
8330b57cec5SDimitry Andric           if (Flags & (object::BasicSymbolRef::SF_Weak |
8340b57cec5SDimitry Andric                        object::BasicSymbolRef::SF_Global))
8350b57cec5SDimitry Andric             return;
8360b57cec5SDimitry Andric           HasLocalInlineAsmSymbol = true;
8370b57cec5SDimitry Andric           GlobalValue *GV = M.getNamedValue(Name);
8380b57cec5SDimitry Andric           if (!GV)
8390b57cec5SDimitry Andric             return;
8400b57cec5SDimitry Andric           assert(GV->isDeclaration() && "Def in module asm already has definition");
841fe6060f1SDimitry Andric           GlobalValueSummary::GVFlags GVFlags(
842fe6060f1SDimitry Andric               GlobalValue::InternalLinkage, GlobalValue::DefaultVisibility,
8430b57cec5SDimitry Andric               /* NotEligibleToImport = */ true,
8440b57cec5SDimitry Andric               /* Live = */ true,
84581ad6265SDimitry Andric               /* Local */ GV->isDSOLocal(), GV->canBeOmittedFromSymbolTable());
8460b57cec5SDimitry Andric           CantBePromoted.insert(GV->getGUID());
8470b57cec5SDimitry Andric           // Create the appropriate summary type.
8480b57cec5SDimitry Andric           if (Function *F = dyn_cast<Function>(GV)) {
8490b57cec5SDimitry Andric             std::unique_ptr<FunctionSummary> Summary =
8508bcb0991SDimitry Andric                 std::make_unique<FunctionSummary>(
8510b57cec5SDimitry Andric                     GVFlags, /*InstCount=*/0,
8520b57cec5SDimitry Andric                     FunctionSummary::FFlags{
8530b57cec5SDimitry Andric                         F->hasFnAttribute(Attribute::ReadNone),
8540b57cec5SDimitry Andric                         F->hasFnAttribute(Attribute::ReadOnly),
8550b57cec5SDimitry Andric                         F->hasFnAttribute(Attribute::NoRecurse),
8560b57cec5SDimitry Andric                         F->returnDoesNotAlias(),
857480093f4SDimitry Andric                         /* NoInline = */ false,
858349cc55cSDimitry Andric                         F->hasFnAttribute(Attribute::AlwaysInline),
859349cc55cSDimitry Andric                         F->hasFnAttribute(Attribute::NoUnwind),
860349cc55cSDimitry Andric                         /* MayThrow */ true,
8610eae32dcSDimitry Andric                         /* HasUnknownCall */ true,
8620eae32dcSDimitry Andric                         /* MustBeUnreachable */ false},
8630b57cec5SDimitry Andric                     /*EntryCount=*/0, ArrayRef<ValueInfo>{},
8640b57cec5SDimitry Andric                     ArrayRef<FunctionSummary::EdgeTy>{},
8650b57cec5SDimitry Andric                     ArrayRef<GlobalValue::GUID>{},
8660b57cec5SDimitry Andric                     ArrayRef<FunctionSummary::VFuncId>{},
8670b57cec5SDimitry Andric                     ArrayRef<FunctionSummary::VFuncId>{},
8680b57cec5SDimitry Andric                     ArrayRef<FunctionSummary::ConstVCall>{},
8695ffd83dbSDimitry Andric                     ArrayRef<FunctionSummary::ConstVCall>{},
870bdd1243dSDimitry Andric                     ArrayRef<FunctionSummary::ParamAccess>{},
871bdd1243dSDimitry Andric                     ArrayRef<CallsiteInfo>{}, ArrayRef<AllocInfo>{});
8720b57cec5SDimitry Andric             Index.addGlobalValueSummary(*GV, std::move(Summary));
8730b57cec5SDimitry Andric           } else {
8740b57cec5SDimitry Andric             std::unique_ptr<GlobalVarSummary> Summary =
8758bcb0991SDimitry Andric                 std::make_unique<GlobalVarSummary>(
8765ffd83dbSDimitry Andric                     GVFlags,
8775ffd83dbSDimitry Andric                     GlobalVarSummary::GVarFlags(
8785ffd83dbSDimitry Andric                         false, false, cast<GlobalVariable>(GV)->isConstant(),
8795ffd83dbSDimitry Andric                         GlobalObject::VCallVisibilityPublic),
8800b57cec5SDimitry Andric                     ArrayRef<ValueInfo>{});
8810b57cec5SDimitry Andric             Index.addGlobalValueSummary(*GV, std::move(Summary));
8820b57cec5SDimitry Andric           }
8830b57cec5SDimitry Andric         });
8840b57cec5SDimitry Andric   }
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric   bool IsThinLTO = true;
8870b57cec5SDimitry Andric   if (auto *MD =
8880b57cec5SDimitry Andric           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
8890b57cec5SDimitry Andric     IsThinLTO = MD->getZExtValue();
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric   // Compute summaries for all functions defined in module, and save in the
8920b57cec5SDimitry Andric   // index.
893fcaf7f86SDimitry Andric   for (const auto &F : M) {
8940b57cec5SDimitry Andric     if (F.isDeclaration())
8950b57cec5SDimitry Andric       continue;
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric     DominatorTree DT(const_cast<Function &>(F));
8980b57cec5SDimitry Andric     BlockFrequencyInfo *BFI = nullptr;
8990b57cec5SDimitry Andric     std::unique_ptr<BlockFrequencyInfo> BFIPtr;
9000b57cec5SDimitry Andric     if (GetBFICallback)
9010b57cec5SDimitry Andric       BFI = GetBFICallback(F);
9020b57cec5SDimitry Andric     else if (F.hasProfileData()) {
9030b57cec5SDimitry Andric       LoopInfo LI{DT};
9040b57cec5SDimitry Andric       BranchProbabilityInfo BPI{F, LI};
9058bcb0991SDimitry Andric       BFIPtr = std::make_unique<BlockFrequencyInfo>(F, BPI, LI);
9060b57cec5SDimitry Andric       BFI = BFIPtr.get();
9070b57cec5SDimitry Andric     }
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric     computeFunctionSummary(Index, M, F, BFI, PSI, DT,
9100b57cec5SDimitry Andric                            !LocalsUsed.empty() || HasLocalInlineAsmSymbol,
9115ffd83dbSDimitry Andric                            CantBePromoted, IsThinLTO, GetSSICallback);
9120b57cec5SDimitry Andric   }
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric   // Compute summaries for all variables defined in module, and save in the
9150b57cec5SDimitry Andric   // index.
9160b57cec5SDimitry Andric   SmallVector<MDNode *, 2> Types;
9170b57cec5SDimitry Andric   for (const GlobalVariable &G : M.globals()) {
9180b57cec5SDimitry Andric     if (G.isDeclaration())
9190b57cec5SDimitry Andric       continue;
9200b57cec5SDimitry Andric     computeVariableSummary(Index, G, CantBePromoted, M, Types);
9210b57cec5SDimitry Andric   }
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric   // Compute summaries for all aliases defined in module, and save in the
9240b57cec5SDimitry Andric   // index.
9250b57cec5SDimitry Andric   for (const GlobalAlias &A : M.aliases())
9260b57cec5SDimitry Andric     computeAliasSummary(Index, A, CantBePromoted);
9270b57cec5SDimitry Andric 
928fcaf7f86SDimitry Andric   // Iterate through ifuncs, set their resolvers all alive.
929fcaf7f86SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
930fcaf7f86SDimitry Andric     I.applyAlongResolverPath([&Index](const GlobalValue &GV) {
931fcaf7f86SDimitry Andric       Index.getGlobalValueSummary(GV)->setLive(true);
932fcaf7f86SDimitry Andric     });
933fcaf7f86SDimitry Andric   }
934fcaf7f86SDimitry Andric 
9350b57cec5SDimitry Andric   for (auto *V : LocalsUsed) {
9360b57cec5SDimitry Andric     auto *Summary = Index.getGlobalValueSummary(*V);
9370b57cec5SDimitry Andric     assert(Summary && "Missing summary for global value");
9380b57cec5SDimitry Andric     Summary->setNotEligibleToImport();
9390b57cec5SDimitry Andric   }
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   // The linker doesn't know about these LLVM produced values, so we need
9420b57cec5SDimitry Andric   // to flag them as live in the index to ensure index-based dead value
9430b57cec5SDimitry Andric   // analysis treats them as live roots of the analysis.
9440b57cec5SDimitry Andric   setLiveRoot(Index, "llvm.used");
9450b57cec5SDimitry Andric   setLiveRoot(Index, "llvm.compiler.used");
9460b57cec5SDimitry Andric   setLiveRoot(Index, "llvm.global_ctors");
9470b57cec5SDimitry Andric   setLiveRoot(Index, "llvm.global_dtors");
9480b57cec5SDimitry Andric   setLiveRoot(Index, "llvm.global.annotations");
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   for (auto &GlobalList : Index) {
9510b57cec5SDimitry Andric     // Ignore entries for references that are undefined in the current module.
9520b57cec5SDimitry Andric     if (GlobalList.second.SummaryList.empty())
9530b57cec5SDimitry Andric       continue;
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric     assert(GlobalList.second.SummaryList.size() == 1 &&
9560b57cec5SDimitry Andric            "Expected module's index to have one summary per GUID");
9570b57cec5SDimitry Andric     auto &Summary = GlobalList.second.SummaryList[0];
9580b57cec5SDimitry Andric     if (!IsThinLTO) {
9590b57cec5SDimitry Andric       Summary->setNotEligibleToImport();
9600b57cec5SDimitry Andric       continue;
9610b57cec5SDimitry Andric     }
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric     bool AllRefsCanBeExternallyReferenced =
9640b57cec5SDimitry Andric         llvm::all_of(Summary->refs(), [&](const ValueInfo &VI) {
9650b57cec5SDimitry Andric           return !CantBePromoted.count(VI.getGUID());
9660b57cec5SDimitry Andric         });
9670b57cec5SDimitry Andric     if (!AllRefsCanBeExternallyReferenced) {
9680b57cec5SDimitry Andric       Summary->setNotEligibleToImport();
9690b57cec5SDimitry Andric       continue;
9700b57cec5SDimitry Andric     }
9710b57cec5SDimitry Andric 
9720b57cec5SDimitry Andric     if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
9730b57cec5SDimitry Andric       bool AllCallsCanBeExternallyReferenced = llvm::all_of(
9740b57cec5SDimitry Andric           FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
9750b57cec5SDimitry Andric             return !CantBePromoted.count(Edge.first.getGUID());
9760b57cec5SDimitry Andric           });
9770b57cec5SDimitry Andric       if (!AllCallsCanBeExternallyReferenced)
9780b57cec5SDimitry Andric         Summary->setNotEligibleToImport();
9790b57cec5SDimitry Andric     }
9800b57cec5SDimitry Andric   }
9810b57cec5SDimitry Andric 
9820b57cec5SDimitry Andric   if (!ModuleSummaryDotFile.empty()) {
9830b57cec5SDimitry Andric     std::error_code EC;
9848bcb0991SDimitry Andric     raw_fd_ostream OSDot(ModuleSummaryDotFile, EC, sys::fs::OpenFlags::OF_None);
9850b57cec5SDimitry Andric     if (EC)
9860b57cec5SDimitry Andric       report_fatal_error(Twine("Failed to open dot file ") +
9870b57cec5SDimitry Andric                          ModuleSummaryDotFile + ": " + EC.message() + "\n");
988480093f4SDimitry Andric     Index.exportToDot(OSDot, {});
9890b57cec5SDimitry Andric   }
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric   return Index;
9920b57cec5SDimitry Andric }
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric AnalysisKey ModuleSummaryIndexAnalysis::Key;
9950b57cec5SDimitry Andric 
9960b57cec5SDimitry Andric ModuleSummaryIndex
9970b57cec5SDimitry Andric ModuleSummaryIndexAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
9980b57cec5SDimitry Andric   ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
9990b57cec5SDimitry Andric   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
10005ffd83dbSDimitry Andric   bool NeedSSI = needsParamAccessSummary(M);
10010b57cec5SDimitry Andric   return buildModuleSummaryIndex(
10020b57cec5SDimitry Andric       M,
10030b57cec5SDimitry Andric       [&FAM](const Function &F) {
10040b57cec5SDimitry Andric         return &FAM.getResult<BlockFrequencyAnalysis>(
10050b57cec5SDimitry Andric             *const_cast<Function *>(&F));
10060b57cec5SDimitry Andric       },
10075ffd83dbSDimitry Andric       &PSI,
10085ffd83dbSDimitry Andric       [&FAM, NeedSSI](const Function &F) -> const StackSafetyInfo * {
10095ffd83dbSDimitry Andric         return NeedSSI ? &FAM.getResult<StackSafetyAnalysis>(
10105ffd83dbSDimitry Andric                              const_cast<Function &>(F))
10115ffd83dbSDimitry Andric                        : nullptr;
10125ffd83dbSDimitry Andric       });
10130b57cec5SDimitry Andric }
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric char ModuleSummaryIndexWrapperPass::ID = 0;
10160b57cec5SDimitry Andric 
10170b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
10180b57cec5SDimitry Andric                       "Module Summary Analysis", false, true)
10190b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
10200b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
10215ffd83dbSDimitry Andric INITIALIZE_PASS_DEPENDENCY(StackSafetyInfoWrapperPass)
10220b57cec5SDimitry Andric INITIALIZE_PASS_END(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
10230b57cec5SDimitry Andric                     "Module Summary Analysis", false, true)
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric ModulePass *llvm::createModuleSummaryIndexWrapperPass() {
10260b57cec5SDimitry Andric   return new ModuleSummaryIndexWrapperPass();
10270b57cec5SDimitry Andric }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric ModuleSummaryIndexWrapperPass::ModuleSummaryIndexWrapperPass()
10300b57cec5SDimitry Andric     : ModulePass(ID) {
10310b57cec5SDimitry Andric   initializeModuleSummaryIndexWrapperPassPass(*PassRegistry::getPassRegistry());
10320b57cec5SDimitry Andric }
10330b57cec5SDimitry Andric 
10340b57cec5SDimitry Andric bool ModuleSummaryIndexWrapperPass::runOnModule(Module &M) {
10350b57cec5SDimitry Andric   auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
10365ffd83dbSDimitry Andric   bool NeedSSI = needsParamAccessSummary(M);
10370b57cec5SDimitry Andric   Index.emplace(buildModuleSummaryIndex(
10380b57cec5SDimitry Andric       M,
10390b57cec5SDimitry Andric       [this](const Function &F) {
10400b57cec5SDimitry Andric         return &(this->getAnalysis<BlockFrequencyInfoWrapperPass>(
10410b57cec5SDimitry Andric                          *const_cast<Function *>(&F))
10420b57cec5SDimitry Andric                      .getBFI());
10430b57cec5SDimitry Andric       },
10445ffd83dbSDimitry Andric       PSI,
10455ffd83dbSDimitry Andric       [&](const Function &F) -> const StackSafetyInfo * {
10465ffd83dbSDimitry Andric         return NeedSSI ? &getAnalysis<StackSafetyInfoWrapperPass>(
10475ffd83dbSDimitry Andric                               const_cast<Function &>(F))
10485ffd83dbSDimitry Andric                               .getResult()
10495ffd83dbSDimitry Andric                        : nullptr;
10505ffd83dbSDimitry Andric       }));
10510b57cec5SDimitry Andric   return false;
10520b57cec5SDimitry Andric }
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric bool ModuleSummaryIndexWrapperPass::doFinalization(Module &M) {
10550b57cec5SDimitry Andric   Index.reset();
10560b57cec5SDimitry Andric   return false;
10570b57cec5SDimitry Andric }
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric void ModuleSummaryIndexWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10600b57cec5SDimitry Andric   AU.setPreservesAll();
10610b57cec5SDimitry Andric   AU.addRequired<BlockFrequencyInfoWrapperPass>();
10620b57cec5SDimitry Andric   AU.addRequired<ProfileSummaryInfoWrapperPass>();
10635ffd83dbSDimitry Andric   AU.addRequired<StackSafetyInfoWrapperPass>();
10640b57cec5SDimitry Andric }
10655ffd83dbSDimitry Andric 
10665ffd83dbSDimitry Andric char ImmutableModuleSummaryIndexWrapperPass::ID = 0;
10675ffd83dbSDimitry Andric 
10685ffd83dbSDimitry Andric ImmutableModuleSummaryIndexWrapperPass::ImmutableModuleSummaryIndexWrapperPass(
10695ffd83dbSDimitry Andric     const ModuleSummaryIndex *Index)
10705ffd83dbSDimitry Andric     : ImmutablePass(ID), Index(Index) {
10715ffd83dbSDimitry Andric   initializeImmutableModuleSummaryIndexWrapperPassPass(
10725ffd83dbSDimitry Andric       *PassRegistry::getPassRegistry());
10735ffd83dbSDimitry Andric }
10745ffd83dbSDimitry Andric 
10755ffd83dbSDimitry Andric void ImmutableModuleSummaryIndexWrapperPass::getAnalysisUsage(
10765ffd83dbSDimitry Andric     AnalysisUsage &AU) const {
10775ffd83dbSDimitry Andric   AU.setPreservesAll();
10785ffd83dbSDimitry Andric }
10795ffd83dbSDimitry Andric 
10805ffd83dbSDimitry Andric ImmutablePass *llvm::createImmutableModuleSummaryIndexWrapperPass(
10815ffd83dbSDimitry Andric     const ModuleSummaryIndex *Index) {
10825ffd83dbSDimitry Andric   return new ImmutableModuleSummaryIndexWrapperPass(Index);
10835ffd83dbSDimitry Andric }
10845ffd83dbSDimitry Andric 
10855ffd83dbSDimitry Andric INITIALIZE_PASS(ImmutableModuleSummaryIndexWrapperPass, "module-summary-info",
10865ffd83dbSDimitry Andric                 "Module summary info", false, true)
1087*06c3fb27SDimitry Andric 
1088*06c3fb27SDimitry Andric bool llvm::mayHaveMemprofSummary(const CallBase *CB) {
1089*06c3fb27SDimitry Andric   if (!CB)
1090*06c3fb27SDimitry Andric     return false;
1091*06c3fb27SDimitry Andric   if (CB->isDebugOrPseudoInst())
1092*06c3fb27SDimitry Andric     return false;
1093*06c3fb27SDimitry Andric   auto *CI = dyn_cast<CallInst>(CB);
1094*06c3fb27SDimitry Andric   auto *CalledValue = CB->getCalledOperand();
1095*06c3fb27SDimitry Andric   auto *CalledFunction = CB->getCalledFunction();
1096*06c3fb27SDimitry Andric   if (CalledValue && !CalledFunction) {
1097*06c3fb27SDimitry Andric     CalledValue = CalledValue->stripPointerCasts();
1098*06c3fb27SDimitry Andric     // Stripping pointer casts can reveal a called function.
1099*06c3fb27SDimitry Andric     CalledFunction = dyn_cast<Function>(CalledValue);
1100*06c3fb27SDimitry Andric   }
1101*06c3fb27SDimitry Andric   // Check if this is an alias to a function. If so, get the
1102*06c3fb27SDimitry Andric   // called aliasee for the checks below.
1103*06c3fb27SDimitry Andric   if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
1104*06c3fb27SDimitry Andric     assert(!CalledFunction &&
1105*06c3fb27SDimitry Andric            "Expected null called function in callsite for alias");
1106*06c3fb27SDimitry Andric     CalledFunction = dyn_cast<Function>(GA->getAliaseeObject());
1107*06c3fb27SDimitry Andric   }
1108*06c3fb27SDimitry Andric   // Check if this is a direct call to a known function or a known
1109*06c3fb27SDimitry Andric   // intrinsic, or an indirect call with profile data.
1110*06c3fb27SDimitry Andric   if (CalledFunction) {
1111*06c3fb27SDimitry Andric     if (CI && CalledFunction->isIntrinsic())
1112*06c3fb27SDimitry Andric       return false;
1113*06c3fb27SDimitry Andric   } else {
1114*06c3fb27SDimitry Andric     // TODO: For now skip indirect calls. See comments in
1115*06c3fb27SDimitry Andric     // computeFunctionSummary for what is needed to handle this.
1116*06c3fb27SDimitry Andric     return false;
1117*06c3fb27SDimitry Andric   }
1118*06c3fb27SDimitry Andric   return true;
1119*06c3fb27SDimitry Andric }
1120