xref: /llvm-project/llvm/lib/Analysis/ModuleSummaryAnalysis.cpp (revision a7fa35a629e85a72b8cf07a8f95c7c09d9663808)
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/IndirectCallPromotionAnalysis.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/Analysis/ProfileSummaryInfo.h"
28 #include "llvm/Analysis/TypeMetadataUtils.h"
29 #include "llvm/IR/Attributes.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/Constant.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalAlias.h"
36 #include "llvm/IR/GlobalValue.h"
37 #include "llvm/IR/GlobalVariable.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/Metadata.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/ModuleSummaryIndex.h"
44 #include "llvm/IR/Use.h"
45 #include "llvm/IR/User.h"
46 #include "llvm/InitializePasses.h"
47 #include "llvm/Object/ModuleSymbolTable.h"
48 #include "llvm/Object/SymbolicFile.h"
49 #include "llvm/Pass.h"
50 #include "llvm/Support/Casting.h"
51 #include "llvm/Support/CommandLine.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 // Option to force edges cold which will block importing when the
62 // -import-cold-multiplier is set to 0. Useful for debugging.
63 FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold =
64     FunctionSummary::FSHT_None;
65 cl::opt<FunctionSummary::ForceSummaryHotnessType, true> FSEC(
66     "force-summary-edges-cold", cl::Hidden, cl::location(ForceSummaryEdgesCold),
67     cl::desc("Force all edges in the function summary to cold"),
68     cl::values(clEnumValN(FunctionSummary::FSHT_None, "none", "None."),
69                clEnumValN(FunctionSummary::FSHT_AllNonCritical,
70                           "all-non-critical", "All non-critical edges."),
71                clEnumValN(FunctionSummary::FSHT_All, "all", "All edges.")));
72 
73 cl::opt<std::string> ModuleSummaryDotFile(
74     "module-summary-dot-file", cl::init(""), cl::Hidden,
75     cl::value_desc("filename"),
76     cl::desc("File to emit dot graph of new summary into."));
77 
78 // Walk through the operands of a given User via worklist iteration and populate
79 // the set of GlobalValue references encountered. Invoked either on an
80 // Instruction or a GlobalVariable (which walks its initializer).
81 // Return true if any of the operands contains blockaddress. This is important
82 // to know when computing summary for global var, because if global variable
83 // references basic block address we can't import it separately from function
84 // containing that basic block. For simplicity we currently don't import such
85 // global vars at all. When importing function we aren't interested if any
86 // instruction in it takes an address of any basic block, because instruction
87 // can only take an address of basic block located in the same function.
88 static bool findRefEdges(ModuleSummaryIndex &Index, const User *CurUser,
89                          SetVector<ValueInfo> &RefEdges,
90                          SmallPtrSet<const User *, 8> &Visited) {
91   bool HasBlockAddress = false;
92   SmallVector<const User *, 32> Worklist;
93   Worklist.push_back(CurUser);
94 
95   while (!Worklist.empty()) {
96     const User *U = Worklist.pop_back_val();
97 
98     if (!Visited.insert(U).second)
99       continue;
100 
101     const auto *CB = dyn_cast<CallBase>(U);
102 
103     for (const auto &OI : U->operands()) {
104       const User *Operand = dyn_cast<User>(OI);
105       if (!Operand)
106         continue;
107       if (isa<BlockAddress>(Operand)) {
108         HasBlockAddress = true;
109         continue;
110       }
111       if (auto *GV = dyn_cast<GlobalValue>(Operand)) {
112         // We have a reference to a global value. This should be added to
113         // the reference set unless it is a callee. Callees are handled
114         // specially by WriteFunction and are added to a separate list.
115         if (!(CB && CB->isCallee(&OI)))
116           RefEdges.insert(Index.getOrInsertValueInfo(GV));
117         continue;
118       }
119       Worklist.push_back(Operand);
120     }
121   }
122   return HasBlockAddress;
123 }
124 
125 static CalleeInfo::HotnessType getHotness(uint64_t ProfileCount,
126                                           ProfileSummaryInfo *PSI) {
127   if (!PSI)
128     return CalleeInfo::HotnessType::Unknown;
129   if (PSI->isHotCount(ProfileCount))
130     return CalleeInfo::HotnessType::Hot;
131   if (PSI->isColdCount(ProfileCount))
132     return CalleeInfo::HotnessType::Cold;
133   return CalleeInfo::HotnessType::None;
134 }
135 
136 static bool isNonRenamableLocal(const GlobalValue &GV) {
137   return GV.hasSection() && GV.hasLocalLinkage();
138 }
139 
140 /// Determine whether this call has all constant integer arguments (excluding
141 /// "this") and summarize it to VCalls or ConstVCalls as appropriate.
142 static void addVCallToSet(DevirtCallSite Call, GlobalValue::GUID Guid,
143                           SetVector<FunctionSummary::VFuncId> &VCalls,
144                           SetVector<FunctionSummary::ConstVCall> &ConstVCalls) {
145   std::vector<uint64_t> Args;
146   // Start from the second argument to skip the "this" pointer.
147   for (auto &Arg : make_range(Call.CB.arg_begin() + 1, Call.CB.arg_end())) {
148     auto *CI = dyn_cast<ConstantInt>(Arg);
149     if (!CI || CI->getBitWidth() > 64) {
150       VCalls.insert({Guid, Call.Offset});
151       return;
152     }
153     Args.push_back(CI->getZExtValue());
154   }
155   ConstVCalls.insert({{Guid, Call.Offset}, std::move(Args)});
156 }
157 
158 /// If this intrinsic call requires that we add information to the function
159 /// summary, do so via the non-constant reference arguments.
160 static void addIntrinsicToSummary(
161     const CallInst *CI, SetVector<GlobalValue::GUID> &TypeTests,
162     SetVector<FunctionSummary::VFuncId> &TypeTestAssumeVCalls,
163     SetVector<FunctionSummary::VFuncId> &TypeCheckedLoadVCalls,
164     SetVector<FunctionSummary::ConstVCall> &TypeTestAssumeConstVCalls,
165     SetVector<FunctionSummary::ConstVCall> &TypeCheckedLoadConstVCalls,
166     DominatorTree &DT) {
167   switch (CI->getCalledFunction()->getIntrinsicID()) {
168   case Intrinsic::type_test: {
169     auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(1));
170     auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
171     if (!TypeId)
172       break;
173     GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
174 
175     // Produce a summary from type.test intrinsics. We only summarize type.test
176     // intrinsics that are used other than by an llvm.assume intrinsic.
177     // Intrinsics that are assumed are relevant only to the devirtualization
178     // pass, not the type test lowering pass.
179     bool HasNonAssumeUses = llvm::any_of(CI->uses(), [](const Use &CIU) {
180       auto *AssumeCI = dyn_cast<CallInst>(CIU.getUser());
181       if (!AssumeCI)
182         return true;
183       Function *F = AssumeCI->getCalledFunction();
184       return !F || F->getIntrinsicID() != Intrinsic::assume;
185     });
186     if (HasNonAssumeUses)
187       TypeTests.insert(Guid);
188 
189     SmallVector<DevirtCallSite, 4> DevirtCalls;
190     SmallVector<CallInst *, 4> Assumes;
191     findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
192     for (auto &Call : DevirtCalls)
193       addVCallToSet(Call, Guid, TypeTestAssumeVCalls,
194                     TypeTestAssumeConstVCalls);
195 
196     break;
197   }
198 
199   case Intrinsic::type_checked_load: {
200     auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(2));
201     auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
202     if (!TypeId)
203       break;
204     GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
205 
206     SmallVector<DevirtCallSite, 4> DevirtCalls;
207     SmallVector<Instruction *, 4> LoadedPtrs;
208     SmallVector<Instruction *, 4> Preds;
209     bool HasNonCallUses = false;
210     findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
211                                                HasNonCallUses, CI, DT);
212     // Any non-call uses of the result of llvm.type.checked.load will
213     // prevent us from optimizing away the llvm.type.test.
214     if (HasNonCallUses)
215       TypeTests.insert(Guid);
216     for (auto &Call : DevirtCalls)
217       addVCallToSet(Call, Guid, TypeCheckedLoadVCalls,
218                     TypeCheckedLoadConstVCalls);
219 
220     break;
221   }
222   default:
223     break;
224   }
225 }
226 
227 static bool isNonVolatileLoad(const Instruction *I) {
228   if (const auto *LI = dyn_cast<LoadInst>(I))
229     return !LI->isVolatile();
230 
231   return false;
232 }
233 
234 static bool isNonVolatileStore(const Instruction *I) {
235   if (const auto *SI = dyn_cast<StoreInst>(I))
236     return !SI->isVolatile();
237 
238   return false;
239 }
240 
241 static void computeFunctionSummary(ModuleSummaryIndex &Index, const Module &M,
242                                    const Function &F, BlockFrequencyInfo *BFI,
243                                    ProfileSummaryInfo *PSI, DominatorTree &DT,
244                                    bool HasLocalsInUsedOrAsm,
245                                    DenseSet<GlobalValue::GUID> &CantBePromoted,
246                                    bool IsThinLTO) {
247   // Summary not currently supported for anonymous functions, they should
248   // have been named.
249   assert(F.hasName());
250 
251   unsigned NumInsts = 0;
252   // Map from callee ValueId to profile count. Used to accumulate profile
253   // counts for all static calls to a given callee.
254   MapVector<ValueInfo, CalleeInfo> CallGraphEdges;
255   SetVector<ValueInfo> RefEdges, LoadRefEdges, StoreRefEdges;
256   SetVector<GlobalValue::GUID> TypeTests;
257   SetVector<FunctionSummary::VFuncId> TypeTestAssumeVCalls,
258       TypeCheckedLoadVCalls;
259   SetVector<FunctionSummary::ConstVCall> TypeTestAssumeConstVCalls,
260       TypeCheckedLoadConstVCalls;
261   ICallPromotionAnalysis ICallAnalysis;
262   SmallPtrSet<const User *, 8> Visited;
263 
264   // Add personality function, prefix data and prologue data to function's ref
265   // list.
266   findRefEdges(Index, &F, RefEdges, Visited);
267   std::vector<const Instruction *> NonVolatileLoads;
268   std::vector<const Instruction *> NonVolatileStores;
269 
270   bool HasInlineAsmMaybeReferencingInternal = false;
271   for (const BasicBlock &BB : F)
272     for (const Instruction &I : BB) {
273       if (isa<DbgInfoIntrinsic>(I))
274         continue;
275       ++NumInsts;
276       // Regular LTO module doesn't participate in ThinLTO import,
277       // so no reference from it can be read/writeonly, since this
278       // would require importing variable as local copy
279       if (IsThinLTO) {
280         if (isNonVolatileLoad(&I)) {
281           // Postpone processing of non-volatile load instructions
282           // See comments below
283           Visited.insert(&I);
284           NonVolatileLoads.push_back(&I);
285           continue;
286         } else if (isNonVolatileStore(&I)) {
287           Visited.insert(&I);
288           NonVolatileStores.push_back(&I);
289           // All references from second operand of store (destination address)
290           // can be considered write-only if they're not referenced by any
291           // non-store instruction. References from first operand of store
292           // (stored value) can't be treated either as read- or as write-only
293           // so we add them to RefEdges as we do with all other instructions
294           // except non-volatile load.
295           Value *Stored = I.getOperand(0);
296           if (auto *GV = dyn_cast<GlobalValue>(Stored))
297             // findRefEdges will try to examine GV operands, so instead
298             // of calling it we should add GV to RefEdges directly.
299             RefEdges.insert(Index.getOrInsertValueInfo(GV));
300           else if (auto *U = dyn_cast<User>(Stored))
301             findRefEdges(Index, U, RefEdges, Visited);
302           continue;
303         }
304       }
305       findRefEdges(Index, &I, RefEdges, Visited);
306       const auto *CB = dyn_cast<CallBase>(&I);
307       if (!CB)
308         continue;
309 
310       const auto *CI = dyn_cast<CallInst>(&I);
311       // Since we don't know exactly which local values are referenced in inline
312       // assembly, conservatively mark the function as possibly referencing
313       // a local value from inline assembly to ensure we don't export a
314       // reference (which would require renaming and promotion of the
315       // referenced value).
316       if (HasLocalsInUsedOrAsm && CI && CI->isInlineAsm())
317         HasInlineAsmMaybeReferencingInternal = true;
318 
319       auto *CalledValue = CB->getCalledOperand();
320       auto *CalledFunction = CB->getCalledFunction();
321       if (CalledValue && !CalledFunction) {
322         CalledValue = CalledValue->stripPointerCasts();
323         // Stripping pointer casts can reveal a called function.
324         CalledFunction = dyn_cast<Function>(CalledValue);
325       }
326       // Check if this is an alias to a function. If so, get the
327       // called aliasee for the checks below.
328       if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
329         assert(!CalledFunction && "Expected null called function in callsite for alias");
330         CalledFunction = dyn_cast<Function>(GA->getBaseObject());
331       }
332       // Check if this is a direct call to a known function or a known
333       // intrinsic, or an indirect call with profile data.
334       if (CalledFunction) {
335         if (CI && CalledFunction->isIntrinsic()) {
336           addIntrinsicToSummary(
337               CI, TypeTests, TypeTestAssumeVCalls, TypeCheckedLoadVCalls,
338               TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls, DT);
339           continue;
340         }
341         // We should have named any anonymous globals
342         assert(CalledFunction->hasName());
343         auto ScaledCount = PSI->getProfileCount(*CB, BFI);
344         auto Hotness = ScaledCount ? getHotness(ScaledCount.getValue(), PSI)
345                                    : CalleeInfo::HotnessType::Unknown;
346         if (ForceSummaryEdgesCold != FunctionSummary::FSHT_None)
347           Hotness = CalleeInfo::HotnessType::Cold;
348 
349         // Use the original CalledValue, in case it was an alias. We want
350         // to record the call edge to the alias in that case. Eventually
351         // an alias summary will be created to associate the alias and
352         // aliasee.
353         auto &ValueInfo = CallGraphEdges[Index.getOrInsertValueInfo(
354             cast<GlobalValue>(CalledValue))];
355         ValueInfo.updateHotness(Hotness);
356         // Add the relative block frequency to CalleeInfo if there is no profile
357         // information.
358         if (BFI != nullptr && Hotness == CalleeInfo::HotnessType::Unknown) {
359           uint64_t BBFreq = BFI->getBlockFreq(&BB).getFrequency();
360           uint64_t EntryFreq = BFI->getEntryFreq();
361           ValueInfo.updateRelBlockFreq(BBFreq, EntryFreq);
362         }
363       } else {
364         // Skip inline assembly calls.
365         if (CI && CI->isInlineAsm())
366           continue;
367         // Skip direct calls.
368         if (!CalledValue || isa<Constant>(CalledValue))
369           continue;
370 
371         // Check if the instruction has a callees metadata. If so, add callees
372         // to CallGraphEdges to reflect the references from the metadata, and
373         // to enable importing for subsequent indirect call promotion and
374         // inlining.
375         if (auto *MD = I.getMetadata(LLVMContext::MD_callees)) {
376           for (auto &Op : MD->operands()) {
377             Function *Callee = mdconst::extract_or_null<Function>(Op);
378             if (Callee)
379               CallGraphEdges[Index.getOrInsertValueInfo(Callee)];
380           }
381         }
382 
383         uint32_t NumVals, NumCandidates;
384         uint64_t TotalCount;
385         auto CandidateProfileData =
386             ICallAnalysis.getPromotionCandidatesForInstruction(
387                 &I, NumVals, TotalCount, NumCandidates);
388         for (auto &Candidate : CandidateProfileData)
389           CallGraphEdges[Index.getOrInsertValueInfo(Candidate.Value)]
390               .updateHotness(getHotness(Candidate.Count, PSI));
391       }
392     }
393   Index.addBlockCount(F.size());
394 
395   std::vector<ValueInfo> Refs;
396   if (IsThinLTO) {
397     auto AddRefEdges = [&](const std::vector<const Instruction *> &Instrs,
398                            SetVector<ValueInfo> &Edges,
399                            SmallPtrSet<const User *, 8> &Cache) {
400       for (const auto *I : Instrs) {
401         Cache.erase(I);
402         findRefEdges(Index, I, Edges, Cache);
403       }
404     };
405 
406     // By now we processed all instructions in a function, except
407     // non-volatile loads and non-volatile value stores. Let's find
408     // ref edges for both of instruction sets
409     AddRefEdges(NonVolatileLoads, LoadRefEdges, Visited);
410     // We can add some values to the Visited set when processing load
411     // instructions which are also used by stores in NonVolatileStores.
412     // For example this can happen if we have following code:
413     //
414     // store %Derived* @foo, %Derived** bitcast (%Base** @bar to %Derived**)
415     // %42 = load %Derived*, %Derived** bitcast (%Base** @bar to %Derived**)
416     //
417     // After processing loads we'll add bitcast to the Visited set, and if
418     // we use the same set while processing stores, we'll never see store
419     // to @bar and @bar will be mistakenly treated as readonly.
420     SmallPtrSet<const llvm::User *, 8> StoreCache;
421     AddRefEdges(NonVolatileStores, StoreRefEdges, StoreCache);
422 
423     // If both load and store instruction reference the same variable
424     // we won't be able to optimize it. Add all such reference edges
425     // to RefEdges set.
426     for (auto &VI : StoreRefEdges)
427       if (LoadRefEdges.remove(VI))
428         RefEdges.insert(VI);
429 
430     unsigned RefCnt = RefEdges.size();
431     // All new reference edges inserted in two loops below are either
432     // read or write only. They will be grouped in the end of RefEdges
433     // vector, so we can use a single integer value to identify them.
434     for (auto &VI : LoadRefEdges)
435       RefEdges.insert(VI);
436 
437     unsigned FirstWORef = RefEdges.size();
438     for (auto &VI : StoreRefEdges)
439       RefEdges.insert(VI);
440 
441     Refs = RefEdges.takeVector();
442     for (; RefCnt < FirstWORef; ++RefCnt)
443       Refs[RefCnt].setReadOnly();
444 
445     for (; RefCnt < Refs.size(); ++RefCnt)
446       Refs[RefCnt].setWriteOnly();
447   } else {
448     Refs = RefEdges.takeVector();
449   }
450   // Explicit add hot edges to enforce importing for designated GUIDs for
451   // sample PGO, to enable the same inlines as the profiled optimized binary.
452   for (auto &I : F.getImportGUIDs())
453     CallGraphEdges[Index.getOrInsertValueInfo(I)].updateHotness(
454         ForceSummaryEdgesCold == FunctionSummary::FSHT_All
455             ? CalleeInfo::HotnessType::Cold
456             : CalleeInfo::HotnessType::Critical);
457 
458   bool NonRenamableLocal = isNonRenamableLocal(F);
459   bool NotEligibleForImport =
460       NonRenamableLocal || HasInlineAsmMaybeReferencingInternal;
461   GlobalValueSummary::GVFlags Flags(F.getLinkage(), NotEligibleForImport,
462                                     /* Live = */ false, F.isDSOLocal(),
463                                     F.hasLinkOnceODRLinkage() && F.hasGlobalUnnamedAddr());
464   FunctionSummary::FFlags FunFlags{
465       F.hasFnAttribute(Attribute::ReadNone),
466       F.hasFnAttribute(Attribute::ReadOnly),
467       F.hasFnAttribute(Attribute::NoRecurse), F.returnDoesNotAlias(),
468       // FIXME: refactor this to use the same code that inliner is using.
469       // Don't try to import functions with noinline attribute.
470       F.getAttributes().hasFnAttribute(Attribute::NoInline),
471       F.hasFnAttribute(Attribute::AlwaysInline)};
472   auto FuncSummary = std::make_unique<FunctionSummary>(
473       Flags, NumInsts, FunFlags, /*EntryCount=*/0, std::move(Refs),
474       CallGraphEdges.takeVector(), TypeTests.takeVector(),
475       TypeTestAssumeVCalls.takeVector(), TypeCheckedLoadVCalls.takeVector(),
476       TypeTestAssumeConstVCalls.takeVector(),
477       TypeCheckedLoadConstVCalls.takeVector());
478   if (NonRenamableLocal)
479     CantBePromoted.insert(F.getGUID());
480   Index.addGlobalValueSummary(F, std::move(FuncSummary));
481 }
482 
483 /// Find function pointers referenced within the given vtable initializer
484 /// (or subset of an initializer) \p I. The starting offset of \p I within
485 /// the vtable initializer is \p StartingOffset. Any discovered function
486 /// pointers are added to \p VTableFuncs along with their cumulative offset
487 /// within the initializer.
488 static void findFuncPointers(const Constant *I, uint64_t StartingOffset,
489                              const Module &M, ModuleSummaryIndex &Index,
490                              VTableFuncList &VTableFuncs) {
491   // First check if this is a function pointer.
492   if (I->getType()->isPointerTy()) {
493     auto Fn = dyn_cast<Function>(I->stripPointerCasts());
494     // We can disregard __cxa_pure_virtual as a possible call target, as
495     // calls to pure virtuals are UB.
496     if (Fn && Fn->getName() != "__cxa_pure_virtual")
497       VTableFuncs.push_back({Index.getOrInsertValueInfo(Fn), StartingOffset});
498     return;
499   }
500 
501   // Walk through the elements in the constant struct or array and recursively
502   // look for virtual function pointers.
503   const DataLayout &DL = M.getDataLayout();
504   if (auto *C = dyn_cast<ConstantStruct>(I)) {
505     StructType *STy = dyn_cast<StructType>(C->getType());
506     assert(STy);
507     const StructLayout *SL = DL.getStructLayout(C->getType());
508 
509     for (StructType::element_iterator EB = STy->element_begin(), EI = EB,
510                                       EE = STy->element_end();
511          EI != EE; ++EI) {
512       auto Offset = SL->getElementOffset(EI - EB);
513       unsigned Op = SL->getElementContainingOffset(Offset);
514       findFuncPointers(cast<Constant>(I->getOperand(Op)),
515                        StartingOffset + Offset, M, Index, VTableFuncs);
516     }
517   } else if (auto *C = dyn_cast<ConstantArray>(I)) {
518     ArrayType *ATy = C->getType();
519     Type *EltTy = ATy->getElementType();
520     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
521     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
522       findFuncPointers(cast<Constant>(I->getOperand(i)),
523                        StartingOffset + i * EltSize, M, Index, VTableFuncs);
524     }
525   }
526 }
527 
528 // Identify the function pointers referenced by vtable definition \p V.
529 static void computeVTableFuncs(ModuleSummaryIndex &Index,
530                                const GlobalVariable &V, const Module &M,
531                                VTableFuncList &VTableFuncs) {
532   if (!V.isConstant())
533     return;
534 
535   findFuncPointers(V.getInitializer(), /*StartingOffset=*/0, M, Index,
536                    VTableFuncs);
537 
538 #ifndef NDEBUG
539   // Validate that the VTableFuncs list is ordered by offset.
540   uint64_t PrevOffset = 0;
541   for (auto &P : VTableFuncs) {
542     // The findVFuncPointers traversal should have encountered the
543     // functions in offset order. We need to use ">=" since PrevOffset
544     // starts at 0.
545     assert(P.VTableOffset >= PrevOffset);
546     PrevOffset = P.VTableOffset;
547   }
548 #endif
549 }
550 
551 /// Record vtable definition \p V for each type metadata it references.
552 static void
553 recordTypeIdCompatibleVtableReferences(ModuleSummaryIndex &Index,
554                                        const GlobalVariable &V,
555                                        SmallVectorImpl<MDNode *> &Types) {
556   for (MDNode *Type : Types) {
557     auto TypeID = Type->getOperand(1).get();
558 
559     uint64_t Offset =
560         cast<ConstantInt>(
561             cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
562             ->getZExtValue();
563 
564     if (auto *TypeId = dyn_cast<MDString>(TypeID))
565       Index.getOrInsertTypeIdCompatibleVtableSummary(TypeId->getString())
566           .push_back({Offset, Index.getOrInsertValueInfo(&V)});
567   }
568 }
569 
570 static void computeVariableSummary(ModuleSummaryIndex &Index,
571                                    const GlobalVariable &V,
572                                    DenseSet<GlobalValue::GUID> &CantBePromoted,
573                                    const Module &M,
574                                    SmallVectorImpl<MDNode *> &Types) {
575   SetVector<ValueInfo> RefEdges;
576   SmallPtrSet<const User *, 8> Visited;
577   bool HasBlockAddress = findRefEdges(Index, &V, RefEdges, Visited);
578   bool NonRenamableLocal = isNonRenamableLocal(V);
579   GlobalValueSummary::GVFlags Flags(V.getLinkage(), NonRenamableLocal,
580                                     /* Live = */ false, V.isDSOLocal(),
581                                     V.hasLinkOnceODRLinkage() && V.hasGlobalUnnamedAddr());
582 
583   VTableFuncList VTableFuncs;
584   // If splitting is not enabled, then we compute the summary information
585   // necessary for index-based whole program devirtualization.
586   if (!Index.enableSplitLTOUnit()) {
587     Types.clear();
588     V.getMetadata(LLVMContext::MD_type, Types);
589     if (!Types.empty()) {
590       // Identify the function pointers referenced by this vtable definition.
591       computeVTableFuncs(Index, V, M, VTableFuncs);
592 
593       // Record this vtable definition for each type metadata it references.
594       recordTypeIdCompatibleVtableReferences(Index, V, Types);
595     }
596   }
597 
598   // Don't mark variables we won't be able to internalize as read/write-only.
599   bool CanBeInternalized =
600       !V.hasComdat() && !V.hasAppendingLinkage() && !V.isInterposable() &&
601       !V.hasAvailableExternallyLinkage() && !V.hasDLLExportStorageClass();
602   bool Constant = V.isConstant();
603   GlobalVarSummary::GVarFlags VarFlags(CanBeInternalized,
604                                        Constant ? false : CanBeInternalized,
605                                        Constant, V.getVCallVisibility());
606   auto GVarSummary = std::make_unique<GlobalVarSummary>(Flags, VarFlags,
607                                                          RefEdges.takeVector());
608   if (NonRenamableLocal)
609     CantBePromoted.insert(V.getGUID());
610   if (HasBlockAddress)
611     GVarSummary->setNotEligibleToImport();
612   if (!VTableFuncs.empty())
613     GVarSummary->setVTableFuncs(VTableFuncs);
614   Index.addGlobalValueSummary(V, std::move(GVarSummary));
615 }
616 
617 static void
618 computeAliasSummary(ModuleSummaryIndex &Index, const GlobalAlias &A,
619                     DenseSet<GlobalValue::GUID> &CantBePromoted) {
620   bool NonRenamableLocal = isNonRenamableLocal(A);
621   GlobalValueSummary::GVFlags Flags(A.getLinkage(), NonRenamableLocal,
622                                     /* Live = */ false, A.isDSOLocal(),
623                                     A.hasLinkOnceODRLinkage() && A.hasGlobalUnnamedAddr());
624   auto AS = std::make_unique<AliasSummary>(Flags);
625   auto *Aliasee = A.getBaseObject();
626   auto AliaseeVI = Index.getValueInfo(Aliasee->getGUID());
627   assert(AliaseeVI && "Alias expects aliasee summary to be available");
628   assert(AliaseeVI.getSummaryList().size() == 1 &&
629          "Expected a single entry per aliasee in per-module index");
630   AS->setAliasee(AliaseeVI, AliaseeVI.getSummaryList()[0].get());
631   if (NonRenamableLocal)
632     CantBePromoted.insert(A.getGUID());
633   Index.addGlobalValueSummary(A, std::move(AS));
634 }
635 
636 // Set LiveRoot flag on entries matching the given value name.
637 static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) {
638   if (ValueInfo VI = Index.getValueInfo(GlobalValue::getGUID(Name)))
639     for (auto &Summary : VI.getSummaryList())
640       Summary->setLive(true);
641 }
642 
643 ModuleSummaryIndex llvm::buildModuleSummaryIndex(
644     const Module &M,
645     std::function<BlockFrequencyInfo *(const Function &F)> GetBFICallback,
646     ProfileSummaryInfo *PSI) {
647   assert(PSI);
648   bool EnableSplitLTOUnit = false;
649   if (auto *MD = mdconst::extract_or_null<ConstantInt>(
650           M.getModuleFlag("EnableSplitLTOUnit")))
651     EnableSplitLTOUnit = MD->getZExtValue();
652   ModuleSummaryIndex Index(/*HaveGVs=*/true, EnableSplitLTOUnit);
653 
654   // Identify the local values in the llvm.used and llvm.compiler.used sets,
655   // which should not be exported as they would then require renaming and
656   // promotion, but we may have opaque uses e.g. in inline asm. We collect them
657   // here because we use this information to mark functions containing inline
658   // assembly calls as not importable.
659   SmallPtrSet<GlobalValue *, 8> LocalsUsed;
660   SmallPtrSet<GlobalValue *, 8> Used;
661   // First collect those in the llvm.used set.
662   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
663   // Next collect those in the llvm.compiler.used set.
664   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ true);
665   DenseSet<GlobalValue::GUID> CantBePromoted;
666   for (auto *V : Used) {
667     if (V->hasLocalLinkage()) {
668       LocalsUsed.insert(V);
669       CantBePromoted.insert(V->getGUID());
670     }
671   }
672 
673   bool HasLocalInlineAsmSymbol = false;
674   if (!M.getModuleInlineAsm().empty()) {
675     // Collect the local values defined by module level asm, and set up
676     // summaries for these symbols so that they can be marked as NoRename,
677     // to prevent export of any use of them in regular IR that would require
678     // renaming within the module level asm. Note we don't need to create a
679     // summary for weak or global defs, as they don't need to be flagged as
680     // NoRename, and defs in module level asm can't be imported anyway.
681     // Also, any values used but not defined within module level asm should
682     // be listed on the llvm.used or llvm.compiler.used global and marked as
683     // referenced from there.
684     ModuleSymbolTable::CollectAsmSymbols(
685         M, [&](StringRef Name, object::BasicSymbolRef::Flags Flags) {
686           // Symbols not marked as Weak or Global are local definitions.
687           if (Flags & (object::BasicSymbolRef::SF_Weak |
688                        object::BasicSymbolRef::SF_Global))
689             return;
690           HasLocalInlineAsmSymbol = true;
691           GlobalValue *GV = M.getNamedValue(Name);
692           if (!GV)
693             return;
694           assert(GV->isDeclaration() && "Def in module asm already has definition");
695           GlobalValueSummary::GVFlags GVFlags(GlobalValue::InternalLinkage,
696                                               /* NotEligibleToImport = */ true,
697                                               /* Live = */ true,
698                                               /* Local */ GV->isDSOLocal(),
699                                               GV->hasLinkOnceODRLinkage() && GV->hasGlobalUnnamedAddr());
700           CantBePromoted.insert(GV->getGUID());
701           // Create the appropriate summary type.
702           if (Function *F = dyn_cast<Function>(GV)) {
703             std::unique_ptr<FunctionSummary> Summary =
704                 std::make_unique<FunctionSummary>(
705                     GVFlags, /*InstCount=*/0,
706                     FunctionSummary::FFlags{
707                         F->hasFnAttribute(Attribute::ReadNone),
708                         F->hasFnAttribute(Attribute::ReadOnly),
709                         F->hasFnAttribute(Attribute::NoRecurse),
710                         F->returnDoesNotAlias(),
711                         /* NoInline = */ false,
712                         F->hasFnAttribute(Attribute::AlwaysInline)},
713                     /*EntryCount=*/0, ArrayRef<ValueInfo>{},
714                     ArrayRef<FunctionSummary::EdgeTy>{},
715                     ArrayRef<GlobalValue::GUID>{},
716                     ArrayRef<FunctionSummary::VFuncId>{},
717                     ArrayRef<FunctionSummary::VFuncId>{},
718                     ArrayRef<FunctionSummary::ConstVCall>{},
719                     ArrayRef<FunctionSummary::ConstVCall>{});
720             Index.addGlobalValueSummary(*GV, std::move(Summary));
721           } else {
722             std::unique_ptr<GlobalVarSummary> Summary =
723                 std::make_unique<GlobalVarSummary>(
724                     GVFlags,
725                     GlobalVarSummary::GVarFlags(
726                         false, false, cast<GlobalVariable>(GV)->isConstant(),
727                         GlobalObject::VCallVisibilityPublic),
728                     ArrayRef<ValueInfo>{});
729             Index.addGlobalValueSummary(*GV, std::move(Summary));
730           }
731         });
732   }
733 
734   bool IsThinLTO = true;
735   if (auto *MD =
736           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
737     IsThinLTO = MD->getZExtValue();
738 
739   // Compute summaries for all functions defined in module, and save in the
740   // index.
741   for (auto &F : M) {
742     if (F.isDeclaration())
743       continue;
744 
745     DominatorTree DT(const_cast<Function &>(F));
746     BlockFrequencyInfo *BFI = nullptr;
747     std::unique_ptr<BlockFrequencyInfo> BFIPtr;
748     if (GetBFICallback)
749       BFI = GetBFICallback(F);
750     else if (F.hasProfileData()) {
751       LoopInfo LI{DT};
752       BranchProbabilityInfo BPI{F, LI};
753       BFIPtr = std::make_unique<BlockFrequencyInfo>(F, BPI, LI);
754       BFI = BFIPtr.get();
755     }
756 
757     computeFunctionSummary(Index, M, F, BFI, PSI, DT,
758                            !LocalsUsed.empty() || HasLocalInlineAsmSymbol,
759                            CantBePromoted, IsThinLTO);
760   }
761 
762   // Compute summaries for all variables defined in module, and save in the
763   // index.
764   SmallVector<MDNode *, 2> Types;
765   for (const GlobalVariable &G : M.globals()) {
766     if (G.isDeclaration())
767       continue;
768     computeVariableSummary(Index, G, CantBePromoted, M, Types);
769   }
770 
771   // Compute summaries for all aliases defined in module, and save in the
772   // index.
773   for (const GlobalAlias &A : M.aliases())
774     computeAliasSummary(Index, A, CantBePromoted);
775 
776   for (auto *V : LocalsUsed) {
777     auto *Summary = Index.getGlobalValueSummary(*V);
778     assert(Summary && "Missing summary for global value");
779     Summary->setNotEligibleToImport();
780   }
781 
782   // The linker doesn't know about these LLVM produced values, so we need
783   // to flag them as live in the index to ensure index-based dead value
784   // analysis treats them as live roots of the analysis.
785   setLiveRoot(Index, "llvm.used");
786   setLiveRoot(Index, "llvm.compiler.used");
787   setLiveRoot(Index, "llvm.global_ctors");
788   setLiveRoot(Index, "llvm.global_dtors");
789   setLiveRoot(Index, "llvm.global.annotations");
790 
791   for (auto &GlobalList : Index) {
792     // Ignore entries for references that are undefined in the current module.
793     if (GlobalList.second.SummaryList.empty())
794       continue;
795 
796     assert(GlobalList.second.SummaryList.size() == 1 &&
797            "Expected module's index to have one summary per GUID");
798     auto &Summary = GlobalList.second.SummaryList[0];
799     if (!IsThinLTO) {
800       Summary->setNotEligibleToImport();
801       continue;
802     }
803 
804     bool AllRefsCanBeExternallyReferenced =
805         llvm::all_of(Summary->refs(), [&](const ValueInfo &VI) {
806           return !CantBePromoted.count(VI.getGUID());
807         });
808     if (!AllRefsCanBeExternallyReferenced) {
809       Summary->setNotEligibleToImport();
810       continue;
811     }
812 
813     if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
814       bool AllCallsCanBeExternallyReferenced = llvm::all_of(
815           FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
816             return !CantBePromoted.count(Edge.first.getGUID());
817           });
818       if (!AllCallsCanBeExternallyReferenced)
819         Summary->setNotEligibleToImport();
820     }
821   }
822 
823   if (!ModuleSummaryDotFile.empty()) {
824     std::error_code EC;
825     raw_fd_ostream OSDot(ModuleSummaryDotFile, EC, sys::fs::OpenFlags::OF_None);
826     if (EC)
827       report_fatal_error(Twine("Failed to open dot file ") +
828                          ModuleSummaryDotFile + ": " + EC.message() + "\n");
829     Index.exportToDot(OSDot, {});
830   }
831 
832   return Index;
833 }
834 
835 AnalysisKey ModuleSummaryIndexAnalysis::Key;
836 
837 ModuleSummaryIndex
838 ModuleSummaryIndexAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
839   ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
840   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
841   return buildModuleSummaryIndex(
842       M,
843       [&FAM](const Function &F) {
844         return &FAM.getResult<BlockFrequencyAnalysis>(
845             *const_cast<Function *>(&F));
846       },
847       &PSI);
848 }
849 
850 char ModuleSummaryIndexWrapperPass::ID = 0;
851 
852 INITIALIZE_PASS_BEGIN(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
853                       "Module Summary Analysis", false, true)
854 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
855 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
856 INITIALIZE_PASS_END(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
857                     "Module Summary Analysis", false, true)
858 
859 ModulePass *llvm::createModuleSummaryIndexWrapperPass() {
860   return new ModuleSummaryIndexWrapperPass();
861 }
862 
863 ModuleSummaryIndexWrapperPass::ModuleSummaryIndexWrapperPass()
864     : ModulePass(ID) {
865   initializeModuleSummaryIndexWrapperPassPass(*PassRegistry::getPassRegistry());
866 }
867 
868 bool ModuleSummaryIndexWrapperPass::runOnModule(Module &M) {
869   auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
870   Index.emplace(buildModuleSummaryIndex(
871       M,
872       [this](const Function &F) {
873         return &(this->getAnalysis<BlockFrequencyInfoWrapperPass>(
874                          *const_cast<Function *>(&F))
875                      .getBFI());
876       },
877       PSI));
878   return false;
879 }
880 
881 bool ModuleSummaryIndexWrapperPass::doFinalization(Module &M) {
882   Index.reset();
883   return false;
884 }
885 
886 void ModuleSummaryIndexWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
887   AU.setPreservesAll();
888   AU.addRequired<BlockFrequencyInfoWrapperPass>();
889   AU.addRequired<ProfileSummaryInfoWrapperPass>();
890 }
891