LLVM 22.0.0git
ModuleSummaryIndex.h
Go to the documentation of this file.
1//===- llvm/ModuleSummaryIndex.h - Module Summary Index ---------*- C++ -*-===//
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/// @file
10/// ModuleSummaryIndex.h This file contains the declarations the classes that
11/// hold the module index and summary for function importing.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_MODULESUMMARYINDEX_H
16#define LLVM_IR_MODULESUMMARYINDEX_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/ADT/StringRef.h"
28#include "llvm/IR/GlobalValue.h"
29#include "llvm/IR/Module.h"
37#include <algorithm>
38#include <array>
39#include <cassert>
40#include <cstddef>
41#include <cstdint>
42#include <map>
43#include <memory>
44#include <optional>
45#include <set>
46#include <string>
47#include <unordered_set>
48#include <utility>
49#include <vector>
50
51namespace llvm {
52
53template <class GraphType> struct GraphTraits;
54
55namespace yaml {
56
57template <typename T> struct MappingTraits;
58
59} // end namespace yaml
60
61/// Class to accumulate and hold information about a callee.
62struct CalleeInfo {
63 enum class HotnessType : uint8_t {
65 Cold = 1,
66 None = 2,
67 Hot = 3,
69 };
70
71 // The size of the bit-field might need to be adjusted if more values are
72 // added to HotnessType enum.
74
75 // True if at least one of the calls to the callee is a tail call.
78
79 /// The value stored in RelBlockFreq has to be interpreted as the digits of
80 /// a scaled number with a scale of \p -ScaleShift.
81 static constexpr unsigned RelBlockFreqBits = 28;
83 static constexpr int32_t ScaleShift = 8;
84 static constexpr uint64_t MaxRelBlockFreq = (1 << RelBlockFreqBits) - 1;
85
89 explicit CalleeInfo(HotnessType Hotness, bool HasTC, uint64_t RelBF)
90 : Hotness(static_cast<uint32_t>(Hotness)), HasTailCall(HasTC),
91 RelBlockFreq(RelBF) {}
92
93 void updateHotness(const HotnessType OtherHotness) {
94 Hotness = std::max(Hotness, static_cast<uint32_t>(OtherHotness));
95 }
96
97 bool hasTailCall() const { return HasTailCall; }
98
99 void setHasTailCall(const bool HasTC) { HasTailCall = HasTC; }
100
102
103 /// Update \p RelBlockFreq from \p BlockFreq and \p EntryFreq
104 ///
105 /// BlockFreq is divided by EntryFreq and added to RelBlockFreq. To represent
106 /// fractional values, the result is represented as a fixed point number with
107 /// scale of -ScaleShift.
108 void updateRelBlockFreq(uint64_t BlockFreq, uint64_t EntryFreq) {
109 if (EntryFreq == 0)
110 return;
111 using Scaled64 = ScaledNumber<uint64_t>;
112 Scaled64 Temp(BlockFreq, ScaleShift);
113 Temp /= Scaled64::get(EntryFreq);
114
115 uint64_t Sum =
117 Sum = std::min(Sum, uint64_t(MaxRelBlockFreq));
118 RelBlockFreq = static_cast<uint32_t>(Sum);
119 }
120};
121
123 switch (HT) {
125 return "unknown";
127 return "cold";
129 return "none";
131 return "hot";
133 return "critical";
134 }
135 llvm_unreachable("invalid hotness");
136}
137
138class GlobalValueSummary;
139
140using GlobalValueSummaryList = std::vector<std::unique_ptr<GlobalValueSummary>>;
141
142struct alignas(8) GlobalValueSummaryInfo {
143 union NameOrGV {
144 NameOrGV(bool HaveGVs) {
145 if (HaveGVs)
146 GV = nullptr;
147 else
148 Name = "";
149 }
150
151 /// The GlobalValue corresponding to this summary. This is only used in
152 /// per-module summaries and when the IR is available. E.g. when module
153 /// analysis is being run, or when parsing both the IR and the summary
154 /// from assembly.
156
157 /// Summary string representation. This StringRef points to BC module
158 /// string table and is valid until module data is stored in memory.
159 /// This is guaranteed to happen until runThinLTOBackend function is
160 /// called, so it is safe to use this field during thin link. This field
161 /// is only valid if summary index was loaded from BC file.
163 } U;
164
165 inline GlobalValueSummaryInfo(bool HaveGVs);
166
167 /// Access a read-only list of global value summary structures for a
168 /// particular value held in the GlobalValueMap.
170 return SummaryList;
171 }
172
173 /// Add a summary corresponding to a global value definition in a module with
174 /// the corresponding GUID.
175 inline void addSummary(std::unique_ptr<GlobalValueSummary> Summary);
176
177 /// Verify that the HasLocal flag is consistent with the SummaryList. Should
178 /// only be called prior to index-based internalization and promotion.
179 inline void verifyLocal() const;
180
181 bool hasLocal() const { return HasLocal; }
182
183private:
184 /// List of global value summary structures for a particular value held
185 /// in the GlobalValueMap. Requires a vector in the case of multiple
186 /// COMDAT values of the same name, weak symbols, locals of the same name when
187 /// compiling without sufficient distinguishing path, or (theoretically) hash
188 /// collisions. Each summary is from a different module.
189 GlobalValueSummaryList SummaryList;
190
191 /// True if the SummaryList contains at least one summary with local linkage.
192 /// In most cases there should be only one, unless translation units with
193 /// same-named locals were compiled without distinguishing path. And generally
194 /// there should not be a mix of local and non-local summaries, because the
195 /// GUID for a local is computed with the path prepended and a ';' delimiter.
196 /// In extremely rare cases there could be a GUID hash collision. Having the
197 /// flag saves having to walk through all summaries to prove the existence or
198 /// not of any locals.
199 /// NOTE: this flag is set when the index is built. It does not reflect
200 /// index-based internalization and promotion decisions. Generally most
201 /// index-based analysis occurs before then, but any users should assert that
202 /// the withInternalizeAndPromote() flag is not set on the index.
203 /// TODO: Replace checks in various ThinLTO analyses that loop through all
204 /// summaries to handle the local case with a check of the flag.
205 bool HasLocal : 1;
206};
207
208/// Map from global value GUID to corresponding summary structures. Use a
209/// std::map rather than a DenseMap so that pointers to the map's value_type
210/// (which are used by ValueInfo) are not invalidated by insertion. Also it will
211/// likely incur less overhead, as the value type is not very small and the size
212/// of the map is unknown, resulting in inefficiencies due to repeated
213/// insertions and resizing.
215 std::map<GlobalValue::GUID, GlobalValueSummaryInfo>;
216
217/// Struct that holds a reference to a particular GUID in a global value
218/// summary.
219struct ValueInfo {
220 enum Flags { HaveGV = 1, ReadOnly = 2, WriteOnly = 4 };
223
224 ValueInfo() = default;
225 ValueInfo(bool HaveGVs, const GlobalValueSummaryMapTy::value_type *R) {
226 RefAndFlags.setPointer(R);
227 RefAndFlags.setInt(HaveGVs);
228 }
229
230 explicit operator bool() const { return getRef(); }
231
232 GlobalValue::GUID getGUID() const { return getRef()->first; }
233 const GlobalValue *getValue() const {
234 assert(haveGVs());
235 return getRef()->second.U.GV;
236 }
237
239 return getRef()->second.getSummaryList();
240 }
241
242 void verifyLocal() const { getRef()->second.verifyLocal(); }
243
244 bool hasLocal() const { return getRef()->second.hasLocal(); }
245
246 // Even if the index is built with GVs available, we may not have one for
247 // summary entries synthesized for profiled indirect call targets.
248 bool hasName() const { return !haveGVs() || getValue(); }
249
250 StringRef name() const {
251 assert(!haveGVs() || getRef()->second.U.GV);
252 return haveGVs() ? getRef()->second.U.GV->getName()
253 : getRef()->second.U.Name;
254 }
255
256 bool haveGVs() const { return RefAndFlags.getInt() & HaveGV; }
257 bool isReadOnly() const {
259 return RefAndFlags.getInt() & ReadOnly;
260 }
261 bool isWriteOnly() const {
263 return RefAndFlags.getInt() & WriteOnly;
264 }
265 unsigned getAccessSpecifier() const {
267 return RefAndFlags.getInt() & (ReadOnly | WriteOnly);
268 }
270 unsigned BadAccessMask = ReadOnly | WriteOnly;
271 return (RefAndFlags.getInt() & BadAccessMask) != BadAccessMask;
272 }
273 void setReadOnly() {
274 // We expect ro/wo attribute to set only once during
275 // ValueInfo lifetime.
277 RefAndFlags.setInt(RefAndFlags.getInt() | ReadOnly);
278 }
281 RefAndFlags.setInt(RefAndFlags.getInt() | WriteOnly);
282 }
283
284 const GlobalValueSummaryMapTy::value_type *getRef() const {
285 return RefAndFlags.getPointer();
286 }
287
288 /// Returns the most constraining visibility among summaries. The
289 /// visibilities, ordered from least to most constraining, are: default,
290 /// protected and hidden.
292
293 /// Checks if all summaries are DSO local (have the flag set). When DSOLocal
294 /// propagation has been done, set the parameter to enable fast check.
295 LLVM_ABI bool isDSOLocal(bool WithDSOLocalPropagation = false) const;
296
297 /// Checks if all copies are eligible for auto-hiding (have flag set).
298 LLVM_ABI bool canAutoHide() const;
299};
300
302 OS << VI.getGUID();
303 if (!VI.name().empty())
304 OS << " (" << VI.name() << ")";
305 return OS;
306}
307
308inline bool operator==(const ValueInfo &A, const ValueInfo &B) {
309 assert(A.getRef() && B.getRef() &&
310 "Need ValueInfo with non-null Ref for comparison");
311 return A.getRef() == B.getRef();
312}
313
314inline bool operator!=(const ValueInfo &A, const ValueInfo &B) {
315 assert(A.getRef() && B.getRef() &&
316 "Need ValueInfo with non-null Ref for comparison");
317 return A.getRef() != B.getRef();
318}
319
320inline bool operator<(const ValueInfo &A, const ValueInfo &B) {
321 assert(A.getRef() && B.getRef() &&
322 "Need ValueInfo with non-null Ref to compare GUIDs");
323 return A.getGUID() < B.getGUID();
324}
325
326template <> struct DenseMapInfo<ValueInfo> {
327 static inline ValueInfo getEmptyKey() {
328 return ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
329 }
330
331 static inline ValueInfo getTombstoneKey() {
332 return ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-16);
333 }
334
335 static inline bool isSpecialKey(ValueInfo V) {
336 return V == getTombstoneKey() || V == getEmptyKey();
337 }
338
339 static bool isEqual(ValueInfo L, ValueInfo R) {
340 // We are not supposed to mix ValueInfo(s) with different HaveGVs flag
341 // in a same container.
342 assert(isSpecialKey(L) || isSpecialKey(R) || (L.haveGVs() == R.haveGVs()));
343 return L.getRef() == R.getRef();
344 }
345 static unsigned getHashValue(ValueInfo I) { return hash_value(I.getRef()); }
346};
347
348// For optional hinted size reporting, holds a pair of the full stack id
349// (pre-trimming, from the full context in the profile), and the associated
350// total profiled size.
355
356/// Summary of memprof callsite metadata.
358 // Actual callee function.
360
361 // Used to record whole program analysis cloning decisions.
362 // The ThinLTO backend will need to create as many clones as there are entries
363 // in the vector (it is expected and should be confirmed that all such
364 // summaries in the same FunctionSummary have the same number of entries).
365 // Each index records version info for the corresponding clone of this
366 // function. The value is the callee clone it calls (becomes the appended
367 // suffix id). Index 0 is the original version, and a value of 0 calls the
368 // original callee.
370
371 // Represents stack ids in this context, recorded as indices into the
372 // StackIds vector in the summary index, which in turn holds the full 64-bit
373 // stack ids. This reduces memory as there are in practice far fewer unique
374 // stack ids than stack id references.
376
383};
384
386 OS << "Callee: " << SNI.Callee;
387 OS << " Clones: " << llvm::interleaved(SNI.Clones);
388 OS << " StackIds: " << llvm::interleaved(SNI.StackIdIndices);
389 return OS;
390}
391
392// Allocation type assigned to an allocation reached by a given context.
393// More can be added, now this is cold, notcold and hot.
394// Values should be powers of two so that they can be ORed, in particular to
395// track allocations that have different behavior with different calling
396// contexts.
398 None = 0,
400 Cold = 2,
401 Hot = 4,
402 All = 7 // This should always be set to the OR of all values.
403};
404
405/// Summary of a single MIB in a memprof metadata on allocations.
406struct MIBInfo {
407 // The allocation type for this profiled context.
409
410 // Represents stack ids in this context, recorded as indices into the
411 // StackIds vector in the summary index, which in turn holds the full 64-bit
412 // stack ids. This reduces memory as there are in practice far fewer unique
413 // stack ids than stack id references.
415
418};
419
420inline raw_ostream &operator<<(raw_ostream &OS, const MIBInfo &MIB) {
421 OS << "AllocType " << (unsigned)MIB.AllocType;
422 OS << " StackIds: " << llvm::interleaved(MIB.StackIdIndices);
423 return OS;
424}
425
426/// Summary of memprof metadata on allocations.
427struct AllocInfo {
428 // Used to record whole program analysis cloning decisions.
429 // The ThinLTO backend will need to create as many clones as there are entries
430 // in the vector (it is expected and should be confirmed that all such
431 // summaries in the same FunctionSummary have the same number of entries).
432 // Each index records version info for the corresponding clone of this
433 // function. The value is the allocation type of the corresponding allocation.
434 // Index 0 is the original version. Before cloning, index 0 may have more than
435 // one allocation type.
437
438 // Vector of MIBs in this memprof metadata.
439 std::vector<MIBInfo> MIBs;
440
441 // If requested, keep track of full stack contexts and total profiled sizes
442 // for each MIB. This will be a vector of the same length and order as the
443 // MIBs vector, if non-empty. Note that each MIB in the summary can have
444 // multiple of these as we trim the contexts when possible during matching.
445 // For hinted size reporting we, however, want the original pre-trimmed full
446 // stack context id for better correlation with the profile.
447 std::vector<std::vector<ContextTotalSize>> ContextSizeInfos;
448
449 AllocInfo(std::vector<MIBInfo> MIBs) : MIBs(std::move(MIBs)) {
450 Versions.push_back(0);
451 }
454};
455
457 bool First = true;
458 OS << "Versions: ";
459 for (auto V : AE.Versions) {
460 if (!First)
461 OS << ", ";
462 First = false;
463 OS << (unsigned)V;
464 }
465 OS << " MIB:\n";
466 for (auto &M : AE.MIBs) {
467 OS << "\t\t" << M << "\n";
468 }
469 if (!AE.ContextSizeInfos.empty()) {
470 OS << "\tContextSizeInfo per MIB:\n";
471 for (auto Infos : AE.ContextSizeInfos) {
472 OS << "\t\t";
473 bool FirstInfo = true;
474 for (auto [FullStackId, TotalSize] : Infos) {
475 if (!FirstInfo)
476 OS << ", ";
477 FirstInfo = false;
478 OS << "{ " << FullStackId << ", " << TotalSize << " }";
479 }
480 OS << "\n";
481 }
482 }
483 return OS;
484}
485
486/// Function and variable summary information to aid decisions and
487/// implementation of importing.
489public:
490 /// Sububclass discriminator (for dyn_cast<> et al.)
492
493 enum ImportKind : unsigned {
494 // The global value definition corresponding to the summary should be
495 // imported from source module
497
498 // When its definition doesn't exist in the destination module and not
499 // imported (e.g., function is too large to be inlined), the global value
500 // declaration corresponding to the summary should be imported, or the
501 // attributes from summary should be annotated on the function declaration.
503 };
504
505 /// Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
506 struct GVFlags {
507 /// The linkage type of the associated global value.
508 ///
509 /// One use is to flag values that have local linkage types and need to
510 /// have module identifier appended before placing into the combined
511 /// index, to disambiguate from other values with the same name.
512 /// In the future this will be used to update and optimize linkage
513 /// types based on global summary-based analysis.
514 unsigned Linkage : 4;
515
516 /// Indicates the visibility.
517 unsigned Visibility : 2;
518
519 /// Indicate if the global value cannot be imported (e.g. it cannot
520 /// be renamed or references something that can't be renamed).
522
523 /// In per-module summary, indicate that the global value must be considered
524 /// a live root for index-based liveness analysis. Used for special LLVM
525 /// values such as llvm.global_ctors that the linker does not know about.
526 ///
527 /// In combined summary, indicate that the global value is live.
528 unsigned Live : 1;
529
530 /// Indicates that the linker resolved the symbol to a definition from
531 /// within the same linkage unit.
532 unsigned DSOLocal : 1;
533
534 /// In the per-module summary, indicates that the global value is
535 /// linkonce_odr and global unnamed addr (so eligible for auto-hiding
536 /// via hidden visibility). In the combined summary, indicates that the
537 /// prevailing linkonce_odr copy can be auto-hidden via hidden visibility
538 /// when it is upgraded to weak_odr in the backend. This is legal when
539 /// all copies are eligible for auto-hiding (i.e. all copies were
540 /// linkonce_odr global unnamed addr. If any copy is not (e.g. it was
541 /// originally weak_odr, we cannot auto-hide the prevailing copy as it
542 /// means the symbol was externally visible.
543 unsigned CanAutoHide : 1;
544
545 /// This field is written by the ThinLTO indexing step to postlink combined
546 /// summary. The value is interpreted as 'ImportKind' enum defined above.
547 unsigned ImportType : 1;
548
549 /// Convenience Constructors
558 };
559
560private:
561 /// Kind of summary for use in dyn_cast<> et al.
562 SummaryKind Kind;
563
564 GVFlags Flags;
565
566 /// This is the hash of the name of the symbol in the original file. It is
567 /// identical to the GUID for global symbols, but differs for local since the
568 /// GUID includes the module level id in the hash.
569 GlobalValue::GUID OriginalName = 0;
570
571 /// Path of module IR containing value's definition, used to locate
572 /// module during importing.
573 ///
574 /// This is only used during parsing of the combined index, or when
575 /// parsing the per-module index for creation of the combined summary index,
576 /// not during writing of the per-module index which doesn't contain a
577 /// module path string table.
578 StringRef ModulePath;
579
580 /// List of values referenced by this global value's definition
581 /// (either by the initializer of a global variable, or referenced
582 /// from within a function). This does not include functions called, which
583 /// are listed in the derived FunctionSummary object.
584 /// We use SmallVector<ValueInfo, 0> instead of std::vector<ValueInfo> for its
585 /// smaller memory footprint.
586 SmallVector<ValueInfo, 0> RefEdgeList;
587
588protected:
591 : Kind(K), Flags(Flags), RefEdgeList(std::move(Refs)) {
592 assert((K != AliasKind || Refs.empty()) &&
593 "Expect no references for AliasSummary");
594 }
595
596public:
597 virtual ~GlobalValueSummary() = default;
598
599 /// Returns the hash of the original name, it is identical to the GUID for
600 /// externally visible symbols, but not for local ones.
601 GlobalValue::GUID getOriginalName() const { return OriginalName; }
602
603 /// Initialize the original name hash in this summary.
604 void setOriginalName(GlobalValue::GUID Name) { OriginalName = Name; }
605
606 /// Which kind of summary subclass this is.
607 SummaryKind getSummaryKind() const { return Kind; }
608
609 /// Set the path to the module containing this function, for use in
610 /// the combined index.
611 void setModulePath(StringRef ModPath) { ModulePath = ModPath; }
612
613 /// Get the path to the module containing this function.
614 StringRef modulePath() const { return ModulePath; }
615
616 /// Get the flags for this GlobalValue (see \p struct GVFlags).
617 GVFlags flags() const { return Flags; }
618
619 /// Return linkage type recorded for this global value.
621 return static_cast<GlobalValue::LinkageTypes>(Flags.Linkage);
622 }
623
624 /// Sets the linkage to the value determined by global summary-based
625 /// optimization. Will be applied in the ThinLTO backends.
627 Flags.Linkage = Linkage;
628 }
629
630 /// Return true if this global value can't be imported.
631 bool notEligibleToImport() const { return Flags.NotEligibleToImport; }
632
633 bool isLive() const { return Flags.Live; }
634
635 void setLive(bool Live) { Flags.Live = Live; }
636
637 void setDSOLocal(bool Local) { Flags.DSOLocal = Local; }
638
639 bool isDSOLocal() const { return Flags.DSOLocal; }
640
641 void setCanAutoHide(bool CanAutoHide) { Flags.CanAutoHide = CanAutoHide; }
642
643 bool canAutoHide() const { return Flags.CanAutoHide; }
644
645 bool shouldImportAsDecl() const {
646 return Flags.ImportType == GlobalValueSummary::ImportKind::Declaration;
647 }
648
649 void setImportKind(ImportKind IK) { Flags.ImportType = IK; }
650
652 return static_cast<ImportKind>(Flags.ImportType);
653 }
654
656 return (GlobalValue::VisibilityTypes)Flags.Visibility;
657 }
659 Flags.Visibility = (unsigned)Vis;
660 }
661
662 /// Flag that this global value cannot be imported.
663 void setNotEligibleToImport() { Flags.NotEligibleToImport = true; }
664
665 /// Return the list of values referenced by this global value definition.
666 ArrayRef<ValueInfo> refs() const { return RefEdgeList; }
667
668 /// If this is an alias summary, returns the summary of the aliased object (a
669 /// global variable or function), otherwise returns itself.
671 const GlobalValueSummary *getBaseObject() const;
672
673 friend class ModuleSummaryIndex;
674};
675
677 : U(HaveGVs), HasLocal(false) {}
678
680 std::unique_ptr<GlobalValueSummary> Summary) {
681 if (GlobalValue::isLocalLinkage(Summary->linkage()))
682 HasLocal = true;
683 return SummaryList.push_back(std::move(Summary));
684}
685
687 assert(HasLocal ==
688 llvm::any_of(SummaryList,
689 [](const std::unique_ptr<GlobalValueSummary> &Summary) {
690 return GlobalValue::isLocalLinkage(Summary->linkage());
691 }));
692}
693
694/// Alias summary information.
696 ValueInfo AliaseeValueInfo;
697
698 /// This is the Aliasee in the same module as alias (could get from VI, trades
699 /// memory for time). Note that this pointer may be null (and the value info
700 /// empty) when we have a distributed index where the alias is being imported
701 /// (as a copy of the aliasee), but the aliasee is not.
702 GlobalValueSummary *AliaseeSummary = nullptr;
703
704public:
707
708 /// Check if this is an alias summary.
709 static bool classof(const GlobalValueSummary *GVS) {
710 return GVS->getSummaryKind() == AliasKind;
711 }
712
713 void setAliasee(ValueInfo &AliaseeVI, GlobalValueSummary *Aliasee) {
714 AliaseeValueInfo = AliaseeVI;
715 AliaseeSummary = Aliasee;
716 }
717
718 bool hasAliasee() const {
719 assert(!!AliaseeSummary == (AliaseeValueInfo &&
720 !AliaseeValueInfo.getSummaryList().empty()) &&
721 "Expect to have both aliasee summary and summary list or neither");
722 return !!AliaseeSummary;
723 }
724
726 assert(AliaseeSummary && "Unexpected missing aliasee summary");
727 return *AliaseeSummary;
728 }
729
731 return const_cast<GlobalValueSummary &>(
732 static_cast<const AliasSummary *>(this)->getAliasee());
733 }
735 assert(AliaseeValueInfo && "Unexpected missing aliasee");
736 return AliaseeValueInfo;
737 }
739 assert(AliaseeValueInfo && "Unexpected missing aliasee");
740 return AliaseeValueInfo.getGUID();
741 }
742};
743
745 if (auto *AS = dyn_cast<AliasSummary>(this))
746 return &AS->getAliasee();
747 return this;
748}
749
751 if (auto *AS = dyn_cast<AliasSummary>(this))
752 return &AS->getAliasee();
753 return this;
754}
755
756/// Function summary information to aid decisions and implementation of
757/// importing.
759public:
760 /// <CalleeValueInfo, CalleeInfo> call edge pair.
761 using EdgeTy = std::pair<ValueInfo, CalleeInfo>;
762
763 /// Types for -force-summary-edges-cold debugging option.
769
770 /// An "identifier" for a virtual function. This contains the type identifier
771 /// represented as a GUID and the offset from the address point to the virtual
772 /// function pointer, where "address point" is as defined in the Itanium ABI:
773 /// https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vtable-general
778
779 /// A specification for a virtual function call with all constant integer
780 /// arguments. This is used to perform virtual constant propagation on the
781 /// summary.
782 struct ConstVCall {
784 std::vector<uint64_t> Args;
785 };
786
787 /// All type identifier related information. Because these fields are
788 /// relatively uncommon we only allocate space for them if necessary.
789 struct TypeIdInfo {
790 /// List of type identifiers used by this function in llvm.type.test
791 /// intrinsics referenced by something other than an llvm.assume intrinsic,
792 /// represented as GUIDs.
793 std::vector<GlobalValue::GUID> TypeTests;
794
795 /// List of virtual calls made by this function using (respectively)
796 /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics that do
797 /// not have all constant integer arguments.
799
800 /// List of virtual calls made by this function using (respectively)
801 /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics with
802 /// all constant integer arguments.
803 std::vector<ConstVCall> TypeTestAssumeConstVCalls,
805 };
806
807 /// Flags specific to function summaries.
808 struct FFlags {
809 // Function attribute flags. Used to track if a function accesses memory,
810 // recurses or aliases.
811 unsigned ReadNone : 1;
812 unsigned ReadOnly : 1;
813 unsigned NoRecurse : 1;
814 unsigned ReturnDoesNotAlias : 1;
815
816 // Indicate if the global value cannot be inlined.
817 unsigned NoInline : 1;
818 // Indicate if function should be always inlined.
819 unsigned AlwaysInline : 1;
820 // Indicate if function never raises an exception. Can be modified during
821 // thinlink function attribute propagation
822 unsigned NoUnwind : 1;
823 // Indicate if function contains instructions that mayThrow
824 unsigned MayThrow : 1;
825
826 // If there are calls to unknown targets (e.g. indirect)
827 unsigned HasUnknownCall : 1;
828
829 // Indicate if a function must be an unreachable function.
830 //
831 // This bit is sufficient but not necessary;
832 // if this bit is on, the function must be regarded as unreachable;
833 // if this bit is off, the function might be reachable or unreachable.
834 unsigned MustBeUnreachable : 1;
835
837 this->ReadNone &= RHS.ReadNone;
838 this->ReadOnly &= RHS.ReadOnly;
839 this->NoRecurse &= RHS.NoRecurse;
840 this->ReturnDoesNotAlias &= RHS.ReturnDoesNotAlias;
841 this->NoInline &= RHS.NoInline;
842 this->AlwaysInline &= RHS.AlwaysInline;
843 this->NoUnwind &= RHS.NoUnwind;
844 this->MayThrow &= RHS.MayThrow;
845 this->HasUnknownCall &= RHS.HasUnknownCall;
846 this->MustBeUnreachable &= RHS.MustBeUnreachable;
847 return *this;
848 }
849
850 bool anyFlagSet() {
851 return this->ReadNone | this->ReadOnly | this->NoRecurse |
852 this->ReturnDoesNotAlias | this->NoInline | this->AlwaysInline |
853 this->NoUnwind | this->MayThrow | this->HasUnknownCall |
854 this->MustBeUnreachable;
855 }
856
857 operator std::string() {
858 std::string Output;
859 raw_string_ostream OS(Output);
860 OS << "funcFlags: (";
861 OS << "readNone: " << this->ReadNone;
862 OS << ", readOnly: " << this->ReadOnly;
863 OS << ", noRecurse: " << this->NoRecurse;
864 OS << ", returnDoesNotAlias: " << this->ReturnDoesNotAlias;
865 OS << ", noInline: " << this->NoInline;
866 OS << ", alwaysInline: " << this->AlwaysInline;
867 OS << ", noUnwind: " << this->NoUnwind;
868 OS << ", mayThrow: " << this->MayThrow;
869 OS << ", hasUnknownCall: " << this->HasUnknownCall;
870 OS << ", mustBeUnreachable: " << this->MustBeUnreachable;
871 OS << ")";
872 return Output;
873 }
874 };
875
876 /// Describes the uses of a parameter by the function.
877 struct ParamAccess {
878 static constexpr uint32_t RangeWidth = 64;
879
880 /// Describes the use of a value in a call instruction, specifying the
881 /// call's target, the value's parameter number, and the possible range of
882 /// offsets from the beginning of the value that are passed.
892
894 /// The range contains byte offsets from the parameter pointer which
895 /// accessed by the function. In the per-module summary, it only includes
896 /// accesses made by the function instructions. In the combined summary, it
897 /// also includes accesses by nested function calls.
898 ConstantRange Use{/*BitWidth=*/RangeWidth, /*isFullSet=*/true};
899 /// In the per-module summary, it summarizes the byte offset applied to each
900 /// pointer parameter before passing to each corresponding callee.
901 /// In the combined summary, it's empty and information is propagated by
902 /// inter-procedural analysis and applied to the Use field.
903 std::vector<Call> Calls;
904
905 ParamAccess() = default;
908 };
909
910 /// Create an empty FunctionSummary (with specified call edges).
911 /// Used to represent external nodes and the dummy root node.
912 static FunctionSummary
914 return FunctionSummary(
918 /*NotEligibleToImport=*/true, /*Live=*/true, /*IsLocal=*/false,
919 /*CanAutoHide=*/false, GlobalValueSummary::ImportKind::Definition),
921 std::move(Edges), std::vector<GlobalValue::GUID>(),
922 std::vector<FunctionSummary::VFuncId>(),
923 std::vector<FunctionSummary::VFuncId>(),
924 std::vector<FunctionSummary::ConstVCall>(),
925 std::vector<FunctionSummary::ConstVCall>(),
926 std::vector<FunctionSummary::ParamAccess>(),
927 std::vector<CallsiteInfo>(), std::vector<AllocInfo>());
928 }
929
930 /// A dummy node to reference external functions that aren't in the index
932
933private:
934 /// Number of instructions (ignoring debug instructions, e.g.) computed
935 /// during the initial compile step when the summary index is first built.
936 unsigned InstCount;
937
938 /// Function summary specific flags.
939 FFlags FunFlags;
940
941 /// List of <CalleeValueInfo, CalleeInfo> call edge pairs from this function.
942 /// We use SmallVector<ValueInfo, 0> instead of std::vector<ValueInfo> for its
943 /// smaller memory footprint.
944 SmallVector<EdgeTy, 0> CallGraphEdgeList;
945
946 std::unique_ptr<TypeIdInfo> TIdInfo;
947
948 /// Uses for every parameter to this function.
949 using ParamAccessesTy = std::vector<ParamAccess>;
950 std::unique_ptr<ParamAccessesTy> ParamAccesses;
951
952 /// Optional list of memprof callsite metadata summaries. The correspondence
953 /// between the callsite summary and the callsites in the function is implied
954 /// by the order in the vector (and can be validated by comparing the stack
955 /// ids in the CallsiteInfo to those in the instruction callsite metadata).
956 /// As a memory savings optimization, we only create these for the prevailing
957 /// copy of a symbol when creating the combined index during LTO.
958 using CallsitesTy = std::vector<CallsiteInfo>;
959 std::unique_ptr<CallsitesTy> Callsites;
960
961 /// Optional list of allocation memprof metadata summaries. The correspondence
962 /// between the alloc memprof summary and the allocation callsites in the
963 /// function is implied by the order in the vector (and can be validated by
964 /// comparing the stack ids in the AllocInfo to those in the instruction
965 /// memprof metadata).
966 /// As a memory savings optimization, we only create these for the prevailing
967 /// copy of a symbol when creating the combined index during LTO.
968 using AllocsTy = std::vector<AllocInfo>;
969 std::unique_ptr<AllocsTy> Allocs;
970
971public:
972 FunctionSummary(GVFlags Flags, unsigned NumInsts, FFlags FunFlags,
974 SmallVectorImpl<EdgeTy> &&CGEdges,
975 std::vector<GlobalValue::GUID> TypeTests,
976 std::vector<VFuncId> TypeTestAssumeVCalls,
977 std::vector<VFuncId> TypeCheckedLoadVCalls,
978 std::vector<ConstVCall> TypeTestAssumeConstVCalls,
979 std::vector<ConstVCall> TypeCheckedLoadConstVCalls,
980 std::vector<ParamAccess> Params, CallsitesTy CallsiteList,
981 AllocsTy AllocList)
982 : GlobalValueSummary(FunctionKind, Flags, std::move(Refs)),
983 InstCount(NumInsts), FunFlags(FunFlags),
984 CallGraphEdgeList(std::move(CGEdges)) {
985 if (!TypeTests.empty() || !TypeTestAssumeVCalls.empty() ||
986 !TypeCheckedLoadVCalls.empty() || !TypeTestAssumeConstVCalls.empty() ||
987 !TypeCheckedLoadConstVCalls.empty())
988 TIdInfo = std::make_unique<TypeIdInfo>(
989 TypeIdInfo{std::move(TypeTests), std::move(TypeTestAssumeVCalls),
990 std::move(TypeCheckedLoadVCalls),
991 std::move(TypeTestAssumeConstVCalls),
992 std::move(TypeCheckedLoadConstVCalls)});
993 if (!Params.empty())
994 ParamAccesses = std::make_unique<ParamAccessesTy>(std::move(Params));
995 if (!CallsiteList.empty())
996 Callsites = std::make_unique<CallsitesTy>(std::move(CallsiteList));
997 if (!AllocList.empty())
998 Allocs = std::make_unique<AllocsTy>(std::move(AllocList));
999 }
1000 // Gets the number of readonly and writeonly refs in RefEdgeList
1001 LLVM_ABI std::pair<unsigned, unsigned> specialRefCounts() const;
1002
1003 /// Check if this is a function summary.
1004 static bool classof(const GlobalValueSummary *GVS) {
1005 return GVS->getSummaryKind() == FunctionKind;
1006 }
1007
1008 /// Get function summary flags.
1009 FFlags fflags() const { return FunFlags; }
1010
1011 void setNoRecurse() { FunFlags.NoRecurse = true; }
1012
1013 void setNoUnwind() { FunFlags.NoUnwind = true; }
1014
1015 /// Get the instruction count recorded for this function.
1016 unsigned instCount() const { return InstCount; }
1017
1018 /// Return the list of <CalleeValueInfo, CalleeInfo> pairs.
1019 ArrayRef<EdgeTy> calls() const { return CallGraphEdgeList; }
1020
1021 SmallVector<EdgeTy, 0> &mutableCalls() { return CallGraphEdgeList; }
1022
1023 void addCall(EdgeTy E) { CallGraphEdgeList.push_back(E); }
1024
1025 /// Returns the list of type identifiers used by this function in
1026 /// llvm.type.test intrinsics other than by an llvm.assume intrinsic,
1027 /// represented as GUIDs.
1029 if (TIdInfo)
1030 return TIdInfo->TypeTests;
1031 return {};
1032 }
1033
1034 /// Returns the list of virtual calls made by this function using
1035 /// llvm.assume(llvm.type.test) intrinsics that do not have all constant
1036 /// integer arguments.
1038 if (TIdInfo)
1039 return TIdInfo->TypeTestAssumeVCalls;
1040 return {};
1041 }
1042
1043 /// Returns the list of virtual calls made by this function using
1044 /// llvm.type.checked.load intrinsics that do not have all constant integer
1045 /// arguments.
1047 if (TIdInfo)
1048 return TIdInfo->TypeCheckedLoadVCalls;
1049 return {};
1050 }
1051
1052 /// Returns the list of virtual calls made by this function using
1053 /// llvm.assume(llvm.type.test) intrinsics with all constant integer
1054 /// arguments.
1056 if (TIdInfo)
1057 return TIdInfo->TypeTestAssumeConstVCalls;
1058 return {};
1059 }
1060
1061 /// Returns the list of virtual calls made by this function using
1062 /// llvm.type.checked.load intrinsics with all constant integer arguments.
1064 if (TIdInfo)
1065 return TIdInfo->TypeCheckedLoadConstVCalls;
1066 return {};
1067 }
1068
1069 /// Returns the list of known uses of pointer parameters.
1071 if (ParamAccesses)
1072 return *ParamAccesses;
1073 return {};
1074 }
1075
1076 /// Sets the list of known uses of pointer parameters.
1077 void setParamAccesses(std::vector<ParamAccess> NewParams) {
1078 if (NewParams.empty())
1079 ParamAccesses.reset();
1080 else if (ParamAccesses)
1081 *ParamAccesses = std::move(NewParams);
1082 else
1083 ParamAccesses = std::make_unique<ParamAccessesTy>(std::move(NewParams));
1084 }
1085
1086 /// Add a type test to the summary. This is used by WholeProgramDevirt if we
1087 /// were unable to devirtualize a checked call.
1089 if (!TIdInfo)
1090 TIdInfo = std::make_unique<TypeIdInfo>();
1091 TIdInfo->TypeTests.push_back(Guid);
1092 }
1093
1094 const TypeIdInfo *getTypeIdInfo() const { return TIdInfo.get(); };
1095
1097 if (Callsites)
1098 return *Callsites;
1099 return {};
1100 }
1101
1102 CallsitesTy &mutableCallsites() {
1103 assert(Callsites);
1104 return *Callsites;
1105 }
1106
1107 void addCallsite(CallsiteInfo &Callsite) {
1108 if (!Callsites)
1109 Callsites = std::make_unique<CallsitesTy>();
1110 Callsites->push_back(Callsite);
1111 }
1112
1114 if (Allocs)
1115 return *Allocs;
1116 return {};
1117 }
1118
1119 AllocsTy &mutableAllocs() {
1120 assert(Allocs);
1121 return *Allocs;
1122 }
1123
1124 friend struct GraphTraits<ValueInfo>;
1125};
1126
1127template <> struct DenseMapInfo<FunctionSummary::VFuncId> {
1128 static FunctionSummary::VFuncId getEmptyKey() { return {0, uint64_t(-1)}; }
1129
1131 return {0, uint64_t(-2)};
1132 }
1133
1135 return L.GUID == R.GUID && L.Offset == R.Offset;
1136 }
1137
1138 static unsigned getHashValue(FunctionSummary::VFuncId I) { return I.GUID; }
1139};
1140
1141template <> struct DenseMapInfo<FunctionSummary::ConstVCall> {
1143 return {{0, uint64_t(-1)}, {}};
1144 }
1145
1147 return {{0, uint64_t(-2)}, {}};
1148 }
1149
1152 return DenseMapInfo<FunctionSummary::VFuncId>::isEqual(L.VFunc, R.VFunc) &&
1153 L.Args == R.Args;
1154 }
1155
1157 return I.VFunc.GUID;
1158 }
1159};
1160
1161/// The ValueInfo and offset for a function within a vtable definition
1162/// initializer array.
1170/// List of functions referenced by a particular vtable definition.
1171using VTableFuncList = std::vector<VirtFuncOffset>;
1172
1173/// Global variable summary information to aid decisions and
1174/// implementation of importing.
1175///
1176/// Global variable summary has two extra flag, telling if it is
1177/// readonly or writeonly. Both readonly and writeonly variables
1178/// can be optimized in the backed: readonly variables can be
1179/// const-folded, while writeonly vars can be completely eliminated
1180/// together with corresponding stores. We let both things happen
1181/// by means of internalizing such variables after ThinLTO import.
1183private:
1184 /// For vtable definitions this holds the list of functions and
1185 /// their corresponding offsets within the initializer array.
1186 std::unique_ptr<VTableFuncList> VTableFuncs;
1187
1188public:
1189 struct GVarFlags {
1190 GVarFlags(bool ReadOnly, bool WriteOnly, bool Constant,
1192 : MaybeReadOnly(ReadOnly), MaybeWriteOnly(WriteOnly),
1194
1195 // If true indicates that this global variable might be accessed
1196 // purely by non-volatile load instructions. This in turn means
1197 // it can be internalized in source and destination modules during
1198 // thin LTO import because it neither modified nor its address
1199 // is taken.
1200 unsigned MaybeReadOnly : 1;
1201 // If true indicates that variable is possibly only written to, so
1202 // its value isn't loaded and its address isn't taken anywhere.
1203 // False, when 'Constant' attribute is set.
1204 unsigned MaybeWriteOnly : 1;
1205 // Indicates that value is a compile-time constant. Global variable
1206 // can be 'Constant' while not being 'ReadOnly' on several occasions:
1207 // - it is volatile, (e.g mapped device address)
1208 // - its address is taken, meaning that unlike 'ReadOnly' vars we can't
1209 // internalize it.
1210 // Constant variables are always imported thus giving compiler an
1211 // opportunity to make some extra optimizations. Readonly constants
1212 // are also internalized.
1213 unsigned Constant : 1;
1214 // Set from metadata on vtable definitions during the module summary
1215 // analysis.
1216 unsigned VCallVisibility : 2;
1218
1223
1224 /// Check if this is a global variable summary.
1225 static bool classof(const GlobalValueSummary *GVS) {
1226 return GVS->getSummaryKind() == GlobalVarKind;
1227 }
1228
1229 GVarFlags varflags() const { return VarFlags; }
1230 void setReadOnly(bool RO) { VarFlags.MaybeReadOnly = RO; }
1231 void setWriteOnly(bool WO) { VarFlags.MaybeWriteOnly = WO; }
1232 bool maybeReadOnly() const { return VarFlags.MaybeReadOnly; }
1233 bool maybeWriteOnly() const { return VarFlags.MaybeWriteOnly; }
1234 bool isConstant() const { return VarFlags.Constant; }
1236 VarFlags.VCallVisibility = Vis;
1237 }
1241
1243 assert(!VTableFuncs);
1244 VTableFuncs = std::make_unique<VTableFuncList>(std::move(Funcs));
1245 }
1246
1248 if (VTableFuncs)
1249 return *VTableFuncs;
1250 return {};
1251 }
1252};
1253
1255 /// Specifies which kind of type check we should emit for this byte array.
1256 /// See http://clang.llvm.org/docs/ControlFlowIntegrityDesign.html for full
1257 /// details on each kind of check; the enumerators are described with
1258 /// reference to that document.
1259 enum Kind {
1260 Unsat, ///< Unsatisfiable type (i.e. no global has this type metadata)
1261 ByteArray, ///< Test a byte array (first example)
1262 Inline, ///< Inlined bit vector ("Short Inline Bit Vectors")
1263 Single, ///< Single element (last example in "Short Inline Bit Vectors")
1264 AllOnes, ///< All-ones bit vector ("Eliminating Bit Vector Checks for
1265 /// All-Ones Bit Vectors")
1266 Unknown, ///< Unknown (analysis not performed, don't lower)
1268
1269 /// Range of size-1 expressed as a bit width. For example, if the size is in
1270 /// range [1,256], this number will be 8. This helps generate the most compact
1271 /// instruction sequences.
1272 unsigned SizeM1BitWidth = 0;
1273
1274 // The following fields are only used if the target does not support the use
1275 // of absolute symbols to store constants. Their meanings are the same as the
1276 // corresponding fields in LowerTypeTestsModule::TypeIdLowering in
1277 // LowerTypeTests.cpp.
1278
1283};
1284
1286 enum Kind {
1287 Indir, ///< Just do a regular virtual call
1288 SingleImpl, ///< Single implementation devirtualization
1289 BranchFunnel, ///< When retpoline mitigation is enabled, use a branch funnel
1290 ///< that is defined in the merged module. Otherwise same as
1291 ///< Indir.
1293
1294 std::string SingleImplName;
1295
1296 struct ByArg {
1297 enum Kind {
1298 Indir, ///< Just do a regular virtual call
1299 UniformRetVal, ///< Uniform return value optimization
1300 UniqueRetVal, ///< Unique return value optimization
1301 VirtualConstProp, ///< Virtual constant propagation
1303
1304 /// Additional information for the resolution:
1305 /// - UniformRetVal: the uniform return value.
1306 /// - UniqueRetVal: the return value associated with the unique vtable (0 or
1307 /// 1).
1309
1310 // The following fields are only used if the target does not support the use
1311 // of absolute symbols to store constants.
1312
1315 };
1316
1317 /// Resolutions for calls with all constant integer arguments (excluding the
1318 /// first argument, "this"), where the key is the argument vector.
1319 std::map<std::vector<uint64_t>, ByArg> ResByArg;
1320};
1321
1324
1325 /// Mapping from byte offset to whole-program devirt resolution for that
1326 /// (typeid, byte offset) pair.
1327 std::map<uint64_t, WholeProgramDevirtResolution> WPDRes;
1328};
1329
1332 using IndexIterator =
1334 std::set<std::string, std::less<>>>::const_iterator;
1335 using NestedIterator = std::set<std::string, std::less<>>::const_iterator;
1336
1337public:
1338 // Iterates keys of the DenseMap.
1339 class GUIDIterator : public iterator_adaptor_base<GUIDIterator, IndexIterator,
1340 std::forward_iterator_tag,
1341 GlobalValue::GUID> {
1343
1344 public:
1345 GUIDIterator() = default;
1346 explicit GUIDIterator(IndexIterator I) : base(I) {}
1347
1348 GlobalValue::GUID operator*() const { return this->wrapped()->first; }
1349 };
1350
1351 CfiFunctionIndex() = default;
1352 template <typename It> CfiFunctionIndex(It B, It E) {
1353 for (; B != E; ++B)
1354 emplace(*B);
1355 }
1356
1357 std::vector<StringRef> symbols() const {
1358 std::vector<StringRef> Symbols;
1359 for (auto &[GUID, Syms] : Index) {
1360 (void)GUID;
1361 llvm::append_range(Symbols, Syms);
1362 }
1363 return Symbols;
1364 }
1365
1366 GUIDIterator guid_begin() const { return GUIDIterator(Index.begin()); }
1367 GUIDIterator guid_end() const { return GUIDIterator(Index.end()); }
1371
1373 auto I = Index.find(GUID);
1374 if (I == Index.end())
1375 return make_range(NestedIterator{}, NestedIterator{});
1376 return make_range(I->second.begin(), I->second.end());
1377 }
1378
1379 template <typename... Args> void emplace(Args &&...A) {
1380 StringRef S(std::forward<Args>(A)...);
1383 Index[GUID].emplace(S);
1384 }
1385
1386 size_t count(StringRef S) const {
1389 auto I = Index.find(GUID);
1390 if (I == Index.end())
1391 return 0;
1392 return I->second.count(S);
1393 }
1394
1395 bool empty() const { return Index.empty(); }
1396};
1397
1398/// 160 bits SHA1
1399using ModuleHash = std::array<uint32_t, 5>;
1400
1401/// Type used for iterating through the global value summary map.
1402using const_gvsummary_iterator = GlobalValueSummaryMapTy::const_iterator;
1403using gvsummary_iterator = GlobalValueSummaryMapTy::iterator;
1404
1405/// String table to hold/own module path strings, as well as a hash
1406/// of the module. The StringMap makes a copy of and owns inserted strings.
1408
1409/// Map of global value GUID to its summary, used to identify values defined in
1410/// a particular module, and provide efficient access to their summary.
1412
1413/// Map of a module name to the GUIDs and summaries we will import from that
1414/// module.
1416 std::map<std::string, GVSummaryMapTy, std::less<>>;
1417
1418/// A set of global value summary pointers.
1419using GVSummaryPtrSet = std::unordered_set<GlobalValueSummary *>;
1420
1421/// Map of a type GUID to type id string and summary (multimap used
1422/// in case of GUID conflicts).
1424 std::multimap<GlobalValue::GUID, std::pair<StringRef, TypeIdSummary>>;
1425
1426/// The following data structures summarize type metadata information.
1427/// For type metadata overview see https://llvm.org/docs/TypeMetadata.html.
1428/// Each type metadata includes both the type identifier and the offset of
1429/// the address point of the type (the address held by objects of that type
1430/// which may not be the beginning of the virtual table). Vtable definitions
1431/// are decorated with type metadata for the types they are compatible with.
1432///
1433/// Holds information about vtable definitions decorated with type metadata:
1434/// the vtable definition value and its address point offset in a type
1435/// identifier metadata it is decorated (compatible) with.
1443/// List of vtable definitions decorated by a particular type identifier,
1444/// and their corresponding offsets in that type identifier's metadata.
1445/// Note that each type identifier may be compatible with multiple vtables, due
1446/// to inheritance, which is why this is a vector.
1447using TypeIdCompatibleVtableInfo = std::vector<TypeIdOffsetVtableInfo>;
1448
1449/// Class to hold module path string table and global value map,
1450/// and encapsulate methods for operating on them.
1452private:
1453 /// Map from value name to list of summary instances for values of that
1454 /// name (may be duplicates in the COMDAT case, e.g.).
1455 GlobalValueSummaryMapTy GlobalValueMap;
1456
1457 /// Holds strings for combined index, mapping to the corresponding module ID.
1458 ModulePathStringTableTy ModulePathStringTable;
1459
1460 BumpPtrAllocator TypeIdSaverAlloc;
1461 UniqueStringSaver TypeIdSaver;
1462
1463 /// Mapping from type identifier GUIDs to type identifier and its summary
1464 /// information. Produced by thin link.
1465 TypeIdSummaryMapTy TypeIdMap;
1466
1467 /// Mapping from type identifier to information about vtables decorated
1468 /// with that type identifier's metadata. Produced by per module summary
1469 /// analysis and consumed by thin link. For more information, see description
1470 /// above where TypeIdCompatibleVtableInfo is defined.
1471 std::map<StringRef, TypeIdCompatibleVtableInfo, std::less<>>
1472 TypeIdCompatibleVtableMap;
1473
1474 /// Mapping from original ID to GUID. If original ID can map to multiple
1475 /// GUIDs, it will be mapped to 0.
1477
1478 /// Indicates that summary-based GlobalValue GC has run, and values with
1479 /// GVFlags::Live==false are really dead. Otherwise, all values must be
1480 /// considered live.
1481 bool WithGlobalValueDeadStripping = false;
1482
1483 /// Indicates that summary-based attribute propagation has run and
1484 /// GVarFlags::MaybeReadonly / GVarFlags::MaybeWriteonly are really
1485 /// read/write only.
1486 bool WithAttributePropagation = false;
1487
1488 /// Indicates that summary-based DSOLocal propagation has run and the flag in
1489 /// every summary of a GV is synchronized.
1490 bool WithDSOLocalPropagation = false;
1491
1492 /// Indicates that summary-based internalization and promotion has run.
1493 bool WithInternalizeAndPromote = false;
1494
1495 /// Indicates that we have whole program visibility.
1496 bool WithWholeProgramVisibility = false;
1497
1498 /// Indicates that summary-based synthetic entry count propagation has run
1499 bool HasSyntheticEntryCounts = false;
1500
1501 /// Indicates that we linked with allocator supporting hot/cold new operators.
1502 bool WithSupportsHotColdNew = false;
1503
1504 /// Indicates that distributed backend should skip compilation of the
1505 /// module. Flag is suppose to be set by distributed ThinLTO indexing
1506 /// when it detected that the module is not needed during the final
1507 /// linking. As result distributed backend should just output a minimal
1508 /// valid object file.
1509 bool SkipModuleByDistributedBackend = false;
1510
1511 /// If true then we're performing analysis of IR module, or parsing along with
1512 /// the IR from assembly. The value of 'false' means we're reading summary
1513 /// from BC or YAML source. Affects the type of value stored in NameOrGV
1514 /// union.
1515 bool HaveGVs;
1516
1517 // True if the index was created for a module compiled with -fsplit-lto-unit.
1518 bool EnableSplitLTOUnit;
1519
1520 // True if the index was created for a module compiled with -funified-lto
1521 bool UnifiedLTO;
1522
1523 // True if some of the modules were compiled with -fsplit-lto-unit and
1524 // some were not. Set when the combined index is created during the thin link.
1525 bool PartiallySplitLTOUnits = false;
1526
1527 /// True if some of the FunctionSummary contains a ParamAccess.
1528 bool HasParamAccess = false;
1529
1530 CfiFunctionIndex CfiFunctionDefs;
1531 CfiFunctionIndex CfiFunctionDecls;
1532
1533 // Used in cases where we want to record the name of a global, but
1534 // don't have the string owned elsewhere (e.g. the Strtab on a module).
1535 BumpPtrAllocator Alloc;
1536 StringSaver Saver;
1537
1538 // The total number of basic blocks in the module in the per-module summary or
1539 // the total number of basic blocks in the LTO unit in the combined index.
1540 // FIXME: Putting this in the distributed ThinLTO index files breaks LTO
1541 // backend caching on any BB change to any linked file. It is currently not
1542 // used except in the case of a SamplePGO partial profile, and should be
1543 // reevaluated/redesigned to allow more effective incremental builds in that
1544 // case.
1545 uint64_t BlockCount = 0;
1546
1547 // List of unique stack ids (hashes). We use a 4B index of the id in the
1548 // stack id lists on the alloc and callsite summaries for memory savings,
1549 // since the number of unique ids is in practice much smaller than the
1550 // number of stack id references in the summaries.
1551 std::vector<uint64_t> StackIds;
1552
1553 // Temporary map while building StackIds list. Clear when index is completely
1554 // built via releaseTemporaryMemory.
1555 DenseMap<uint64_t, unsigned> StackIdToIndex;
1556
1557 // YAML I/O support.
1559
1560 GlobalValueSummaryMapTy::value_type *
1561 getOrInsertValuePtr(GlobalValue::GUID GUID) {
1562 return &*GlobalValueMap.emplace(GUID, GlobalValueSummaryInfo(HaveGVs))
1563 .first;
1564 }
1565
1566public:
1567 // See HaveGVs variable comment.
1568 ModuleSummaryIndex(bool HaveGVs, bool EnableSplitLTOUnit = false,
1569 bool UnifiedLTO = false)
1570 : TypeIdSaver(TypeIdSaverAlloc), HaveGVs(HaveGVs),
1571 EnableSplitLTOUnit(EnableSplitLTOUnit), UnifiedLTO(UnifiedLTO),
1572 Saver(Alloc) {}
1573
1574 // Current version for the module summary in bitcode files.
1575 // The BitcodeSummaryVersion should be bumped whenever we introduce changes
1576 // in the way some record are interpreted, like flags for instance.
1577 // Note that incrementing this may require changes in both BitcodeReader.cpp
1578 // and BitcodeWriter.cpp.
1579 static constexpr uint64_t BitcodeSummaryVersion = 12;
1580
1581 // Regular LTO module name for ASM writer
1582 static constexpr const char *getRegularLTOModuleName() {
1583 return "[Regular LTO]";
1584 }
1585
1586 bool haveGVs() const { return HaveGVs; }
1587
1588 LLVM_ABI uint64_t getFlags() const;
1589 LLVM_ABI void setFlags(uint64_t Flags);
1590
1591 uint64_t getBlockCount() const { return BlockCount; }
1592 void addBlockCount(uint64_t C) { BlockCount += C; }
1593 void setBlockCount(uint64_t C) { BlockCount = C; }
1594
1595 gvsummary_iterator begin() { return GlobalValueMap.begin(); }
1596 const_gvsummary_iterator begin() const { return GlobalValueMap.begin(); }
1597 gvsummary_iterator end() { return GlobalValueMap.end(); }
1598 const_gvsummary_iterator end() const { return GlobalValueMap.end(); }
1599 size_t size() const { return GlobalValueMap.size(); }
1600
1601 const std::vector<uint64_t> &stackIds() const { return StackIds; }
1602
1603 unsigned addOrGetStackIdIndex(uint64_t StackId) {
1604 auto Inserted = StackIdToIndex.insert({StackId, StackIds.size()});
1605 if (Inserted.second)
1606 StackIds.push_back(StackId);
1607 return Inserted.first->second;
1608 }
1609
1610 uint64_t getStackIdAtIndex(unsigned Index) const {
1611 assert(StackIds.size() > Index);
1612 return StackIds[Index];
1613 }
1614
1615 // Facility to release memory from data structures only needed during index
1616 // construction (including while building combined index). Currently this only
1617 // releases the temporary map used while constructing a correspondence between
1618 // stack ids and their index in the StackIds vector. Mostly impactful when
1619 // building a large combined index.
1621 assert(StackIdToIndex.size() == StackIds.size());
1622 StackIdToIndex.clear();
1623 StackIds.shrink_to_fit();
1624 }
1625
1626 /// Convenience function for doing a DFS on a ValueInfo. Marks the function in
1627 /// the FunctionHasParent map.
1629 std::map<ValueInfo, bool> &FunctionHasParent) {
1630 if (!V.getSummaryList().size())
1631 return; // skip external functions that don't have summaries
1632
1633 // Mark discovered if we haven't yet
1634 auto S = FunctionHasParent.emplace(V, false);
1635
1636 // Stop if we've already discovered this node
1637 if (!S.second)
1638 return;
1639
1641 dyn_cast<FunctionSummary>(V.getSummaryList().front().get());
1642 assert(F != nullptr && "Expected FunctionSummary node");
1643
1644 for (const auto &C : F->calls()) {
1645 // Insert node if necessary
1646 auto S = FunctionHasParent.emplace(C.first, true);
1647
1648 // Skip nodes that we're sure have parents
1649 if (!S.second && S.first->second)
1650 continue;
1651
1652 if (S.second)
1653 discoverNodes(C.first, FunctionHasParent);
1654 else
1655 S.first->second = true;
1656 }
1657 }
1658
1659 // Calculate the callgraph root
1661 // Functions that have a parent will be marked in FunctionHasParent pair.
1662 // Once we've marked all functions, the functions in the map that are false
1663 // have no parent (so they're the roots)
1664 std::map<ValueInfo, bool> FunctionHasParent;
1665
1666 for (auto &S : *this) {
1667 // Skip external functions
1668 if (!S.second.getSummaryList().size() ||
1669 !isa<FunctionSummary>(S.second.getSummaryList().front().get()))
1670 continue;
1671 discoverNodes(ValueInfo(HaveGVs, &S), FunctionHasParent);
1672 }
1673
1675 // create edges to all roots in the Index
1676 for (auto &P : FunctionHasParent) {
1677 if (P.second)
1678 continue; // skip over non-root nodes
1679 Edges.push_back(std::make_pair(P.first, CalleeInfo{}));
1680 }
1681 return FunctionSummary::makeDummyFunctionSummary(std::move(Edges));
1682 }
1683
1685 return WithGlobalValueDeadStripping;
1686 }
1688 WithGlobalValueDeadStripping = true;
1689 }
1690
1691 bool withAttributePropagation() const { return WithAttributePropagation; }
1693 WithAttributePropagation = true;
1694 }
1695
1696 bool withDSOLocalPropagation() const { return WithDSOLocalPropagation; }
1697 void setWithDSOLocalPropagation() { WithDSOLocalPropagation = true; }
1698
1699 bool withInternalizeAndPromote() const { return WithInternalizeAndPromote; }
1700 void setWithInternalizeAndPromote() { WithInternalizeAndPromote = true; }
1701
1702 bool withWholeProgramVisibility() const { return WithWholeProgramVisibility; }
1703 void setWithWholeProgramVisibility() { WithWholeProgramVisibility = true; }
1704
1705 bool isReadOnly(const GlobalVarSummary *GVS) const {
1706 return WithAttributePropagation && GVS->maybeReadOnly();
1707 }
1708 bool isWriteOnly(const GlobalVarSummary *GVS) const {
1709 return WithAttributePropagation && GVS->maybeWriteOnly();
1710 }
1711
1712 bool withSupportsHotColdNew() const { return WithSupportsHotColdNew; }
1713 void setWithSupportsHotColdNew() { WithSupportsHotColdNew = true; }
1714
1716 return SkipModuleByDistributedBackend;
1717 }
1719 SkipModuleByDistributedBackend = true;
1720 }
1721
1722 bool enableSplitLTOUnit() const { return EnableSplitLTOUnit; }
1723 void setEnableSplitLTOUnit() { EnableSplitLTOUnit = true; }
1724
1725 bool hasUnifiedLTO() const { return UnifiedLTO; }
1726 void setUnifiedLTO() { UnifiedLTO = true; }
1727
1728 bool partiallySplitLTOUnits() const { return PartiallySplitLTOUnits; }
1729 void setPartiallySplitLTOUnits() { PartiallySplitLTOUnits = true; }
1730
1731 bool hasParamAccess() const { return HasParamAccess; }
1732
1733 bool isGlobalValueLive(const GlobalValueSummary *GVS) const {
1734 return !WithGlobalValueDeadStripping || GVS->isLive();
1735 }
1736 LLVM_ABI bool isGUIDLive(GlobalValue::GUID GUID) const;
1737
1738 /// Return a ValueInfo for the index value_type (convenient when iterating
1739 /// index).
1740 ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const {
1741 return ValueInfo(HaveGVs, &R);
1742 }
1743
1744 /// Return a ValueInfo for GUID if it exists, otherwise return ValueInfo().
1746 auto I = GlobalValueMap.find(GUID);
1747 return ValueInfo(HaveGVs, I == GlobalValueMap.end() ? nullptr : &*I);
1748 }
1749
1750 /// Return a ValueInfo for \p GUID.
1752 return ValueInfo(HaveGVs, getOrInsertValuePtr(GUID));
1753 }
1754
1755 // Save a string in the Index. Use before passing Name to
1756 // getOrInsertValueInfo when the string isn't owned elsewhere (e.g. on the
1757 // module's Strtab).
1758 StringRef saveString(StringRef String) { return Saver.save(String); }
1759
1760 /// Return a ValueInfo for \p GUID setting value \p Name.
1762 assert(!HaveGVs);
1763 auto VP = getOrInsertValuePtr(GUID);
1764 VP->second.U.Name = Name;
1765 return ValueInfo(HaveGVs, VP);
1766 }
1767
1768 /// Return a ValueInfo for \p GV and mark it as belonging to GV.
1770 assert(HaveGVs);
1771 auto VP = getOrInsertValuePtr(GV->getGUID());
1772 VP->second.U.GV = GV;
1773 return ValueInfo(HaveGVs, VP);
1774 }
1775
1776 /// Return the GUID for \p OriginalId in the OidGuidMap.
1778 const auto I = OidGuidMap.find(OriginalID);
1779 return I == OidGuidMap.end() ? 0 : I->second;
1780 }
1781
1782 CfiFunctionIndex &cfiFunctionDefs() { return CfiFunctionDefs; }
1783 const CfiFunctionIndex &cfiFunctionDefs() const { return CfiFunctionDefs; }
1784
1785 CfiFunctionIndex &cfiFunctionDecls() { return CfiFunctionDecls; }
1786 const CfiFunctionIndex &cfiFunctionDecls() const { return CfiFunctionDecls; }
1787
1788 /// Add a global value summary for a value.
1790 std::unique_ptr<GlobalValueSummary> Summary) {
1791 addGlobalValueSummary(getOrInsertValueInfo(&GV), std::move(Summary));
1792 }
1793
1794 /// Add a global value summary for a value of the given name.
1796 std::unique_ptr<GlobalValueSummary> Summary) {
1800 std::move(Summary));
1801 }
1802
1803 /// Add a global value summary for the given ValueInfo.
1805 std::unique_ptr<GlobalValueSummary> Summary) {
1806 if (const FunctionSummary *FS = dyn_cast<FunctionSummary>(Summary.get()))
1807 HasParamAccess |= !FS->paramAccesses().empty();
1808 addOriginalName(VI.getGUID(), Summary->getOriginalName());
1809 // Here we have a notionally const VI, but the value it points to is owned
1810 // by the non-const *this.
1811 const_cast<GlobalValueSummaryMapTy::value_type *>(VI.getRef())
1812 ->second.addSummary(std::move(Summary));
1813 }
1814
1815 /// Add an original name for the value of the given GUID.
1817 GlobalValue::GUID OrigGUID) {
1818 if (OrigGUID == 0 || ValueGUID == OrigGUID)
1819 return;
1820 auto [It, Inserted] = OidGuidMap.try_emplace(OrigGUID, ValueGUID);
1821 if (!Inserted && It->second != ValueGUID)
1822 It->second = 0;
1823 }
1824
1825 /// Find the summary for ValueInfo \p VI in module \p ModuleId, or nullptr if
1826 /// not found.
1828 auto SummaryList = VI.getSummaryList();
1829 auto Summary =
1830 llvm::find_if(SummaryList,
1831 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
1832 return Summary->modulePath() == ModuleId;
1833 });
1834 if (Summary == SummaryList.end())
1835 return nullptr;
1836 return Summary->get();
1837 }
1838
1839 /// Find the summary for global \p GUID in module \p ModuleId, or nullptr if
1840 /// not found.
1842 StringRef ModuleId) const {
1843 auto CalleeInfo = getValueInfo(ValueGUID);
1844 if (!CalleeInfo)
1845 return nullptr; // This function does not have a summary
1846 return findSummaryInModule(CalleeInfo, ModuleId);
1847 }
1848
1849 /// Returns the first GlobalValueSummary for \p GV, asserting that there
1850 /// is only one if \p PerModuleIndex.
1852 bool PerModuleIndex = true) const {
1853 assert(GV.hasName() && "Can't get GlobalValueSummary for GV with no name");
1854 return getGlobalValueSummary(GV.getGUID(), PerModuleIndex);
1855 }
1856
1857 /// Returns the first GlobalValueSummary for \p ValueGUID, asserting that
1858 /// there
1859 /// is only one if \p PerModuleIndex.
1862 bool PerModuleIndex = true) const;
1863
1864 /// Table of modules, containing module hash and id.
1866 return ModulePathStringTable;
1867 }
1868
1869 /// Table of modules, containing hash and id.
1870 StringMap<ModuleHash> &modulePaths() { return ModulePathStringTable; }
1871
1872 /// Get the module SHA1 hash recorded for the given module path.
1873 const ModuleHash &getModuleHash(const StringRef ModPath) const {
1874 auto It = ModulePathStringTable.find(ModPath);
1875 assert(It != ModulePathStringTable.end() && "Module not registered");
1876 return It->second;
1877 }
1878
1879 /// Convenience method for creating a promoted global name
1880 /// for the given value name of a local, and its original module's ID.
1881 static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash) {
1882 std::string Suffix = utostr((uint64_t(ModHash[0]) << 32) |
1883 ModHash[1]); // Take the first 64 bits
1884 return getGlobalNameForLocal(Name, Suffix);
1885 }
1886
1887 static std::string getGlobalNameForLocal(StringRef Name, StringRef Suffix) {
1888 SmallString<256> NewName(Name);
1889 NewName += ".llvm.";
1890 NewName += Suffix;
1891 return std::string(NewName);
1892 }
1893
1894 /// Helper to obtain the unpromoted name for a global value (or the original
1895 /// name if not promoted). Split off the rightmost ".llvm.${hash}" suffix,
1896 /// because it is possible in certain clients (not clang at the moment) for
1897 /// two rounds of ThinLTO optimization and therefore promotion to occur.
1899 std::pair<StringRef, StringRef> Pair = Name.rsplit(".llvm.");
1900 return Pair.first;
1901 }
1902
1904
1905 /// Add a new module with the given \p Hash, mapped to the given \p
1906 /// ModID, and return a reference to the module.
1908 return &*ModulePathStringTable.insert({ModPath, Hash}).first;
1909 }
1910
1911 /// Return module entry for module with the given \p ModPath.
1913 auto It = ModulePathStringTable.find(ModPath);
1914 assert(It != ModulePathStringTable.end() && "Module not registered");
1915 return &*It;
1916 }
1917
1918 /// Return module entry for module with the given \p ModPath.
1919 const ModuleInfo *getModule(StringRef ModPath) const {
1920 auto It = ModulePathStringTable.find(ModPath);
1921 assert(It != ModulePathStringTable.end() && "Module not registered");
1922 return &*It;
1923 }
1924
1925 /// Check if the given Module has any functions available for exporting
1926 /// in the index. We consider any module present in the ModulePathStringTable
1927 /// to have exported functions.
1928 bool hasExportedFunctions(const Module &M) const {
1929 return ModulePathStringTable.count(M.getModuleIdentifier());
1930 }
1931
1932 const TypeIdSummaryMapTy &typeIds() const { return TypeIdMap; }
1933
1934 /// Return an existing or new TypeIdSummary entry for \p TypeId.
1935 /// This accessor can mutate the map and therefore should not be used in
1936 /// the ThinLTO backends.
1938 auto TidIter = TypeIdMap.equal_range(
1940 for (auto &[GUID, TypeIdPair] : make_range(TidIter))
1941 if (TypeIdPair.first == TypeId)
1942 return TypeIdPair.second;
1943 auto It =
1944 TypeIdMap.insert({GlobalValue::getGUIDAssumingExternalLinkage(TypeId),
1945 {TypeIdSaver.save(TypeId), TypeIdSummary()}});
1946 return It->second.second;
1947 }
1948
1949 /// This returns either a pointer to the type id summary (if present in the
1950 /// summary map) or null (if not present). This may be used when importing.
1952 auto TidIter = TypeIdMap.equal_range(
1954 for (const auto &[GUID, TypeIdPair] : make_range(TidIter))
1955 if (TypeIdPair.first == TypeId)
1956 return &TypeIdPair.second;
1957 return nullptr;
1958 }
1959
1961 return const_cast<TypeIdSummary *>(
1962 static_cast<const ModuleSummaryIndex *>(this)->getTypeIdSummary(
1963 TypeId));
1964 }
1965
1966 const auto &typeIdCompatibleVtableMap() const {
1967 return TypeIdCompatibleVtableMap;
1968 }
1969
1970 /// Return an existing or new TypeIdCompatibleVtableMap entry for \p TypeId.
1971 /// This accessor can mutate the map and therefore should not be used in
1972 /// the ThinLTO backends.
1975 return TypeIdCompatibleVtableMap[TypeIdSaver.save(TypeId)];
1976 }
1977
1978 /// For the given \p TypeId, this returns the TypeIdCompatibleVtableMap
1979 /// entry if present in the summary map. This may be used when importing.
1980 std::optional<TypeIdCompatibleVtableInfo>
1982 auto I = TypeIdCompatibleVtableMap.find(TypeId);
1983 if (I == TypeIdCompatibleVtableMap.end())
1984 return std::nullopt;
1985 return I->second;
1986 }
1987
1988 /// Collect for the given module the list of functions it defines
1989 /// (GUID -> Summary).
1990 LLVM_ABI void
1992 GVSummaryMapTy &GVSummaryMap) const;
1993
1994 /// Collect for each module the list of Summaries it defines (GUID ->
1995 /// Summary).
1996 template <class Map>
1997 void
1998 collectDefinedGVSummariesPerModule(Map &ModuleToDefinedGVSummaries) const {
1999 for (const auto &GlobalList : *this) {
2000 auto GUID = GlobalList.first;
2001 for (const auto &Summary : GlobalList.second.getSummaryList()) {
2002 ModuleToDefinedGVSummaries[Summary->modulePath()][GUID] = Summary.get();
2003 }
2004 }
2005 }
2006
2007 /// Print to an output stream.
2008 LLVM_ABI void print(raw_ostream &OS, bool IsForDebug = false) const;
2009
2010 /// Dump to stderr (for debugging).
2011 LLVM_ABI void dump() const;
2012
2013 /// Export summary to dot file for GraphViz.
2014 LLVM_ABI void
2016 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) const;
2017
2018 /// Print out strongly connected components for debugging.
2019 LLVM_ABI void dumpSCCs(raw_ostream &OS);
2020
2021 /// Do the access attribute and DSOLocal propagation in combined index.
2022 LLVM_ABI void
2023 propagateAttributes(const DenseSet<GlobalValue::GUID> &PreservedSymbols);
2024
2025 /// Checks if we can import global variable from another module.
2027 bool AnalyzeRefs) const;
2028
2029 /// Same as above but checks whether the global var is importable as a
2030 /// declaration.
2032 bool AnalyzeRefs, bool &CanImportDecl) const;
2033};
2034
2035/// GraphTraits definition to build SCC for the index
2036template <> struct GraphTraits<ValueInfo> {
2039
2041 return P.first;
2042 }
2045 decltype(&valueInfoFromEdge)>;
2046
2049
2050 static NodeRef getEntryNode(ValueInfo V) { return V; }
2051
2053 if (!N.getSummaryList().size()) // handle external function
2054 return ChildIteratorType(
2055 FunctionSummary::ExternalNode.CallGraphEdgeList.begin(),
2058 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2059 return ChildIteratorType(F->CallGraphEdgeList.begin(), &valueInfoFromEdge);
2060 }
2061
2063 if (!N.getSummaryList().size()) // handle external function
2064 return ChildIteratorType(
2065 FunctionSummary::ExternalNode.CallGraphEdgeList.end(),
2068 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2069 return ChildIteratorType(F->CallGraphEdgeList.end(), &valueInfoFromEdge);
2070 }
2071
2073 if (!N.getSummaryList().size()) // handle external function
2074 return FunctionSummary::ExternalNode.CallGraphEdgeList.begin();
2075
2077 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2078 return F->CallGraphEdgeList.begin();
2079 }
2080
2082 if (!N.getSummaryList().size()) // handle external function
2083 return FunctionSummary::ExternalNode.CallGraphEdgeList.end();
2084
2086 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2087 return F->CallGraphEdgeList.end();
2088 }
2089
2090 static NodeRef edge_dest(EdgeRef E) { return E.first; }
2091};
2092
2093template <>
2096 std::unique_ptr<GlobalValueSummary> Root =
2097 std::make_unique<FunctionSummary>(I->calculateCallGraphRoot());
2098 GlobalValueSummaryInfo G(I->haveGVs());
2099 G.addSummary(std::move(Root));
2100 static auto P =
2101 GlobalValueSummaryMapTy::value_type(GlobalValue::GUID(0), std::move(G));
2102 return ValueInfo(I->haveGVs(), &P);
2103 }
2104};
2105} // end namespace llvm
2106
2107#endif // LLVM_IR_MODULESUMMARYINDEX_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_PREFERRED_TYPE(T)
\macro LLVM_PREFERRED_TYPE Adjust type of bit-field in debug info.
Definition Compiler.h:706
#define LLVM_ABI
Definition Compiler.h:213
DXIL Finalize Linkage
This file defines the DenseMap class.
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
#define G(x, y, z)
Definition MD5.cpp:56
#define P(N)
if(PassOpts->AAPipeline)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallString class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
Value * RHS
GlobalValue::GUID getAliaseeGUID() const
const GlobalValueSummary & getAliasee() const
ValueInfo getAliaseeVI() const
static bool classof(const GlobalValueSummary *GVS)
Check if this is an alias summary.
AliasSummary(GVFlags Flags)
GlobalValueSummary & getAliasee()
void setAliasee(ValueInfo &AliaseeVI, GlobalValueSummary *Aliasee)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
GUIDIterator guid_end() const
size_t count(StringRef S) const
std::vector< StringRef > symbols() const
iterator_range< GUIDIterator > guids() const
iterator_range< NestedIterator > forGuid(GlobalValue::GUID GUID) const
GUIDIterator guid_begin() const
This class represents a range of values.
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
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.
void addCallsite(CallsiteInfo &Callsite)
static FunctionSummary makeDummyFunctionSummary(SmallVectorImpl< FunctionSummary::EdgeTy > &&Edges)
Create an empty FunctionSummary (with specified call edges).
FunctionSummary(GVFlags Flags, unsigned NumInsts, FFlags FunFlags, SmallVectorImpl< ValueInfo > &&Refs, SmallVectorImpl< EdgeTy > &&CGEdges, std::vector< GlobalValue::GUID > TypeTests, std::vector< VFuncId > TypeTestAssumeVCalls, std::vector< VFuncId > TypeCheckedLoadVCalls, std::vector< ConstVCall > TypeTestAssumeConstVCalls, std::vector< ConstVCall > TypeCheckedLoadConstVCalls, std::vector< ParamAccess > Params, CallsitesTy CallsiteList, AllocsTy AllocList)
ArrayRef< VFuncId > type_test_assume_vcalls() const
Returns the list of virtual calls made by this function using llvm.assume(llvm.type....
ArrayRef< ConstVCall > type_test_assume_const_vcalls() const
Returns the list of virtual calls made by this function using llvm.assume(llvm.type....
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
LLVM_ABI std::pair< unsigned, unsigned > specialRefCounts() const
SmallVector< EdgeTy, 0 > & mutableCalls()
ArrayRef< AllocInfo > allocs() const
ArrayRef< CallsiteInfo > callsites() const
void addTypeTest(GlobalValue::GUID Guid)
Add a type test to the summary.
ArrayRef< VFuncId > type_checked_load_vcalls() const
Returns the list of virtual calls made by this function using llvm.type.checked.load intrinsics that ...
void setParamAccesses(std::vector< ParamAccess > NewParams)
Sets the list of known uses of pointer parameters.
unsigned instCount() const
Get the instruction count recorded for this function.
const TypeIdInfo * getTypeIdInfo() const
ArrayRef< ConstVCall > type_checked_load_const_vcalls() const
Returns the list of virtual calls made by this function using llvm.type.checked.load intrinsics with ...
ArrayRef< EdgeTy > calls() const
Return the list of <CalleeValueInfo, CalleeInfo> pairs.
ArrayRef< ParamAccess > paramAccesses() const
Returns the list of known uses of pointer parameters.
CallsitesTy & mutableCallsites()
ForceSummaryHotnessType
Types for -force-summary-edges-cold debugging option.
FFlags fflags() const
Get function summary flags.
ArrayRef< GlobalValue::GUID > type_tests() const
Returns the list of type identifiers used by this function in llvm.type.test intrinsics other than by...
static bool classof(const GlobalValueSummary *GVS)
Check if this is a function summary.
Function and variable summary information to aid decisions and implementation of importing.
SummaryKind
Sububclass discriminator (for dyn_cast<> et al.)
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
GlobalValueSummary * getBaseObject()
If this is an alias summary, returns the summary of the aliased object (a global variable or function...
SummaryKind getSummaryKind() const
Which kind of summary subclass this is.
GlobalValue::GUID getOriginalName() const
Returns the hash of the original name, it is identical to the GUID for externally visible symbols,...
GlobalValue::VisibilityTypes getVisibility() const
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
void setLinkage(GlobalValue::LinkageTypes Linkage)
Sets the linkage to the value determined by global summary-based optimization.
void setVisibility(GlobalValue::VisibilityTypes Vis)
virtual ~GlobalValueSummary()=default
GlobalValueSummary::ImportKind importType() const
void setModulePath(StringRef ModPath)
Set the path to the module containing this function, for use in the combined index.
void setNotEligibleToImport()
Flag that this global value cannot be imported.
void setCanAutoHide(bool CanAutoHide)
GlobalValueSummary(SummaryKind K, GVFlags Flags, SmallVectorImpl< ValueInfo > &&Refs)
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.
void setImportKind(ImportKind IK)
void setOriginalName(GlobalValue::GUID Name)
Initialize the original name hash in this summary.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:77
static bool isLocalLinkage(LinkageTypes Linkage)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
Global variable summary information to aid decisions and implementation of importing.
void setVCallVisibility(GlobalObject::VCallVisibility Vis)
struct llvm::GlobalVarSummary::GVarFlags VarFlags
ArrayRef< VirtFuncOffset > vTableFuncs() const
GlobalVarSummary(GVFlags Flags, GVarFlags VarFlags, SmallVectorImpl< ValueInfo > &&Refs)
GlobalObject::VCallVisibility getVCallVisibility() const
static bool classof(const GlobalValueSummary *GVS)
Check if this is a global variable summary.
void setVTableFuncs(VTableFuncList Funcs)
Class to hold module path string table and global value map, and encapsulate methods for operating on...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
std::optional< TypeIdCompatibleVtableInfo > getTypeIdCompatibleVtableSummary(StringRef TypeId) const
For the given TypeId, this returns the TypeIdCompatibleVtableMap entry if present in the summary map.
void addGlobalValueSummary(ValueInfo VI, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for the given ValueInfo.
ModulePathStringTableTy::value_type ModuleInfo
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
static void discoverNodes(ValueInfo V, std::map< ValueInfo, bool > &FunctionHasParent)
Convenience function for doing a DFS on a ValueInfo.
StringRef saveString(StringRef String)
const TypeIdSummaryMapTy & typeIds() const
static StringRef getOriginalNameBeforePromote(StringRef Name)
Helper to obtain the unpromoted name for a global value (or the original name if not promoted).
const TypeIdSummary * getTypeIdSummary(StringRef TypeId) const
This returns either a pointer to the type id summary (if present in the summary map) or null (if not ...
LLVM_ABI bool isGUIDLive(GlobalValue::GUID GUID) const
const_gvsummary_iterator end() const
bool isReadOnly(const GlobalVarSummary *GVS) const
LLVM_ABI void setFlags(uint64_t Flags)
const_gvsummary_iterator begin() const
CfiFunctionIndex & cfiFunctionDecls()
bool isWriteOnly(const GlobalVarSummary *GVS) const
const std::vector< uint64_t > & stackIds() const
GlobalValueSummary * findSummaryInModule(GlobalValue::GUID ValueGUID, StringRef ModuleId) const
Find the summary for global GUID in module ModuleId, or nullptr if not found.
ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const
Return a ValueInfo for the index value_type (convenient when iterating index).
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
static constexpr const char * getRegularLTOModuleName()
const CfiFunctionIndex & cfiFunctionDefs() const
void addGlobalValueSummary(StringRef ValueName, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value of the given name.
ModuleSummaryIndex(bool HaveGVs, bool EnableSplitLTOUnit=false, bool UnifiedLTO=false)
LLVM_ABI void collectDefinedFunctionsForModule(StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const
Collect for the given module the list of functions it defines (GUID -> Summary).
const auto & typeIdCompatibleVtableMap() const
LLVM_ABI void dumpSCCs(raw_ostream &OS)
Print out strongly connected components for debugging.
bool isGlobalValueLive(const GlobalValueSummary *GVS) const
const ModuleInfo * getModule(StringRef ModPath) const
Return module entry for module with the given ModPath.
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.
LLVM_ABI void dump() const
Dump to stderr (for debugging).
ModuleInfo * addModule(StringRef ModPath, ModuleHash Hash=ModuleHash{{0}})
Add a new module with the given Hash, mapped to the given ModID, and return a reference to the module...
void collectDefinedGVSummariesPerModule(Map &ModuleToDefinedGVSummaries) const
Collect for each module the list of Summaries it defines (GUID -> Summary).
void addGlobalValueSummary(const GlobalValue &GV, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value.
bool hasExportedFunctions(const Module &M) const
Check if the given Module has any functions available for exporting in the index.
static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash)
Convenience method for creating a promoted global name for the given value name of a local,...
static constexpr uint64_t BitcodeSummaryVersion
LLVM_ABI void exportToDot(raw_ostream &OS, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols) const
Export summary to dot file for GraphViz.
uint64_t getStackIdAtIndex(unsigned Index) const
StringMap< ModuleHash > & modulePaths()
Table of modules, containing hash and id.
LLVM_ABI void print(raw_ostream &OS, bool IsForDebug=false) const
Print to an output stream.
bool skipModuleByDistributedBackend() const
CfiFunctionIndex & cfiFunctionDefs()
ValueInfo getOrInsertValueInfo(const GlobalValue *GV)
Return a ValueInfo for GV and mark it as belonging to GV.
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
ValueInfo getValueInfo(GlobalValue::GUID GUID) const
Return a ValueInfo for GUID if it exists, otherwise return ValueInfo().
LLVM_ABI uint64_t getFlags() const
unsigned addOrGetStackIdIndex(uint64_t StackId)
GlobalValue::GUID getGUIDFromOriginalID(GlobalValue::GUID OriginalID) const
Return the GUID for OriginalId in the OidGuidMap.
GlobalValueSummary * getGlobalValueSummary(const GlobalValue &GV, bool PerModuleIndex=true) const
Returns the first GlobalValueSummary for GV, asserting that there is only one if PerModuleIndex.
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID, StringRef Name)
Return a ValueInfo for GUID setting value Name.
LLVM_ABI bool canImportGlobalVar(const GlobalValueSummary *S, bool AnalyzeRefs) const
Checks if we can import global variable from another module.
static std::string getGlobalNameForLocal(StringRef Name, StringRef Suffix)
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
FunctionSummary calculateCallGraphRoot()
const CfiFunctionIndex & cfiFunctionDecls() const
TypeIdSummary * getTypeIdSummary(StringRef TypeId)
TypeIdCompatibleVtableInfo & getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId)
Return an existing or new TypeIdCompatibleVtableMap entry for TypeId.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
PointerIntPair - This class implements a pair of a pointer and small integer.
Simple representation of a scaled number.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
StringMapEntry< ModuleHash > value_type
Definition StringMap.h:217
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition StringMap.h:321
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition StringSaver.h:22
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition StringSaver.h:45
bool hasName() const
Definition Value.h:262
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:477
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:362
StringMapEntry< Value * > ValueName
Definition Value.h:56
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
hash_code hash_value(const FixedPointSemantics &Val)
std::unordered_set< GlobalValueSummary * > GVSummaryPtrSet
A set of global value summary pointers.
std::vector< std::unique_ptr< GlobalValueSummary > > GlobalValueSummaryList
InterleavedRange< Range > interleaved(const Range &R, StringRef Separator=", ", StringRef Prefix="", StringRef Suffix="")
Output range R as a sequence of interleaved elements.
const char * getHotnessName(CalleeInfo::HotnessType HT)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
std::multimap< GlobalValue::GUID, std::pair< StringRef, TypeIdSummary > > TypeIdSummaryMapTy
Map of a type GUID to type id string and summary (multimap used in case of GUID conflicts).
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2113
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2136
std::string utostr(uint64_t X, bool isNeg=false)
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1732
GlobalValueSummaryMapTy::iterator gvsummary_iterator
std::map< GlobalValue::GUID, GlobalValueSummaryInfo > GlobalValueSummaryMapTy
Map from global value GUID to corresponding summary structures.
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
StringMap< ModuleHash > ModulePathStringTableTy
String table to hold/own module path strings, as well as a hash of the module.
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
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:71
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1867
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1758
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
GlobalValueSummaryMapTy::const_iterator const_gvsummary_iterator
Type used for iterating through the global value summary map.
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition MathExtras.h:609
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867
#define N
Summary of memprof metadata on allocations.
AllocInfo(std::vector< MIBInfo > MIBs)
AllocInfo(SmallVector< uint8_t > Versions, std::vector< MIBInfo > MIBs)
std::vector< std::vector< ContextTotalSize > > ContextSizeInfos
SmallVector< uint8_t > Versions
std::vector< MIBInfo > MIBs
Class to accumulate and hold information about a callee.
static constexpr uint64_t MaxRelBlockFreq
bool hasTailCall() const
void updateHotness(const HotnessType OtherHotness)
CalleeInfo(HotnessType Hotness, bool HasTC, uint64_t RelBF)
HotnessType getHotness() const
static constexpr int32_t ScaleShift
void setHasTailCall(const bool HasTC)
void updateRelBlockFreq(uint64_t BlockFreq, uint64_t EntryFreq)
Update RelBlockFreq from BlockFreq and EntryFreq.
static constexpr unsigned RelBlockFreqBits
The value stored in RelBlockFreq has to be interpreted as the digits of a scaled number with a scale ...
Summary of memprof callsite metadata.
SmallVector< unsigned > StackIdIndices
SmallVector< unsigned > Clones
CallsiteInfo(ValueInfo Callee, SmallVector< unsigned > StackIdIndices)
CallsiteInfo(ValueInfo Callee, SmallVector< unsigned > Clones, SmallVector< unsigned > StackIdIndices)
static FunctionSummary::ConstVCall getEmptyKey()
static FunctionSummary::ConstVCall getTombstoneKey()
static unsigned getHashValue(FunctionSummary::ConstVCall I)
static bool isEqual(FunctionSummary::ConstVCall L, FunctionSummary::ConstVCall R)
static FunctionSummary::VFuncId getEmptyKey()
static bool isEqual(FunctionSummary::VFuncId L, FunctionSummary::VFuncId R)
static FunctionSummary::VFuncId getTombstoneKey()
static unsigned getHashValue(FunctionSummary::VFuncId I)
static bool isEqual(ValueInfo L, ValueInfo R)
static bool isSpecialKey(ValueInfo V)
static unsigned getHashValue(ValueInfo I)
An information struct used to provide DenseMap with the various necessary components for a given valu...
A specification for a virtual function call with all constant integer arguments.
Flags specific to function summaries.
FFlags & operator&=(const FFlags &RHS)
Call(uint64_t ParamNo, ValueInfo Callee, const ConstantRange &Offsets)
ParamAccess(uint64_t ParamNo, const ConstantRange &Use)
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
ConstantRange Use
The range contains byte offsets from the parameter pointer which accessed by the function.
static constexpr uint32_t RangeWidth
All type identifier related information.
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
An "identifier" for a virtual function.
void addSummary(std::unique_ptr< GlobalValueSummary > Summary)
Add a summary corresponding to a global value definition in a module with the corresponding GUID.
void verifyLocal() const
Verify that the HasLocal flag is consistent with the SummaryList.
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
Access a read-only list of global value summary structures for a particular value held in the GlobalV...
union llvm::GlobalValueSummaryInfo::NameOrGV U
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
GVFlags(GlobalValue::LinkageTypes Linkage, GlobalValue::VisibilityTypes Visibility, bool NotEligibleToImport, bool Live, bool IsLocal, bool CanAutoHide, ImportKind ImportType)
Convenience Constructors.
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
GVarFlags(bool ReadOnly, bool WriteOnly, bool Constant, GlobalObject::VCallVisibility Vis)
static NodeRef getEntryNode(ModuleSummaryIndex *I)
static NodeRef valueInfoFromEdge(FunctionSummary::EdgeTy &P)
static ChildIteratorType child_begin(NodeRef N)
static ChildEdgeIteratorType child_edge_begin(NodeRef N)
static NodeRef edge_dest(EdgeRef E)
SmallVector< FunctionSummary::EdgeTy, 0 >::iterator ChildEdgeIteratorType
mapped_iterator< SmallVector< FunctionSummary::EdgeTy, 0 >::iterator, decltype(&valueInfoFromEdge)> ChildIteratorType
static NodeRef getEntryNode(ValueInfo V)
static ChildIteratorType child_end(NodeRef N)
static ChildEdgeIteratorType child_edge_end(NodeRef N)
FunctionSummary::EdgeTy & EdgeRef
typename ModuleSummaryIndex *::UnknownGraphTypeError NodeRef
Definition GraphTraits.h:95
Summary of a single MIB in a memprof metadata on allocations.
MIBInfo(AllocationType AllocType, SmallVector< unsigned > StackIdIndices)
AllocationType AllocType
SmallVector< unsigned > StackIdIndices
TypeIdOffsetVtableInfo(uint64_t Offset, ValueInfo VI)
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
Kind
Specifies which kind of type check we should emit for this byte array.
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
Struct that holds a reference to a particular GUID in a global value summary.
PointerIntPair< const GlobalValueSummaryMapTy::value_type *, 3, int > RefAndFlags
LLVM_ABI GlobalValue::VisibilityTypes getELFVisibility() const
Returns the most constraining visibility among summaries.
bool isValidAccessSpecifier() const
const GlobalValueSummaryMapTy::value_type * getRef() const
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
StringRef name() const
bool isWriteOnly() const
const GlobalValue * getValue() const
void verifyLocal() const
ValueInfo(bool HaveGVs, const GlobalValueSummaryMapTy::value_type *R)
bool isReadOnly() const
LLVM_ABI bool canAutoHide() const
Checks if all copies are eligible for auto-hiding (have flag set).
unsigned getAccessSpecifier() const
ValueInfo()=default
LLVM_ABI bool isDSOLocal(bool WithDSOLocalPropagation=false) const
Checks if all summaries are DSO local (have the flag set).
GlobalValue::GUID getGUID() const
VirtFuncOffset(ValueInfo VI, uint64_t Offset)
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.
This class should be specialized by any type that needs to be converted to/from a YAML mapping.
Definition YAMLTraits.h:62
const GlobalValue * GV
The GlobalValue corresponding to this summary.
StringRef Name
Summary string representation.