ModuleSummaryIndex.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. //===-- ModuleSummaryIndex.cpp - Module Summary Index ---------------------===//
  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 file implements the module index and summary classes for the
  10. // IR library.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/IR/ModuleSummaryIndex.h"
  14. #include "llvm/ADT/SCCIterator.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/Support/CommandLine.h"
  17. #include "llvm/Support/Path.h"
  18. #include "llvm/Support/raw_ostream.h"
  19. using namespace llvm;
  20. #define DEBUG_TYPE "module-summary-index"
  21. STATISTIC(ReadOnlyLiveGVars,
  22. "Number of live global variables marked read only");
  23. STATISTIC(WriteOnlyLiveGVars,
  24. "Number of live global variables marked write only");
  25. static cl::opt<bool> PropagateAttrs("propagate-attrs", cl::init(true),
  26. cl::Hidden,
  27. cl::desc("Propagate attributes in index"));
  28. static cl::opt<bool> ImportConstantsWithRefs(
  29. "import-constants-with-refs", cl::init(true), cl::Hidden,
  30. cl::desc("Import constant global variables with references"));
  31. constexpr uint32_t FunctionSummary::ParamAccess::RangeWidth;
  32. FunctionSummary FunctionSummary::ExternalNode =
  33. FunctionSummary::makeDummyFunctionSummary({});
  34. GlobalValue::VisibilityTypes ValueInfo::getELFVisibility() const {
  35. bool HasProtected = false;
  36. for (const auto &S : make_pointee_range(getSummaryList())) {
  37. if (S.getVisibility() == GlobalValue::HiddenVisibility)
  38. return GlobalValue::HiddenVisibility;
  39. if (S.getVisibility() == GlobalValue::ProtectedVisibility)
  40. HasProtected = true;
  41. }
  42. return HasProtected ? GlobalValue::ProtectedVisibility
  43. : GlobalValue::DefaultVisibility;
  44. }
  45. bool ValueInfo::isDSOLocal(bool WithDSOLocalPropagation) const {
  46. // With DSOLocal propagation done, the flag in evey summary is the same.
  47. // Check the first one is enough.
  48. return WithDSOLocalPropagation
  49. ? getSummaryList().size() && getSummaryList()[0]->isDSOLocal()
  50. : getSummaryList().size() &&
  51. llvm::all_of(
  52. getSummaryList(),
  53. [](const std::unique_ptr<GlobalValueSummary> &Summary) {
  54. return Summary->isDSOLocal();
  55. });
  56. }
  57. bool ValueInfo::canAutoHide() const {
  58. // Can only auto hide if all copies are eligible to auto hide.
  59. return getSummaryList().size() &&
  60. llvm::all_of(getSummaryList(),
  61. [](const std::unique_ptr<GlobalValueSummary> &Summary) {
  62. return Summary->canAutoHide();
  63. });
  64. }
  65. // Gets the number of readonly and writeonly refs in RefEdgeList
  66. std::pair<unsigned, unsigned> FunctionSummary::specialRefCounts() const {
  67. // Here we take advantage of having all readonly and writeonly references
  68. // located in the end of the RefEdgeList.
  69. auto Refs = refs();
  70. unsigned RORefCnt = 0, WORefCnt = 0;
  71. int I;
  72. for (I = Refs.size() - 1; I >= 0 && Refs[I].isWriteOnly(); --I)
  73. WORefCnt++;
  74. for (; I >= 0 && Refs[I].isReadOnly(); --I)
  75. RORefCnt++;
  76. return {RORefCnt, WORefCnt};
  77. }
  78. constexpr uint64_t ModuleSummaryIndex::BitcodeSummaryVersion;
  79. uint64_t ModuleSummaryIndex::getFlags() const {
  80. uint64_t Flags = 0;
  81. if (withGlobalValueDeadStripping())
  82. Flags |= 0x1;
  83. if (skipModuleByDistributedBackend())
  84. Flags |= 0x2;
  85. if (hasSyntheticEntryCounts())
  86. Flags |= 0x4;
  87. if (enableSplitLTOUnit())
  88. Flags |= 0x8;
  89. if (partiallySplitLTOUnits())
  90. Flags |= 0x10;
  91. if (withAttributePropagation())
  92. Flags |= 0x20;
  93. if (withDSOLocalPropagation())
  94. Flags |= 0x40;
  95. return Flags;
  96. }
  97. void ModuleSummaryIndex::setFlags(uint64_t Flags) {
  98. assert(Flags <= 0x7f && "Unexpected bits in flag");
  99. // 1 bit: WithGlobalValueDeadStripping flag.
  100. // Set on combined index only.
  101. if (Flags & 0x1)
  102. setWithGlobalValueDeadStripping();
  103. // 1 bit: SkipModuleByDistributedBackend flag.
  104. // Set on combined index only.
  105. if (Flags & 0x2)
  106. setSkipModuleByDistributedBackend();
  107. // 1 bit: HasSyntheticEntryCounts flag.
  108. // Set on combined index only.
  109. if (Flags & 0x4)
  110. setHasSyntheticEntryCounts();
  111. // 1 bit: DisableSplitLTOUnit flag.
  112. // Set on per module indexes. It is up to the client to validate
  113. // the consistency of this flag across modules being linked.
  114. if (Flags & 0x8)
  115. setEnableSplitLTOUnit();
  116. // 1 bit: PartiallySplitLTOUnits flag.
  117. // Set on combined index only.
  118. if (Flags & 0x10)
  119. setPartiallySplitLTOUnits();
  120. // 1 bit: WithAttributePropagation flag.
  121. // Set on combined index only.
  122. if (Flags & 0x20)
  123. setWithAttributePropagation();
  124. // 1 bit: WithDSOLocalPropagation flag.
  125. // Set on combined index only.
  126. if (Flags & 0x40)
  127. setWithDSOLocalPropagation();
  128. }
  129. // Collect for the given module the list of function it defines
  130. // (GUID -> Summary).
  131. void ModuleSummaryIndex::collectDefinedFunctionsForModule(
  132. StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const {
  133. for (auto &GlobalList : *this) {
  134. auto GUID = GlobalList.first;
  135. for (auto &GlobSummary : GlobalList.second.SummaryList) {
  136. auto *Summary = dyn_cast_or_null<FunctionSummary>(GlobSummary.get());
  137. if (!Summary)
  138. // Ignore global variable, focus on functions
  139. continue;
  140. // Ignore summaries from other modules.
  141. if (Summary->modulePath() != ModulePath)
  142. continue;
  143. GVSummaryMap[GUID] = Summary;
  144. }
  145. }
  146. }
  147. GlobalValueSummary *
  148. ModuleSummaryIndex::getGlobalValueSummary(uint64_t ValueGUID,
  149. bool PerModuleIndex) const {
  150. auto VI = getValueInfo(ValueGUID);
  151. assert(VI && "GlobalValue not found in index");
  152. assert((!PerModuleIndex || VI.getSummaryList().size() == 1) &&
  153. "Expected a single entry per global value in per-module index");
  154. auto &Summary = VI.getSummaryList()[0];
  155. return Summary.get();
  156. }
  157. bool ModuleSummaryIndex::isGUIDLive(GlobalValue::GUID GUID) const {
  158. auto VI = getValueInfo(GUID);
  159. if (!VI)
  160. return true;
  161. const auto &SummaryList = VI.getSummaryList();
  162. if (SummaryList.empty())
  163. return true;
  164. for (auto &I : SummaryList)
  165. if (isGlobalValueLive(I.get()))
  166. return true;
  167. return false;
  168. }
  169. static void
  170. propagateAttributesToRefs(GlobalValueSummary *S,
  171. DenseSet<ValueInfo> &MarkedNonReadWriteOnly) {
  172. // If reference is not readonly or writeonly then referenced summary is not
  173. // read/writeonly either. Note that:
  174. // - All references from GlobalVarSummary are conservatively considered as
  175. // not readonly or writeonly. Tracking them properly requires more complex
  176. // analysis then we have now.
  177. //
  178. // - AliasSummary objects have no refs at all so this function is a no-op
  179. // for them.
  180. for (auto &VI : S->refs()) {
  181. assert(VI.getAccessSpecifier() == 0 || isa<FunctionSummary>(S));
  182. if (!VI.getAccessSpecifier()) {
  183. if (!MarkedNonReadWriteOnly.insert(VI).second)
  184. continue;
  185. } else if (MarkedNonReadWriteOnly.contains(VI))
  186. continue;
  187. for (auto &Ref : VI.getSummaryList())
  188. // If references to alias is not read/writeonly then aliasee
  189. // is not read/writeonly
  190. if (auto *GVS = dyn_cast<GlobalVarSummary>(Ref->getBaseObject())) {
  191. if (!VI.isReadOnly())
  192. GVS->setReadOnly(false);
  193. if (!VI.isWriteOnly())
  194. GVS->setWriteOnly(false);
  195. }
  196. }
  197. }
  198. // Do the access attribute and DSOLocal propagation in combined index.
  199. // The goal of attribute propagation is internalization of readonly (RO)
  200. // or writeonly (WO) variables. To determine which variables are RO or WO
  201. // and which are not we take following steps:
  202. // - During analysis we speculatively assign readonly and writeonly
  203. // attribute to all variables which can be internalized. When computing
  204. // function summary we also assign readonly or writeonly attribute to a
  205. // reference if function doesn't modify referenced variable (readonly)
  206. // or doesn't read it (writeonly).
  207. //
  208. // - After computing dead symbols in combined index we do the attribute
  209. // and DSOLocal propagation. During this step we:
  210. // a. clear RO and WO attributes from variables which are preserved or
  211. // can't be imported
  212. // b. clear RO and WO attributes from variables referenced by any global
  213. // variable initializer
  214. // c. clear RO attribute from variable referenced by a function when
  215. // reference is not readonly
  216. // d. clear WO attribute from variable referenced by a function when
  217. // reference is not writeonly
  218. // e. clear IsDSOLocal flag in every summary if any of them is false.
  219. //
  220. // Because of (c, d) we don't internalize variables read by function A
  221. // and modified by function B.
  222. //
  223. // Internalization itself happens in the backend after import is finished
  224. // See internalizeGVsAfterImport.
  225. void ModuleSummaryIndex::propagateAttributes(
  226. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
  227. if (!PropagateAttrs)
  228. return;
  229. DenseSet<ValueInfo> MarkedNonReadWriteOnly;
  230. for (auto &P : *this) {
  231. bool IsDSOLocal = true;
  232. for (auto &S : P.second.SummaryList) {
  233. if (!isGlobalValueLive(S.get())) {
  234. // computeDeadSymbolsAndUpdateIndirectCalls should have marked all
  235. // copies live. Note that it is possible that there is a GUID collision
  236. // between internal symbols with the same name in different files of the
  237. // same name but not enough distinguishing path. Because
  238. // computeDeadSymbolsAndUpdateIndirectCalls should conservatively mark
  239. // all copies live we can assert here that all are dead if any copy is
  240. // dead.
  241. assert(llvm::none_of(
  242. P.second.SummaryList,
  243. [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
  244. return isGlobalValueLive(Summary.get());
  245. }));
  246. // We don't examine references from dead objects
  247. break;
  248. }
  249. // Global variable can't be marked read/writeonly if it is not eligible
  250. // to import since we need to ensure that all external references get
  251. // a local (imported) copy. It also can't be marked read/writeonly if
  252. // it or any alias (since alias points to the same memory) are preserved
  253. // or notEligibleToImport, since either of those means there could be
  254. // writes (or reads in case of writeonly) that are not visible (because
  255. // preserved means it could have external to DSO writes or reads, and
  256. // notEligibleToImport means it could have writes or reads via inline
  257. // assembly leading it to be in the @llvm.*used).
  258. if (auto *GVS = dyn_cast<GlobalVarSummary>(S->getBaseObject()))
  259. // Here we intentionally pass S.get() not GVS, because S could be
  260. // an alias. We don't analyze references here, because we have to
  261. // know exactly if GV is readonly to do so.
  262. if (!canImportGlobalVar(S.get(), /* AnalyzeRefs */ false) ||
  263. GUIDPreservedSymbols.count(P.first)) {
  264. GVS->setReadOnly(false);
  265. GVS->setWriteOnly(false);
  266. }
  267. propagateAttributesToRefs(S.get(), MarkedNonReadWriteOnly);
  268. // If the flag from any summary is false, the GV is not DSOLocal.
  269. IsDSOLocal &= S->isDSOLocal();
  270. }
  271. if (!IsDSOLocal)
  272. // Mark the flag in all summaries false so that we can do quick check
  273. // without going through the whole list.
  274. for (const std::unique_ptr<GlobalValueSummary> &Summary :
  275. P.second.SummaryList)
  276. Summary->setDSOLocal(false);
  277. }
  278. setWithAttributePropagation();
  279. setWithDSOLocalPropagation();
  280. if (llvm::AreStatisticsEnabled())
  281. for (auto &P : *this)
  282. if (P.second.SummaryList.size())
  283. if (auto *GVS = dyn_cast<GlobalVarSummary>(
  284. P.second.SummaryList[0]->getBaseObject()))
  285. if (isGlobalValueLive(GVS)) {
  286. if (GVS->maybeReadOnly())
  287. ReadOnlyLiveGVars++;
  288. if (GVS->maybeWriteOnly())
  289. WriteOnlyLiveGVars++;
  290. }
  291. }
  292. bool ModuleSummaryIndex::canImportGlobalVar(GlobalValueSummary *S,
  293. bool AnalyzeRefs) const {
  294. auto HasRefsPreventingImport = [this](const GlobalVarSummary *GVS) {
  295. // We don't analyze GV references during attribute propagation, so
  296. // GV with non-trivial initializer can be marked either read or
  297. // write-only.
  298. // Importing definiton of readonly GV with non-trivial initializer
  299. // allows us doing some extra optimizations (like converting indirect
  300. // calls to direct).
  301. // Definition of writeonly GV with non-trivial initializer should also
  302. // be imported. Not doing so will result in:
  303. // a) GV internalization in source module (because it's writeonly)
  304. // b) Importing of GV declaration to destination module as a result
  305. // of promotion.
  306. // c) Link error (external declaration with internal definition).
  307. // However we do not promote objects referenced by writeonly GV
  308. // initializer by means of converting it to 'zeroinitializer'
  309. return !(ImportConstantsWithRefs && GVS->isConstant()) &&
  310. !isReadOnly(GVS) && !isWriteOnly(GVS) && GVS->refs().size();
  311. };
  312. auto *GVS = cast<GlobalVarSummary>(S->getBaseObject());
  313. // Global variable with non-trivial initializer can be imported
  314. // if it's readonly. This gives us extra opportunities for constant
  315. // folding and converting indirect calls to direct calls. We don't
  316. // analyze GV references during attribute propagation, because we
  317. // don't know yet if it is readonly or not.
  318. return !GlobalValue::isInterposableLinkage(S->linkage()) &&
  319. !S->notEligibleToImport() &&
  320. (!AnalyzeRefs || !HasRefsPreventingImport(GVS));
  321. }
  322. // TODO: write a graphviz dumper for SCCs (see ModuleSummaryIndex::exportToDot)
  323. // then delete this function and update its tests
  324. LLVM_DUMP_METHOD
  325. void ModuleSummaryIndex::dumpSCCs(raw_ostream &O) {
  326. for (scc_iterator<ModuleSummaryIndex *> I =
  327. scc_begin<ModuleSummaryIndex *>(this);
  328. !I.isAtEnd(); ++I) {
  329. O << "SCC (" << utostr(I->size()) << " node" << (I->size() == 1 ? "" : "s")
  330. << ") {\n";
  331. for (const ValueInfo &V : *I) {
  332. FunctionSummary *F = nullptr;
  333. if (V.getSummaryList().size())
  334. F = cast<FunctionSummary>(V.getSummaryList().front().get());
  335. O << " " << (F == nullptr ? "External" : "") << " " << utostr(V.getGUID())
  336. << (I.hasCycle() ? " (has cycle)" : "") << "\n";
  337. }
  338. O << "}\n";
  339. }
  340. }
  341. namespace {
  342. struct Attributes {
  343. void add(const Twine &Name, const Twine &Value,
  344. const Twine &Comment = Twine());
  345. void addComment(const Twine &Comment);
  346. std::string getAsString() const;
  347. std::vector<std::string> Attrs;
  348. std::string Comments;
  349. };
  350. struct Edge {
  351. uint64_t SrcMod;
  352. int Hotness;
  353. GlobalValue::GUID Src;
  354. GlobalValue::GUID Dst;
  355. };
  356. }
  357. void Attributes::add(const Twine &Name, const Twine &Value,
  358. const Twine &Comment) {
  359. std::string A = Name.str();
  360. A += "=\"";
  361. A += Value.str();
  362. A += "\"";
  363. Attrs.push_back(A);
  364. addComment(Comment);
  365. }
  366. void Attributes::addComment(const Twine &Comment) {
  367. if (!Comment.isTriviallyEmpty()) {
  368. if (Comments.empty())
  369. Comments = " // ";
  370. else
  371. Comments += ", ";
  372. Comments += Comment.str();
  373. }
  374. }
  375. std::string Attributes::getAsString() const {
  376. if (Attrs.empty())
  377. return "";
  378. std::string Ret = "[";
  379. for (auto &A : Attrs)
  380. Ret += A + ",";
  381. Ret.pop_back();
  382. Ret += "];";
  383. Ret += Comments;
  384. return Ret;
  385. }
  386. static std::string linkageToString(GlobalValue::LinkageTypes LT) {
  387. switch (LT) {
  388. case GlobalValue::ExternalLinkage:
  389. return "extern";
  390. case GlobalValue::AvailableExternallyLinkage:
  391. return "av_ext";
  392. case GlobalValue::LinkOnceAnyLinkage:
  393. return "linkonce";
  394. case GlobalValue::LinkOnceODRLinkage:
  395. return "linkonce_odr";
  396. case GlobalValue::WeakAnyLinkage:
  397. return "weak";
  398. case GlobalValue::WeakODRLinkage:
  399. return "weak_odr";
  400. case GlobalValue::AppendingLinkage:
  401. return "appending";
  402. case GlobalValue::InternalLinkage:
  403. return "internal";
  404. case GlobalValue::PrivateLinkage:
  405. return "private";
  406. case GlobalValue::ExternalWeakLinkage:
  407. return "extern_weak";
  408. case GlobalValue::CommonLinkage:
  409. return "common";
  410. }
  411. return "<unknown>";
  412. }
  413. static std::string fflagsToString(FunctionSummary::FFlags F) {
  414. auto FlagValue = [](unsigned V) { return V ? '1' : '0'; };
  415. char FlagRep[] = {FlagValue(F.ReadNone),
  416. FlagValue(F.ReadOnly),
  417. FlagValue(F.NoRecurse),
  418. FlagValue(F.ReturnDoesNotAlias),
  419. FlagValue(F.NoInline),
  420. FlagValue(F.AlwaysInline),
  421. FlagValue(F.NoUnwind),
  422. FlagValue(F.MayThrow),
  423. FlagValue(F.HasUnknownCall),
  424. FlagValue(F.MustBeUnreachable),
  425. 0};
  426. return FlagRep;
  427. }
  428. // Get string representation of function instruction count and flags.
  429. static std::string getSummaryAttributes(GlobalValueSummary* GVS) {
  430. auto *FS = dyn_cast_or_null<FunctionSummary>(GVS);
  431. if (!FS)
  432. return "";
  433. return std::string("inst: ") + std::to_string(FS->instCount()) +
  434. ", ffl: " + fflagsToString(FS->fflags());
  435. }
  436. static std::string getNodeVisualName(GlobalValue::GUID Id) {
  437. return std::string("@") + std::to_string(Id);
  438. }
  439. static std::string getNodeVisualName(const ValueInfo &VI) {
  440. return VI.name().empty() ? getNodeVisualName(VI.getGUID()) : VI.name().str();
  441. }
  442. static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS) {
  443. if (isa<AliasSummary>(GVS))
  444. return getNodeVisualName(VI);
  445. std::string Attrs = getSummaryAttributes(GVS);
  446. std::string Label =
  447. getNodeVisualName(VI) + "|" + linkageToString(GVS->linkage());
  448. if (!Attrs.empty())
  449. Label += std::string(" (") + Attrs + ")";
  450. Label += "}";
  451. return Label;
  452. }
  453. // Write definition of external node, which doesn't have any
  454. // specific module associated with it. Typically this is function
  455. // or variable defined in native object or library.
  456. static void defineExternalNode(raw_ostream &OS, const char *Pfx,
  457. const ValueInfo &VI, GlobalValue::GUID Id) {
  458. auto StrId = std::to_string(Id);
  459. OS << " " << StrId << " [label=\"";
  460. if (VI) {
  461. OS << getNodeVisualName(VI);
  462. } else {
  463. OS << getNodeVisualName(Id);
  464. }
  465. OS << "\"]; // defined externally\n";
  466. }
  467. static bool hasReadOnlyFlag(const GlobalValueSummary *S) {
  468. if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
  469. return GVS->maybeReadOnly();
  470. return false;
  471. }
  472. static bool hasWriteOnlyFlag(const GlobalValueSummary *S) {
  473. if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
  474. return GVS->maybeWriteOnly();
  475. return false;
  476. }
  477. static bool hasConstantFlag(const GlobalValueSummary *S) {
  478. if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
  479. return GVS->isConstant();
  480. return false;
  481. }
  482. void ModuleSummaryIndex::exportToDot(
  483. raw_ostream &OS,
  484. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) const {
  485. std::vector<Edge> CrossModuleEdges;
  486. DenseMap<GlobalValue::GUID, std::vector<uint64_t>> NodeMap;
  487. using GVSOrderedMapTy = std::map<GlobalValue::GUID, GlobalValueSummary *>;
  488. std::map<StringRef, GVSOrderedMapTy> ModuleToDefinedGVS;
  489. collectDefinedGVSummariesPerModule(ModuleToDefinedGVS);
  490. // Get node identifier in form MXXX_<GUID>. The MXXX prefix is required,
  491. // because we may have multiple linkonce functions summaries.
  492. auto NodeId = [](uint64_t ModId, GlobalValue::GUID Id) {
  493. return ModId == (uint64_t)-1 ? std::to_string(Id)
  494. : std::string("M") + std::to_string(ModId) +
  495. "_" + std::to_string(Id);
  496. };
  497. auto DrawEdge = [&](const char *Pfx, uint64_t SrcMod, GlobalValue::GUID SrcId,
  498. uint64_t DstMod, GlobalValue::GUID DstId,
  499. int TypeOrHotness) {
  500. // 0 - alias
  501. // 1 - reference
  502. // 2 - constant reference
  503. // 3 - writeonly reference
  504. // Other value: (hotness - 4).
  505. TypeOrHotness += 4;
  506. static const char *EdgeAttrs[] = {
  507. " [style=dotted]; // alias",
  508. " [style=dashed]; // ref",
  509. " [style=dashed,color=forestgreen]; // const-ref",
  510. " [style=dashed,color=violetred]; // writeOnly-ref",
  511. " // call (hotness : Unknown)",
  512. " [color=blue]; // call (hotness : Cold)",
  513. " // call (hotness : None)",
  514. " [color=brown]; // call (hotness : Hot)",
  515. " [style=bold,color=red]; // call (hotness : Critical)"};
  516. assert(static_cast<size_t>(TypeOrHotness) <
  517. sizeof(EdgeAttrs) / sizeof(EdgeAttrs[0]));
  518. OS << Pfx << NodeId(SrcMod, SrcId) << " -> " << NodeId(DstMod, DstId)
  519. << EdgeAttrs[TypeOrHotness] << "\n";
  520. };
  521. OS << "digraph Summary {\n";
  522. for (auto &ModIt : ModuleToDefinedGVS) {
  523. auto ModId = getModuleId(ModIt.first);
  524. OS << " // Module: " << ModIt.first << "\n";
  525. OS << " subgraph cluster_" << std::to_string(ModId) << " {\n";
  526. OS << " style = filled;\n";
  527. OS << " color = lightgrey;\n";
  528. OS << " label = \"" << sys::path::filename(ModIt.first) << "\";\n";
  529. OS << " node [style=filled,fillcolor=lightblue];\n";
  530. auto &GVSMap = ModIt.second;
  531. auto Draw = [&](GlobalValue::GUID IdFrom, GlobalValue::GUID IdTo, int Hotness) {
  532. if (!GVSMap.count(IdTo)) {
  533. CrossModuleEdges.push_back({ModId, Hotness, IdFrom, IdTo});
  534. return;
  535. }
  536. DrawEdge(" ", ModId, IdFrom, ModId, IdTo, Hotness);
  537. };
  538. for (auto &SummaryIt : GVSMap) {
  539. NodeMap[SummaryIt.first].push_back(ModId);
  540. auto Flags = SummaryIt.second->flags();
  541. Attributes A;
  542. if (isa<FunctionSummary>(SummaryIt.second)) {
  543. A.add("shape", "record", "function");
  544. } else if (isa<AliasSummary>(SummaryIt.second)) {
  545. A.add("style", "dotted,filled", "alias");
  546. A.add("shape", "box");
  547. } else {
  548. A.add("shape", "Mrecord", "variable");
  549. if (Flags.Live && hasReadOnlyFlag(SummaryIt.second))
  550. A.addComment("immutable");
  551. if (Flags.Live && hasWriteOnlyFlag(SummaryIt.second))
  552. A.addComment("writeOnly");
  553. if (Flags.Live && hasConstantFlag(SummaryIt.second))
  554. A.addComment("constant");
  555. }
  556. if (Flags.Visibility)
  557. A.addComment("visibility");
  558. if (Flags.DSOLocal)
  559. A.addComment("dsoLocal");
  560. if (Flags.CanAutoHide)
  561. A.addComment("canAutoHide");
  562. if (GUIDPreservedSymbols.count(SummaryIt.first))
  563. A.addComment("preserved");
  564. auto VI = getValueInfo(SummaryIt.first);
  565. A.add("label", getNodeLabel(VI, SummaryIt.second));
  566. if (!Flags.Live)
  567. A.add("fillcolor", "red", "dead");
  568. else if (Flags.NotEligibleToImport)
  569. A.add("fillcolor", "yellow", "not eligible to import");
  570. OS << " " << NodeId(ModId, SummaryIt.first) << " " << A.getAsString()
  571. << "\n";
  572. }
  573. OS << " // Edges:\n";
  574. for (auto &SummaryIt : GVSMap) {
  575. auto *GVS = SummaryIt.second;
  576. for (auto &R : GVS->refs())
  577. Draw(SummaryIt.first, R.getGUID(),
  578. R.isWriteOnly() ? -1 : (R.isReadOnly() ? -2 : -3));
  579. if (auto *AS = dyn_cast_or_null<AliasSummary>(SummaryIt.second)) {
  580. Draw(SummaryIt.first, AS->getAliaseeGUID(), -4);
  581. continue;
  582. }
  583. if (auto *FS = dyn_cast_or_null<FunctionSummary>(SummaryIt.second))
  584. for (auto &CGEdge : FS->calls())
  585. Draw(SummaryIt.first, CGEdge.first.getGUID(),
  586. static_cast<int>(CGEdge.second.Hotness));
  587. }
  588. OS << " }\n";
  589. }
  590. OS << " // Cross-module edges:\n";
  591. for (auto &E : CrossModuleEdges) {
  592. auto &ModList = NodeMap[E.Dst];
  593. if (ModList.empty()) {
  594. defineExternalNode(OS, " ", getValueInfo(E.Dst), E.Dst);
  595. // Add fake module to the list to draw an edge to an external node
  596. // in the loop below.
  597. ModList.push_back(-1);
  598. }
  599. for (auto DstMod : ModList)
  600. // The edge representing call or ref is drawn to every module where target
  601. // symbol is defined. When target is a linkonce symbol there can be
  602. // multiple edges representing a single call or ref, both intra-module and
  603. // cross-module. As we've already drawn all intra-module edges before we
  604. // skip it here.
  605. if (DstMod != E.SrcMod)
  606. DrawEdge(" ", E.SrcMod, E.Src, DstMod, E.Dst, E.Hotness);
  607. }
  608. OS << "}";
  609. }