xref: /llvm-project/llvm/lib/Analysis/ModuleSummaryAnalysis.cpp (revision d4ddf06b0c7f38612f334db71ef1d7a58a3cc8e0)
1 //===- ModuleSummaryAnalysis.cpp - Module summary index builder -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass builds a ModuleSummaryIndex object for the module, to be written
10 // to bitcode or LLVM assembly.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/Analysis/BlockFrequencyInfo.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/MemoryProfileInfo.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/StackSafetyAnalysis.h"
31 #include "llvm/Analysis/TypeMetadataUtils.h"
32 #include "llvm/IR/Attributes.h"
33 #include "llvm/IR/BasicBlock.h"
34 #include "llvm/IR/Constant.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/IntrinsicInst.h"
43 #include "llvm/IR/Metadata.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/IR/ModuleSummaryIndex.h"
46 #include "llvm/IR/Use.h"
47 #include "llvm/IR/User.h"
48 #include "llvm/InitializePasses.h"
49 #include "llvm/Object/ModuleSymbolTable.h"
50 #include "llvm/Object/SymbolicFile.h"
51 #include "llvm/Pass.h"
52 #include "llvm/Support/Casting.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/FileSystem.h"
55 #include <algorithm>
56 #include <cassert>
57 #include <cstdint>
58 #include <vector>
59 
60 using namespace llvm;
61 using namespace llvm::memprof;
62 
63 #define DEBUG_TYPE "module-summary-analysis"
64 
65 // Option to force edges cold which will block importing when the
66 // -import-cold-multiplier is set to 0. Useful for debugging.
67 namespace llvm {
68 FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold =
69     FunctionSummary::FSHT_None;
70 } // namespace llvm
71 
72 static cl::opt<FunctionSummary::ForceSummaryHotnessType, true> FSEC(
73     "force-summary-edges-cold", cl::Hidden, cl::location(ForceSummaryEdgesCold),
74     cl::desc("Force all edges in the function summary to cold"),
75     cl::values(clEnumValN(FunctionSummary::FSHT_None, "none", "None."),
76                clEnumValN(FunctionSummary::FSHT_AllNonCritical,
77                           "all-non-critical", "All non-critical edges."),
78                clEnumValN(FunctionSummary::FSHT_All, "all", "All edges.")));
79 
80 static cl::opt<std::string> ModuleSummaryDotFile(
81     "module-summary-dot-file", cl::Hidden, cl::value_desc("filename"),
82     cl::desc("File to emit dot graph of new summary into"));
83 
84 extern cl::opt<bool> ScalePartialSampleProfileWorkingSetSize;
85 
86 extern cl::opt<unsigned> MaxNumVTableAnnotations;
87 
88 extern cl::opt<bool> MemProfReportHintedSizes;
89 
90 // Walk through the operands of a given User via worklist iteration and populate
91 // the set of GlobalValue references encountered. Invoked either on an
92 // Instruction or a GlobalVariable (which walks its initializer).
93 // Return true if any of the operands contains blockaddress. This is important
94 // to know when computing summary for global var, because if global variable
95 // references basic block address we can't import it separately from function
96 // containing that basic block. For simplicity we currently don't import such
97 // global vars at all. When importing function we aren't interested if any
98 // instruction in it takes an address of any basic block, because instruction
99 // can only take an address of basic block located in the same function.
100 // Set `RefLocalLinkageIFunc` to true if the analyzed value references a
101 // local-linkage ifunc.
102 static bool
103 findRefEdges(ModuleSummaryIndex &Index, const User *CurUser,
104              SetVector<ValueInfo, SmallVector<ValueInfo, 0>> &RefEdges,
105              SmallPtrSet<const User *, 8> &Visited,
106              bool &RefLocalLinkageIFunc) {
107   bool HasBlockAddress = false;
108   SmallVector<const User *, 32> Worklist;
109   if (Visited.insert(CurUser).second)
110     Worklist.push_back(CurUser);
111 
112   while (!Worklist.empty()) {
113     const User *U = Worklist.pop_back_val();
114     const auto *CB = dyn_cast<CallBase>(U);
115 
116     for (const auto &OI : U->operands()) {
117       const User *Operand = dyn_cast<User>(OI);
118       if (!Operand)
119         continue;
120       if (isa<BlockAddress>(Operand)) {
121         HasBlockAddress = true;
122         continue;
123       }
124       if (auto *GV = dyn_cast<GlobalValue>(Operand)) {
125         // We have a reference to a global value. This should be added to
126         // the reference set unless it is a callee. Callees are handled
127         // specially by WriteFunction and are added to a separate list.
128         if (!(CB && CB->isCallee(&OI))) {
129           // If an ifunc has local linkage, do not add it into ref edges, and
130           // sets `RefLocalLinkageIFunc` to true. The referencer is not eligible
131           // for import. An ifunc doesn't have summary and ThinLTO cannot
132           // promote it; importing the referencer may cause linkage errors.
133           if (auto *GI = dyn_cast_if_present<GlobalIFunc>(GV);
134               GI && GI->hasLocalLinkage()) {
135             RefLocalLinkageIFunc = true;
136             continue;
137           }
138           RefEdges.insert(Index.getOrInsertValueInfo(GV));
139         }
140         continue;
141       }
142       if (Visited.insert(Operand).second)
143         Worklist.push_back(Operand);
144     }
145   }
146 
147   const Instruction *I = dyn_cast<Instruction>(CurUser);
148   if (I) {
149     uint64_t TotalCount = 0;
150     // MaxNumVTableAnnotations is the maximum number of vtables annotated on
151     // the instruction.
152     auto ValueDataArray = getValueProfDataFromInst(
153         *I, IPVK_VTableTarget, MaxNumVTableAnnotations, TotalCount);
154 
155     for (const auto &V : ValueDataArray)
156       RefEdges.insert(Index.getOrInsertValueInfo(/* VTableGUID = */
157                                                  V.Value));
158   }
159   return HasBlockAddress;
160 }
161 
162 static CalleeInfo::HotnessType getHotness(uint64_t ProfileCount,
163                                           ProfileSummaryInfo *PSI) {
164   if (!PSI)
165     return CalleeInfo::HotnessType::Unknown;
166   if (PSI->isHotCount(ProfileCount))
167     return CalleeInfo::HotnessType::Hot;
168   if (PSI->isColdCount(ProfileCount))
169     return CalleeInfo::HotnessType::Cold;
170   return CalleeInfo::HotnessType::None;
171 }
172 
173 static bool isNonRenamableLocal(const GlobalValue &GV) {
174   return GV.hasSection() && GV.hasLocalLinkage();
175 }
176 
177 /// Determine whether this call has all constant integer arguments (excluding
178 /// "this") and summarize it to VCalls or ConstVCalls as appropriate.
179 static void addVCallToSet(
180     DevirtCallSite Call, GlobalValue::GUID Guid,
181     SetVector<FunctionSummary::VFuncId, std::vector<FunctionSummary::VFuncId>>
182         &VCalls,
183     SetVector<FunctionSummary::ConstVCall,
184               std::vector<FunctionSummary::ConstVCall>> &ConstVCalls) {
185   std::vector<uint64_t> Args;
186   // Start from the second argument to skip the "this" pointer.
187   for (auto &Arg : drop_begin(Call.CB.args())) {
188     auto *CI = dyn_cast<ConstantInt>(Arg);
189     if (!CI || CI->getBitWidth() > 64) {
190       VCalls.insert({Guid, Call.Offset});
191       return;
192     }
193     Args.push_back(CI->getZExtValue());
194   }
195   ConstVCalls.insert({{Guid, Call.Offset}, std::move(Args)});
196 }
197 
198 /// If this intrinsic call requires that we add information to the function
199 /// summary, do so via the non-constant reference arguments.
200 static void addIntrinsicToSummary(
201     const CallInst *CI,
202     SetVector<GlobalValue::GUID, std::vector<GlobalValue::GUID>> &TypeTests,
203     SetVector<FunctionSummary::VFuncId, std::vector<FunctionSummary::VFuncId>>
204         &TypeTestAssumeVCalls,
205     SetVector<FunctionSummary::VFuncId, std::vector<FunctionSummary::VFuncId>>
206         &TypeCheckedLoadVCalls,
207     SetVector<FunctionSummary::ConstVCall,
208               std::vector<FunctionSummary::ConstVCall>>
209         &TypeTestAssumeConstVCalls,
210     SetVector<FunctionSummary::ConstVCall,
211               std::vector<FunctionSummary::ConstVCall>>
212         &TypeCheckedLoadConstVCalls,
213     DominatorTree &DT) {
214   switch (CI->getCalledFunction()->getIntrinsicID()) {
215   case Intrinsic::type_test:
216   case Intrinsic::public_type_test: {
217     auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(1));
218     auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
219     if (!TypeId)
220       break;
221     GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
222 
223     // Produce a summary from type.test intrinsics. We only summarize type.test
224     // intrinsics that are used other than by an llvm.assume intrinsic.
225     // Intrinsics that are assumed are relevant only to the devirtualization
226     // pass, not the type test lowering pass.
227     bool HasNonAssumeUses = llvm::any_of(CI->uses(), [](const Use &CIU) {
228       return !isa<AssumeInst>(CIU.getUser());
229     });
230     if (HasNonAssumeUses)
231       TypeTests.insert(Guid);
232 
233     SmallVector<DevirtCallSite, 4> DevirtCalls;
234     SmallVector<CallInst *, 4> Assumes;
235     findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
236     for (auto &Call : DevirtCalls)
237       addVCallToSet(Call, Guid, TypeTestAssumeVCalls,
238                     TypeTestAssumeConstVCalls);
239 
240     break;
241   }
242 
243   case Intrinsic::type_checked_load_relative:
244   case Intrinsic::type_checked_load: {
245     auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(2));
246     auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
247     if (!TypeId)
248       break;
249     GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
250 
251     SmallVector<DevirtCallSite, 4> DevirtCalls;
252     SmallVector<Instruction *, 4> LoadedPtrs;
253     SmallVector<Instruction *, 4> Preds;
254     bool HasNonCallUses = false;
255     findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
256                                                HasNonCallUses, CI, DT);
257     // Any non-call uses of the result of llvm.type.checked.load will
258     // prevent us from optimizing away the llvm.type.test.
259     if (HasNonCallUses)
260       TypeTests.insert(Guid);
261     for (auto &Call : DevirtCalls)
262       addVCallToSet(Call, Guid, TypeCheckedLoadVCalls,
263                     TypeCheckedLoadConstVCalls);
264 
265     break;
266   }
267   default:
268     break;
269   }
270 }
271 
272 static bool isNonVolatileLoad(const Instruction *I) {
273   if (const auto *LI = dyn_cast<LoadInst>(I))
274     return !LI->isVolatile();
275 
276   return false;
277 }
278 
279 static bool isNonVolatileStore(const Instruction *I) {
280   if (const auto *SI = dyn_cast<StoreInst>(I))
281     return !SI->isVolatile();
282 
283   return false;
284 }
285 
286 // Returns true if the function definition must be unreachable.
287 //
288 // Note if this helper function returns true, `F` is guaranteed
289 // to be unreachable; if it returns false, `F` might still
290 // be unreachable but not covered by this helper function.
291 static bool mustBeUnreachableFunction(const Function &F) {
292   // A function must be unreachable if its entry block ends with an
293   // 'unreachable'.
294   assert(!F.isDeclaration());
295   return isa<UnreachableInst>(F.getEntryBlock().getTerminator());
296 }
297 
298 static void computeFunctionSummary(
299     ModuleSummaryIndex &Index, const Module &M, const Function &F,
300     BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, DominatorTree &DT,
301     bool HasLocalsInUsedOrAsm, DenseSet<GlobalValue::GUID> &CantBePromoted,
302     bool IsThinLTO,
303     std::function<const StackSafetyInfo *(const Function &F)> GetSSICallback) {
304   // Summary not currently supported for anonymous functions, they should
305   // have been named.
306   assert(F.hasName());
307 
308   unsigned NumInsts = 0;
309   // Map from callee ValueId to profile count. Used to accumulate profile
310   // counts for all static calls to a given callee.
311   MapVector<ValueInfo, CalleeInfo, DenseMap<ValueInfo, unsigned>,
312             std::vector<std::pair<ValueInfo, CalleeInfo>>>
313       CallGraphEdges;
314   SetVector<ValueInfo, SmallVector<ValueInfo, 0>> RefEdges, LoadRefEdges,
315       StoreRefEdges;
316   SetVector<GlobalValue::GUID, std::vector<GlobalValue::GUID>> TypeTests;
317   SetVector<FunctionSummary::VFuncId, std::vector<FunctionSummary::VFuncId>>
318       TypeTestAssumeVCalls, TypeCheckedLoadVCalls;
319   SetVector<FunctionSummary::ConstVCall,
320             std::vector<FunctionSummary::ConstVCall>>
321       TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls;
322   ICallPromotionAnalysis ICallAnalysis;
323   SmallPtrSet<const User *, 8> Visited;
324 
325   // Add personality function, prefix data and prologue data to function's ref
326   // list.
327   bool HasLocalIFuncCallOrRef = false;
328   findRefEdges(Index, &F, RefEdges, Visited, HasLocalIFuncCallOrRef);
329   std::vector<const Instruction *> NonVolatileLoads;
330   std::vector<const Instruction *> NonVolatileStores;
331 
332   std::vector<CallsiteInfo> Callsites;
333   std::vector<AllocInfo> Allocs;
334 
335 #ifndef NDEBUG
336   DenseSet<const CallBase *> CallsThatMayHaveMemprofSummary;
337 #endif
338 
339   bool HasInlineAsmMaybeReferencingInternal = false;
340   bool HasIndirBranchToBlockAddress = false;
341   bool HasUnknownCall = false;
342   bool MayThrow = false;
343   for (const BasicBlock &BB : F) {
344     // We don't allow inlining of function with indirect branch to blockaddress.
345     // If the blockaddress escapes the function, e.g., via a global variable,
346     // inlining may lead to an invalid cross-function reference. So we shouldn't
347     // import such function either.
348     if (BB.hasAddressTaken()) {
349       for (User *U : BlockAddress::get(const_cast<BasicBlock *>(&BB))->users())
350         if (!isa<CallBrInst>(*U)) {
351           HasIndirBranchToBlockAddress = true;
352           break;
353         }
354     }
355 
356     for (const Instruction &I : BB) {
357       if (I.isDebugOrPseudoInst())
358         continue;
359       ++NumInsts;
360 
361       // Regular LTO module doesn't participate in ThinLTO import,
362       // so no reference from it can be read/writeonly, since this
363       // would require importing variable as local copy
364       if (IsThinLTO) {
365         if (isNonVolatileLoad(&I)) {
366           // Postpone processing of non-volatile load instructions
367           // See comments below
368           Visited.insert(&I);
369           NonVolatileLoads.push_back(&I);
370           continue;
371         } else if (isNonVolatileStore(&I)) {
372           Visited.insert(&I);
373           NonVolatileStores.push_back(&I);
374           // All references from second operand of store (destination address)
375           // can be considered write-only if they're not referenced by any
376           // non-store instruction. References from first operand of store
377           // (stored value) can't be treated either as read- or as write-only
378           // so we add them to RefEdges as we do with all other instructions
379           // except non-volatile load.
380           Value *Stored = I.getOperand(0);
381           if (auto *GV = dyn_cast<GlobalValue>(Stored))
382             // findRefEdges will try to examine GV operands, so instead
383             // of calling it we should add GV to RefEdges directly.
384             RefEdges.insert(Index.getOrInsertValueInfo(GV));
385           else if (auto *U = dyn_cast<User>(Stored))
386             findRefEdges(Index, U, RefEdges, Visited, HasLocalIFuncCallOrRef);
387           continue;
388         }
389       }
390       findRefEdges(Index, &I, RefEdges, Visited, HasLocalIFuncCallOrRef);
391       const auto *CB = dyn_cast<CallBase>(&I);
392       if (!CB) {
393         if (I.mayThrow())
394           MayThrow = true;
395         continue;
396       }
397 
398       const auto *CI = dyn_cast<CallInst>(&I);
399       // Since we don't know exactly which local values are referenced in inline
400       // assembly, conservatively mark the function as possibly referencing
401       // a local value from inline assembly to ensure we don't export a
402       // reference (which would require renaming and promotion of the
403       // referenced value).
404       if (HasLocalsInUsedOrAsm && CI && CI->isInlineAsm())
405         HasInlineAsmMaybeReferencingInternal = true;
406 
407       auto *CalledValue = CB->getCalledOperand();
408       auto *CalledFunction = CB->getCalledFunction();
409       if (CalledValue && !CalledFunction) {
410         CalledValue = CalledValue->stripPointerCasts();
411         // Stripping pointer casts can reveal a called function.
412         CalledFunction = dyn_cast<Function>(CalledValue);
413       }
414       // Check if this is an alias to a function. If so, get the
415       // called aliasee for the checks below.
416       if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
417         assert(!CalledFunction && "Expected null called function in callsite for alias");
418         CalledFunction = dyn_cast<Function>(GA->getAliaseeObject());
419       }
420       // Check if this is a direct call to a known function or a known
421       // intrinsic, or an indirect call with profile data.
422       if (CalledFunction) {
423         if (CI && CalledFunction->isIntrinsic()) {
424           addIntrinsicToSummary(
425               CI, TypeTests, TypeTestAssumeVCalls, TypeCheckedLoadVCalls,
426               TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls, DT);
427           continue;
428         }
429         // We should have named any anonymous globals
430         assert(CalledFunction->hasName());
431         auto ScaledCount = PSI->getProfileCount(*CB, BFI);
432         auto Hotness = ScaledCount ? getHotness(*ScaledCount, PSI)
433                                    : CalleeInfo::HotnessType::Unknown;
434         if (ForceSummaryEdgesCold != FunctionSummary::FSHT_None)
435           Hotness = CalleeInfo::HotnessType::Cold;
436 
437         // Use the original CalledValue, in case it was an alias. We want
438         // to record the call edge to the alias in that case. Eventually
439         // an alias summary will be created to associate the alias and
440         // aliasee.
441         auto &ValueInfo = CallGraphEdges[Index.getOrInsertValueInfo(
442             cast<GlobalValue>(CalledValue))];
443         ValueInfo.updateHotness(Hotness);
444         if (CB->isTailCall())
445           ValueInfo.setHasTailCall(true);
446         // Add the relative block frequency to CalleeInfo if there is no profile
447         // information.
448         if (BFI != nullptr && Hotness == CalleeInfo::HotnessType::Unknown) {
449           uint64_t BBFreq = BFI->getBlockFreq(&BB).getFrequency();
450           uint64_t EntryFreq = BFI->getEntryFreq().getFrequency();
451           ValueInfo.updateRelBlockFreq(BBFreq, EntryFreq);
452         }
453       } else {
454         HasUnknownCall = true;
455         // If F is imported, a local linkage ifunc (e.g. target_clones on a
456         // static function) called by F will be cloned. Since summaries don't
457         // track ifunc, we do not know implementation functions referenced by
458         // the ifunc resolver need to be promoted in the exporter, and we will
459         // get linker errors due to cloned declarations for implementation
460         // functions. As a simple fix, just mark F as not eligible for import.
461         // Non-local ifunc is not cloned and does not have the issue.
462         if (auto *GI = dyn_cast_if_present<GlobalIFunc>(CalledValue))
463           if (GI->hasLocalLinkage())
464             HasLocalIFuncCallOrRef = true;
465         // Skip inline assembly calls.
466         if (CI && CI->isInlineAsm())
467           continue;
468         // Skip direct calls.
469         if (!CalledValue || isa<Constant>(CalledValue))
470           continue;
471 
472         // Check if the instruction has a callees metadata. If so, add callees
473         // to CallGraphEdges to reflect the references from the metadata, and
474         // to enable importing for subsequent indirect call promotion and
475         // inlining.
476         if (auto *MD = I.getMetadata(LLVMContext::MD_callees)) {
477           for (const auto &Op : MD->operands()) {
478             Function *Callee = mdconst::extract_or_null<Function>(Op);
479             if (Callee)
480               CallGraphEdges[Index.getOrInsertValueInfo(Callee)];
481           }
482         }
483 
484         uint32_t NumCandidates;
485         uint64_t TotalCount;
486         auto CandidateProfileData =
487             ICallAnalysis.getPromotionCandidatesForInstruction(&I, TotalCount,
488                                                                NumCandidates);
489         for (const auto &Candidate : CandidateProfileData)
490           CallGraphEdges[Index.getOrInsertValueInfo(Candidate.Value)]
491               .updateHotness(getHotness(Candidate.Count, PSI));
492       }
493 
494       // Summarize memprof related metadata. This is only needed for ThinLTO.
495       if (!IsThinLTO)
496         continue;
497 
498       // TODO: Skip indirect calls for now. Need to handle these better, likely
499       // by creating multiple Callsites, one per target, then speculatively
500       // devirtualize while applying clone info in the ThinLTO backends. This
501       // will also be important because we will have a different set of clone
502       // versions per target. This handling needs to match that in the ThinLTO
503       // backend so we handle things consistently for matching of callsite
504       // summaries to instructions.
505       if (!CalledFunction)
506         continue;
507 
508       // Ensure we keep this analysis in sync with the handling in the ThinLTO
509       // backend (see MemProfContextDisambiguation::applyImport). Save this call
510       // so that we can skip it in checking the reverse case later.
511       assert(mayHaveMemprofSummary(CB));
512 #ifndef NDEBUG
513       CallsThatMayHaveMemprofSummary.insert(CB);
514 #endif
515 
516       // Compute the list of stack ids first (so we can trim them from the stack
517       // ids on any MIBs).
518       CallStack<MDNode, MDNode::op_iterator> InstCallsite(
519           I.getMetadata(LLVMContext::MD_callsite));
520       auto *MemProfMD = I.getMetadata(LLVMContext::MD_memprof);
521       if (MemProfMD) {
522         std::vector<MIBInfo> MIBs;
523         std::vector<uint64_t> TotalSizes;
524         for (auto &MDOp : MemProfMD->operands()) {
525           auto *MIBMD = cast<const MDNode>(MDOp);
526           MDNode *StackNode = getMIBStackNode(MIBMD);
527           assert(StackNode);
528           SmallVector<unsigned> StackIdIndices;
529           CallStack<MDNode, MDNode::op_iterator> StackContext(StackNode);
530           // Collapse out any on the allocation call (inlining).
531           for (auto ContextIter =
532                    StackContext.beginAfterSharedPrefix(InstCallsite);
533                ContextIter != StackContext.end(); ++ContextIter) {
534             unsigned StackIdIdx = Index.addOrGetStackIdIndex(*ContextIter);
535             // If this is a direct recursion, simply skip the duplicate
536             // entries. If this is mutual recursion, handling is left to
537             // the LTO link analysis client.
538             if (StackIdIndices.empty() || StackIdIndices.back() != StackIdIdx)
539               StackIdIndices.push_back(StackIdIdx);
540           }
541           MIBs.push_back(
542               MIBInfo(getMIBAllocType(MIBMD), std::move(StackIdIndices)));
543           if (MemProfReportHintedSizes) {
544             auto TotalSize = getMIBTotalSize(MIBMD);
545             assert(TotalSize);
546             TotalSizes.push_back(TotalSize);
547           }
548         }
549         Allocs.push_back(AllocInfo(std::move(MIBs)));
550         if (MemProfReportHintedSizes) {
551           assert(Allocs.back().MIBs.size() == TotalSizes.size());
552           Allocs.back().TotalSizes = std::move(TotalSizes);
553         }
554       } else if (!InstCallsite.empty()) {
555         SmallVector<unsigned> StackIdIndices;
556         for (auto StackId : InstCallsite)
557           StackIdIndices.push_back(Index.addOrGetStackIdIndex(StackId));
558         // Use the original CalledValue, in case it was an alias. We want
559         // to record the call edge to the alias in that case. Eventually
560         // an alias summary will be created to associate the alias and
561         // aliasee.
562         auto CalleeValueInfo =
563             Index.getOrInsertValueInfo(cast<GlobalValue>(CalledValue));
564         Callsites.push_back({CalleeValueInfo, StackIdIndices});
565       }
566     }
567   }
568 
569   if (PSI->hasPartialSampleProfile() && ScalePartialSampleProfileWorkingSetSize)
570     Index.addBlockCount(F.size());
571 
572   SmallVector<ValueInfo, 0> Refs;
573   if (IsThinLTO) {
574     auto AddRefEdges =
575         [&](const std::vector<const Instruction *> &Instrs,
576             SetVector<ValueInfo, SmallVector<ValueInfo, 0>> &Edges,
577             SmallPtrSet<const User *, 8> &Cache) {
578           for (const auto *I : Instrs) {
579             Cache.erase(I);
580             findRefEdges(Index, I, Edges, Cache, HasLocalIFuncCallOrRef);
581           }
582         };
583 
584     // By now we processed all instructions in a function, except
585     // non-volatile loads and non-volatile value stores. Let's find
586     // ref edges for both of instruction sets
587     AddRefEdges(NonVolatileLoads, LoadRefEdges, Visited);
588     // We can add some values to the Visited set when processing load
589     // instructions which are also used by stores in NonVolatileStores.
590     // For example this can happen if we have following code:
591     //
592     // store %Derived* @foo, %Derived** bitcast (%Base** @bar to %Derived**)
593     // %42 = load %Derived*, %Derived** bitcast (%Base** @bar to %Derived**)
594     //
595     // After processing loads we'll add bitcast to the Visited set, and if
596     // we use the same set while processing stores, we'll never see store
597     // to @bar and @bar will be mistakenly treated as readonly.
598     SmallPtrSet<const llvm::User *, 8> StoreCache;
599     AddRefEdges(NonVolatileStores, StoreRefEdges, StoreCache);
600 
601     // If both load and store instruction reference the same variable
602     // we won't be able to optimize it. Add all such reference edges
603     // to RefEdges set.
604     for (const auto &VI : StoreRefEdges)
605       if (LoadRefEdges.remove(VI))
606         RefEdges.insert(VI);
607 
608     unsigned RefCnt = RefEdges.size();
609     // All new reference edges inserted in two loops below are either
610     // read or write only. They will be grouped in the end of RefEdges
611     // vector, so we can use a single integer value to identify them.
612     for (const auto &VI : LoadRefEdges)
613       RefEdges.insert(VI);
614 
615     unsigned FirstWORef = RefEdges.size();
616     for (const auto &VI : StoreRefEdges)
617       RefEdges.insert(VI);
618 
619     Refs = RefEdges.takeVector();
620     for (; RefCnt < FirstWORef; ++RefCnt)
621       Refs[RefCnt].setReadOnly();
622 
623     for (; RefCnt < Refs.size(); ++RefCnt)
624       Refs[RefCnt].setWriteOnly();
625   } else {
626     Refs = RefEdges.takeVector();
627   }
628   // Explicit add hot edges to enforce importing for designated GUIDs for
629   // sample PGO, to enable the same inlines as the profiled optimized binary.
630   for (auto &I : F.getImportGUIDs())
631     CallGraphEdges[Index.getOrInsertValueInfo(I)].updateHotness(
632         ForceSummaryEdgesCold == FunctionSummary::FSHT_All
633             ? CalleeInfo::HotnessType::Cold
634             : CalleeInfo::HotnessType::Critical);
635 
636 #ifndef NDEBUG
637   // Make sure that all calls we decided could not have memprof summaries get a
638   // false value for mayHaveMemprofSummary, to ensure that this handling remains
639   // in sync with the ThinLTO backend handling.
640   if (IsThinLTO) {
641     for (const BasicBlock &BB : F) {
642       for (const Instruction &I : BB) {
643         const auto *CB = dyn_cast<CallBase>(&I);
644         if (!CB)
645           continue;
646         // We already checked these above.
647         if (CallsThatMayHaveMemprofSummary.count(CB))
648           continue;
649         assert(!mayHaveMemprofSummary(CB));
650       }
651     }
652   }
653 #endif
654 
655   bool NonRenamableLocal = isNonRenamableLocal(F);
656   bool NotEligibleForImport =
657       NonRenamableLocal || HasInlineAsmMaybeReferencingInternal ||
658       HasIndirBranchToBlockAddress || HasLocalIFuncCallOrRef;
659   GlobalValueSummary::GVFlags Flags(
660       F.getLinkage(), F.getVisibility(), NotEligibleForImport,
661       /* Live = */ false, F.isDSOLocal(), F.canBeOmittedFromSymbolTable(),
662       GlobalValueSummary::ImportKind::Definition);
663   FunctionSummary::FFlags FunFlags{
664       F.doesNotAccessMemory(), F.onlyReadsMemory() && !F.doesNotAccessMemory(),
665       F.hasFnAttribute(Attribute::NoRecurse), F.returnDoesNotAlias(),
666       // FIXME: refactor this to use the same code that inliner is using.
667       // Don't try to import functions with noinline attribute.
668       F.getAttributes().hasFnAttr(Attribute::NoInline),
669       F.hasFnAttribute(Attribute::AlwaysInline),
670       F.hasFnAttribute(Attribute::NoUnwind), MayThrow, HasUnknownCall,
671       mustBeUnreachableFunction(F)};
672   std::vector<FunctionSummary::ParamAccess> ParamAccesses;
673   if (auto *SSI = GetSSICallback(F))
674     ParamAccesses = SSI->getParamAccesses(Index);
675   auto FuncSummary = std::make_unique<FunctionSummary>(
676       Flags, NumInsts, FunFlags, std::move(Refs), CallGraphEdges.takeVector(),
677       TypeTests.takeVector(), TypeTestAssumeVCalls.takeVector(),
678       TypeCheckedLoadVCalls.takeVector(),
679       TypeTestAssumeConstVCalls.takeVector(),
680       TypeCheckedLoadConstVCalls.takeVector(), std::move(ParamAccesses),
681       std::move(Callsites), std::move(Allocs));
682   if (NonRenamableLocal)
683     CantBePromoted.insert(F.getGUID());
684   Index.addGlobalValueSummary(F, std::move(FuncSummary));
685 }
686 
687 /// Find function pointers referenced within the given vtable initializer
688 /// (or subset of an initializer) \p I. The starting offset of \p I within
689 /// the vtable initializer is \p StartingOffset. Any discovered function
690 /// pointers are added to \p VTableFuncs along with their cumulative offset
691 /// within the initializer.
692 static void findFuncPointers(const Constant *I, uint64_t StartingOffset,
693                              const Module &M, ModuleSummaryIndex &Index,
694                              VTableFuncList &VTableFuncs,
695                              const GlobalVariable &OrigGV) {
696   // First check if this is a function pointer.
697   if (I->getType()->isPointerTy()) {
698     auto C = I->stripPointerCasts();
699     auto A = dyn_cast<GlobalAlias>(C);
700     if (isa<Function>(C) || (A && isa<Function>(A->getAliasee()))) {
701       auto GV = dyn_cast<GlobalValue>(C);
702       assert(GV);
703       // We can disregard __cxa_pure_virtual as a possible call target, as
704       // calls to pure virtuals are UB.
705       if (GV && GV->getName() != "__cxa_pure_virtual")
706         VTableFuncs.push_back({Index.getOrInsertValueInfo(GV), StartingOffset});
707       return;
708     }
709   }
710 
711   // Walk through the elements in the constant struct or array and recursively
712   // look for virtual function pointers.
713   const DataLayout &DL = M.getDataLayout();
714   if (auto *C = dyn_cast<ConstantStruct>(I)) {
715     StructType *STy = dyn_cast<StructType>(C->getType());
716     assert(STy);
717     const StructLayout *SL = DL.getStructLayout(C->getType());
718 
719     for (auto EI : llvm::enumerate(STy->elements())) {
720       auto Offset = SL->getElementOffset(EI.index());
721       unsigned Op = SL->getElementContainingOffset(Offset);
722       findFuncPointers(cast<Constant>(I->getOperand(Op)),
723                        StartingOffset + Offset, M, Index, VTableFuncs, OrigGV);
724     }
725   } else if (auto *C = dyn_cast<ConstantArray>(I)) {
726     ArrayType *ATy = C->getType();
727     Type *EltTy = ATy->getElementType();
728     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
729     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
730       findFuncPointers(cast<Constant>(I->getOperand(i)),
731                        StartingOffset + i * EltSize, M, Index, VTableFuncs,
732                        OrigGV);
733     }
734   } else if (const auto *CE = dyn_cast<ConstantExpr>(I)) {
735     // For relative vtables, the next sub-component should be a trunc.
736     if (CE->getOpcode() != Instruction::Trunc ||
737         !(CE = dyn_cast<ConstantExpr>(CE->getOperand(0))))
738       return;
739 
740     // If this constant can be reduced to the offset between a function and a
741     // global, then we know this is a valid virtual function if the RHS is the
742     // original vtable we're scanning through.
743     if (CE->getOpcode() == Instruction::Sub) {
744       GlobalValue *LHS, *RHS;
745       APSInt LHSOffset, RHSOffset;
746       if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHS, LHSOffset, DL) &&
747           IsConstantOffsetFromGlobal(CE->getOperand(1), RHS, RHSOffset, DL) &&
748           RHS == &OrigGV &&
749 
750           // For relative vtables, this component should point to the callable
751           // function without any offsets.
752           LHSOffset == 0 &&
753 
754           // Also, the RHS should always point to somewhere within the vtable.
755           RHSOffset <=
756               static_cast<uint64_t>(DL.getTypeAllocSize(OrigGV.getInitializer()->getType()))) {
757         findFuncPointers(LHS, StartingOffset, M, Index, VTableFuncs, OrigGV);
758       }
759     }
760   }
761 }
762 
763 // Identify the function pointers referenced by vtable definition \p V.
764 static void computeVTableFuncs(ModuleSummaryIndex &Index,
765                                const GlobalVariable &V, const Module &M,
766                                VTableFuncList &VTableFuncs) {
767   if (!V.isConstant())
768     return;
769 
770   findFuncPointers(V.getInitializer(), /*StartingOffset=*/0, M, Index,
771                    VTableFuncs, V);
772 
773 #ifndef NDEBUG
774   // Validate that the VTableFuncs list is ordered by offset.
775   uint64_t PrevOffset = 0;
776   for (auto &P : VTableFuncs) {
777     // The findVFuncPointers traversal should have encountered the
778     // functions in offset order. We need to use ">=" since PrevOffset
779     // starts at 0.
780     assert(P.VTableOffset >= PrevOffset);
781     PrevOffset = P.VTableOffset;
782   }
783 #endif
784 }
785 
786 /// Record vtable definition \p V for each type metadata it references.
787 static void
788 recordTypeIdCompatibleVtableReferences(ModuleSummaryIndex &Index,
789                                        const GlobalVariable &V,
790                                        SmallVectorImpl<MDNode *> &Types) {
791   for (MDNode *Type : Types) {
792     auto TypeID = Type->getOperand(1).get();
793 
794     uint64_t Offset =
795         cast<ConstantInt>(
796             cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
797             ->getZExtValue();
798 
799     if (auto *TypeId = dyn_cast<MDString>(TypeID))
800       Index.getOrInsertTypeIdCompatibleVtableSummary(TypeId->getString())
801           .push_back({Offset, Index.getOrInsertValueInfo(&V)});
802   }
803 }
804 
805 static void computeVariableSummary(ModuleSummaryIndex &Index,
806                                    const GlobalVariable &V,
807                                    DenseSet<GlobalValue::GUID> &CantBePromoted,
808                                    const Module &M,
809                                    SmallVectorImpl<MDNode *> &Types) {
810   SetVector<ValueInfo, SmallVector<ValueInfo, 0>> RefEdges;
811   SmallPtrSet<const User *, 8> Visited;
812   bool RefLocalIFunc = false;
813   bool HasBlockAddress =
814       findRefEdges(Index, &V, RefEdges, Visited, RefLocalIFunc);
815   const bool NotEligibleForImport = (HasBlockAddress || RefLocalIFunc);
816   bool NonRenamableLocal = isNonRenamableLocal(V);
817   GlobalValueSummary::GVFlags Flags(
818       V.getLinkage(), V.getVisibility(), NonRenamableLocal,
819       /* Live = */ false, V.isDSOLocal(), V.canBeOmittedFromSymbolTable(),
820       GlobalValueSummary::Definition);
821 
822   VTableFuncList VTableFuncs;
823   // If splitting is not enabled, then we compute the summary information
824   // necessary for index-based whole program devirtualization.
825   if (!Index.enableSplitLTOUnit()) {
826     Types.clear();
827     V.getMetadata(LLVMContext::MD_type, Types);
828     if (!Types.empty()) {
829       // Identify the function pointers referenced by this vtable definition.
830       computeVTableFuncs(Index, V, M, VTableFuncs);
831 
832       // Record this vtable definition for each type metadata it references.
833       recordTypeIdCompatibleVtableReferences(Index, V, Types);
834     }
835   }
836 
837   // Don't mark variables we won't be able to internalize as read/write-only.
838   bool CanBeInternalized =
839       !V.hasComdat() && !V.hasAppendingLinkage() && !V.isInterposable() &&
840       !V.hasAvailableExternallyLinkage() && !V.hasDLLExportStorageClass();
841   bool Constant = V.isConstant();
842   GlobalVarSummary::GVarFlags VarFlags(CanBeInternalized,
843                                        Constant ? false : CanBeInternalized,
844                                        Constant, V.getVCallVisibility());
845   auto GVarSummary = std::make_unique<GlobalVarSummary>(Flags, VarFlags,
846                                                          RefEdges.takeVector());
847   if (NonRenamableLocal)
848     CantBePromoted.insert(V.getGUID());
849   if (NotEligibleForImport)
850     GVarSummary->setNotEligibleToImport();
851   if (!VTableFuncs.empty())
852     GVarSummary->setVTableFuncs(VTableFuncs);
853   Index.addGlobalValueSummary(V, std::move(GVarSummary));
854 }
855 
856 static void computeAliasSummary(ModuleSummaryIndex &Index, const GlobalAlias &A,
857                                 DenseSet<GlobalValue::GUID> &CantBePromoted) {
858   // Skip summary for indirect function aliases as summary for aliasee will not
859   // be emitted.
860   const GlobalObject *Aliasee = A.getAliaseeObject();
861   if (isa<GlobalIFunc>(Aliasee))
862     return;
863   bool NonRenamableLocal = isNonRenamableLocal(A);
864   GlobalValueSummary::GVFlags Flags(
865       A.getLinkage(), A.getVisibility(), NonRenamableLocal,
866       /* Live = */ false, A.isDSOLocal(), A.canBeOmittedFromSymbolTable(),
867       GlobalValueSummary::Definition);
868   auto AS = std::make_unique<AliasSummary>(Flags);
869   auto AliaseeVI = Index.getValueInfo(Aliasee->getGUID());
870   assert(AliaseeVI && "Alias expects aliasee summary to be available");
871   assert(AliaseeVI.getSummaryList().size() == 1 &&
872          "Expected a single entry per aliasee in per-module index");
873   AS->setAliasee(AliaseeVI, AliaseeVI.getSummaryList()[0].get());
874   if (NonRenamableLocal)
875     CantBePromoted.insert(A.getGUID());
876   Index.addGlobalValueSummary(A, std::move(AS));
877 }
878 
879 // Set LiveRoot flag on entries matching the given value name.
880 static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) {
881   if (ValueInfo VI = Index.getValueInfo(GlobalValue::getGUID(Name)))
882     for (const auto &Summary : VI.getSummaryList())
883       Summary->setLive(true);
884 }
885 
886 ModuleSummaryIndex llvm::buildModuleSummaryIndex(
887     const Module &M,
888     std::function<BlockFrequencyInfo *(const Function &F)> GetBFICallback,
889     ProfileSummaryInfo *PSI,
890     std::function<const StackSafetyInfo *(const Function &F)> GetSSICallback) {
891   assert(PSI);
892   bool EnableSplitLTOUnit = false;
893   bool UnifiedLTO = false;
894   if (auto *MD = mdconst::extract_or_null<ConstantInt>(
895           M.getModuleFlag("EnableSplitLTOUnit")))
896     EnableSplitLTOUnit = MD->getZExtValue();
897   if (auto *MD =
898           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("UnifiedLTO")))
899     UnifiedLTO = MD->getZExtValue();
900   ModuleSummaryIndex Index(/*HaveGVs=*/true, EnableSplitLTOUnit, UnifiedLTO);
901 
902   // Identify the local values in the llvm.used and llvm.compiler.used sets,
903   // which should not be exported as they would then require renaming and
904   // promotion, but we may have opaque uses e.g. in inline asm. We collect them
905   // here because we use this information to mark functions containing inline
906   // assembly calls as not importable.
907   SmallPtrSet<GlobalValue *, 4> LocalsUsed;
908   SmallVector<GlobalValue *, 4> Used;
909   // First collect those in the llvm.used set.
910   collectUsedGlobalVariables(M, Used, /*CompilerUsed=*/false);
911   // Next collect those in the llvm.compiler.used set.
912   collectUsedGlobalVariables(M, Used, /*CompilerUsed=*/true);
913   DenseSet<GlobalValue::GUID> CantBePromoted;
914   for (auto *V : Used) {
915     if (V->hasLocalLinkage()) {
916       LocalsUsed.insert(V);
917       CantBePromoted.insert(V->getGUID());
918     }
919   }
920 
921   bool HasLocalInlineAsmSymbol = false;
922   if (!M.getModuleInlineAsm().empty()) {
923     // Collect the local values defined by module level asm, and set up
924     // summaries for these symbols so that they can be marked as NoRename,
925     // to prevent export of any use of them in regular IR that would require
926     // renaming within the module level asm. Note we don't need to create a
927     // summary for weak or global defs, as they don't need to be flagged as
928     // NoRename, and defs in module level asm can't be imported anyway.
929     // Also, any values used but not defined within module level asm should
930     // be listed on the llvm.used or llvm.compiler.used global and marked as
931     // referenced from there.
932     ModuleSymbolTable::CollectAsmSymbols(
933         M, [&](StringRef Name, object::BasicSymbolRef::Flags Flags) {
934           // Symbols not marked as Weak or Global are local definitions.
935           if (Flags & (object::BasicSymbolRef::SF_Weak |
936                        object::BasicSymbolRef::SF_Global))
937             return;
938           HasLocalInlineAsmSymbol = true;
939           GlobalValue *GV = M.getNamedValue(Name);
940           if (!GV)
941             return;
942           assert(GV->isDeclaration() && "Def in module asm already has definition");
943           GlobalValueSummary::GVFlags GVFlags(
944               GlobalValue::InternalLinkage, GlobalValue::DefaultVisibility,
945               /* NotEligibleToImport = */ true,
946               /* Live = */ true,
947               /* Local */ GV->isDSOLocal(), GV->canBeOmittedFromSymbolTable(),
948               GlobalValueSummary::Definition);
949           CantBePromoted.insert(GV->getGUID());
950           // Create the appropriate summary type.
951           if (Function *F = dyn_cast<Function>(GV)) {
952             std::unique_ptr<FunctionSummary> Summary =
953                 std::make_unique<FunctionSummary>(
954                     GVFlags, /*InstCount=*/0,
955                     FunctionSummary::FFlags{
956                         F->hasFnAttribute(Attribute::ReadNone),
957                         F->hasFnAttribute(Attribute::ReadOnly),
958                         F->hasFnAttribute(Attribute::NoRecurse),
959                         F->returnDoesNotAlias(),
960                         /* NoInline = */ false,
961                         F->hasFnAttribute(Attribute::AlwaysInline),
962                         F->hasFnAttribute(Attribute::NoUnwind),
963                         /* MayThrow */ true,
964                         /* HasUnknownCall */ true,
965                         /* MustBeUnreachable */ false},
966                     SmallVector<ValueInfo, 0>{},
967                     ArrayRef<FunctionSummary::EdgeTy>{},
968                     ArrayRef<GlobalValue::GUID>{},
969                     ArrayRef<FunctionSummary::VFuncId>{},
970                     ArrayRef<FunctionSummary::VFuncId>{},
971                     ArrayRef<FunctionSummary::ConstVCall>{},
972                     ArrayRef<FunctionSummary::ConstVCall>{},
973                     ArrayRef<FunctionSummary::ParamAccess>{},
974                     ArrayRef<CallsiteInfo>{}, ArrayRef<AllocInfo>{});
975             Index.addGlobalValueSummary(*GV, std::move(Summary));
976           } else {
977             std::unique_ptr<GlobalVarSummary> Summary =
978                 std::make_unique<GlobalVarSummary>(
979                     GVFlags,
980                     GlobalVarSummary::GVarFlags(
981                         false, false, cast<GlobalVariable>(GV)->isConstant(),
982                         GlobalObject::VCallVisibilityPublic),
983                     SmallVector<ValueInfo, 0>{});
984             Index.addGlobalValueSummary(*GV, std::move(Summary));
985           }
986         });
987   }
988 
989   bool IsThinLTO = true;
990   if (auto *MD =
991           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
992     IsThinLTO = MD->getZExtValue();
993 
994   // Compute summaries for all functions defined in module, and save in the
995   // index.
996   for (const auto &F : M) {
997     if (F.isDeclaration())
998       continue;
999 
1000     DominatorTree DT(const_cast<Function &>(F));
1001     BlockFrequencyInfo *BFI = nullptr;
1002     std::unique_ptr<BlockFrequencyInfo> BFIPtr;
1003     if (GetBFICallback)
1004       BFI = GetBFICallback(F);
1005     else if (F.hasProfileData()) {
1006       LoopInfo LI{DT};
1007       BranchProbabilityInfo BPI{F, LI};
1008       BFIPtr = std::make_unique<BlockFrequencyInfo>(F, BPI, LI);
1009       BFI = BFIPtr.get();
1010     }
1011 
1012     computeFunctionSummary(Index, M, F, BFI, PSI, DT,
1013                            !LocalsUsed.empty() || HasLocalInlineAsmSymbol,
1014                            CantBePromoted, IsThinLTO, GetSSICallback);
1015   }
1016 
1017   // Compute summaries for all variables defined in module, and save in the
1018   // index.
1019   SmallVector<MDNode *, 2> Types;
1020   for (const GlobalVariable &G : M.globals()) {
1021     if (G.isDeclaration())
1022       continue;
1023     computeVariableSummary(Index, G, CantBePromoted, M, Types);
1024   }
1025 
1026   // Compute summaries for all aliases defined in module, and save in the
1027   // index.
1028   for (const GlobalAlias &A : M.aliases())
1029     computeAliasSummary(Index, A, CantBePromoted);
1030 
1031   // Iterate through ifuncs, set their resolvers all alive.
1032   for (const GlobalIFunc &I : M.ifuncs()) {
1033     I.applyAlongResolverPath([&Index](const GlobalValue &GV) {
1034       Index.getGlobalValueSummary(GV)->setLive(true);
1035     });
1036   }
1037 
1038   for (auto *V : LocalsUsed) {
1039     auto *Summary = Index.getGlobalValueSummary(*V);
1040     assert(Summary && "Missing summary for global value");
1041     Summary->setNotEligibleToImport();
1042   }
1043 
1044   // The linker doesn't know about these LLVM produced values, so we need
1045   // to flag them as live in the index to ensure index-based dead value
1046   // analysis treats them as live roots of the analysis.
1047   setLiveRoot(Index, "llvm.used");
1048   setLiveRoot(Index, "llvm.compiler.used");
1049   setLiveRoot(Index, "llvm.global_ctors");
1050   setLiveRoot(Index, "llvm.global_dtors");
1051   setLiveRoot(Index, "llvm.global.annotations");
1052 
1053   for (auto &GlobalList : Index) {
1054     // Ignore entries for references that are undefined in the current module.
1055     if (GlobalList.second.SummaryList.empty())
1056       continue;
1057 
1058     assert(GlobalList.second.SummaryList.size() == 1 &&
1059            "Expected module's index to have one summary per GUID");
1060     auto &Summary = GlobalList.second.SummaryList[0];
1061     if (!IsThinLTO) {
1062       Summary->setNotEligibleToImport();
1063       continue;
1064     }
1065 
1066     bool AllRefsCanBeExternallyReferenced =
1067         llvm::all_of(Summary->refs(), [&](const ValueInfo &VI) {
1068           return !CantBePromoted.count(VI.getGUID());
1069         });
1070     if (!AllRefsCanBeExternallyReferenced) {
1071       Summary->setNotEligibleToImport();
1072       continue;
1073     }
1074 
1075     if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
1076       bool AllCallsCanBeExternallyReferenced = llvm::all_of(
1077           FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
1078             return !CantBePromoted.count(Edge.first.getGUID());
1079           });
1080       if (!AllCallsCanBeExternallyReferenced)
1081         Summary->setNotEligibleToImport();
1082     }
1083   }
1084 
1085   if (!ModuleSummaryDotFile.empty()) {
1086     std::error_code EC;
1087     raw_fd_ostream OSDot(ModuleSummaryDotFile, EC, sys::fs::OpenFlags::OF_Text);
1088     if (EC)
1089       report_fatal_error(Twine("Failed to open dot file ") +
1090                          ModuleSummaryDotFile + ": " + EC.message() + "\n");
1091     Index.exportToDot(OSDot, {});
1092   }
1093 
1094   return Index;
1095 }
1096 
1097 AnalysisKey ModuleSummaryIndexAnalysis::Key;
1098 
1099 ModuleSummaryIndex
1100 ModuleSummaryIndexAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
1101   ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
1102   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1103   bool NeedSSI = needsParamAccessSummary(M);
1104   return buildModuleSummaryIndex(
1105       M,
1106       [&FAM](const Function &F) {
1107         return &FAM.getResult<BlockFrequencyAnalysis>(
1108             *const_cast<Function *>(&F));
1109       },
1110       &PSI,
1111       [&FAM, NeedSSI](const Function &F) -> const StackSafetyInfo * {
1112         return NeedSSI ? &FAM.getResult<StackSafetyAnalysis>(
1113                              const_cast<Function &>(F))
1114                        : nullptr;
1115       });
1116 }
1117 
1118 char ModuleSummaryIndexWrapperPass::ID = 0;
1119 
1120 INITIALIZE_PASS_BEGIN(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
1121                       "Module Summary Analysis", false, true)
1122 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
1123 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
1124 INITIALIZE_PASS_DEPENDENCY(StackSafetyInfoWrapperPass)
1125 INITIALIZE_PASS_END(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
1126                     "Module Summary Analysis", false, true)
1127 
1128 ModulePass *llvm::createModuleSummaryIndexWrapperPass() {
1129   return new ModuleSummaryIndexWrapperPass();
1130 }
1131 
1132 ModuleSummaryIndexWrapperPass::ModuleSummaryIndexWrapperPass()
1133     : ModulePass(ID) {
1134   initializeModuleSummaryIndexWrapperPassPass(*PassRegistry::getPassRegistry());
1135 }
1136 
1137 bool ModuleSummaryIndexWrapperPass::runOnModule(Module &M) {
1138   auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1139   bool NeedSSI = needsParamAccessSummary(M);
1140   Index.emplace(buildModuleSummaryIndex(
1141       M,
1142       [this](const Function &F) {
1143         return &(this->getAnalysis<BlockFrequencyInfoWrapperPass>(
1144                          *const_cast<Function *>(&F))
1145                      .getBFI());
1146       },
1147       PSI,
1148       [&](const Function &F) -> const StackSafetyInfo * {
1149         return NeedSSI ? &getAnalysis<StackSafetyInfoWrapperPass>(
1150                               const_cast<Function &>(F))
1151                               .getResult()
1152                        : nullptr;
1153       }));
1154   return false;
1155 }
1156 
1157 bool ModuleSummaryIndexWrapperPass::doFinalization(Module &M) {
1158   Index.reset();
1159   return false;
1160 }
1161 
1162 void ModuleSummaryIndexWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1163   AU.setPreservesAll();
1164   AU.addRequired<BlockFrequencyInfoWrapperPass>();
1165   AU.addRequired<ProfileSummaryInfoWrapperPass>();
1166   AU.addRequired<StackSafetyInfoWrapperPass>();
1167 }
1168 
1169 char ImmutableModuleSummaryIndexWrapperPass::ID = 0;
1170 
1171 ImmutableModuleSummaryIndexWrapperPass::ImmutableModuleSummaryIndexWrapperPass(
1172     const ModuleSummaryIndex *Index)
1173     : ImmutablePass(ID), Index(Index) {
1174   initializeImmutableModuleSummaryIndexWrapperPassPass(
1175       *PassRegistry::getPassRegistry());
1176 }
1177 
1178 void ImmutableModuleSummaryIndexWrapperPass::getAnalysisUsage(
1179     AnalysisUsage &AU) const {
1180   AU.setPreservesAll();
1181 }
1182 
1183 ImmutablePass *llvm::createImmutableModuleSummaryIndexWrapperPass(
1184     const ModuleSummaryIndex *Index) {
1185   return new ImmutableModuleSummaryIndexWrapperPass(Index);
1186 }
1187 
1188 INITIALIZE_PASS(ImmutableModuleSummaryIndexWrapperPass, "module-summary-info",
1189                 "Module summary info", false, true)
1190 
1191 bool llvm::mayHaveMemprofSummary(const CallBase *CB) {
1192   if (!CB)
1193     return false;
1194   if (CB->isDebugOrPseudoInst())
1195     return false;
1196   auto *CI = dyn_cast<CallInst>(CB);
1197   auto *CalledValue = CB->getCalledOperand();
1198   auto *CalledFunction = CB->getCalledFunction();
1199   if (CalledValue && !CalledFunction) {
1200     CalledValue = CalledValue->stripPointerCasts();
1201     // Stripping pointer casts can reveal a called function.
1202     CalledFunction = dyn_cast<Function>(CalledValue);
1203   }
1204   // Check if this is an alias to a function. If so, get the
1205   // called aliasee for the checks below.
1206   if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
1207     assert(!CalledFunction &&
1208            "Expected null called function in callsite for alias");
1209     CalledFunction = dyn_cast<Function>(GA->getAliaseeObject());
1210   }
1211   // Check if this is a direct call to a known function or a known
1212   // intrinsic, or an indirect call with profile data.
1213   if (CalledFunction) {
1214     if (CI && CalledFunction->isIntrinsic())
1215       return false;
1216   } else {
1217     // TODO: For now skip indirect calls. See comments in
1218     // computeFunctionSummary for what is needed to handle this.
1219     return false;
1220   }
1221   return true;
1222 }
1223