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