blob: bb5b7d0d3ab130b5d18c4ecdd380ab9546f75400 [file] [log] [blame]
Teresa Johnson26ab5772016-03-15 00:04:37 +00001//===-- ModuleSummaryIndex.cpp - Module Summary Index ---------------------===//
Teresa Johnsoncec0cae2016-03-14 21:18:10 +00002//
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 file implements the module index and summary classes for the
11// IR library.
12//
13//===----------------------------------------------------------------------===//
14
Teresa Johnson26ab5772016-03-15 00:04:37 +000015#include "llvm/IR/ModuleSummaryIndex.h"
Charles Saternosb040fcc2018-02-19 15:14:50 +000016#include "llvm/ADT/SCCIterator.h"
Teresa Johnson8c1915c2018-11-17 20:03:22 +000017#include "llvm/ADT/Statistic.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000018#include "llvm/ADT/StringMap.h"
Eugene Leviant28d8a492018-01-22 13:35:40 +000019#include "llvm/Support/Path.h"
Charles Saternosb040fcc2018-02-19 15:14:50 +000020#include "llvm/Support/raw_ostream.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000021using namespace llvm;
22
Teresa Johnson8c1915c2018-11-17 20:03:22 +000023#define DEBUG_TYPE "module-summary-index"
24
25STATISTIC(ReadOnlyLiveGVars,
26 "Number of live global variables marked read only");
27
Charles Saternosb040fcc2018-02-19 15:14:50 +000028FunctionSummary FunctionSummary::ExternalNode =
29 FunctionSummary::makeDummyFunctionSummary({});
Peter Collingbourneb4edfb92018-02-05 17:17:51 +000030bool ValueInfo::isDSOLocal() const {
31 // Need to check all summaries are local in case of hash collisions.
32 return getSummaryList().size() &&
33 llvm::all_of(getSummaryList(),
34 [](const std::unique_ptr<GlobalValueSummary> &Summary) {
35 return Summary->isDSOLocal();
36 });
37}
38
Eugene Leviantbf46e742018-11-16 07:08:00 +000039// Gets the number of immutable refs in RefEdgeList
40unsigned FunctionSummary::immutableRefCount() const {
41 // Here we take advantage of having all readonly references
42 // located in the end of the RefEdgeList.
43 auto Refs = refs();
44 unsigned ImmutableRefCnt = 0;
45 for (int I = Refs.size() - 1; I >= 0 && Refs[I].isReadOnly(); --I)
46 ImmutableRefCnt++;
47 return ImmutableRefCnt;
48}
49
Teresa Johnsonc86af332016-04-12 21:13:11 +000050// Collect for the given module the list of function it defines
51// (GUID -> Summary).
52void ModuleSummaryIndex::collectDefinedFunctionsForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +000053 StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const {
Teresa Johnsonc86af332016-04-12 21:13:11 +000054 for (auto &GlobalList : *this) {
55 auto GUID = GlobalList.first;
Peter Collingbourne9667b912017-05-04 18:03:25 +000056 for (auto &GlobSummary : GlobalList.second.SummaryList) {
Teresa Johnson28e457b2016-04-24 14:57:11 +000057 auto *Summary = dyn_cast_or_null<FunctionSummary>(GlobSummary.get());
Teresa Johnsonc86af332016-04-12 21:13:11 +000058 if (!Summary)
59 // Ignore global variable, focus on functions
60 continue;
61 // Ignore summaries from other modules.
62 if (Summary->modulePath() != ModulePath)
63 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +000064 GVSummaryMap[GUID] = Summary;
Teresa Johnsonc86af332016-04-12 21:13:11 +000065 }
66 }
67}
68
Mehdi Amini1aafabf2016-04-16 07:02:16 +000069// Collect for each module the list of function it defines (GUID -> Summary).
70void ModuleSummaryIndex::collectDefinedGVSummariesPerModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +000071 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries) const {
Mehdi Amini1aafabf2016-04-16 07:02:16 +000072 for (auto &GlobalList : *this) {
73 auto GUID = GlobalList.first;
Peter Collingbourne9667b912017-05-04 18:03:25 +000074 for (auto &Summary : GlobalList.second.SummaryList) {
Teresa Johnson28e457b2016-04-24 14:57:11 +000075 ModuleToDefinedGVSummaries[Summary->modulePath()][GUID] = Summary.get();
Mehdi Amini1aafabf2016-04-16 07:02:16 +000076 }
77 }
78}
79
Teresa Johnson28e457b2016-04-24 14:57:11 +000080GlobalValueSummary *
81ModuleSummaryIndex::getGlobalValueSummary(uint64_t ValueGUID,
82 bool PerModuleIndex) const {
Peter Collingbourne9667b912017-05-04 18:03:25 +000083 auto VI = getValueInfo(ValueGUID);
84 assert(VI && "GlobalValue not found in index");
85 assert((!PerModuleIndex || VI.getSummaryList().size() == 1) &&
Haojian Wu591ae462016-04-05 09:07:47 +000086 "Expected a single entry per global value in per-module index");
Peter Collingbourne9667b912017-05-04 18:03:25 +000087 auto &Summary = VI.getSummaryList()[0];
Teresa Johnson28e457b2016-04-24 14:57:11 +000088 return Summary.get();
Teresa Johnsonfb7c7642016-04-05 00:40:16 +000089}
Peter Collingbournedbd2fed2017-06-15 17:26:13 +000090
91bool ModuleSummaryIndex::isGUIDLive(GlobalValue::GUID GUID) const {
92 auto VI = getValueInfo(GUID);
93 if (!VI)
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +000094 return true;
95 const auto &SummaryList = VI.getSummaryList();
96 if (SummaryList.empty())
97 return true;
98 for (auto &I : SummaryList)
Peter Collingbournedbd2fed2017-06-15 17:26:13 +000099 if (isGlobalValueLive(I.get()))
100 return true;
101 return false;
102}
Eugene Leviant28d8a492018-01-22 13:35:40 +0000103
Eugene Leviantbf46e742018-11-16 07:08:00 +0000104static void propagateConstantsToRefs(GlobalValueSummary *S) {
105 // If reference is not readonly then referenced summary is not
106 // readonly either. Note that:
107 // - All references from GlobalVarSummary are conservatively considered as
108 // not readonly. Tracking them properly requires more complex analysis
109 // then we have now.
110 //
111 // - AliasSummary objects have no refs at all so this function is a no-op
112 // for them.
113 for (auto &VI : S->refs()) {
114 if (VI.isReadOnly()) {
115 // We only mark refs as readonly when computing function summaries on
116 // analysis phase.
117 assert(isa<FunctionSummary>(S));
118 continue;
119 }
120 for (auto &Ref : VI.getSummaryList())
121 // If references to alias is not readonly then aliasee is not readonly
122 if (auto *GVS = dyn_cast<GlobalVarSummary>(Ref->getBaseObject()))
123 GVS->setReadOnly(false);
124 }
125}
126
127// Do the constant propagation in combined index.
128// The goal of constant propagation is internalization of readonly
129// variables. To determine which variables are readonly and which
130// are not we take following steps:
131// - During analysis we speculatively assign readonly attribute to
132// all variables which can be internalized. When computing function
133// summary we also assign readonly attribute to a reference if
134// function doesn't modify referenced variable.
135//
136// - After computing dead symbols in combined index we do the constant
137// propagation. During this step we clear readonly attribute from
138// all variables which:
139// a. are dead, preserved or can't be imported
140// b. referenced by any global variable initializer
141// c. referenced by a function and reference is not readonly
142//
143// Internalization itself happens in the backend after import is finished
144// See internalizeImmutableGVs.
145void ModuleSummaryIndex::propagateConstants(
146 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
147 for (auto &P : *this)
148 for (auto &S : P.second.SummaryList) {
149 if (!isGlobalValueLive(S.get()))
150 // We don't examine references from dead objects
151 continue;
152
153 // Global variable can't be marked read only if it is not eligible
154 // to import since we need to ensure that all external references
155 // get a local (imported) copy. It also can't be marked read only
156 // if it or any alias (since alias points to the same memory) are
157 // preserved or notEligibleToImport, since either of those means
158 // there could be writes that are not visible (because preserved
159 // means it could have external to DSO writes, and notEligibleToImport
160 // means it could have writes via inline assembly leading it to be
161 // in the @llvm.*used).
162 if (auto *GVS = dyn_cast<GlobalVarSummary>(S->getBaseObject()))
163 // Here we intentionally pass S.get() not GVS, because S could be
164 // an alias.
165 if (!canImportGlobalVar(S.get()) || GUIDPreservedSymbols.count(P.first))
166 GVS->setReadOnly(false);
167 propagateConstantsToRefs(S.get());
168 }
Teresa Johnson8c1915c2018-11-17 20:03:22 +0000169#if LLVM_ENABLE_STATS
170 for (auto &P : *this)
171 if (P.second.SummaryList.size())
172 if (auto *GVS = dyn_cast<GlobalVarSummary>(
173 P.second.SummaryList[0]->getBaseObject()))
174 if (isGlobalValueLive(GVS) && GVS->isReadOnly())
175 ReadOnlyLiveGVars++;
176#endif
Eugene Leviantbf46e742018-11-16 07:08:00 +0000177}
178
Charles Saternosb040fcc2018-02-19 15:14:50 +0000179// TODO: write a graphviz dumper for SCCs (see ModuleSummaryIndex::exportToDot)
180// then delete this function and update its tests
181LLVM_DUMP_METHOD
182void ModuleSummaryIndex::dumpSCCs(raw_ostream &O) {
183 for (scc_iterator<ModuleSummaryIndex *> I =
184 scc_begin<ModuleSummaryIndex *>(this);
185 !I.isAtEnd(); ++I) {
186 O << "SCC (" << utostr(I->size()) << " node" << (I->size() == 1 ? "" : "s")
187 << ") {\n";
188 for (const ValueInfo V : *I) {
189 FunctionSummary *F = nullptr;
190 if (V.getSummaryList().size())
191 F = cast<FunctionSummary>(V.getSummaryList().front().get());
192 O << " " << (F == nullptr ? "External" : "") << " " << utostr(V.getGUID())
193 << (I.hasLoop() ? " (has loop)" : "") << "\n";
194 }
195 O << "}\n";
196 }
197}
198
Eugene Leviant28d8a492018-01-22 13:35:40 +0000199namespace {
200struct Attributes {
201 void add(const Twine &Name, const Twine &Value,
202 const Twine &Comment = Twine());
Eugene Leviantbf46e742018-11-16 07:08:00 +0000203 void addComment(const Twine &Comment);
Eugene Leviant28d8a492018-01-22 13:35:40 +0000204 std::string getAsString() const;
205
206 std::vector<std::string> Attrs;
207 std::string Comments;
208};
209
210struct Edge {
211 uint64_t SrcMod;
212 int Hotness;
213 GlobalValue::GUID Src;
214 GlobalValue::GUID Dst;
215};
216}
217
218void Attributes::add(const Twine &Name, const Twine &Value,
219 const Twine &Comment) {
220 std::string A = Name.str();
221 A += "=\"";
222 A += Value.str();
223 A += "\"";
224 Attrs.push_back(A);
Eugene Leviantbf46e742018-11-16 07:08:00 +0000225 addComment(Comment);
226}
227
228void Attributes::addComment(const Twine &Comment) {
Eugene Leviant28d8a492018-01-22 13:35:40 +0000229 if (!Comment.isTriviallyEmpty()) {
230 if (Comments.empty())
231 Comments = " // ";
232 else
233 Comments += ", ";
234 Comments += Comment.str();
235 }
236}
237
238std::string Attributes::getAsString() const {
239 if (Attrs.empty())
240 return "";
241
242 std::string Ret = "[";
243 for (auto &A : Attrs)
244 Ret += A + ",";
245 Ret.pop_back();
246 Ret += "];";
247 Ret += Comments;
248 return Ret;
249}
250
251static std::string linkageToString(GlobalValue::LinkageTypes LT) {
252 switch (LT) {
253 case GlobalValue::ExternalLinkage:
254 return "extern";
255 case GlobalValue::AvailableExternallyLinkage:
256 return "av_ext";
257 case GlobalValue::LinkOnceAnyLinkage:
258 return "linkonce";
259 case GlobalValue::LinkOnceODRLinkage:
260 return "linkonce_odr";
261 case GlobalValue::WeakAnyLinkage:
262 return "weak";
263 case GlobalValue::WeakODRLinkage:
264 return "weak_odr";
265 case GlobalValue::AppendingLinkage:
266 return "appending";
267 case GlobalValue::InternalLinkage:
268 return "internal";
269 case GlobalValue::PrivateLinkage:
270 return "private";
271 case GlobalValue::ExternalWeakLinkage:
272 return "extern_weak";
273 case GlobalValue::CommonLinkage:
274 return "common";
275 }
276
277 return "<unknown>";
278}
279
280static std::string fflagsToString(FunctionSummary::FFlags F) {
281 auto FlagValue = [](unsigned V) { return V ? '1' : '0'; };
Teresa Johnsoncb397462018-11-06 19:41:35 +0000282 char FlagRep[] = {FlagValue(F.ReadNone), FlagValue(F.ReadOnly),
283 FlagValue(F.NoRecurse), FlagValue(F.ReturnDoesNotAlias),
284 FlagValue(F.NoInline), 0};
Eugene Leviant28d8a492018-01-22 13:35:40 +0000285
286 return FlagRep;
287}
288
289// Get string representation of function instruction count and flags.
290static std::string getSummaryAttributes(GlobalValueSummary* GVS) {
291 auto *FS = dyn_cast_or_null<FunctionSummary>(GVS);
292 if (!FS)
293 return "";
294
295 return std::string("inst: ") + std::to_string(FS->instCount()) +
296 ", ffl: " + fflagsToString(FS->fflags());
297}
298
Teresa Johnson7a92bc32018-11-02 23:49:21 +0000299static std::string getNodeVisualName(GlobalValue::GUID Id) {
300 return std::string("@") + std::to_string(Id);
301}
302
Eugene Leviant28d8a492018-01-22 13:35:40 +0000303static std::string getNodeVisualName(const ValueInfo &VI) {
Teresa Johnson7a92bc32018-11-02 23:49:21 +0000304 return VI.name().empty() ? getNodeVisualName(VI.getGUID()) : VI.name().str();
Eugene Leviant28d8a492018-01-22 13:35:40 +0000305}
306
307static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS) {
308 if (isa<AliasSummary>(GVS))
309 return getNodeVisualName(VI);
310
311 std::string Attrs = getSummaryAttributes(GVS);
312 std::string Label =
313 getNodeVisualName(VI) + "|" + linkageToString(GVS->linkage());
314 if (!Attrs.empty())
315 Label += std::string(" (") + Attrs + ")";
316 Label += "}";
317
318 return Label;
319}
320
321// Write definition of external node, which doesn't have any
322// specific module associated with it. Typically this is function
323// or variable defined in native object or library.
324static void defineExternalNode(raw_ostream &OS, const char *Pfx,
Teresa Johnson7a92bc32018-11-02 23:49:21 +0000325 const ValueInfo &VI, GlobalValue::GUID Id) {
326 auto StrId = std::to_string(Id);
327 OS << " " << StrId << " [label=\"";
328
329 if (VI) {
330 OS << getNodeVisualName(VI);
331 } else {
332 OS << getNodeVisualName(Id);
333 }
334 OS << "\"]; // defined externally\n";
Eugene Leviant28d8a492018-01-22 13:35:40 +0000335}
336
Eugene Leviantbf46e742018-11-16 07:08:00 +0000337static bool hasReadOnlyFlag(const GlobalValueSummary *S) {
338 if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
339 return GVS->isReadOnly();
340 return false;
341}
342
Teresa Johnson7a92bc32018-11-02 23:49:21 +0000343void ModuleSummaryIndex::exportToDot(raw_ostream &OS) const {
Eugene Leviant28d8a492018-01-22 13:35:40 +0000344 std::vector<Edge> CrossModuleEdges;
345 DenseMap<GlobalValue::GUID, std::vector<uint64_t>> NodeMap;
346 StringMap<GVSummaryMapTy> ModuleToDefinedGVS;
347 collectDefinedGVSummariesPerModule(ModuleToDefinedGVS);
348
349 // Get node identifier in form MXXX_<GUID>. The MXXX prefix is required,
350 // because we may have multiple linkonce functions summaries.
351 auto NodeId = [](uint64_t ModId, GlobalValue::GUID Id) {
352 return ModId == (uint64_t)-1 ? std::to_string(Id)
353 : std::string("M") + std::to_string(ModId) +
354 "_" + std::to_string(Id);
355 };
356
Eugene Leviant1f545002018-10-24 07:48:32 +0000357 auto DrawEdge = [&](const char *Pfx, uint64_t SrcMod, GlobalValue::GUID SrcId,
Eugene Leviantbf46e742018-11-16 07:08:00 +0000358 uint64_t DstMod, GlobalValue::GUID DstId,
359 int TypeOrHotness) {
360 // 0 - alias
361 // 1 - reference
362 // 2 - constant reference
363 // Other value: (hotness - 3).
364 TypeOrHotness += 3;
Eugene Leviant28d8a492018-01-22 13:35:40 +0000365 static const char *EdgeAttrs[] = {
366 " [style=dotted]; // alias",
367 " [style=dashed]; // ref",
Eugene Leviantbf46e742018-11-16 07:08:00 +0000368 " [style=dashed,color=forestgreen]; // const-ref",
Eugene Leviant28d8a492018-01-22 13:35:40 +0000369 " // call (hotness : Unknown)",
370 " [color=blue]; // call (hotness : Cold)",
371 " // call (hotness : None)",
372 " [color=brown]; // call (hotness : Hot)",
373 " [style=bold,color=red]; // call (hotness : Critical)"};
374
375 assert(static_cast<size_t>(TypeOrHotness) <
376 sizeof(EdgeAttrs) / sizeof(EdgeAttrs[0]));
377 OS << Pfx << NodeId(SrcMod, SrcId) << " -> " << NodeId(DstMod, DstId)
378 << EdgeAttrs[TypeOrHotness] << "\n";
379 };
380
381 OS << "digraph Summary {\n";
382 for (auto &ModIt : ModuleToDefinedGVS) {
383 auto ModId = getModuleId(ModIt.first());
384 OS << " // Module: " << ModIt.first() << "\n";
385 OS << " subgraph cluster_" << std::to_string(ModId) << " {\n";
386 OS << " style = filled;\n";
387 OS << " color = lightgrey;\n";
388 OS << " label = \"" << sys::path::filename(ModIt.first()) << "\";\n";
389 OS << " node [style=filled,fillcolor=lightblue];\n";
390
391 auto &GVSMap = ModIt.second;
392 auto Draw = [&](GlobalValue::GUID IdFrom, GlobalValue::GUID IdTo, int Hotness) {
393 if (!GVSMap.count(IdTo)) {
394 CrossModuleEdges.push_back({ModId, Hotness, IdFrom, IdTo});
395 return;
396 }
397 DrawEdge(" ", ModId, IdFrom, ModId, IdTo, Hotness);
398 };
399
400 for (auto &SummaryIt : GVSMap) {
401 NodeMap[SummaryIt.first].push_back(ModId);
402 auto Flags = SummaryIt.second->flags();
403 Attributes A;
404 if (isa<FunctionSummary>(SummaryIt.second)) {
405 A.add("shape", "record", "function");
406 } else if (isa<AliasSummary>(SummaryIt.second)) {
407 A.add("style", "dotted,filled", "alias");
408 A.add("shape", "box");
409 } else {
410 A.add("shape", "Mrecord", "variable");
Eugene Leviantbf46e742018-11-16 07:08:00 +0000411 if (Flags.Live && hasReadOnlyFlag(SummaryIt.second))
412 A.addComment("immutable");
Eugene Leviant28d8a492018-01-22 13:35:40 +0000413 }
414
415 auto VI = getValueInfo(SummaryIt.first);
416 A.add("label", getNodeLabel(VI, SummaryIt.second));
417 if (!Flags.Live)
418 A.add("fillcolor", "red", "dead");
419 else if (Flags.NotEligibleToImport)
420 A.add("fillcolor", "yellow", "not eligible to import");
421
422 OS << " " << NodeId(ModId, SummaryIt.first) << " " << A.getAsString()
423 << "\n";
424 }
425 OS << " // Edges:\n";
426
427 for (auto &SummaryIt : GVSMap) {
428 auto *GVS = SummaryIt.second;
429 for (auto &R : GVS->refs())
Eugene Leviantbf46e742018-11-16 07:08:00 +0000430 Draw(SummaryIt.first, R.getGUID(), R.isReadOnly() ? -1 : -2);
Eugene Leviant28d8a492018-01-22 13:35:40 +0000431
432 if (auto *AS = dyn_cast_or_null<AliasSummary>(SummaryIt.second)) {
Teresa Johnson7a92bc32018-11-02 23:49:21 +0000433 GlobalValue::GUID AliaseeId;
434 if (AS->hasAliaseeGUID())
435 AliaseeId = AS->getAliaseeGUID();
436 else {
437 auto AliaseeOrigId = AS->getAliasee().getOriginalName();
438 AliaseeId = getGUIDFromOriginalID(AliaseeOrigId);
439 if (!AliaseeId)
440 AliaseeId = AliaseeOrigId;
441 }
Eugene Leviant28d8a492018-01-22 13:35:40 +0000442
Eugene Leviantbf46e742018-11-16 07:08:00 +0000443 Draw(SummaryIt.first, AliaseeId, -3);
Eugene Leviant28d8a492018-01-22 13:35:40 +0000444 continue;
445 }
446
447 if (auto *FS = dyn_cast_or_null<FunctionSummary>(SummaryIt.second))
448 for (auto &CGEdge : FS->calls())
449 Draw(SummaryIt.first, CGEdge.first.getGUID(),
450 static_cast<int>(CGEdge.second.Hotness));
451 }
452 OS << " }\n";
453 }
454
455 OS << " // Cross-module edges:\n";
456 for (auto &E : CrossModuleEdges) {
457 auto &ModList = NodeMap[E.Dst];
458 if (ModList.empty()) {
Teresa Johnson7a92bc32018-11-02 23:49:21 +0000459 defineExternalNode(OS, " ", getValueInfo(E.Dst), E.Dst);
Eugene Leviant28d8a492018-01-22 13:35:40 +0000460 // Add fake module to the list to draw an edge to an external node
461 // in the loop below.
462 ModList.push_back(-1);
463 }
464 for (auto DstMod : ModList)
465 // The edge representing call or ref is drawn to every module where target
466 // symbol is defined. When target is a linkonce symbol there can be
467 // multiple edges representing a single call or ref, both intra-module and
468 // cross-module. As we've already drawn all intra-module edges before we
469 // skip it here.
470 if (DstMod != E.SrcMod)
471 DrawEdge(" ", E.SrcMod, E.Src, DstMod, E.Dst, E.Hotness);
472 }
473
474 OS << "}";
475}