LLVM 24.0.0git
ModuleSummaryIndex.cpp
Go to the documentation of this file.
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
16#include "llvm/ADT/Statistic.h"
18#include "llvm/Support/Path.h"
20using namespace llvm;
21
22#define DEBUG_TYPE "module-summary-index"
23
24STATISTIC(ReadOnlyLiveGVars,
25 "Number of live global variables marked read only");
26STATISTIC(WriteOnlyLiveGVars,
27 "Number of live global variables marked write only");
28
29namespace llvm {
31 AlwaysRenamePromotedLocals("always-rename-promoted-locals", cl::init(true),
33 cl::desc("Always rename promoted locals."));
34} // namespace llvm
35
36static cl::opt<bool> PropagateAttrs("propagate-attrs", cl::init(true),
38 cl::desc("Propagate attributes in index"));
39
41 "import-constants-with-refs", cl::init(true), cl::Hidden,
42 cl::desc("Import constant global variables with references"));
43
47
49 bool HasProtected = false;
50 for (const auto &S : make_pointee_range(getSummaryList())) {
51 if (S.getVisibility() == GlobalValue::HiddenVisibility)
53 if (S.getVisibility() == GlobalValue::ProtectedVisibility)
54 HasProtected = true;
55 }
56 return HasProtected ? GlobalValue::ProtectedVisibility
58}
59
60bool ValueInfo::isDSOLocal(bool WithDSOLocalPropagation) const {
61 // With DSOLocal propagation done, the flag in evey summary is the same.
62 // Check the first one is enough.
63 return WithDSOLocalPropagation
64 ? getSummaryList().size() && getSummaryList()[0]->isDSOLocal()
65 : getSummaryList().size() &&
68 [](const std::unique_ptr<GlobalValueSummary> &Summary) {
69 return Summary->isDSOLocal();
70 });
71}
72
74 // Can only auto hide if all copies are eligible to auto hide.
75 return getSummaryList().size() &&
77 [](const std::unique_ptr<GlobalValueSummary> &Summary) {
78 return Summary->canAutoHide();
79 });
80}
81
82// Gets the number of readonly and writeonly refs in RefEdgeList
83std::pair<unsigned, unsigned> FunctionSummary::specialRefCounts() const {
84 // Here we take advantage of having all readonly and writeonly references
85 // located in the end of the RefEdgeList.
86 auto Refs = refs();
87 unsigned RORefCnt = 0, WORefCnt = 0;
88 int I;
89 for (I = Refs.size() - 1; I >= 0 && Refs[I].isWriteOnly(); --I)
90 WORefCnt++;
91 for (; I >= 0 && Refs[I].isReadOnly(); --I)
92 RORefCnt++;
93 return {RORefCnt, WORefCnt};
94}
95
97 uint64_t Flags = 0;
98 // Flags & 0x4 is reserved. DO NOT REUSE.
100 Flags |= 0x1;
102 Flags |= 0x2;
103 if (enableSplitLTOUnit())
104 Flags |= 0x8;
106 Flags |= 0x10;
108 Flags |= 0x20;
110 Flags |= 0x40;
112 Flags |= 0x80;
114 Flags |= 0x100;
115 if (hasUnifiedLTO())
116 Flags |= 0x200;
118 Flags |= 0x400;
120 Flags |= 0x800;
121 return Flags;
122}
123
124void ModuleSummaryIndex::setFlags(uint64_t Flags) {
125 assert(Flags <= 0xfff && "Unexpected bits in flag");
126 // 1 bit: WithGlobalValueDeadStripping flag.
127 // Set on combined index only.
128 if (Flags & 0x1)
130 // 1 bit: SkipModuleByDistributedBackend flag.
131 // Set on combined index only.
132 if (Flags & 0x2)
134 // Flags & 0x4 is reserved. DO NOT REUSE.
135 // 1 bit: DisableSplitLTOUnit flag.
136 // Set on per module indexes. It is up to the client to validate
137 // the consistency of this flag across modules being linked.
138 if (Flags & 0x8)
140 // 1 bit: PartiallySplitLTOUnits flag.
141 // Set on combined index only.
142 if (Flags & 0x10)
144 // 1 bit: WithAttributePropagation flag.
145 // Set on combined index only.
146 if (Flags & 0x20)
148 // 1 bit: WithDSOLocalPropagation flag.
149 // Set on combined index only.
150 if (Flags & 0x40)
152 // 1 bit: WithWholeProgramVisibility flag.
153 // Set on combined index only.
154 if (Flags & 0x80)
156 // 1 bit: WithSupportsHotColdNew flag.
157 // Set on combined index only.
158 if (Flags & 0x100)
160 // 1 bit: WithUnifiedLTO flag.
161 // Set on combined index only.
162 if (Flags & 0x200)
164 // 1 bit: WithInternalizeAndPromote flag.
165 // Set on combined index only.
166 if (Flags & 0x400)
168 // 1 bit: WithSpeculativeDevirt flag.
169 // Set on combined index only.
170 if (Flags & 0x800)
172}
173
174// Collect for the given module the list of function it defines
175// (GUID -> Summary).
177 StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const {
178 for (auto &GlobalList : *this) {
179 auto GUID = GlobalList.first;
180 for (auto &GlobSummary : GlobalList.second.getSummaryList()) {
181 auto *Summary = dyn_cast_or_null<FunctionSummary>(GlobSummary.get());
182 if (!Summary)
183 // Ignore global variable, focus on functions
184 continue;
185 // Ignore summaries from other modules.
186 if (Summary->modulePath() != ModulePath)
187 continue;
188 GVSummaryMap[GUID] = Summary;
189 }
190 }
191}
192
195 bool PerModuleIndex) const {
196 auto VI = getValueInfo(ValueGUID);
197 assert(VI && "GlobalValue not found in index");
198 assert((!PerModuleIndex || VI.getSummaryList().size() == 1) &&
199 "Expected a single entry per global value in per-module index");
200 auto &Summary = VI.getSummaryList()[0];
201 return Summary.get();
202}
203
205 auto VI = getValueInfo(GUID);
206 if (!VI)
207 return true;
208 const auto &SummaryList = VI.getSummaryList();
209 if (SummaryList.empty())
210 return true;
211 for (auto &I : SummaryList)
212 if (isGlobalValueLive(I.get()))
213 return true;
214 return false;
215}
216
217static void
219 DenseSet<ValueInfo> &MarkedNonReadWriteOnly) {
220 // If reference is not readonly or writeonly then referenced summary is not
221 // read/writeonly either. Note that:
222 // - All references from GlobalVarSummary are conservatively considered as
223 // not readonly or writeonly. Tracking them properly requires more complex
224 // analysis then we have now.
225 //
226 // - AliasSummary objects have no refs at all so this function is a no-op
227 // for them.
228 for (auto &VI : S->refs()) {
229 assert(VI.getAccessSpecifier() == 0 || isa<FunctionSummary>(S));
230 if (!VI.getAccessSpecifier()) {
231 if (!MarkedNonReadWriteOnly.insert(VI).second)
232 continue;
233 } else if (MarkedNonReadWriteOnly.contains(VI))
234 continue;
235 bool HasNonGVar = false;
236 for (auto &Ref : VI.getSummaryList()) {
237 // If references to alias is not read/writeonly then aliasee
238 // is not read/writeonly
239 if (auto *GVS = dyn_cast<GlobalVarSummary>(Ref->getBaseObject())) {
240 if (!VI.isReadOnly())
241 GVS->setReadOnly(false);
242 if (!VI.isWriteOnly())
243 GVS->setWriteOnly(false);
244 } else {
245 // Note that this needs special processing.
246 HasNonGVar = true;
247 break;
248 }
249 }
250 // In the case where we have a reference to a VI that is a function not a
251 // variable, conservatively mark all summaries as non-read or write only.
252 // In most cases that would have happened in the above loop. However,
253 // this will make a difference in a few rare cases where there are same
254 // named locals in modules without enough distinguishing path, which end up
255 // with the same GUID. If these are a mix of variables and functions we want
256 // to handle the variables conservatively.
257 if (HasNonGVar) {
258 for (auto &Ref : VI.getSummaryList()) {
259 auto *GVS = dyn_cast<GlobalVarSummary>(Ref->getBaseObject());
260 if (!GVS)
261 continue;
262 GVS->setReadOnly(false);
263 GVS->setWriteOnly(false);
264 }
265 MarkedNonReadWriteOnly.insert(VI);
266 }
267 }
268}
269
270// Do the access attribute and DSOLocal propagation in combined index.
271// The goal of attribute propagation is internalization of readonly (RO)
272// or writeonly (WO) variables. To determine which variables are RO or WO
273// and which are not we take following steps:
274// - During analysis we speculatively assign readonly and writeonly
275// attribute to all variables which can be internalized. When computing
276// function summary we also assign readonly or writeonly attribute to a
277// reference if function doesn't modify referenced variable (readonly)
278// or doesn't read it (writeonly).
279//
280// - After computing dead symbols in combined index we do the attribute
281// and DSOLocal propagation. During this step we:
282// a. clear RO and WO attributes from variables which are preserved or
283// can't be imported
284// b. clear RO and WO attributes from variables referenced by any global
285// variable initializer
286// c. clear RO attribute from variable referenced by a function when
287// reference is not readonly
288// d. clear WO attribute from variable referenced by a function when
289// reference is not writeonly
290// e. clear RO and WO attributes from variables with the same GUID as
291// a non-variable.
292// f. clear IsDSOLocal flag in every summary if any of them is false.
293//
294// Because of (c, d) we don't internalize variables read by function A
295// and modified by function B.
296//
297// Internalization itself happens in the backend after import is finished
298// See internalizeGVsAfterImport.
300 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
301 if (!PropagateAttrs)
302 return;
303 DenseSet<ValueInfo> MarkedNonReadWriteOnly;
304 for (auto &P : *this) {
305 bool IsDSOLocal = true;
306 for (auto &S : P.second.getSummaryList()) {
307 if (!isGlobalValueLive(S.get())) {
308 // computeDeadSymbolsAndUpdateIndirectCalls should have marked all
309 // copies live. Note that it is possible that there is a GUID collision
310 // between internal symbols with the same name in different files of the
311 // same name but not enough distinguishing path. Because
312 // computeDeadSymbolsAndUpdateIndirectCalls should conservatively mark
313 // all copies live we can assert here that all are dead if any copy is
314 // dead.
316 P.second.getSummaryList(),
317 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
318 return isGlobalValueLive(Summary.get());
319 }));
320 // We don't examine references from dead objects
321 break;
322 }
323
324 // Global variable can't be marked read/writeonly if it is not eligible
325 // to import since we need to ensure that all external references get
326 // a local (imported) copy. It also can't be marked read/writeonly if
327 // it or any alias (since alias points to the same memory) are preserved
328 // or notEligibleToImport, since either of those means there could be
329 // writes (or reads in case of writeonly) that are not visible (because
330 // preserved means it could have external to DSO writes or reads, and
331 // notEligibleToImport means it could have writes or reads via inline
332 // assembly leading it to be in the @llvm.*used).
333 if (auto *GVS = dyn_cast<GlobalVarSummary>(S->getBaseObject()))
334 // Here we intentionally pass S.get() not GVS, because S could be
335 // an alias. We don't analyze references here, because we have to
336 // know exactly if GV is readonly to do so.
337 if (!canImportGlobalVar(S.get(), /* AnalyzeRefs */ false) ||
338 GUIDPreservedSymbols.count(P.first)) {
339 GVS->setReadOnly(false);
340 GVS->setWriteOnly(false);
341 }
342 propagateAttributesToRefs(S.get(), MarkedNonReadWriteOnly);
343
344 // If the flag from any summary is false, the GV is not DSOLocal.
345 IsDSOLocal &= S->isDSOLocal();
346 }
347 if (!IsDSOLocal)
348 // Mark the flag in all summaries false so that we can do quick check
349 // without going through the whole list.
350 for (const std::unique_ptr<GlobalValueSummary> &Summary :
351 P.second.getSummaryList())
352 Summary->setDSOLocal(false);
353 }
357 for (auto &P : *this)
358 if (P.second.getSummaryList().size())
359 if (auto *GVS = dyn_cast<GlobalVarSummary>(
360 P.second.getSummaryList()[0]->getBaseObject()))
361 if (isGlobalValueLive(GVS)) {
362 if (GVS->maybeReadOnly())
363 ReadOnlyLiveGVars++;
364 if (GVS->maybeWriteOnly())
365 WriteOnlyLiveGVars++;
366 }
367}
368
370 bool AnalyzeRefs) const {
371 bool CanImportDecl;
372 return canImportGlobalVar(S, AnalyzeRefs, CanImportDecl);
373}
374
376 bool AnalyzeRefs,
377 bool &CanImportDecl) const {
378 auto HasRefsPreventingImport = [this](const GlobalVarSummary *GVS) {
379 // We don't analyze GV references during attribute propagation, so
380 // GV with non-trivial initializer can be marked either read or
381 // write-only.
382 // Importing definiton of readonly GV with non-trivial initializer
383 // allows us doing some extra optimizations (like converting indirect
384 // calls to direct).
385 // Definition of writeonly GV with non-trivial initializer should also
386 // be imported. Not doing so will result in:
387 // a) GV internalization in source module (because it's writeonly)
388 // b) Importing of GV declaration to destination module as a result
389 // of promotion.
390 // c) Link error (external declaration with internal definition).
391 // However we do not promote objects referenced by writeonly GV
392 // initializer by means of converting it to 'zeroinitializer'
393 return !(ImportConstantsWithRefs && GVS->isConstant()) &&
394 !isReadOnly(GVS) && !isWriteOnly(GVS) && GVS->refs().size();
395 };
396 auto *GVS = cast<GlobalVarSummary>(S->getBaseObject());
397
398 const bool nonInterposable =
400 const bool eligibleToImport = !S->notEligibleToImport();
401
402 // It's correct to import a global variable only when it is not interposable
403 // and eligible to import.
404 CanImportDecl = (nonInterposable && eligibleToImport);
405
406 // Global variable with non-trivial initializer can be imported
407 // if it's readonly. This gives us extra opportunities for constant
408 // folding and converting indirect calls to direct calls. We don't
409 // analyze GV references during attribute propagation, because we
410 // don't know yet if it is readonly or not.
411 return nonInterposable && eligibleToImport &&
412 (!AnalyzeRefs || !HasRefsPreventingImport(GVS));
413}
414
415// TODO: write a graphviz dumper for SCCs (see ModuleSummaryIndex::exportToDot)
416// then delete this function and update its tests
421 !I.isAtEnd(); ++I) {
422 O << "SCC (" << utostr(I->size()) << " node" << (I->size() == 1 ? "" : "s")
423 << ") {\n";
424 for (const ValueInfo &V : *I) {
425 FunctionSummary *F = nullptr;
426 if (V.getSummaryList().size())
427 F = cast<FunctionSummary>(V.getSummaryList().front().get());
428 O << " " << (F == nullptr ? "External" : "") << " " << utostr(V.getGUID())
429 << (I.hasCycle() ? " (has cycle)" : "") << "\n";
430 }
431 O << "}\n";
432 }
433}
434
435namespace {
436struct Attributes {
437 void add(const Twine &Name, const Twine &Value,
438 const Twine &Comment = Twine());
439 void addComment(const Twine &Comment);
440 std::string getAsString() const;
441
442 std::vector<std::string> Attrs;
443 std::string Comments;
444};
445
446struct Edge {
447 uint64_t SrcMod;
448 int Hotness;
451};
452} // namespace
453
454void Attributes::add(const Twine &Name, const Twine &Value,
455 const Twine &Comment) {
456 std::string A = Name.str();
457 A += "=\"";
458 A += Value.str();
459 A += "\"";
460 Attrs.push_back(A);
461 addComment(Comment);
462}
463
464void Attributes::addComment(const Twine &Comment) {
465 if (!Comment.isTriviallyEmpty()) {
466 if (Comments.empty())
467 Comments = " // ";
468 else
469 Comments += ", ";
470 Comments += Comment.str();
471 }
472}
473
474std::string Attributes::getAsString() const {
475 if (Attrs.empty())
476 return "";
477
478 std::string Ret = "[";
479 for (auto &A : Attrs)
480 Ret += A + ",";
481 Ret.pop_back();
482 Ret += "];";
483 Ret += Comments;
484 return Ret;
485}
486
488 switch (LT) {
490 return "extern";
492 return "av_ext";
494 return "linkonce";
496 return "linkonce_odr";
498 return "weak";
500 return "weak_odr";
502 return "appending";
504 return "internal";
506 return "private";
508 return "extern_weak";
510 return "common";
511 }
512
513 return "<unknown>";
514}
515
517 auto FlagValue = [](unsigned V) { return V ? '1' : '0'; };
518 char FlagRep[] = {FlagValue(F.ReadNone),
519 FlagValue(F.ReadOnly),
520 FlagValue(F.NoRecurse),
521 FlagValue(F.ReturnDoesNotAlias),
522 FlagValue(F.NoInline),
523 FlagValue(F.AlwaysInline),
524 FlagValue(F.NoUnwind),
525 FlagValue(F.MayThrow),
526 FlagValue(F.HasUnknownCall),
527 FlagValue(F.MustBeUnreachable),
528 0};
529
530 return FlagRep;
531}
532
533// Get string representation of function instruction count and flags.
534static std::string getSummaryAttributes(GlobalValueSummary* GVS) {
535 auto *FS = dyn_cast_or_null<FunctionSummary>(GVS);
536 if (!FS)
537 return "";
538
539 return std::string("inst: ") + std::to_string(FS->instCount()) +
540 ", ffl: " + fflagsToString(FS->fflags());
541}
542
543static std::string getNodeVisualName(GlobalValue::GUID Id) {
544 return std::string("@") + std::to_string(Id);
545}
546
547static std::string getNodeVisualName(const ValueInfo &VI) {
548 return VI.name().empty() ? getNodeVisualName(VI.getGUID()) : VI.name().str();
549}
550
551static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS) {
552 if (isa<AliasSummary>(GVS))
553 return getNodeVisualName(VI);
554
555 std::string Attrs = getSummaryAttributes(GVS);
556 std::string Label =
557 getNodeVisualName(VI) + "|" + linkageToString(GVS->linkage());
558 if (!Attrs.empty())
559 Label += std::string(" (") + Attrs + ")";
560 Label += "}";
561
562 return Label;
563}
564
565// Write definition of external node, which doesn't have any
566// specific module associated with it. Typically this is function
567// or variable defined in native object or library.
568static void defineExternalNode(raw_ostream &OS, const char *Pfx,
569 const ValueInfo &VI, GlobalValue::GUID Id) {
570 auto StrId = std::to_string(Id);
571 OS << " " << StrId << " [label=\"";
572
573 if (VI) {
574 OS << getNodeVisualName(VI);
575 } else {
576 OS << getNodeVisualName(Id);
577 }
578 OS << "\"]; // defined externally\n";
579}
580
581static bool hasReadOnlyFlag(const GlobalValueSummary *S) {
582 if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
583 return GVS->maybeReadOnly();
584 return false;
585}
586
588 if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
589 return GVS->maybeWriteOnly();
590 return false;
591}
592
593static bool hasConstantFlag(const GlobalValueSummary *S) {
594 if (auto *GVS = dyn_cast<GlobalVarSummary>(S))
595 return GVS->isConstant();
596 return false;
597}
598
600 raw_ostream &OS,
601 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) const {
602 std::vector<Edge> CrossModuleEdges;
604 using GVSOrderedMapTy = std::map<GlobalValue::GUID, GlobalValueSummary *>;
605 std::map<StringRef, GVSOrderedMapTy> ModuleToDefinedGVS;
606 collectDefinedGVSummariesPerModule(ModuleToDefinedGVS);
607
608 // Assign an id to each module path for use in graph labels. Since the
609 // StringMap iteration order isn't guaranteed, order by path string before
610 // assigning ids.
611 std::vector<StringRef> ModulePaths;
612 for (auto &[ModPath, _] : modulePaths())
613 ModulePaths.push_back(ModPath);
614 llvm::sort(ModulePaths);
616 for (auto &ModPath : ModulePaths)
617 ModuleIdMap.try_emplace(ModPath, ModuleIdMap.size());
618
619 // Get node identifier in form MXXX_<GUID>. The MXXX prefix is required,
620 // because we may have multiple linkonce functions summaries.
621 auto NodeId = [](uint64_t ModId, GlobalValue::GUID Id) {
622 return ModId == (uint64_t)-1 ? std::to_string(Id)
623 : std::string("M") + std::to_string(ModId) +
624 "_" + std::to_string(Id);
625 };
626
627 auto DrawEdge = [&](const char *Pfx, uint64_t SrcMod, GlobalValue::GUID SrcId,
628 uint64_t DstMod, GlobalValue::GUID DstId,
629 int TypeOrHotness) {
630 // 0 - alias
631 // 1 - reference
632 // 2 - constant reference
633 // 3 - writeonly reference
634 // Other value: (hotness - 4).
635 TypeOrHotness += 4;
636 static const char *EdgeAttrs[] = {
637 " [style=dotted]; // alias",
638 " [style=dashed]; // ref",
639 " [style=dashed,color=forestgreen]; // const-ref",
640 " [style=dashed,color=violetred]; // writeOnly-ref",
641 " // call (hotness : Unknown)",
642 " [color=blue]; // call (hotness : Cold)",
643 " // call (hotness : None)",
644 " [color=brown]; // call (hotness : Hot)",
645 " [style=bold,color=red]; // call (hotness : Critical)"};
646
647 assert(static_cast<size_t>(TypeOrHotness) < std::size(EdgeAttrs));
648 OS << Pfx << NodeId(SrcMod, SrcId) << " -> " << NodeId(DstMod, DstId)
649 << EdgeAttrs[TypeOrHotness] << "\n";
650 };
651
652 OS << "digraph Summary {\n";
653 for (auto &ModIt : ModuleToDefinedGVS) {
654 // Will be empty for a just built per-module index, which doesn't setup a
655 // module paths table. In that case use 0 as the module id.
656 assert(ModuleIdMap.count(ModIt.first) || ModuleIdMap.empty());
657 auto ModId = ModuleIdMap.empty() ? 0 : ModuleIdMap[ModIt.first];
658 OS << " // Module: " << ModIt.first << "\n";
659 OS << " subgraph cluster_" << std::to_string(ModId) << " {\n";
660 OS << " style = filled;\n";
661 OS << " color = lightgrey;\n";
662 OS << " label = \"" << sys::path::filename(ModIt.first) << "\";\n";
663 OS << " node [style=filled,fillcolor=lightblue];\n";
664
665 auto &GVSMap = ModIt.second;
666 auto Draw = [&](GlobalValue::GUID IdFrom, GlobalValue::GUID IdTo, int Hotness) {
667 if (!GVSMap.count(IdTo)) {
668 CrossModuleEdges.push_back({ModId, Hotness, IdFrom, IdTo});
669 return;
670 }
671 DrawEdge(" ", ModId, IdFrom, ModId, IdTo, Hotness);
672 };
673
674 for (auto &SummaryIt : GVSMap) {
675 NodeMap[SummaryIt.first].push_back(ModId);
676 auto Flags = SummaryIt.second->flags();
677 Attributes A;
678 if (isa<FunctionSummary>(SummaryIt.second)) {
679 A.add("shape", "record", "function");
680 } else if (isa<AliasSummary>(SummaryIt.second)) {
681 A.add("style", "dotted,filled", "alias");
682 A.add("shape", "box");
683 } else {
684 A.add("shape", "Mrecord", "variable");
685 if (Flags.Live && hasReadOnlyFlag(SummaryIt.second))
686 A.addComment("immutable");
687 if (Flags.Live && hasWriteOnlyFlag(SummaryIt.second))
688 A.addComment("writeOnly");
689 if (Flags.Live && hasConstantFlag(SummaryIt.second))
690 A.addComment("constant");
691 }
692 if (Flags.Visibility)
693 A.addComment("visibility");
694 if (Flags.DSOLocal)
695 A.addComment("dsoLocal");
696 if (Flags.CanAutoHide)
697 A.addComment("canAutoHide");
698 switch (SummaryIt.second->importType()) {
700 A.addComment("definition");
701 break;
703 A.addComment("declaration");
704 break;
705 }
706 if (Flags.NoRenameOnPromotion)
707 A.addComment("noRenameOnPromotion");
708 if (GUIDPreservedSymbols.count(SummaryIt.first))
709 A.addComment("preserved");
710
711 auto VI = getValueInfo(SummaryIt.first);
712 A.add("label", getNodeLabel(VI, SummaryIt.second));
713 if (!Flags.Live)
714 A.add("fillcolor", "red", "dead");
715 else if (Flags.NotEligibleToImport)
716 A.add("fillcolor", "yellow", "not eligible to import");
717
718 OS << " " << NodeId(ModId, SummaryIt.first) << " " << A.getAsString()
719 << "\n";
720 }
721 OS << " // Edges:\n";
722
723 for (auto &SummaryIt : GVSMap) {
724 auto *GVS = SummaryIt.second;
725 for (auto &R : GVS->refs())
726 Draw(SummaryIt.first, R.getGUID(),
727 R.isWriteOnly() ? -1 : (R.isReadOnly() ? -2 : -3));
728
729 if (auto *AS = dyn_cast_or_null<AliasSummary>(SummaryIt.second)) {
730 Draw(SummaryIt.first, AS->getAliaseeGUID(), -4);
731 continue;
732 }
733
734 if (auto *FS = dyn_cast_or_null<FunctionSummary>(SummaryIt.second))
735 for (auto &CGEdge : FS->calls())
736 Draw(SummaryIt.first, CGEdge.first.getGUID(),
737 static_cast<int>(CGEdge.second.Hotness));
738 }
739 OS << " }\n";
740 }
741
742 OS << " // Cross-module edges:\n";
743 for (auto &E : CrossModuleEdges) {
744 auto &ModList = NodeMap[E.Dst];
745 if (ModList.empty()) {
746 defineExternalNode(OS, " ", getValueInfo(E.Dst), E.Dst);
747 // Add fake module to the list to draw an edge to an external node
748 // in the loop below.
749 ModList.push_back(-1);
750 }
751 for (auto DstMod : ModList)
752 // The edge representing call or ref is drawn to every module where target
753 // symbol is defined. When target is a linkonce symbol there can be
754 // multiple edges representing a single call or ref, both intra-module and
755 // cross-module. As we've already drawn all intra-module edges before we
756 // skip it here.
757 if (DstMod != E.SrcMod)
758 DrawEdge(" ", E.SrcMod, E.Src, DstMod, E.Dst, E.Hotness);
759 }
760
761 OS << "}";
762}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
#define _
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static std::string getNodeVisualName(GlobalValue::GUID Id)
static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS)
static std::string getSummaryAttributes(GlobalValueSummary *GVS)
static cl::opt< bool > ImportConstantsWithRefs("import-constants-with-refs", cl::init(true), cl::Hidden, cl::desc("Import constant global variables with references"))
static std::string fflagsToString(FunctionSummary::FFlags F)
static bool hasWriteOnlyFlag(const GlobalValueSummary *S)
static void propagateAttributesToRefs(GlobalValueSummary *S, DenseSet< ValueInfo > &MarkedNonReadWriteOnly)
static std::string linkageToString(GlobalValue::LinkageTypes LT)
static void defineExternalNode(raw_ostream &OS, const char *Pfx, const ValueInfo &VI, GlobalValue::GUID Id)
static cl::opt< bool > PropagateAttrs("propagate-attrs", cl::init(true), cl::Hidden, cl::desc("Propagate attributes in index"))
static bool hasReadOnlyFlag(const GlobalValueSummary *S)
static bool hasConstantFlag(const GlobalValueSummary *S)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
#define P(N)
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
bool empty() const
Definition DenseMap.h:716
unsigned size() const
Definition DenseMap.h:717
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Function summary information to aid decisions and implementation of importing.
static LLVM_ABI FunctionSummary ExternalNode
A dummy node to reference external functions that aren't in the index.
static FunctionSummary makeDummyFunctionSummary(SmallVectorImpl< FunctionSummary::EdgeTy > &&Edges)
Create an empty FunctionSummary (with specified call edges).
LLVM_ABI std::pair< unsigned, unsigned > specialRefCounts() const
Function and variable summary information to aid decisions and implementation of importing.
GlobalValueSummary * getBaseObject()
If this is an alias summary, returns the summary of the aliased object (a global variable or function...
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
GlobalValue::LinkageTypes linkage() const
Return linkage type recorded for this global value.
bool notEligibleToImport() const
Return true if this global value can't be imported.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time.
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Global variable summary information to aid decisions and implementation of importing.
LLVM_ABI bool isGUIDLive(GlobalValue::GUID GUID) const
bool isReadOnly(const GlobalVarSummary *GVS) const
LLVM_ABI void setFlags(uint64_t Flags)
bool isWriteOnly(const GlobalVarSummary *GVS) const
ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const
Return a ValueInfo for the index value_type (convenient when iterating index).
LLVM_ABI void collectDefinedFunctionsForModule(StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const
Collect for the given module the list of functions it defines (GUID -> Summary).
LLVM_ABI void dumpSCCs(raw_ostream &OS)
Print out strongly connected components for debugging.
bool isGlobalValueLive(const GlobalValueSummary *GVS) const
LLVM_ABI void propagateAttributes(const DenseSet< GlobalValue::GUID > &PreservedSymbols)
Do the access attribute and DSOLocal propagation in combined index.
const StringMap< ModuleHash > & modulePaths() const
Table of modules, containing module hash and id.
void collectDefinedGVSummariesPerModule(Map &ModuleToDefinedGVSummaries) const
Collect for each module the list of Summaries it defines (GUID -> Summary).
LLVM_ABI void exportToDot(raw_ostream &OS, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols) const
Export summary to dot file for GraphViz.
bool skipModuleByDistributedBackend() const
LLVM_ABI uint64_t getFlags() const
GlobalValueSummary * getGlobalValueSummary(const GlobalValue &GV, bool PerModuleIndex=true) const
Returns the first GlobalValueSummary for GV, asserting that there is only one if PerModuleIndex.
LLVM_ABI bool canImportGlobalVar(const GlobalValueSummary *S, bool AnalyzeRefs) const
Checks if we can import global variable from another module.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Enumerate the SCCs of a directed graph in reverse topological order of the SCC DAG.
Definition SCCIterator.h:48
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
initializer< Ty > init(const Ty &Val)
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
std::string utostr(uint64_t X, bool isNeg=false)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
iterator_range< pointee_iterator< WrappedIteratorT > > make_pointee_range(RangeT &&Range)
Definition iterator.h:341
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
cl::opt< bool > AlwaysRenamePromotedLocals("always-rename-promoted-locals", cl::init(true), cl::Hidden, cl::desc("Always rename promoted locals."))
Definition LTO.cpp:113
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Flags specific to function summaries.
Struct that holds a reference to a particular GUID in a global value summary.
LLVM_ABI GlobalValue::VisibilityTypes getELFVisibility() const
Returns the most constraining visibility among summaries.
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
LLVM_ABI bool canAutoHide() const
Checks if all copies are eligible for auto-hiding (have flag set).
LLVM_ABI bool isDSOLocal(bool WithDSOLocalPropagation=false) const
Checks if all summaries are DSO local (have the flag set).