ModuleSummaryAnalysis.cpp 23 KB

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