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