xref: /llvm-project/llvm/lib/Analysis/ModuleSummaryAnalysis.cpp (revision bb1b2d09cffa1332c959424fcf0fdc0feea0ff7d)
1 //===- ModuleSummaryAnalysis.cpp - Module summary index builder -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass builds a ModuleSummaryIndex object for the module, to be written
11 // to bitcode or LLVM assembly.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Analysis/BlockFrequencyInfo.h"
25 #include "llvm/Analysis/BranchProbabilityInfo.h"
26 #include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/ProfileSummaryInfo.h"
29 #include "llvm/Analysis/TypeMetadataUtils.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/CallSite.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/Dominators.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/IntrinsicInst.h"
42 #include "llvm/IR/Intrinsics.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/Object/ModuleSymbolTable.h"
49 #include "llvm/Object/SymbolicFile.h"
50 #include "llvm/Pass.h"
51 #include "llvm/Support/Casting.h"
52 #include <algorithm>
53 #include <cassert>
54 #include <cstdint>
55 #include <vector>
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "module-summary-analysis"
60 
61 // Walk through the operands of a given User via worklist iteration and populate
62 // the set of GlobalValue references encountered. Invoked either on an
63 // Instruction or a GlobalVariable (which walks its initializer).
64 static void findRefEdges(ModuleSummaryIndex &Index, const User *CurUser,
65                          SetVector<ValueInfo> &RefEdges,
66                          SmallPtrSet<const User *, 8> &Visited) {
67   SmallVector<const User *, 32> Worklist;
68   Worklist.push_back(CurUser);
69 
70   while (!Worklist.empty()) {
71     const User *U = Worklist.pop_back_val();
72 
73     if (!Visited.insert(U).second)
74       continue;
75 
76     ImmutableCallSite CS(U);
77 
78     for (const auto &OI : U->operands()) {
79       const User *Operand = dyn_cast<User>(OI);
80       if (!Operand)
81         continue;
82       if (isa<BlockAddress>(Operand))
83         continue;
84       if (auto *GV = dyn_cast<GlobalValue>(Operand)) {
85         // We have a reference to a global value. This should be added to
86         // the reference set unless it is a callee. Callees are handled
87         // specially by WriteFunction and are added to a separate list.
88         if (!(CS && CS.isCallee(&OI)))
89           RefEdges.insert(Index.getOrInsertValueInfo(GV));
90         continue;
91       }
92       Worklist.push_back(Operand);
93     }
94   }
95 }
96 
97 static CalleeInfo::HotnessType getHotness(uint64_t ProfileCount,
98                                           ProfileSummaryInfo *PSI) {
99   if (!PSI)
100     return CalleeInfo::HotnessType::Unknown;
101   if (PSI->isHotCount(ProfileCount))
102     return CalleeInfo::HotnessType::Hot;
103   if (PSI->isColdCount(ProfileCount))
104     return CalleeInfo::HotnessType::Cold;
105   return CalleeInfo::HotnessType::None;
106 }
107 
108 static bool isNonRenamableLocal(const GlobalValue &GV) {
109   return GV.hasSection() && GV.hasLocalLinkage();
110 }
111 
112 /// Determine whether this call has all constant integer arguments (excluding
113 /// "this") and summarize it to VCalls or ConstVCalls as appropriate.
114 static void addVCallToSet(DevirtCallSite Call, GlobalValue::GUID Guid,
115                           SetVector<FunctionSummary::VFuncId> &VCalls,
116                           SetVector<FunctionSummary::ConstVCall> &ConstVCalls) {
117   std::vector<uint64_t> Args;
118   // Start from the second argument to skip the "this" pointer.
119   for (auto &Arg : make_range(Call.CS.arg_begin() + 1, Call.CS.arg_end())) {
120     auto *CI = dyn_cast<ConstantInt>(Arg);
121     if (!CI || CI->getBitWidth() > 64) {
122       VCalls.insert({Guid, Call.Offset});
123       return;
124     }
125     Args.push_back(CI->getZExtValue());
126   }
127   ConstVCalls.insert({{Guid, Call.Offset}, std::move(Args)});
128 }
129 
130 /// If this intrinsic call requires that we add information to the function
131 /// summary, do so via the non-constant reference arguments.
132 static void addIntrinsicToSummary(
133     const CallInst *CI, SetVector<GlobalValue::GUID> &TypeTests,
134     SetVector<FunctionSummary::VFuncId> &TypeTestAssumeVCalls,
135     SetVector<FunctionSummary::VFuncId> &TypeCheckedLoadVCalls,
136     SetVector<FunctionSummary::ConstVCall> &TypeTestAssumeConstVCalls,
137     SetVector<FunctionSummary::ConstVCall> &TypeCheckedLoadConstVCalls) {
138   switch (CI->getCalledFunction()->getIntrinsicID()) {
139   case Intrinsic::type_test: {
140     auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(1));
141     auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
142     if (!TypeId)
143       break;
144     GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
145 
146     // Produce a summary from type.test intrinsics. We only summarize type.test
147     // intrinsics that are used other than by an llvm.assume intrinsic.
148     // Intrinsics that are assumed are relevant only to the devirtualization
149     // pass, not the type test lowering pass.
150     bool HasNonAssumeUses = llvm::any_of(CI->uses(), [](const Use &CIU) {
151       auto *AssumeCI = dyn_cast<CallInst>(CIU.getUser());
152       if (!AssumeCI)
153         return true;
154       Function *F = AssumeCI->getCalledFunction();
155       return !F || F->getIntrinsicID() != Intrinsic::assume;
156     });
157     if (HasNonAssumeUses)
158       TypeTests.insert(Guid);
159 
160     SmallVector<DevirtCallSite, 4> DevirtCalls;
161     SmallVector<CallInst *, 4> Assumes;
162     findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
163     for (auto &Call : DevirtCalls)
164       addVCallToSet(Call, Guid, TypeTestAssumeVCalls,
165                     TypeTestAssumeConstVCalls);
166 
167     break;
168   }
169 
170   case Intrinsic::type_checked_load: {
171     auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(2));
172     auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
173     if (!TypeId)
174       break;
175     GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
176 
177     SmallVector<DevirtCallSite, 4> DevirtCalls;
178     SmallVector<Instruction *, 4> LoadedPtrs;
179     SmallVector<Instruction *, 4> Preds;
180     bool HasNonCallUses = false;
181     findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
182                                                HasNonCallUses, CI);
183     // Any non-call uses of the result of llvm.type.checked.load will
184     // prevent us from optimizing away the llvm.type.test.
185     if (HasNonCallUses)
186       TypeTests.insert(Guid);
187     for (auto &Call : DevirtCalls)
188       addVCallToSet(Call, Guid, TypeCheckedLoadVCalls,
189                     TypeCheckedLoadConstVCalls);
190 
191     break;
192   }
193   default:
194     break;
195   }
196 }
197 
198 static void
199 computeFunctionSummary(ModuleSummaryIndex &Index, const Module &M,
200                        const Function &F, BlockFrequencyInfo *BFI,
201                        ProfileSummaryInfo *PSI, bool HasLocalsInUsed,
202                        DenseSet<GlobalValue::GUID> &CantBePromoted) {
203   // Summary not currently supported for anonymous functions, they should
204   // have been named.
205   assert(F.hasName());
206 
207   unsigned NumInsts = 0;
208   // Map from callee ValueId to profile count. Used to accumulate profile
209   // counts for all static calls to a given callee.
210   MapVector<ValueInfo, CalleeInfo> CallGraphEdges;
211   SetVector<ValueInfo> RefEdges;
212   SetVector<GlobalValue::GUID> TypeTests;
213   SetVector<FunctionSummary::VFuncId> TypeTestAssumeVCalls,
214       TypeCheckedLoadVCalls;
215   SetVector<FunctionSummary::ConstVCall> TypeTestAssumeConstVCalls,
216       TypeCheckedLoadConstVCalls;
217   ICallPromotionAnalysis ICallAnalysis;
218 
219   bool HasInlineAsmMaybeReferencingInternal = false;
220   SmallPtrSet<const User *, 8> Visited;
221   for (const BasicBlock &BB : F)
222     for (const Instruction &I : BB) {
223       if (isa<DbgInfoIntrinsic>(I))
224         continue;
225       ++NumInsts;
226       findRefEdges(Index, &I, RefEdges, Visited);
227       auto CS = ImmutableCallSite(&I);
228       if (!CS)
229         continue;
230 
231       const auto *CI = dyn_cast<CallInst>(&I);
232       // Since we don't know exactly which local values are referenced in inline
233       // assembly, conservatively mark the function as possibly referencing
234       // a local value from inline assembly to ensure we don't export a
235       // reference (which would require renaming and promotion of the
236       // referenced value).
237       if (HasLocalsInUsed && CI && CI->isInlineAsm())
238         HasInlineAsmMaybeReferencingInternal = true;
239 
240       auto *CalledValue = CS.getCalledValue();
241       auto *CalledFunction = CS.getCalledFunction();
242       // Check if this is an alias to a function. If so, get the
243       // called aliasee for the checks below.
244       if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
245         assert(!CalledFunction && "Expected null called function in callsite for alias");
246         CalledFunction = dyn_cast<Function>(GA->getBaseObject());
247       }
248       // Check if this is a direct call to a known function or a known
249       // intrinsic, or an indirect call with profile data.
250       if (CalledFunction) {
251         if (CI && CalledFunction->isIntrinsic()) {
252           addIntrinsicToSummary(
253               CI, TypeTests, TypeTestAssumeVCalls, TypeCheckedLoadVCalls,
254               TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls);
255           continue;
256         }
257         // We should have named any anonymous globals
258         assert(CalledFunction->hasName());
259         auto ScaledCount = PSI->getProfileCount(&I, BFI);
260         auto Hotness = ScaledCount ? getHotness(ScaledCount.getValue(), PSI)
261                                    : CalleeInfo::HotnessType::Unknown;
262 
263         // Use the original CalledValue, in case it was an alias. We want
264         // to record the call edge to the alias in that case. Eventually
265         // an alias summary will be created to associate the alias and
266         // aliasee.
267         CallGraphEdges[Index.getOrInsertValueInfo(
268                            cast<GlobalValue>(CalledValue))]
269             .updateHotness(Hotness);
270       } else {
271         // Skip inline assembly calls.
272         if (CI && CI->isInlineAsm())
273           continue;
274         // Skip direct calls.
275         if (!CS.getCalledValue() || isa<Constant>(CS.getCalledValue()))
276           continue;
277 
278         uint32_t NumVals, NumCandidates;
279         uint64_t TotalCount;
280         auto CandidateProfileData =
281             ICallAnalysis.getPromotionCandidatesForInstruction(
282                 &I, NumVals, TotalCount, NumCandidates);
283         for (auto &Candidate : CandidateProfileData)
284           CallGraphEdges[Index.getOrInsertValueInfo(Candidate.Value)]
285               .updateHotness(getHotness(Candidate.Count, PSI));
286       }
287     }
288 
289   // Explicit add hot edges to enforce importing for designated GUIDs for
290   // sample PGO, to enable the same inlines as the profiled optimized binary.
291   for (auto &I : F.getImportGUIDs())
292     CallGraphEdges[Index.getOrInsertValueInfo(I)].updateHotness(
293         CalleeInfo::HotnessType::Critical);
294 
295   bool NonRenamableLocal = isNonRenamableLocal(F);
296   bool NotEligibleForImport =
297       NonRenamableLocal || HasInlineAsmMaybeReferencingInternal ||
298       // Inliner doesn't handle variadic functions.
299       // FIXME: refactor this to use the same code that inliner is using.
300       F.isVarArg();
301   GlobalValueSummary::GVFlags Flags(F.getLinkage(), NotEligibleForImport,
302                                     /* Live = */ false);
303   FunctionSummary::FFlags FunFlags{
304       F.hasFnAttribute(Attribute::ReadNone),
305       F.hasFnAttribute(Attribute::ReadOnly),
306       F.hasFnAttribute(Attribute::NoRecurse),
307       F.returnDoesNotAlias(),
308   };
309   auto FuncSummary = llvm::make_unique<FunctionSummary>(
310       Flags, NumInsts, FunFlags, RefEdges.takeVector(),
311       CallGraphEdges.takeVector(), TypeTests.takeVector(),
312       TypeTestAssumeVCalls.takeVector(), TypeCheckedLoadVCalls.takeVector(),
313       TypeTestAssumeConstVCalls.takeVector(),
314       TypeCheckedLoadConstVCalls.takeVector());
315   if (NonRenamableLocal)
316     CantBePromoted.insert(F.getGUID());
317   Index.addGlobalValueSummary(F.getName(), std::move(FuncSummary));
318 }
319 
320 static void
321 computeVariableSummary(ModuleSummaryIndex &Index, const GlobalVariable &V,
322                        DenseSet<GlobalValue::GUID> &CantBePromoted) {
323   SetVector<ValueInfo> RefEdges;
324   SmallPtrSet<const User *, 8> Visited;
325   findRefEdges(Index, &V, RefEdges, Visited);
326   bool NonRenamableLocal = isNonRenamableLocal(V);
327   GlobalValueSummary::GVFlags Flags(V.getLinkage(), NonRenamableLocal,
328                                     /* Live = */ false);
329   auto GVarSummary =
330       llvm::make_unique<GlobalVarSummary>(Flags, RefEdges.takeVector());
331   if (NonRenamableLocal)
332     CantBePromoted.insert(V.getGUID());
333   Index.addGlobalValueSummary(V.getName(), std::move(GVarSummary));
334 }
335 
336 static void
337 computeAliasSummary(ModuleSummaryIndex &Index, const GlobalAlias &A,
338                     DenseSet<GlobalValue::GUID> &CantBePromoted) {
339   bool NonRenamableLocal = isNonRenamableLocal(A);
340   GlobalValueSummary::GVFlags Flags(A.getLinkage(), NonRenamableLocal,
341                                     /* Live = */ false);
342   auto AS = llvm::make_unique<AliasSummary>(Flags, ArrayRef<ValueInfo>{});
343   auto *Aliasee = A.getBaseObject();
344   auto *AliaseeSummary = Index.getGlobalValueSummary(*Aliasee);
345   assert(AliaseeSummary && "Alias expects aliasee summary to be parsed");
346   AS->setAliasee(AliaseeSummary);
347   if (NonRenamableLocal)
348     CantBePromoted.insert(A.getGUID());
349   Index.addGlobalValueSummary(A.getName(), std::move(AS));
350 }
351 
352 // Set LiveRoot flag on entries matching the given value name.
353 static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) {
354   if (ValueInfo VI = Index.getValueInfo(GlobalValue::getGUID(Name)))
355     for (auto &Summary : VI.getSummaryList())
356       Summary->setLive(true);
357 }
358 
359 ModuleSummaryIndex llvm::buildModuleSummaryIndex(
360     const Module &M,
361     std::function<BlockFrequencyInfo *(const Function &F)> GetBFICallback,
362     ProfileSummaryInfo *PSI) {
363   assert(PSI);
364   ModuleSummaryIndex Index;
365 
366   // Identify the local values in the llvm.used and llvm.compiler.used sets,
367   // which should not be exported as they would then require renaming and
368   // promotion, but we may have opaque uses e.g. in inline asm. We collect them
369   // here because we use this information to mark functions containing inline
370   // assembly calls as not importable.
371   SmallPtrSet<GlobalValue *, 8> LocalsUsed;
372   SmallPtrSet<GlobalValue *, 8> Used;
373   // First collect those in the llvm.used set.
374   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
375   // Next collect those in the llvm.compiler.used set.
376   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ true);
377   DenseSet<GlobalValue::GUID> CantBePromoted;
378   for (auto *V : Used) {
379     if (V->hasLocalLinkage()) {
380       LocalsUsed.insert(V);
381       CantBePromoted.insert(V->getGUID());
382     }
383   }
384 
385   // Compute summaries for all functions defined in module, and save in the
386   // index.
387   for (auto &F : M) {
388     if (F.isDeclaration())
389       continue;
390 
391     BlockFrequencyInfo *BFI = nullptr;
392     std::unique_ptr<BlockFrequencyInfo> BFIPtr;
393     if (GetBFICallback)
394       BFI = GetBFICallback(F);
395     else if (F.getEntryCount().hasValue()) {
396       LoopInfo LI{DominatorTree(const_cast<Function &>(F))};
397       BranchProbabilityInfo BPI{F, LI};
398       BFIPtr = llvm::make_unique<BlockFrequencyInfo>(F, BPI, LI);
399       BFI = BFIPtr.get();
400     }
401 
402     computeFunctionSummary(Index, M, F, BFI, PSI, !LocalsUsed.empty(),
403                            CantBePromoted);
404   }
405 
406   // Compute summaries for all variables defined in module, and save in the
407   // index.
408   for (const GlobalVariable &G : M.globals()) {
409     if (G.isDeclaration())
410       continue;
411     computeVariableSummary(Index, G, CantBePromoted);
412   }
413 
414   // Compute summaries for all aliases defined in module, and save in the
415   // index.
416   for (const GlobalAlias &A : M.aliases())
417     computeAliasSummary(Index, A, CantBePromoted);
418 
419   for (auto *V : LocalsUsed) {
420     auto *Summary = Index.getGlobalValueSummary(*V);
421     assert(Summary && "Missing summary for global value");
422     Summary->setNotEligibleToImport();
423   }
424 
425   // The linker doesn't know about these LLVM produced values, so we need
426   // to flag them as live in the index to ensure index-based dead value
427   // analysis treats them as live roots of the analysis.
428   setLiveRoot(Index, "llvm.used");
429   setLiveRoot(Index, "llvm.compiler.used");
430   setLiveRoot(Index, "llvm.global_ctors");
431   setLiveRoot(Index, "llvm.global_dtors");
432   setLiveRoot(Index, "llvm.global.annotations");
433 
434   if (!M.getModuleInlineAsm().empty()) {
435     // Collect the local values defined by module level asm, and set up
436     // summaries for these symbols so that they can be marked as NoRename,
437     // to prevent export of any use of them in regular IR that would require
438     // renaming within the module level asm. Note we don't need to create a
439     // summary for weak or global defs, as they don't need to be flagged as
440     // NoRename, and defs in module level asm can't be imported anyway.
441     // Also, any values used but not defined within module level asm should
442     // be listed on the llvm.used or llvm.compiler.used global and marked as
443     // referenced from there.
444     ModuleSymbolTable::CollectAsmSymbols(
445         M, [&M, &Index, &CantBePromoted](StringRef Name,
446                                          object::BasicSymbolRef::Flags Flags) {
447           // Symbols not marked as Weak or Global are local definitions.
448           if (Flags & (object::BasicSymbolRef::SF_Weak |
449                        object::BasicSymbolRef::SF_Global))
450             return;
451           GlobalValue *GV = M.getNamedValue(Name);
452           if (!GV)
453             return;
454           assert(GV->isDeclaration() && "Def in module asm already has definition");
455           GlobalValueSummary::GVFlags GVFlags(GlobalValue::InternalLinkage,
456                                               /* NotEligibleToImport = */ true,
457                                               /* Live = */ true);
458           CantBePromoted.insert(GlobalValue::getGUID(Name));
459           // Create the appropriate summary type.
460           if (Function *F = dyn_cast<Function>(GV)) {
461             std::unique_ptr<FunctionSummary> Summary =
462                 llvm::make_unique<FunctionSummary>(
463                     GVFlags, 0,
464                     FunctionSummary::FFlags{
465                         F->hasFnAttribute(Attribute::ReadNone),
466                         F->hasFnAttribute(Attribute::ReadOnly),
467                         F->hasFnAttribute(Attribute::NoRecurse),
468                         F->returnDoesNotAlias()},
469                     ArrayRef<ValueInfo>{}, ArrayRef<FunctionSummary::EdgeTy>{},
470                     ArrayRef<GlobalValue::GUID>{},
471                     ArrayRef<FunctionSummary::VFuncId>{},
472                     ArrayRef<FunctionSummary::VFuncId>{},
473                     ArrayRef<FunctionSummary::ConstVCall>{},
474                     ArrayRef<FunctionSummary::ConstVCall>{});
475             Index.addGlobalValueSummary(Name, std::move(Summary));
476           } else {
477             std::unique_ptr<GlobalVarSummary> Summary =
478                 llvm::make_unique<GlobalVarSummary>(GVFlags,
479                                                     ArrayRef<ValueInfo>{});
480             Index.addGlobalValueSummary(Name, std::move(Summary));
481           }
482         });
483   }
484 
485   bool IsThinLTO = true;
486   if (auto *MD =
487           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
488     IsThinLTO = MD->getZExtValue();
489 
490   for (auto &GlobalList : Index) {
491     // Ignore entries for references that are undefined in the current module.
492     if (GlobalList.second.SummaryList.empty())
493       continue;
494 
495     assert(GlobalList.second.SummaryList.size() == 1 &&
496            "Expected module's index to have one summary per GUID");
497     auto &Summary = GlobalList.second.SummaryList[0];
498     if (!IsThinLTO) {
499       Summary->setNotEligibleToImport();
500       continue;
501     }
502 
503     bool AllRefsCanBeExternallyReferenced =
504         llvm::all_of(Summary->refs(), [&](const ValueInfo &VI) {
505           return !CantBePromoted.count(VI.getGUID());
506         });
507     if (!AllRefsCanBeExternallyReferenced) {
508       Summary->setNotEligibleToImport();
509       continue;
510     }
511 
512     if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
513       bool AllCallsCanBeExternallyReferenced = llvm::all_of(
514           FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
515             return !CantBePromoted.count(Edge.first.getGUID());
516           });
517       if (!AllCallsCanBeExternallyReferenced)
518         Summary->setNotEligibleToImport();
519     }
520   }
521 
522   return Index;
523 }
524 
525 AnalysisKey ModuleSummaryIndexAnalysis::Key;
526 
527 ModuleSummaryIndex
528 ModuleSummaryIndexAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
529   ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
530   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
531   return buildModuleSummaryIndex(
532       M,
533       [&FAM](const Function &F) {
534         return &FAM.getResult<BlockFrequencyAnalysis>(
535             *const_cast<Function *>(&F));
536       },
537       &PSI);
538 }
539 
540 char ModuleSummaryIndexWrapperPass::ID = 0;
541 
542 INITIALIZE_PASS_BEGIN(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
543                       "Module Summary Analysis", false, true)
544 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
545 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
546 INITIALIZE_PASS_END(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
547                     "Module Summary Analysis", false, true)
548 
549 ModulePass *llvm::createModuleSummaryIndexWrapperPass() {
550   return new ModuleSummaryIndexWrapperPass();
551 }
552 
553 ModuleSummaryIndexWrapperPass::ModuleSummaryIndexWrapperPass()
554     : ModulePass(ID) {
555   initializeModuleSummaryIndexWrapperPassPass(*PassRegistry::getPassRegistry());
556 }
557 
558 bool ModuleSummaryIndexWrapperPass::runOnModule(Module &M) {
559   auto &PSI = *getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
560   Index = buildModuleSummaryIndex(
561       M,
562       [this](const Function &F) {
563         return &(this->getAnalysis<BlockFrequencyInfoWrapperPass>(
564                          *const_cast<Function *>(&F))
565                      .getBFI());
566       },
567       &PSI);
568   return false;
569 }
570 
571 bool ModuleSummaryIndexWrapperPass::doFinalization(Module &M) {
572   Index.reset();
573   return false;
574 }
575 
576 void ModuleSummaryIndexWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
577   AU.setPreservesAll();
578   AU.addRequired<BlockFrequencyInfoWrapperPass>();
579   AU.addRequired<ProfileSummaryInfoWrapperPass>();
580 }
581