LLVM 24.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"
21#include "llvm/ADT/SetVector.h"
26#include "llvm/ADT/StringMap.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/ADT/StringSet.h"
29#include "llvm/ADT/iterator.h"
32#include "llvm/IR/GlobalValue.h"
33#include "llvm/IR/Module.h"
40#include <algorithm>
41#include <array>
42#include <cassert>
43#include <cstddef>
44#include <cstdint>
45#include <deque>
46#include <map>
47#include <memory>
48#include <optional>
49#include <set>
50#include <string>
51#include <utility>
52#include <vector>
53
54namespace llvm {
55
56template <class GraphType> struct GraphTraits;
57
58namespace yaml {
59
60template <typename T> struct MappingTraits;
61
62} // end namespace yaml
63
64/// Class to accumulate and hold information about a callee.
65struct CalleeInfo {
66 enum class HotnessType : uint8_t {
68 Cold = 1,
69 None = 2,
70 Hot = 3,
72 };
73
74 // The size of the bit-field might need to be adjusted if more values are
75 // added to HotnessType enum.
77
78 // True if at least one of the calls to the callee is a tail call.
81
82 // True if at least one of the calls to the callee is an indirect call, i.e.
83 // the edge was added for a profiled indirect call target (from value profile
84 // metadata) or for a possible target from !callees metadata.
87
88 // True if the thin link determined that at least a declaration of the callee
89 // must be available in any module containing the caller (including any
90 // module the caller is imported into), e.g. so that the ThinLTO backend can
91 // perform MemProf ICP to it. If the callee definition is not imported into
92 // such a module, a declaration is imported instead. This is only computed
93 // and used within the thin link, and is not serialized.
94 // Note that keeping this in-memory only information here does not increase
95 // the size of CalleeInfo, since it fits in the existing bit-field storage.
96 // If that changes, it could instead be tracked in a side structure computed
97 // by the thin link MemProf context disambiguation and passed to the function
98 // importer.
101
105 explicit CalleeInfo(HotnessType Hotness, bool HasTC, bool HasIC = false)
106 : Hotness(static_cast<uint32_t>(Hotness)), HasTailCall(HasTC),
108
109 void updateHotness(const HotnessType OtherHotness) {
110 Hotness = std::max(Hotness, static_cast<uint32_t>(OtherHotness));
111 }
112
113 bool hasTailCall() const { return HasTailCall; }
114
115 void setHasTailCall(const bool HasTC) { HasTailCall = HasTC; }
116
117 bool hasIndirectCall() const { return HasIndirectCall; }
118
119 void setHasIndirectCall(const bool HasIC) { HasIndirectCall = HasIC; }
120
121 bool requiresDeclImport() const { return RequiresDeclImport; }
122
123 void setRequiresDeclImport(const bool RI) { RequiresDeclImport = RI; }
124
126};
127
129 switch (HT) {
131 return "unknown";
133 return "cold";
135 return "none";
137 return "hot";
139 return "critical";
140 }
141 llvm_unreachable("invalid hotness");
142}
143
144class GlobalValueSummary;
145
146using GlobalValueSummaryList = std::vector<std::unique_ptr<GlobalValueSummary>>;
147
148struct alignas(8) GlobalValueSummaryInfo {
149 union NameOrGV {
150 NameOrGV(bool HaveGVs) {
151 if (HaveGVs)
152 GV = nullptr;
153 else
154 Name = "";
155 }
156
157 /// The GlobalValue corresponding to this summary. This is only used in
158 /// per-module summaries and when the IR is available. E.g. when module
159 /// analysis is being run, or when parsing both the IR and the summary
160 /// from assembly.
162
163 /// Summary string representation. This StringRef points to BC module
164 /// string table and is valid until module data is stored in memory.
165 /// This is guaranteed to happen until runThinLTOBackend function is
166 /// called, so it is safe to use this field during thin link. This field
167 /// is only valid if summary index was loaded from BC file.
169 } U;
170
171 inline GlobalValueSummaryInfo(bool HaveGVs);
172
173 /// Access a read-only list of global value summary structures for a
174 /// particular value held in the GlobalValueMap.
176 return SummaryList;
177 }
178
179 /// Add a summary corresponding to a global value definition in a module with
180 /// the corresponding GUID.
181 inline void addSummary(std::unique_ptr<GlobalValueSummary> Summary);
182
183 /// Verify that the HasLocal flag is consistent with the SummaryList. Should
184 /// only be called prior to index-based internalization and promotion.
185 inline void verifyLocal() const;
186
187 bool hasLocal() const { return HasLocal; }
188
189private:
190 /// List of global value summary structures for a particular value held
191 /// in the GlobalValueMap. Requires a vector in the case of multiple
192 /// COMDAT values of the same name, weak symbols, locals of the same name when
193 /// compiling without sufficient distinguishing path, or (theoretically) hash
194 /// collisions. Each summary is from a different module.
195 GlobalValueSummaryList SummaryList;
196
197 /// True if the SummaryList contains at least one summary with local linkage.
198 /// In most cases there should be only one, unless translation units with
199 /// same-named locals were compiled without distinguishing path. And generally
200 /// there should not be a mix of local and non-local summaries, because the
201 /// GUID for a local is computed with the path prepended and a ';' delimiter.
202 /// In extremely rare cases there could be a GUID hash collision. Having the
203 /// flag saves having to walk through all summaries to prove the existence or
204 /// not of any locals.
205 /// NOTE: this flag is set when the index is built. It does not reflect
206 /// index-based internalization and promotion decisions. Generally most
207 /// index-based analysis occurs before then, but any users should assert that
208 /// the withInternalizeAndPromote() flag is not set on the index.
209 /// TODO: Replace checks in various ThinLTO analyses that loop through all
210 /// summaries to handle the local case with a check of the flag.
211 bool HasLocal : 1;
212};
213
214/// Map from global value GUID to corresponding summary structures. Use a
215/// DenseMap for O(1) lookup and a std::deque for storage. std::deque
216/// guarantees that pointers to elements are not invalidated by push_back,
217/// which is required because ValueInfo stores a raw pointer to elements of
218/// this container.
220public:
223 using value_type = std::pair<key_type, mapped_type>;
224 using iterator = std::deque<value_type>::iterator;
225 using const_iterator = std::deque<value_type>::const_iterator;
226 using size_type = std::deque<value_type>::size_type;
227
228private:
229 /// Vector of pointers into Storage, used for key-sorted iteration.
230 using SortedEntriesVec = SmallVector<const value_type *, 0>;
231
233 std::deque<value_type> Storage;
234
235public:
236 template <typename... Ts>
237 std::pair<iterator, bool> try_emplace(key_type Key, Ts &&...Args) {
238 auto Res = Map.try_emplace(Key, Storage.size());
239 if (Res.second) {
240 Storage.emplace_back(std::piecewise_construct, std::forward_as_tuple(Key),
241 std::forward_as_tuple(std::forward<Ts>(Args)...));
242 return {std::prev(Storage.end()), true};
243 }
244 return {Storage.begin() + Res.first->second, false};
245 }
246
248 auto It = Map.find(Key);
249 return It == Map.end() ? Storage.end() : Storage.begin() + It->second;
250 }
251
253 auto It = Map.find(Key);
254 return It == Map.end() ? Storage.end() : Storage.begin() + It->second;
255 }
256
257 iterator begin() { return Storage.begin(); }
258 const_iterator begin() const { return Storage.begin(); }
259 iterator end() { return Storage.end(); }
260 const_iterator end() const { return Storage.end(); }
261 size_type size() const { return Storage.size(); }
262 bool empty() const { return Storage.empty(); }
263
264 /// An owning range over the entries sorted by key, yielding each entry by
265 /// reference.
267 SortedEntriesVec Entries;
268
269 public:
271
272 explicit SortedEntriesRange(SortedEntriesVec Entries)
273 : Entries(std::move(Entries)) {}
274
275 iterator begin() const { return iterator(Entries.begin()); }
276 iterator end() const { return iterator(Entries.end()); }
277 size_t size() const { return Entries.size(); }
278 bool empty() const { return Entries.empty(); }
279 };
280
281 /// Return an owning range over the entries sorted by key. Storage is in
282 /// insertion order; some serialization paths and tests rely on key-sorted
283 /// iteration.
285 return SortedEntriesRange(getSortedEntries());
286 }
287
288private:
289 SortedEntriesVec getSortedEntries() const {
290 SortedEntriesVec Sorted;
291 Sorted.reserve(Storage.size());
292 for (const auto &E : Storage)
293 Sorted.push_back(&E);
294 llvm::sort(Sorted, [](const auto *A, const auto *B) {
295 return A->first < B->first;
296 });
297 return Sorted;
298 }
299};
300
302
303/// Struct that holds a reference to a particular GUID in a global value
304/// summary.
305struct ValueInfo {
306 enum Flags { HaveGV = 1, ReadOnly = 2, WriteOnly = 4 };
309
310 ValueInfo() = default;
312 RefAndFlags.setPointer(R);
313 RefAndFlags.setInt(HaveGVs);
314 }
315
316 explicit operator bool() const { return getRef(); }
317
318 GlobalValue::GUID getGUID() const { return getRef()->first; }
319 const GlobalValue *getValue() const {
320 assert(haveGVs());
321 return getRef()->second.U.GV;
322 }
323
325 return getRef()->second.getSummaryList();
326 }
327
328 void verifyLocal() const { getRef()->second.verifyLocal(); }
329
330 bool hasLocal() const { return getRef()->second.hasLocal(); }
331
332 // Even if the index is built with GVs available, we may not have one for
333 // summary entries synthesized for profiled indirect call targets.
334 bool hasName() const { return !haveGVs() || getValue(); }
335
336 StringRef name() const {
337 assert(!haveGVs() || getRef()->second.U.GV);
338 return haveGVs() ? getRef()->second.U.GV->getName()
339 : getRef()->second.U.Name;
340 }
341
342 bool haveGVs() const { return RefAndFlags.getInt() & HaveGV; }
343 bool isReadOnly() const {
345 return RefAndFlags.getInt() & ReadOnly;
346 }
347 bool isWriteOnly() const {
349 return RefAndFlags.getInt() & WriteOnly;
350 }
351 unsigned getAccessSpecifier() const {
353 return RefAndFlags.getInt() & (ReadOnly | WriteOnly);
354 }
356 unsigned BadAccessMask = ReadOnly | WriteOnly;
357 return (RefAndFlags.getInt() & BadAccessMask) != BadAccessMask;
358 }
359 void setReadOnly() {
360 // We expect ro/wo attribute to set only once during
361 // ValueInfo lifetime.
363 RefAndFlags.setInt(RefAndFlags.getInt() | ReadOnly);
364 }
367 RefAndFlags.setInt(RefAndFlags.getInt() | WriteOnly);
368 }
369
371 return RefAndFlags.getPointer();
372 }
373
374 /// Returns the most constraining visibility among summaries. The
375 /// visibilities, ordered from least to most constraining, are: default,
376 /// protected and hidden.
378
379 /// Checks if all summaries are DSO local (have the flag set). When DSOLocal
380 /// propagation has been done, set the parameter to enable fast check.
381 LLVM_ABI bool isDSOLocal(bool WithDSOLocalPropagation = false) const;
382
383 /// Checks if all copies are eligible for auto-hiding (have flag set).
384 LLVM_ABI bool canAutoHide() const;
385};
386
388 OS << VI.getGUID();
389 if (!VI.name().empty())
390 OS << " (" << VI.name() << ")";
391 return OS;
392}
393
394inline bool operator==(const ValueInfo &A, const ValueInfo &B) {
395 assert(A.getRef() && B.getRef() &&
396 "Need ValueInfo with non-null Ref for comparison");
397 return A.getRef() == B.getRef();
398}
399
400inline bool operator!=(const ValueInfo &A, const ValueInfo &B) {
401 assert(A.getRef() && B.getRef() &&
402 "Need ValueInfo with non-null Ref for comparison");
403 return A.getRef() != B.getRef();
404}
405
406inline bool operator<(const ValueInfo &A, const ValueInfo &B) {
407 assert(A.getRef() && B.getRef() &&
408 "Need ValueInfo with non-null Ref to compare GUIDs");
409 return A.getGUID() < B.getGUID();
410}
411
412template <> struct DenseMapInfo<ValueInfo> {
413 static bool isEqual(ValueInfo L, ValueInfo R) {
414 // We are not supposed to mix ValueInfo(s) with different HaveGVs flag
415 // in a same container.
416 assert(L.haveGVs() == R.haveGVs());
417 return L.getRef() == R.getRef();
418 }
419 static unsigned getHashValue(ValueInfo I) { return hash_value(I.getRef()); }
420};
421
422// For optional hinted size reporting, holds a pair of the full stack id
423// (pre-trimming, from the full context in the profile), and the associated
424// total profiled size.
429
430/// Summary of memprof callsite metadata.
432 // Actual callee function.
434
435 // Used to record whole program analysis cloning decisions.
436 // The ThinLTO backend will need to create as many clones as there are entries
437 // in the vector (it is expected and should be confirmed that all such
438 // summaries in the same FunctionSummary have the same number of entries).
439 // Each index records version info for the corresponding clone of this
440 // function. The value is the callee clone it calls (becomes the appended
441 // suffix id). Index 0 is the original version, and a value of 0 calls the
442 // original callee.
444
445 // Represents stack ids in this context, recorded as indices into the
446 // StackIds vector in the summary index, which in turn holds the full 64-bit
447 // stack ids. This reduces memory as there are in practice far fewer unique
448 // stack ids than stack id references.
450
457};
458
460 OS << "Callee: " << SNI.Callee;
461 OS << " Clones: " << llvm::interleaved(SNI.Clones);
462 OS << " StackIds: " << llvm::interleaved(SNI.StackIdIndices);
463 return OS;
464}
465
466// Allocation type assigned to an allocation reached by a given context.
467// More can be added, now this is cold, notcold and hot.
468// Values should be powers of two so that they can be ORed, in particular to
469// track allocations that have different behavior with different calling
470// contexts.
472 None = 0,
474 Cold = 2,
475 Hot = 4,
476 All = 7 // This should always be set to the OR of all values.
477};
478
479/// Summary of a single MIB in a memprof metadata on allocations.
480struct MIBInfo {
481 // The allocation type for this profiled context.
483
484 // Represents stack ids in this context, recorded as indices into the
485 // StackIds vector in the summary index, which in turn holds the full 64-bit
486 // stack ids. This reduces memory as there are in practice far fewer unique
487 // stack ids than stack id references.
489
492};
493
494inline raw_ostream &operator<<(raw_ostream &OS, const MIBInfo &MIB) {
495 OS << "AllocType " << (unsigned)MIB.AllocType;
496 OS << " StackIds: " << llvm::interleaved(MIB.StackIdIndices);
497 return OS;
498}
499
500/// Summary of memprof metadata on allocations.
501struct AllocInfo {
502 // Used to record whole program analysis cloning decisions.
503 // The ThinLTO backend will need to create as many clones as there are entries
504 // in the vector (it is expected and should be confirmed that all such
505 // summaries in the same FunctionSummary have the same number of entries).
506 // Each index records version info for the corresponding clone of this
507 // function. The value is the allocation type of the corresponding allocation.
508 // Index 0 is the original version. Before cloning, index 0 may have more than
509 // one allocation type.
511
512 // Vector of MIBs in this memprof metadata.
513 std::vector<MIBInfo> MIBs;
514
515 // If requested, keep track of full stack contexts and total profiled sizes
516 // for each MIB. This will be a vector of the same length and order as the
517 // MIBs vector, if non-empty. Note that each MIB in the summary can have
518 // multiple of these as we trim the contexts when possible during matching.
519 // For hinted size reporting we, however, want the original pre-trimmed full
520 // stack context id for better correlation with the profile.
521 std::vector<std::vector<ContextTotalSize>> ContextSizeInfos;
522
523 AllocInfo(std::vector<MIBInfo> MIBs) : MIBs(std::move(MIBs)) {
524 Versions.push_back(0);
525 }
528};
529
531 OS << "Versions: "
533
534 OS << " MIB:\n";
535 for (auto &M : AE.MIBs)
536 OS << "\t\t" << M << "\n";
537 if (!AE.ContextSizeInfos.empty()) {
538 OS << "\tContextSizeInfo per MIB:\n";
539 for (auto Infos : AE.ContextSizeInfos) {
540 OS << "\t\t";
541 ListSeparator InfoLS;
542 for (auto [FullStackId, TotalSize] : Infos)
543 OS << InfoLS << "{ " << FullStackId << ", " << TotalSize << " }";
544 OS << "\n";
545 }
546 }
547 return OS;
548}
549
550/// Function and variable summary information to aid decisions and
551/// implementation of importing.
553public:
554 /// Sububclass discriminator (for dyn_cast<> et al.)
556
557 enum ImportKind : unsigned {
558 // The global value definition corresponding to the summary should be
559 // imported from source module
561
562 // When its definition doesn't exist in the destination module and not
563 // imported (e.g., function is too large to be inlined), the global value
564 // declaration corresponding to the summary should be imported, or the
565 // attributes from summary should be annotated on the function declaration.
567 };
568
569 /// Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
570 struct GVFlags {
571 /// The linkage type of the associated global value.
572 ///
573 /// One use is to flag values that have local linkage types and need to
574 /// have module identifier appended before placing into the combined
575 /// index, to disambiguate from other values with the same name.
576 /// In the future this will be used to update and optimize linkage
577 /// types based on global summary-based analysis.
578 unsigned Linkage : 4;
579
580 /// Indicates the visibility.
581 unsigned Visibility : 2;
582
583 /// Indicate if the global value cannot be imported (e.g. it cannot
584 /// be renamed or references something that can't be renamed).
586
587 /// In per-module summary, indicate that the global value must be considered
588 /// a live root for index-based liveness analysis. Used for special LLVM
589 /// values such as llvm.global_ctors that the linker does not know about.
590 ///
591 /// In combined summary, indicate that the global value is live.
592 unsigned Live : 1;
593
594 /// Indicates that the linker resolved the symbol to a definition from
595 /// within the same linkage unit.
596 unsigned DSOLocal : 1;
597
598 /// In the per-module summary, indicates that the global value is
599 /// linkonce_odr and global unnamed addr (so eligible for auto-hiding
600 /// via hidden visibility). In the combined summary, indicates that the
601 /// prevailing linkonce_odr copy can be auto-hidden via hidden visibility
602 /// when it is upgraded to weak_odr in the backend. This is legal when
603 /// all copies are eligible for auto-hiding (i.e. all copies were
604 /// linkonce_odr global unnamed addr. If any copy is not (e.g. it was
605 /// originally weak_odr, we cannot auto-hide the prevailing copy as it
606 /// means the symbol was externally visible.
607 unsigned CanAutoHide : 1;
608
609 /// This field is written by the ThinLTO indexing step to postlink combined
610 /// summary. The value is interpreted as 'ImportKind' enum defined above.
611 unsigned ImportType : 1;
612
613 /// This symbol was promoted. Thinlink stages need to be aware of this
614 /// transition
615 unsigned Promoted : 1;
616
617 /// This field is written by the ThinLTO prelink stage to decide whether
618 /// a particular static global value should be promoted or not.
620
621 /// Convenience Constructors
632 };
633
634private:
635 /// Kind of summary for use in dyn_cast<> et al.
636 SummaryKind Kind;
637
638 GVFlags Flags;
639
640 /// This is the hash of the name of the symbol in the original file. It is
641 /// identical to the GUID for global symbols, but differs for local since the
642 /// GUID includes the module level id in the hash.
643 GlobalValue::GUID OriginalName = 0;
644
645 /// Path of module IR containing value's definition, used to locate
646 /// module during importing.
647 ///
648 /// This is only used during parsing of the combined index, or when
649 /// parsing the per-module index for creation of the combined summary index,
650 /// not during writing of the per-module index which doesn't contain a
651 /// module path string table.
652 StringRef ModulePath;
653
654 /// List of values referenced by this global value's definition
655 /// (either by the initializer of a global variable, or referenced
656 /// from within a function). This does not include functions called, which
657 /// are listed in the derived FunctionSummary object.
658 /// We use SmallVector<ValueInfo, 0> instead of std::vector<ValueInfo> for its
659 /// smaller memory footprint.
660 SmallVector<ValueInfo, 0> RefEdgeList;
661
662protected:
665 : Kind(K), Flags(Flags), RefEdgeList(std::move(Refs)) {
666 assert((K != AliasKind || Refs.empty()) &&
667 "Expect no references for AliasSummary");
668 }
669
670public:
671 virtual ~GlobalValueSummary() = default;
672
673 /// Returns the hash of the original name, it is identical to the GUID for
674 /// externally visible symbols, but not for local ones.
675 GlobalValue::GUID getOriginalName() const { return OriginalName; }
676
677 /// Initialize the original name hash in this summary.
678 void setOriginalName(GlobalValue::GUID Name) { OriginalName = Name; }
679
680 /// Which kind of summary subclass this is.
681 SummaryKind getSummaryKind() const { return Kind; }
682
683 /// Set the path to the module containing this function, for use in
684 /// the combined index.
685 void setModulePath(StringRef ModPath) { ModulePath = ModPath; }
686
687 /// Get the path to the module containing this function.
688 StringRef modulePath() const { return ModulePath; }
689
690 /// Get the flags for this GlobalValue (see \p struct GVFlags).
691 GVFlags flags() const { return Flags; }
692
693 /// Return linkage type recorded for this global value.
695 return static_cast<GlobalValue::LinkageTypes>(Flags.Linkage);
696 }
697
698 bool wasPromoted() const { return Flags.Promoted; }
699
700 void promote() {
702 "unexpected (re-)promotion of non-local symbol");
703 assert(!Flags.Promoted);
704 Flags.Promoted = true;
706 }
707
708 /// Sets the linkage to the value determined by global summary-based
709 /// optimization. Will be applied in the ThinLTO backends.
712 assert(!GlobalValue::isExternalLinkage(Linkage) && "use `promote` instead");
713 Flags.Linkage = Linkage;
714 }
715
719
720 /// Return true if this global value can't be imported.
721 bool notEligibleToImport() const { return Flags.NotEligibleToImport; }
722
723 bool isLive() const { return Flags.Live; }
724
725 void setLive(bool Live) { Flags.Live = Live; }
726
727 void setDSOLocal(bool Local) { Flags.DSOLocal = Local; }
728
729 bool isDSOLocal() const { return Flags.DSOLocal; }
730
731 void setCanAutoHide(bool CanAutoHide) { Flags.CanAutoHide = CanAutoHide; }
732
733 bool canAutoHide() const { return Flags.CanAutoHide; }
734
735 bool shouldImportAsDecl() const {
736 return Flags.ImportType == GlobalValueSummary::ImportKind::Declaration;
737 }
738
739 void setImportKind(ImportKind IK) { Flags.ImportType = IK; }
740
741 void setNoRenameOnPromotion(bool NoRenameOnPromotion) {
742 Flags.NoRenameOnPromotion = NoRenameOnPromotion;
743 }
744
745 bool noRenameOnPromotion() const { return Flags.NoRenameOnPromotion; }
746
748 return static_cast<ImportKind>(Flags.ImportType);
749 }
750
752 return (GlobalValue::VisibilityTypes)Flags.Visibility;
753 }
755 Flags.Visibility = (unsigned)Vis;
756 }
757
758 /// Flag that this global value cannot be imported.
759 void setNotEligibleToImport() { Flags.NotEligibleToImport = true; }
760
761 /// Return the list of values referenced by this global value definition.
762 ArrayRef<ValueInfo> refs() const { return RefEdgeList; }
763
764 /// If this is an alias summary, returns the summary of the aliased object (a
765 /// global variable or function), otherwise returns itself.
767 const GlobalValueSummary *getBaseObject() const;
768
769 friend class ModuleSummaryIndex;
770};
771
773 : U(HaveGVs), HasLocal(false) {}
774
776 std::unique_ptr<GlobalValueSummary> Summary) {
777 if (GlobalValue::isLocalLinkage(Summary->linkage()))
778 HasLocal = true;
779 return SummaryList.push_back(std::move(Summary));
780}
781
783 assert(HasLocal ==
784 llvm::any_of(SummaryList,
785 [](const std::unique_ptr<GlobalValueSummary> &Summary) {
786 return GlobalValue::isLocalLinkage(Summary->linkage());
787 }));
788}
789
790/// Alias summary information.
792 ValueInfo AliaseeValueInfo;
793
794 /// This is the Aliasee in the same module as alias (could get from VI, trades
795 /// memory for time). Note that this pointer may be null (and the value info
796 /// empty) when we have a distributed index where the alias is being imported
797 /// (as a copy of the aliasee), but the aliasee is not.
798 GlobalValueSummary *AliaseeSummary = nullptr;
799
800public:
803
804 /// Check if this is an alias summary.
805 static bool classof(const GlobalValueSummary *GVS) {
806 return GVS->getSummaryKind() == AliasKind;
807 }
808
809 void setAliasee(ValueInfo &AliaseeVI, GlobalValueSummary *Aliasee) {
810 AliaseeValueInfo = AliaseeVI;
811 AliaseeSummary = Aliasee;
812 }
813
814 bool hasAliasee() const {
815 assert(!!AliaseeSummary == (AliaseeValueInfo &&
816 !AliaseeValueInfo.getSummaryList().empty()) &&
817 "Expect to have both aliasee summary and summary list or neither");
818 return !!AliaseeSummary;
819 }
820
822 assert(AliaseeSummary && "Unexpected missing aliasee summary");
823 return *AliaseeSummary;
824 }
825
827 return const_cast<GlobalValueSummary &>(
828 static_cast<const AliasSummary *>(this)->getAliasee());
829 }
831 assert(AliaseeValueInfo && "Unexpected missing aliasee");
832 return AliaseeValueInfo;
833 }
835 assert(AliaseeValueInfo && "Unexpected missing aliasee");
836 return AliaseeValueInfo.getGUID();
837 }
838};
839
841 if (auto *AS = dyn_cast<AliasSummary>(this))
842 return &AS->getAliasee();
843 return this;
844}
845
847 if (auto *AS = dyn_cast<AliasSummary>(this))
848 return &AS->getAliasee();
849 return this;
850}
851
852/// Function summary information to aid decisions and implementation of
853/// importing.
855public:
856 /// <CalleeValueInfo, CalleeInfo> call edge pair.
857 using EdgeTy = std::pair<ValueInfo, CalleeInfo>;
858
859 /// Types for -force-summary-edges-cold debugging option.
865
866 /// An "identifier" for a virtual function. This contains the type identifier
867 /// represented as a GUID and the offset from the address point to the virtual
868 /// function pointer, where "address point" is as defined in the Itanium ABI:
869 /// https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vtable-general
874
875 /// A specification for a virtual function call with all constant integer
876 /// arguments. This is used to perform virtual constant propagation on the
877 /// summary.
878 struct ConstVCall {
880 std::vector<uint64_t> Args;
881 };
882
883 /// All type identifier related information. Because these fields are
884 /// relatively uncommon we only allocate space for them if necessary.
885 struct TypeIdInfo {
886 /// List of type identifiers used by this function in llvm.type.test
887 /// intrinsics referenced by something other than an llvm.assume intrinsic,
888 /// represented as GUIDs.
889 std::vector<GlobalValue::GUID> TypeTests;
890
891 /// List of virtual calls made by this function using (respectively)
892 /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics that do
893 /// not have all constant integer arguments.
895
896 /// List of virtual calls made by this function using (respectively)
897 /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics with
898 /// all constant integer arguments.
899 std::vector<ConstVCall> TypeTestAssumeConstVCalls,
901 };
902
903 /// Flags specific to function summaries.
904 struct FFlags {
905 // Function attribute flags. Used to track if a function accesses memory,
906 // recurses or aliases.
907 unsigned ReadNone : 1;
908 unsigned ReadOnly : 1;
909 unsigned NoRecurse : 1;
910 unsigned ReturnDoesNotAlias : 1;
911
912 // Indicate if the global value cannot be inlined.
913 unsigned NoInline : 1;
914 // Indicate if function should be always inlined.
915 unsigned AlwaysInline : 1;
916 // Indicate if function never raises an exception. Can be modified during
917 // thinlink function attribute propagation
918 unsigned NoUnwind : 1;
919 // Indicate if function contains instructions that mayThrow
920 unsigned MayThrow : 1;
921
922 // If there are calls to unknown targets (e.g. indirect)
923 unsigned HasUnknownCall : 1;
924
925 // Indicate if a function must be an unreachable function.
926 //
927 // This bit is sufficient but not necessary;
928 // if this bit is on, the function must be regarded as unreachable;
929 // if this bit is off, the function might be reachable or unreachable.
930 unsigned MustBeUnreachable : 1;
931
933 this->ReadNone &= RHS.ReadNone;
934 this->ReadOnly &= RHS.ReadOnly;
935 this->NoRecurse &= RHS.NoRecurse;
936 this->ReturnDoesNotAlias &= RHS.ReturnDoesNotAlias;
937 this->NoInline &= RHS.NoInline;
938 this->AlwaysInline &= RHS.AlwaysInline;
939 this->NoUnwind &= RHS.NoUnwind;
940 this->MayThrow &= RHS.MayThrow;
941 this->HasUnknownCall &= RHS.HasUnknownCall;
942 this->MustBeUnreachable &= RHS.MustBeUnreachable;
943 return *this;
944 }
945
946 bool anyFlagSet() {
947 return this->ReadNone | this->ReadOnly | this->NoRecurse |
948 this->ReturnDoesNotAlias | this->NoInline | this->AlwaysInline |
949 this->NoUnwind | this->MayThrow | this->HasUnknownCall |
950 this->MustBeUnreachable;
951 }
952
953 operator std::string() {
954 std::string Output;
955 raw_string_ostream OS(Output);
956 OS << "funcFlags: (";
957 OS << "readNone: " << this->ReadNone;
958 OS << ", readOnly: " << this->ReadOnly;
959 OS << ", noRecurse: " << this->NoRecurse;
960 OS << ", returnDoesNotAlias: " << this->ReturnDoesNotAlias;
961 OS << ", noInline: " << this->NoInline;
962 OS << ", alwaysInline: " << this->AlwaysInline;
963 OS << ", noUnwind: " << this->NoUnwind;
964 OS << ", mayThrow: " << this->MayThrow;
965 OS << ", hasUnknownCall: " << this->HasUnknownCall;
966 OS << ", mustBeUnreachable: " << this->MustBeUnreachable;
967 OS << ")";
968 return Output;
969 }
970 };
971
972 /// Describes the uses of a parameter by the function.
973 struct ParamAccess {
974 static constexpr uint32_t RangeWidth = 64;
975
976 /// Describes the use of a value in a call instruction, specifying the
977 /// call's target, the value's parameter number, and the possible range of
978 /// offsets from the beginning of the value that are passed.
988
990 /// The range contains byte offsets from the parameter pointer which
991 /// accessed by the function. In the per-module summary, it only includes
992 /// accesses made by the function instructions. In the combined summary, it
993 /// also includes accesses by nested function calls.
994 ConstantRange Use{/*BitWidth=*/RangeWidth, /*isFullSet=*/true};
995 /// In the per-module summary, it summarizes the byte offset applied to each
996 /// pointer parameter before passing to each corresponding callee.
997 /// In the combined summary, it's empty and information is propagated by
998 /// inter-procedural analysis and applied to the Use field.
999 std::vector<Call> Calls;
1000
1001 ParamAccess() = default;
1004 };
1005
1006 /// Create an empty FunctionSummary (with specified call edges).
1007 /// Used to represent external nodes and the dummy root node.
1008 static FunctionSummary
1010 return FunctionSummary(
1014 /*NotEligibleToImport=*/true, /*Live=*/true, /*IsLocal=*/false,
1015 /*CanAutoHide=*/false, GlobalValueSummary::ImportKind::Definition,
1016 /*NoRenameOnPromotion=*/false),
1018 std::move(Edges), std::vector<GlobalValue::GUID>(),
1019 std::vector<FunctionSummary::VFuncId>(),
1020 std::vector<FunctionSummary::VFuncId>(),
1021 std::vector<FunctionSummary::ConstVCall>(),
1022 std::vector<FunctionSummary::ConstVCall>(),
1023 std::vector<FunctionSummary::ParamAccess>(),
1024 std::vector<CallsiteInfo>(), std::vector<AllocInfo>());
1025 }
1026
1027 /// A dummy node to reference external functions that aren't in the index
1029
1030private:
1031 /// Number of instructions (ignoring debug instructions, e.g.) computed
1032 /// during the initial compile step when the summary index is first built.
1033 unsigned InstCount;
1034
1035 /// Function summary specific flags.
1036 FFlags FunFlags;
1037
1038 /// List of <CalleeValueInfo, CalleeInfo> call edge pairs from this function.
1039 /// We use SmallVector<ValueInfo, 0> instead of std::vector<ValueInfo> for its
1040 /// smaller memory footprint.
1041 SmallVector<EdgeTy, 0> CallGraphEdgeList;
1042
1043 std::unique_ptr<TypeIdInfo> TIdInfo;
1044
1045 /// Uses for every parameter to this function.
1046 using ParamAccessesTy = std::vector<ParamAccess>;
1047 std::unique_ptr<ParamAccessesTy> ParamAccesses;
1048
1049 /// Optional list of memprof callsite metadata summaries. The correspondence
1050 /// between the callsite summary and the callsites in the function is implied
1051 /// by the order in the vector (and can be validated by comparing the stack
1052 /// ids in the CallsiteInfo to those in the instruction callsite metadata).
1053 /// As a memory savings optimization, we only create these for the prevailing
1054 /// copy of a symbol when creating the combined index during LTO.
1055 using CallsitesTy = std::vector<CallsiteInfo>;
1056 std::unique_ptr<CallsitesTy> Callsites;
1057
1058 /// Optional list of allocation memprof metadata summaries. The correspondence
1059 /// between the alloc memprof summary and the allocation callsites in the
1060 /// function is implied by the order in the vector (and can be validated by
1061 /// comparing the stack ids in the AllocInfo to those in the instruction
1062 /// memprof metadata).
1063 /// As a memory savings optimization, we only create these for the prevailing
1064 /// copy of a symbol when creating the combined index during LTO.
1065 using AllocsTy = std::vector<AllocInfo>;
1066 std::unique_ptr<AllocsTy> Allocs;
1067
1068public:
1069 FunctionSummary(GVFlags Flags, unsigned NumInsts, FFlags FunFlags,
1071 SmallVectorImpl<EdgeTy> &&CGEdges,
1072 std::vector<GlobalValue::GUID> TypeTests,
1073 std::vector<VFuncId> TypeTestAssumeVCalls,
1074 std::vector<VFuncId> TypeCheckedLoadVCalls,
1075 std::vector<ConstVCall> TypeTestAssumeConstVCalls,
1076 std::vector<ConstVCall> TypeCheckedLoadConstVCalls,
1077 std::vector<ParamAccess> Params, CallsitesTy CallsiteList,
1078 AllocsTy AllocList)
1079 : GlobalValueSummary(FunctionKind, Flags, std::move(Refs)),
1080 InstCount(NumInsts), FunFlags(FunFlags),
1081 CallGraphEdgeList(std::move(CGEdges)) {
1082 if (!TypeTests.empty() || !TypeTestAssumeVCalls.empty() ||
1083 !TypeCheckedLoadVCalls.empty() || !TypeTestAssumeConstVCalls.empty() ||
1084 !TypeCheckedLoadConstVCalls.empty())
1085 TIdInfo = std::make_unique<TypeIdInfo>(
1086 TypeIdInfo{std::move(TypeTests), std::move(TypeTestAssumeVCalls),
1087 std::move(TypeCheckedLoadVCalls),
1088 std::move(TypeTestAssumeConstVCalls),
1089 std::move(TypeCheckedLoadConstVCalls)});
1090 if (!Params.empty())
1091 ParamAccesses = std::make_unique<ParamAccessesTy>(std::move(Params));
1092 if (!CallsiteList.empty())
1093 Callsites = std::make_unique<CallsitesTy>(std::move(CallsiteList));
1094 if (!AllocList.empty())
1095 Allocs = std::make_unique<AllocsTy>(std::move(AllocList));
1096 }
1097 // Gets the number of readonly and writeonly refs in RefEdgeList
1098 LLVM_ABI std::pair<unsigned, unsigned> specialRefCounts() const;
1099
1100 /// Check if this is a function summary.
1101 static bool classof(const GlobalValueSummary *GVS) {
1102 return GVS->getSummaryKind() == FunctionKind;
1103 }
1104
1105 /// Get function summary flags.
1106 FFlags fflags() const { return FunFlags; }
1107
1108 void setNoRecurse() { FunFlags.NoRecurse = true; }
1109
1110 void setNoUnwind() { FunFlags.NoUnwind = true; }
1111
1112 /// Get the instruction count recorded for this function.
1113 unsigned instCount() const { return InstCount; }
1114
1115 /// Return the list of <CalleeValueInfo, CalleeInfo> pairs.
1116 ArrayRef<EdgeTy> calls() const { return CallGraphEdgeList; }
1117
1118 SmallVector<EdgeTy, 0> &mutableCalls() { return CallGraphEdgeList; }
1119
1120 void addCall(EdgeTy E) { CallGraphEdgeList.push_back(E); }
1121
1122 /// Returns the list of type identifiers used by this function in
1123 /// llvm.type.test intrinsics other than by an llvm.assume intrinsic,
1124 /// represented as GUIDs.
1126 if (TIdInfo)
1127 return TIdInfo->TypeTests;
1128 return {};
1129 }
1130
1131 /// Returns the list of virtual calls made by this function using
1132 /// llvm.assume(llvm.type.test) intrinsics that do not have all constant
1133 /// integer arguments.
1135 if (TIdInfo)
1136 return TIdInfo->TypeTestAssumeVCalls;
1137 return {};
1138 }
1139
1140 /// Returns the list of virtual calls made by this function using
1141 /// llvm.type.checked.load intrinsics that do not have all constant integer
1142 /// arguments.
1144 if (TIdInfo)
1145 return TIdInfo->TypeCheckedLoadVCalls;
1146 return {};
1147 }
1148
1149 /// Returns the list of virtual calls made by this function using
1150 /// llvm.assume(llvm.type.test) intrinsics with all constant integer
1151 /// arguments.
1153 if (TIdInfo)
1154 return TIdInfo->TypeTestAssumeConstVCalls;
1155 return {};
1156 }
1157
1158 /// Returns the list of virtual calls made by this function using
1159 /// llvm.type.checked.load intrinsics with all constant integer arguments.
1161 if (TIdInfo)
1162 return TIdInfo->TypeCheckedLoadConstVCalls;
1163 return {};
1164 }
1165
1166 /// Returns the list of known uses of pointer parameters.
1168 if (ParamAccesses)
1169 return *ParamAccesses;
1170 return {};
1171 }
1172
1173 /// Sets the list of known uses of pointer parameters.
1174 void setParamAccesses(std::vector<ParamAccess> NewParams) {
1175 if (NewParams.empty())
1176 ParamAccesses.reset();
1177 else if (ParamAccesses)
1178 *ParamAccesses = std::move(NewParams);
1179 else
1180 ParamAccesses = std::make_unique<ParamAccessesTy>(std::move(NewParams));
1181 }
1182
1183 /// Add a type test to the summary. This is used by WholeProgramDevirt if we
1184 /// were unable to devirtualize a checked call.
1186 if (!TIdInfo)
1187 TIdInfo = std::make_unique<TypeIdInfo>();
1188 TIdInfo->TypeTests.push_back(Guid);
1189 }
1190
1191 const TypeIdInfo *getTypeIdInfo() const { return TIdInfo.get(); };
1192
1194 if (Callsites)
1195 return *Callsites;
1196 return {};
1197 }
1198
1199 CallsitesTy &mutableCallsites() {
1200 assert(Callsites);
1201 return *Callsites;
1202 }
1203
1204 void addCallsite(CallsiteInfo &&Callsite) {
1205 if (!Callsites)
1206 Callsites = std::make_unique<CallsitesTy>();
1207 Callsites->push_back(std::move(Callsite));
1208 }
1209
1211 if (Allocs)
1212 return *Allocs;
1213 return {};
1214 }
1215
1217 if (!Allocs)
1218 Allocs = std::make_unique<AllocsTy>();
1219 Allocs->push_back(std::move(Alloc));
1220 }
1221
1222 AllocsTy &mutableAllocs() {
1223 assert(Allocs);
1224 return *Allocs;
1225 }
1226
1227 friend struct GraphTraits<ValueInfo>;
1228};
1229
1230template <> struct DenseMapInfo<FunctionSummary::VFuncId> {
1232 return L.GUID == R.GUID && L.Offset == R.Offset;
1233 }
1234
1235 static unsigned getHashValue(FunctionSummary::VFuncId I) { return I.GUID; }
1236};
1237
1238template <> struct DenseMapInfo<FunctionSummary::ConstVCall> {
1241 return DenseMapInfo<FunctionSummary::VFuncId>::isEqual(L.VFunc, R.VFunc) &&
1242 L.Args == R.Args;
1243 }
1244
1246 return I.VFunc.GUID;
1247 }
1248};
1249
1250/// The ValueInfo and offset for a function within a vtable definition
1251/// initializer array.
1259/// List of functions referenced by a particular vtable definition.
1260using VTableFuncList = std::vector<VirtFuncOffset>;
1261
1262/// Global variable summary information to aid decisions and
1263/// implementation of importing.
1264///
1265/// Global variable summary has two extra flag, telling if it is
1266/// readonly or writeonly. Both readonly and writeonly variables
1267/// can be optimized in the backed: readonly variables can be
1268/// const-folded, while writeonly vars can be completely eliminated
1269/// together with corresponding stores. We let both things happen
1270/// by means of internalizing such variables after ThinLTO import.
1272private:
1273 /// For vtable definitions this holds the list of functions and
1274 /// their corresponding offsets within the initializer array.
1275 std::unique_ptr<VTableFuncList> VTableFuncs;
1276
1277public:
1278 struct GVarFlags {
1279 GVarFlags(bool ReadOnly, bool WriteOnly, bool Constant,
1281 : MaybeReadOnly(ReadOnly), MaybeWriteOnly(WriteOnly),
1283
1284 // If true indicates that this global variable might be accessed
1285 // purely by non-volatile load instructions. This in turn means
1286 // it can be internalized in source and destination modules during
1287 // thin LTO import because it neither modified nor its address
1288 // is taken.
1289 unsigned MaybeReadOnly : 1;
1290 // If true indicates that variable is possibly only written to, so
1291 // its value isn't loaded and its address isn't taken anywhere.
1292 // False, when 'Constant' attribute is set.
1293 unsigned MaybeWriteOnly : 1;
1294 // Indicates that value is a compile-time constant. Global variable
1295 // can be 'Constant' while not being 'ReadOnly' on several occasions:
1296 // - it is volatile, (e.g mapped device address)
1297 // - its address is taken, meaning that unlike 'ReadOnly' vars we can't
1298 // internalize it.
1299 // Constant variables are always imported thus giving compiler an
1300 // opportunity to make some extra optimizations. Readonly constants
1301 // are also internalized.
1302 unsigned Constant : 1;
1303 // Set from metadata on vtable definitions during the module summary
1304 // analysis.
1305 unsigned VCallVisibility : 2;
1307
1312
1313 /// Check if this is a global variable summary.
1314 static bool classof(const GlobalValueSummary *GVS) {
1315 return GVS->getSummaryKind() == GlobalVarKind;
1316 }
1317
1318 GVarFlags varflags() const { return VarFlags; }
1319 void setReadOnly(bool RO) { VarFlags.MaybeReadOnly = RO; }
1320 void setWriteOnly(bool WO) { VarFlags.MaybeWriteOnly = WO; }
1321 bool maybeReadOnly() const { return VarFlags.MaybeReadOnly; }
1322 bool maybeWriteOnly() const { return VarFlags.MaybeWriteOnly; }
1323 bool isConstant() const { return VarFlags.Constant; }
1325 VarFlags.VCallVisibility = Vis;
1326 }
1330
1332 assert(!VTableFuncs);
1333 VTableFuncs = std::make_unique<VTableFuncList>(std::move(Funcs));
1334 }
1335
1337 if (VTableFuncs)
1338 return *VTableFuncs;
1339 return {};
1340 }
1341};
1342
1344 /// Specifies which kind of type check we should emit for this byte array.
1345 /// See http://clang.llvm.org/docs/ControlFlowIntegrityDesign.html for full
1346 /// details on each kind of check; the enumerators are described with
1347 /// reference to that document.
1348 enum Kind {
1349 Unsat, ///< Unsatisfiable type (i.e. no global has this type metadata)
1350 ByteArray, ///< Test a byte array (first example)
1351 Inline, ///< Inlined bit vector ("Short Inline Bit Vectors")
1352 Single, ///< Single element (last example in "Short Inline Bit Vectors")
1353 AllOnes, ///< All-ones bit vector ("Eliminating Bit Vector Checks for
1354 /// All-Ones Bit Vectors")
1355 Unknown, ///< Unknown (analysis not performed, don't lower)
1357
1358 /// Range of size-1 expressed as a bit width. For example, if the size is in
1359 /// range [1,256], this number will be 8. This helps generate the most compact
1360 /// instruction sequences.
1361 unsigned SizeM1BitWidth = 0;
1362
1363 // The following fields are only used if the target does not support the use
1364 // of absolute symbols to store constants. Their meanings are the same as the
1365 // corresponding fields in LowerTypeTestsModule::TypeIdLowering in
1366 // LowerTypeTests.cpp.
1367
1372};
1373
1375 enum Kind {
1376 Indir, ///< Just do a regular virtual call
1377 SingleImpl, ///< Single implementation devirtualization
1378 BranchFunnel, ///< When retpoline mitigation is enabled, use a branch funnel
1379 ///< that is defined in the merged module. Otherwise same as
1380 ///< Indir.
1382
1383 std::string SingleImplName;
1384
1385 struct ByArg {
1386 enum Kind {
1387 Indir, ///< Just do a regular virtual call
1388 UniformRetVal, ///< Uniform return value optimization
1389 UniqueRetVal, ///< Unique return value optimization
1390 VirtualConstProp, ///< Virtual constant propagation
1392
1393 /// Additional information for the resolution:
1394 /// - UniformRetVal: the uniform return value.
1395 /// - UniqueRetVal: the return value associated with the unique vtable (0 or
1396 /// 1).
1398
1399 // The following fields are only used if the target does not support the use
1400 // of absolute symbols to store constants.
1401
1404 };
1405
1406 /// Resolutions for calls with all constant integer arguments (excluding the
1407 /// first argument, "this"), where the key is the argument vector.
1408 std::map<std::vector<uint64_t>, ByArg> ResByArg;
1409};
1410
1413
1414 /// Mapping from byte offset to whole-program devirt resolution for that
1415 /// (typeid, byte offset) pair.
1416 std::map<uint64_t, WholeProgramDevirtResolution> WPDRes;
1417};
1418
1419/// Encapsulate the names of CFI target functions. It interfaces with ThinLTO to
1420/// determine efficiently which of the names need to be exported for a
1421/// particular module.
1423 // `Names` is the authoritative source of data. `ThinLTOToNamesIndex` is there
1424 // just to efficiently retrieve which names in this index need exporting for
1425 // a particular module index. We cannot guarantee the ThinLTO GUIDs are
1426 // collision - free, so we associate a collection to a guid. Functions with
1427 // the same name may have different GUIDs, too. So we index a list of names
1428 // with the same GUID under that GUID key. We don't need the reverse because
1429 // the queries from ThinLTO use GUIDs as key.
1430 // Note that StringSet rehashing doesn't move keys, so we can safely store the
1431 // StringRef value inserted in `Names` in ThinLTOToNamesIndex, and avoid
1432 // copies.
1433 // Design note: we could do away with Names and use ThinLTOToNamesIndex as
1434 // index and data source, but opted against, for a small heap penalty, to
1435 // avoid confusion wrt the role GUIDs play in this case: they are an artifact
1436 // of the need to interface with ThinLTO, not otherwise necessary to CFI.
1437 StringSet<> Names;
1438
1439 using InternalIndexGroup = SetVector<StringRef>;
1441
1442 using NestedIterator = InternalIndexGroup::const_iterator;
1443
1444public:
1445 CfiFunctionIndex() = default;
1448
1449 /// API used for serialization, e.g. YAML.
1450 std::vector<std::pair<StringRef, GlobalValue::GUID>>
1452 std::vector<std::pair<StringRef, GlobalValue::GUID>> Symbols;
1453 for (auto &[GUID, Names] : ThinLTOToNamesIndex)
1454 for (auto Name : Names)
1455 Symbols.emplace_back(Name, GUID);
1456 llvm::sort(Symbols);
1457 return Symbols;
1458 }
1459
1460 /// get the set of GUIDs that should also be exported because they are the
1461 /// GUIDs of the cfi functions encapsulated here.
1463 return map_range(ThinLTOToNamesIndex, [](auto I) { return I.first; });
1464 }
1465
1466 /// get the name(s) associated with a given ThinLTO GUID. This enables
1467 /// efficient identification of the subset of names that should be included in
1468 /// a module summary.
1470 auto I = ThinLTOToNamesIndex.find(GUID);
1471 if (I == ThinLTOToNamesIndex.end())
1472 return make_range(NestedIterator{}, NestedIterator{});
1473 return make_range(I->second.begin(), I->second.end());
1474 }
1475
1476 /// Add the function name and the GUID that ThinLTO uses for it.
1478 auto [Iter, _] = Names.insert(Name);
1479 ThinLTOToNamesIndex[GUID].insert(Iter->first());
1480 }
1481
1482 bool contains(StringRef Name) const {
1483 return Names.find(Name) != Names.end();
1484 }
1485
1486 bool empty() const {
1487 assert(Names.empty() == ThinLTOToNamesIndex.empty());
1488 return Names.empty();
1489 }
1490};
1491
1492/// 160 bits SHA1
1493using ModuleHash = std::array<uint32_t, 5>;
1494
1495/// Type used for iterating through the global value summary map.
1498
1499/// String table to hold/own module path strings, as well as a hash
1500/// of the module. The StringMap makes a copy of and owns inserted strings.
1502
1503/// Map of global value GUID to its summary, used to identify values defined in
1504/// a particular module, and provide efficient access to their summary.
1506
1507/// Map of a module name to the GUIDs and summaries we will import from that
1508/// module.
1510 std::map<std::string, GVSummaryMapTy, std::less<>>;
1511
1512/// A set of global value summary pointers.
1514
1515/// Map of a type GUID to type id string and summary (multimap used
1516/// in case of GUID conflicts).
1518 std::multimap<GlobalValue::GUID, std::pair<StringRef, TypeIdSummary>>;
1519
1520/// The following data structures summarize type metadata information.
1521/// For type metadata overview see https://llvm.org/docs/TypeMetadata.html.
1522/// Each type metadata includes both the type identifier and the offset of
1523/// the address point of the type (the address held by objects of that type
1524/// which may not be the beginning of the virtual table). Vtable definitions
1525/// are decorated with type metadata for the types they are compatible with.
1526///
1527/// Holds information about vtable definitions decorated with type metadata:
1528/// the vtable definition value and its address point offset in a type
1529/// identifier metadata it is decorated (compatible) with.
1537/// List of vtable definitions decorated by a particular type identifier,
1538/// and their corresponding offsets in that type identifier's metadata.
1539/// Note that each type identifier may be compatible with multiple vtables, due
1540/// to inheritance, which is why this is a vector.
1541using TypeIdCompatibleVtableInfo = std::vector<TypeIdOffsetVtableInfo>;
1542
1543/// Class to hold module path string table and global value map,
1544/// and encapsulate methods for operating on them.
1546private:
1547 /// Map from value name to list of summary instances for values of that
1548 /// name (may be duplicates in the COMDAT case, e.g.).
1549 GlobalValueSummaryMapTy GlobalValueMap;
1550
1551 /// Holds strings for combined index, mapping to the corresponding module ID.
1552 ModulePathStringTableTy ModulePathStringTable;
1553
1554 BumpPtrAllocator TypeIdSaverAlloc;
1555 UniqueStringSaver TypeIdSaver;
1556
1557 /// Mapping from type identifier GUIDs to type identifier and its summary
1558 /// information. Produced by thin link.
1559 TypeIdSummaryMapTy TypeIdMap;
1560
1561 /// Mapping from type identifier to information about vtables decorated
1562 /// with that type identifier's metadata. Produced by per module summary
1563 /// analysis and consumed by thin link. For more information, see description
1564 /// above where TypeIdCompatibleVtableInfo is defined.
1565 std::map<StringRef, TypeIdCompatibleVtableInfo, std::less<>>
1566 TypeIdCompatibleVtableMap;
1567
1568 /// Mapping from original ID to GUID. If original ID can map to multiple
1569 /// GUIDs, it will be mapped to 0.
1571
1572 /// Indicates that summary-based GlobalValue GC has run, and values with
1573 /// GVFlags::Live==false are really dead. Otherwise, all values must be
1574 /// considered live.
1575 bool WithGlobalValueDeadStripping = false;
1576
1577 /// Indicates that summary-based attribute propagation has run and
1578 /// GVarFlags::MaybeReadonly / GVarFlags::MaybeWriteonly are really
1579 /// read/write only.
1580 bool WithAttributePropagation = false;
1581
1582 /// Indicates that summary-based DSOLocal propagation has run and the flag in
1583 /// every summary of a GV is synchronized.
1584 bool WithDSOLocalPropagation = false;
1585
1586 /// Indicates that summary-based internalization and promotion has run.
1587 bool WithInternalizeAndPromote = false;
1588
1589 /// Indicates that we have whole program visibility.
1590 bool WithWholeProgramVisibility = false;
1591
1592 /// Indicates that summary-based synthetic entry count propagation has run
1593 bool HasSyntheticEntryCounts = false;
1594
1595 /// Indicates that we linked with allocator supporting hot/cold new operators.
1596 bool WithSupportsHotColdNew = false;
1597
1598 /// Indicates that distributed backend should skip compilation of the
1599 /// module. Flag is suppose to be set by distributed ThinLTO indexing
1600 /// when it detected that the module is not needed during the final
1601 /// linking. As result distributed backend should just output a minimal
1602 /// valid object file.
1603 bool SkipModuleByDistributedBackend = false;
1604
1605 /// If true then we're performing analysis of IR module, or parsing along with
1606 /// the IR from assembly. The value of 'false' means we're reading summary
1607 /// from BC or YAML source. Affects the type of value stored in NameOrGV
1608 /// union.
1609 bool HaveGVs;
1610
1611 // True if the index was created for a module compiled with -fsplit-lto-unit.
1612 bool EnableSplitLTOUnit;
1613
1614 // True if the index was created for a module compiled with -funified-lto
1615 bool UnifiedLTO;
1616
1617 // True if some of the modules were compiled with -fsplit-lto-unit and
1618 // some were not. Set when the combined index is created during the thin link.
1619 bool PartiallySplitLTOUnits = false;
1620
1621 /// True if some of the FunctionSummary contains a ParamAccess.
1622 bool HasParamAccess = false;
1623
1624 CfiFunctionIndex CfiFunctionDefs;
1625 CfiFunctionIndex CfiFunctionDecls;
1626
1627 // Used in cases where we want to record the name of a global, but
1628 // don't have the string owned elsewhere (e.g. the Strtab on a module).
1629 BumpPtrAllocator Alloc;
1630 StringSaver Saver;
1631
1632 // The total number of basic blocks in the module in the per-module summary or
1633 // the total number of basic blocks in the LTO unit in the combined index.
1634 // FIXME: Putting this in the distributed ThinLTO index files breaks LTO
1635 // backend caching on any BB change to any linked file. It is currently not
1636 // used except in the case of a SamplePGO partial profile, and should be
1637 // reevaluated/redesigned to allow more effective incremental builds in that
1638 // case.
1639 uint64_t BlockCount = 0;
1640
1641 // List of unique stack ids (hashes). We use a 4B index of the id in the
1642 // stack id lists on the alloc and callsite summaries for memory savings,
1643 // since the number of unique ids is in practice much smaller than the
1644 // number of stack id references in the summaries.
1645 std::vector<uint64_t> StackIds;
1646
1647 // Temporary map while building StackIds list. Clear when index is completely
1648 // built via releaseTemporaryMemory.
1649 DenseMap<uint64_t, unsigned> StackIdToIndex;
1650
1651 // YAML I/O support.
1653
1655 getOrInsertValuePtr(GlobalValue::GUID GUID) {
1656 return &*GlobalValueMap.try_emplace(GUID, GlobalValueSummaryInfo(HaveGVs))
1657 .first;
1658 }
1659
1660public:
1661 // See HaveGVs variable comment.
1662 ModuleSummaryIndex(bool HaveGVs, bool EnableSplitLTOUnit = false,
1663 bool UnifiedLTO = false)
1664 : TypeIdSaver(TypeIdSaverAlloc), HaveGVs(HaveGVs),
1665 EnableSplitLTOUnit(EnableSplitLTOUnit), UnifiedLTO(UnifiedLTO),
1666 Saver(Alloc) {}
1667
1668 // Current version for the module summary in bitcode files.
1669 // The BitcodeSummaryVersion should be bumped whenever we introduce changes
1670 // in the way some record are interpreted, like flags for instance.
1671 // Note that incrementing this may require changes in both BitcodeReader.cpp
1672 // and BitcodeWriter.cpp.
1673 static constexpr uint64_t BitcodeSummaryVersion = 14;
1674
1675 // Regular LTO module name for ASM writer
1676 static constexpr const char *getRegularLTOModuleName() {
1677 return "[Regular LTO]";
1678 }
1679
1680 bool haveGVs() const { return HaveGVs; }
1681
1682 LLVM_ABI uint64_t getFlags() const;
1683 LLVM_ABI void setFlags(uint64_t Flags);
1684
1685 uint64_t getBlockCount() const { return BlockCount; }
1686 void addBlockCount(uint64_t C) { BlockCount += C; }
1687 void setBlockCount(uint64_t C) { BlockCount = C; }
1688
1689 gvsummary_iterator begin() { return GlobalValueMap.begin(); }
1690 const_gvsummary_iterator begin() const { return GlobalValueMap.begin(); }
1691 gvsummary_iterator end() { return GlobalValueMap.end(); }
1692 const_gvsummary_iterator end() const { return GlobalValueMap.end(); }
1693 size_t size() const { return GlobalValueMap.size(); }
1694
1697 return GlobalValueMap.sortedRange();
1698 }
1699
1700 const std::vector<uint64_t> &stackIds() const { return StackIds; }
1701
1702 unsigned addOrGetStackIdIndex(uint64_t StackId) {
1703 auto Inserted = StackIdToIndex.insert({StackId, StackIds.size()});
1704 if (Inserted.second)
1705 StackIds.push_back(StackId);
1706 return Inserted.first->second;
1707 }
1708
1709 uint64_t getStackIdAtIndex(unsigned Index) const {
1710 assert(StackIds.size() > Index);
1711 return StackIds[Index];
1712 }
1713
1714 // Facility to release memory from data structures only needed during index
1715 // construction (including while building combined index). Currently this only
1716 // releases the temporary map used while constructing a correspondence between
1717 // stack ids and their index in the StackIds vector. Mostly impactful when
1718 // building a large combined index.
1720 assert(StackIdToIndex.size() == StackIds.size());
1721 StackIdToIndex.clear();
1722 StackIds.shrink_to_fit();
1723 }
1724
1725 /// Convenience function for doing a DFS on a ValueInfo. Marks the function in
1726 /// the FunctionHasParent map.
1728 std::map<ValueInfo, bool> &FunctionHasParent) {
1729 if (!V.getSummaryList().size())
1730 return; // skip external functions that don't have summaries
1731
1732 // Mark discovered if we haven't yet
1733 auto S = FunctionHasParent.emplace(V, false);
1734
1735 // Stop if we've already discovered this node
1736 if (!S.second)
1737 return;
1738
1740 dyn_cast<FunctionSummary>(V.getSummaryList().front().get());
1741 assert(F != nullptr && "Expected FunctionSummary node");
1742
1743 for (const auto &C : F->calls()) {
1744 // Insert node if necessary
1745 auto S = FunctionHasParent.emplace(C.first, true);
1746
1747 // Skip nodes that we're sure have parents
1748 if (!S.second && S.first->second)
1749 continue;
1750
1751 if (S.second)
1752 discoverNodes(C.first, FunctionHasParent);
1753 else
1754 S.first->second = true;
1755 }
1756 }
1757
1758 // Calculate the callgraph root
1760 // Functions that have a parent will be marked in FunctionHasParent pair.
1761 // Once we've marked all functions, the functions in the map that are false
1762 // have no parent (so they're the roots)
1763 std::map<ValueInfo, bool> FunctionHasParent;
1764
1765 for (auto &S : *this) {
1766 // Skip external functions
1767 if (!S.second.getSummaryList().size() ||
1768 !isa<FunctionSummary>(S.second.getSummaryList().front().get()))
1769 continue;
1770 discoverNodes(ValueInfo(HaveGVs, &S), FunctionHasParent);
1771 }
1772
1774 // create edges to all roots in the Index
1775 for (auto &P : FunctionHasParent) {
1776 if (P.second)
1777 continue; // skip over non-root nodes
1778 Edges.push_back(std::make_pair(P.first, CalleeInfo{}));
1779 }
1780 return FunctionSummary::makeDummyFunctionSummary(std::move(Edges));
1781 }
1782
1784 return WithGlobalValueDeadStripping;
1785 }
1787 WithGlobalValueDeadStripping = true;
1788 }
1789
1790 bool withAttributePropagation() const { return WithAttributePropagation; }
1792 WithAttributePropagation = true;
1793 }
1794
1795 bool withDSOLocalPropagation() const { return WithDSOLocalPropagation; }
1796 void setWithDSOLocalPropagation() { WithDSOLocalPropagation = true; }
1797
1798 bool withInternalizeAndPromote() const { return WithInternalizeAndPromote; }
1799 void setWithInternalizeAndPromote() { WithInternalizeAndPromote = true; }
1800
1801 bool withWholeProgramVisibility() const { return WithWholeProgramVisibility; }
1802 void setWithWholeProgramVisibility() { WithWholeProgramVisibility = true; }
1803
1804 bool isReadOnly(const GlobalVarSummary *GVS) const {
1805 return WithAttributePropagation && GVS->maybeReadOnly();
1806 }
1807 bool isWriteOnly(const GlobalVarSummary *GVS) const {
1808 return WithAttributePropagation && GVS->maybeWriteOnly();
1809 }
1810
1811 bool withSupportsHotColdNew() const { return WithSupportsHotColdNew; }
1812 void setWithSupportsHotColdNew() { WithSupportsHotColdNew = true; }
1813
1815 return SkipModuleByDistributedBackend;
1816 }
1818 SkipModuleByDistributedBackend = true;
1819 }
1820
1821 bool enableSplitLTOUnit() const { return EnableSplitLTOUnit; }
1822 void setEnableSplitLTOUnit() { EnableSplitLTOUnit = true; }
1823
1824 bool hasUnifiedLTO() const { return UnifiedLTO; }
1825 void setUnifiedLTO() { UnifiedLTO = true; }
1826
1827 bool partiallySplitLTOUnits() const { return PartiallySplitLTOUnits; }
1828 void setPartiallySplitLTOUnits() { PartiallySplitLTOUnits = true; }
1829
1830 bool hasParamAccess() const { return HasParamAccess; }
1831
1832 bool isGlobalValueLive(const GlobalValueSummary *GVS) const {
1833 return !WithGlobalValueDeadStripping || GVS->isLive();
1834 }
1835 LLVM_ABI bool isGUIDLive(GlobalValue::GUID GUID) const;
1836
1837 /// Return a ValueInfo for the index value_type (convenient when iterating
1838 /// index).
1840 return ValueInfo(HaveGVs, &R);
1841 }
1842
1843 /// Return a ValueInfo for GUID if it exists, otherwise return ValueInfo().
1845 auto I = GlobalValueMap.find(GUID);
1846 return ValueInfo(HaveGVs, I == GlobalValueMap.end() ? nullptr : &*I);
1847 }
1848
1849 /// Return a ValueInfo for \p GUID.
1851 return ValueInfo(HaveGVs, getOrInsertValuePtr(GUID));
1852 }
1853
1854 // Save a string in the Index. Use before passing Name to
1855 // getOrInsertValueInfo when the string isn't owned elsewhere (e.g. on the
1856 // module's Strtab).
1857 StringRef saveString(StringRef String) { return Saver.save(String); }
1858
1859 /// Return a ValueInfo for \p GUID setting value \p Name.
1861 assert(!HaveGVs);
1862 auto VP = getOrInsertValuePtr(GUID);
1863 VP->second.U.Name = Name;
1864 return ValueInfo(HaveGVs, VP);
1865 }
1866
1867 /// Return a ValueInfo for \p GV with GUID \p GUID and mark it as belonging to
1868 /// GV.
1870 GlobalValue::GUID GUID) {
1871 assert(HaveGVs);
1872 auto VP = getOrInsertValuePtr(GUID);
1873 VP->second.U.GV = GV;
1874 return ValueInfo(HaveGVs, VP);
1875 }
1876
1877 /// Return a ValueInfo for \p GV and mark it as belonging to GV.
1879 return getOrInsertValueInfo(GV, GV->getGUID());
1880 }
1881
1882 /// Return the GUID for \p OriginalId in the OidGuidMap.
1884 const auto I = OidGuidMap.find(OriginalID);
1885 return I == OidGuidMap.end() ? 0 : I->second;
1886 }
1887
1888 CfiFunctionIndex &cfiFunctionDefs() { return CfiFunctionDefs; }
1889 const CfiFunctionIndex &cfiFunctionDefs() const { return CfiFunctionDefs; }
1890
1891 CfiFunctionIndex &cfiFunctionDecls() { return CfiFunctionDecls; }
1892 const CfiFunctionIndex &cfiFunctionDecls() const { return CfiFunctionDecls; }
1893
1894 /// Add a global value summary for a value.
1896 std::unique_ptr<GlobalValueSummary> Summary) {
1897 addGlobalValueSummary(getOrInsertValueInfo(&GV), std::move(Summary));
1898 }
1899
1900 /// Add a global value summary for a value of the given name.
1902 std::unique_ptr<GlobalValueSummary> Summary) {
1906 std::move(Summary));
1907 }
1908
1909 /// Add a global value summary for the given ValueInfo.
1911 std::unique_ptr<GlobalValueSummary> Summary) {
1912 if (const FunctionSummary *FS = dyn_cast<FunctionSummary>(Summary.get()))
1913 HasParamAccess |= !FS->paramAccesses().empty();
1914 addOriginalName(VI.getGUID(), Summary->getOriginalName());
1915 // Here we have a notionally const VI, but the value it points to is owned
1916 // by the non-const *this.
1917 const_cast<GlobalValueSummaryMapTy::value_type *>(VI.getRef())
1918 ->second.addSummary(std::move(Summary));
1919 }
1920
1921 /// Add an original name for the value of the given GUID.
1923 GlobalValue::GUID OrigGUID) {
1924 if (OrigGUID == 0 || ValueGUID == OrigGUID)
1925 return;
1926 auto [It, Inserted] = OidGuidMap.try_emplace(OrigGUID, ValueGUID);
1927 if (!Inserted && It->second != ValueGUID)
1928 It->second = 0;
1929 }
1930
1931 /// Find the summary for ValueInfo \p VI in module \p ModuleId, or nullptr if
1932 /// not found.
1934 auto SummaryList = VI.getSummaryList();
1935 auto Summary =
1936 llvm::find_if(SummaryList,
1937 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
1938 return Summary->modulePath() == ModuleId;
1939 });
1940 if (Summary == SummaryList.end())
1941 return nullptr;
1942 return Summary->get();
1943 }
1944
1945 /// Find the summary for global \p GUID in module \p ModuleId, or nullptr if
1946 /// not found.
1948 StringRef ModuleId) const {
1949 auto CalleeInfo = getValueInfo(ValueGUID);
1950 if (!CalleeInfo)
1951 return nullptr; // This function does not have a summary
1952 return findSummaryInModule(CalleeInfo, ModuleId);
1953 }
1954
1955 /// Returns the first GlobalValueSummary for \p GV, asserting that there
1956 /// is only one if \p PerModuleIndex.
1958 bool PerModuleIndex = true) const {
1959 assert(GV.hasName() && "Can't get GlobalValueSummary for GV with no name");
1960 return getGlobalValueSummary(GV.getGUID(), PerModuleIndex);
1961 }
1962
1963 /// Returns the first GlobalValueSummary for \p ValueGUID, asserting that
1964 /// there
1965 /// is only one if \p PerModuleIndex.
1968 bool PerModuleIndex = true) const;
1969
1970 /// Table of modules, containing module hash and id.
1972 return ModulePathStringTable;
1973 }
1974
1975 /// Table of modules, containing hash and id.
1976 StringMap<ModuleHash> &modulePaths() { return ModulePathStringTable; }
1977
1978 /// Get the module SHA1 hash recorded for the given module path.
1979 const ModuleHash &getModuleHash(const StringRef ModPath) const {
1980 auto It = ModulePathStringTable.find(ModPath);
1981 assert(It != ModulePathStringTable.end() && "Module not registered");
1982 return It->second;
1983 }
1984
1985 /// Convenience method for creating a promoted global name
1986 /// for the given value name of a local, and its original module's ID.
1987 static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash) {
1988 std::string Suffix = utostr((uint64_t(ModHash[0]) << 32) |
1989 ModHash[1]); // Take the first 64 bits
1990 return getGlobalNameForLocal(Name, Suffix);
1991 }
1992
1993 static std::string getGlobalNameForLocal(StringRef Name, StringRef Suffix) {
1994 SmallString<256> NewName(Name);
1995 NewName += ".llvm.";
1996 NewName += Suffix;
1997 return std::string(NewName);
1998 }
1999
2000 /// Helper to obtain the unpromoted name for a global value (or the original
2001 /// name if not promoted). Split off the rightmost ".llvm.${hash}" suffix,
2002 /// because it is possible in certain clients (not clang at the moment) for
2003 /// two rounds of ThinLTO optimization and therefore promotion to occur.
2005 std::pair<StringRef, StringRef> Pair = Name.rsplit(".llvm.");
2006 return Pair.first;
2007 }
2008
2010
2011 /// Add a new module with the given \p Hash, mapped to the given \p
2012 /// ModID, and return a reference to the module.
2014 return &*ModulePathStringTable.insert({ModPath, Hash}).first;
2015 }
2016
2017 /// Return module entry for module with the given \p ModPath.
2019 auto It = ModulePathStringTable.find(ModPath);
2020 assert(It != ModulePathStringTable.end() && "Module not registered");
2021 return &*It;
2022 }
2023
2024 /// Return module entry for module with the given \p ModPath.
2025 const ModuleInfo *getModule(StringRef ModPath) const {
2026 auto It = ModulePathStringTable.find(ModPath);
2027 assert(It != ModulePathStringTable.end() && "Module not registered");
2028 return &*It;
2029 }
2030
2031 /// Check if the given Module has any functions available for exporting
2032 /// in the index. We consider any module present in the ModulePathStringTable
2033 /// to have exported functions.
2034 bool hasExportedFunctions(const Module &M) const {
2035 return ModulePathStringTable.count(M.getModuleIdentifier());
2036 }
2037
2038 const TypeIdSummaryMapTy &typeIds() const { return TypeIdMap; }
2039
2040 /// Return an existing or new TypeIdSummary entry for \p TypeId.
2041 /// This accessor can mutate the map and therefore should not be used in
2042 /// the ThinLTO backends.
2044 auto TidIter = TypeIdMap.equal_range(
2046 for (auto &[GUID, TypeIdPair] : make_range(TidIter))
2047 if (TypeIdPair.first == TypeId)
2048 return TypeIdPair.second;
2049 auto It =
2050 TypeIdMap.insert({GlobalValue::getGUIDAssumingExternalLinkage(TypeId),
2051 {TypeIdSaver.save(TypeId), TypeIdSummary()}});
2052 return It->second.second;
2053 }
2054
2055 /// This returns either a pointer to the type id summary (if present in the
2056 /// summary map) or null (if not present). This may be used when importing.
2058 auto TidIter = TypeIdMap.equal_range(
2060 for (const auto &[GUID, TypeIdPair] : make_range(TidIter))
2061 if (TypeIdPair.first == TypeId)
2062 return &TypeIdPair.second;
2063 return nullptr;
2064 }
2065
2067 return const_cast<TypeIdSummary *>(
2068 static_cast<const ModuleSummaryIndex *>(this)->getTypeIdSummary(
2069 TypeId));
2070 }
2071
2072 const auto &typeIdCompatibleVtableMap() const {
2073 return TypeIdCompatibleVtableMap;
2074 }
2075
2076 /// Return an existing or new TypeIdCompatibleVtableMap entry for \p TypeId.
2077 /// This accessor can mutate the map and therefore should not be used in
2078 /// the ThinLTO backends.
2081 return TypeIdCompatibleVtableMap[TypeIdSaver.save(TypeId)];
2082 }
2083
2084 /// For the given \p TypeId, this returns the TypeIdCompatibleVtableMap
2085 /// entry if present in the summary map. This may be used when importing.
2086 std::optional<TypeIdCompatibleVtableInfo>
2088 auto I = TypeIdCompatibleVtableMap.find(TypeId);
2089 if (I == TypeIdCompatibleVtableMap.end())
2090 return std::nullopt;
2091 return I->second;
2092 }
2093
2094 /// Collect for the given module the list of functions it defines
2095 /// (GUID -> Summary).
2096 LLVM_ABI void
2098 GVSummaryMapTy &GVSummaryMap) const;
2099
2100 /// Collect for each module the list of Summaries it defines (GUID ->
2101 /// Summary).
2102 template <class Map>
2103 void
2104 collectDefinedGVSummariesPerModule(Map &ModuleToDefinedGVSummaries) const {
2105 for (const auto &GlobalList : *this) {
2106 auto GUID = GlobalList.first;
2107 for (const auto &Summary : GlobalList.second.getSummaryList()) {
2108 ModuleToDefinedGVSummaries[Summary->modulePath()][GUID] = Summary.get();
2109 }
2110 }
2111 }
2112
2113 /// Print to an output stream.
2114 LLVM_ABI void print(raw_ostream &OS, bool IsForDebug = false) const;
2115
2116 /// Dump to stderr (for debugging).
2117 LLVM_ABI void dump() const;
2118
2119 /// Export summary to dot file for GraphViz.
2120 LLVM_ABI void
2122 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) const;
2123
2124 /// Print out strongly connected components for debugging.
2125 LLVM_ABI void dumpSCCs(raw_ostream &OS);
2126
2127 /// Do the access attribute and DSOLocal propagation in combined index.
2128 LLVM_ABI void
2129 propagateAttributes(const DenseSet<GlobalValue::GUID> &PreservedSymbols);
2130
2131 /// Checks if we can import global variable from another module.
2133 bool AnalyzeRefs) const;
2134
2135 /// Same as above but checks whether the global var is importable as a
2136 /// declaration.
2138 bool AnalyzeRefs, bool &CanImportDecl) const;
2139};
2140
2141/// GraphTraits definition to build SCC for the index
2142template <> struct GraphTraits<ValueInfo> {
2145
2147 return P.first;
2148 }
2151 decltype(&valueInfoFromEdge)>;
2152
2155
2156 static NodeRef getEntryNode(ValueInfo V) { return V; }
2157
2159 if (!N.getSummaryList().size()) // handle external function
2160 return ChildIteratorType(
2161 FunctionSummary::ExternalNode.CallGraphEdgeList.begin(),
2164 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2165 return ChildIteratorType(F->CallGraphEdgeList.begin(), &valueInfoFromEdge);
2166 }
2167
2169 if (!N.getSummaryList().size()) // handle external function
2170 return ChildIteratorType(
2171 FunctionSummary::ExternalNode.CallGraphEdgeList.end(),
2174 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2175 return ChildIteratorType(F->CallGraphEdgeList.end(), &valueInfoFromEdge);
2176 }
2177
2179 if (!N.getSummaryList().size()) // handle external function
2180 return FunctionSummary::ExternalNode.CallGraphEdgeList.begin();
2181
2183 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2184 return F->CallGraphEdgeList.begin();
2185 }
2186
2188 if (!N.getSummaryList().size()) // handle external function
2189 return FunctionSummary::ExternalNode.CallGraphEdgeList.end();
2190
2192 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2193 return F->CallGraphEdgeList.end();
2194 }
2195
2196 static NodeRef edge_dest(EdgeRef E) { return E.first; }
2197};
2198
2199template <>
2202 std::unique_ptr<GlobalValueSummary> Root =
2203 std::make_unique<FunctionSummary>(I->calculateCallGraphRoot());
2204 GlobalValueSummaryInfo G(I->haveGVs());
2205 G.addSummary(std::move(Root));
2206 static auto P =
2208 return ValueInfo(I->haveGVs(), &P);
2209 }
2210};
2211} // end namespace llvm
2212
2213#endif // LLVM_IR_MODULESUMMARYINDEX_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
uint64_t uint64_t
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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:750
#define LLVM_ABI
Definition Compiler.h:211
DXIL Finalize Linkage
This file defines the DenseMap class.
#define _
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 implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
StringSet - A set-like wrapper for the StringMap.
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)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Encapsulate the names of CFI target functions.
std::vector< std::pair< StringRef, GlobalValue::GUID > > getSortedSymbols() const
API used for serialization, e.g. YAML.
auto getExportedThinLTOGUIDs() const
get the set of GUIDs that should also be exported because they are the GUIDs of the cfi functions enc...
CfiFunctionIndex(CfiFunctionIndex &&)=default
auto getNamesForGUID(GlobalValue::GUID GUID) const
get the name(s) associated with a given ThinLTO GUID.
void addSymbolWithThinLTOGUID(StringRef Name, GlobalValue::GUID GUID)
Add the function name and the GUID that ThinLTO uses for it.
bool contains(StringRef Name) const
CfiFunctionIndex(const CfiFunctionIndex &)=delete
This class represents a range of values.
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Function summary information to aid decisions and implementation of importing.
static LLVM_ABI FunctionSummary ExternalNode
A dummy node to reference external functions that aren't in the index.
static FunctionSummary makeDummyFunctionSummary(SmallVectorImpl< FunctionSummary::EdgeTy > &&Edges)
Create an empty FunctionSummary (with specified call edges).
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....
void addCallsite(CallsiteInfo &&Callsite)
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 addAlloc(AllocInfo &&Alloc)
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.
An owning range over the entries sorted by key, yielding each entry by reference.
pointee_iterator< SortedEntriesVec::const_iterator > iterator
Map from global value GUID to corresponding summary structures.
iterator find(key_type Key)
std::pair< iterator, bool > try_emplace(key_type Key, Ts &&...Args)
std::pair< key_type, mapped_type > value_type
GlobalValueSummaryInfo mapped_type
const_iterator begin() const
std::deque< value_type >::size_type size_type
SortedEntriesRange sortedRange() const
Return an owning range over the entries sorted by key.
const_iterator find(key_type Key) const
std::deque< value_type >::iterator iterator
std::deque< value_type >::const_iterator const_iterator
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:80
static bool isLocalLinkage(LinkageTypes Linkage)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ABI GUID getGUID() const
Return a 64-bit global unique ID for this value.
Definition Globals.cpp:103
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.
ValueInfo getOrInsertValueInfo(const GlobalValue *GV, GlobalValue::GUID GUID)
Return a ValueInfo for GV with GUID GUID and mark it as belonging to GV.
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,...
GlobalValueSummaryMapTy::SortedEntriesRange sortedGlobalValueSummariesRange() const
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:68
PointerIntPair - This class implements a pair of a pointer and small integer.
A vector that has set insertion semantics.
Definition SetVector.h:57
typename vector_type::const_iterator const_iterator
Definition SetVector.h:73
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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 reserve(size_type N)
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:129
StringMapEntry< ModuleHash > value_type
Definition StringMap.h:205
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition StringMap.h:311
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition StringSaver.h:22
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:25
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:263
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.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
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::vector< std::unique_ptr< GlobalValueSummary > > GlobalValueSummaryList
@ Unknown
Not known to have no common set bits.
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:2139
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.
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:1762
constexpr detail::StaticCastFunc< To > StaticCastTo
Function objects corresponding to the Cast types defined above.
Definition Casting.h:882
GlobalValueSummaryMapTy::iterator gvsummary_iterator
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
GlobalValueSummaryMap GlobalValueSummaryMapTy
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
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
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:1933
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:1788
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:391
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#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.
void setHasIndirectCall(const bool HasIC)
bool hasIndirectCall() const
bool requiresDeclImport() const
void setRequiresDeclImport(const bool RI)
void updateHotness(const HotnessType OtherHotness)
CalleeInfo(HotnessType Hotness, bool HasTC, bool HasIC=false)
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 unsigned getHashValue(FunctionSummary::ConstVCall I)
static bool isEqual(FunctionSummary::ConstVCall L, FunctionSummary::ConstVCall R)
static bool isEqual(FunctionSummary::VFuncId L, FunctionSummary::VFuncId R)
static unsigned getHashValue(FunctionSummary::VFuncId I)
static bool isEqual(ValueInfo L, ValueInfo R)
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:94
Summary of a single MIB in a memprof metadata on allocations.
MIBInfo(AllocationType AllocType, SmallVector< unsigned > StackIdIndices)
AllocationType AllocType
SmallVector< unsigned > StackIdIndices
TypeIdOffsetVtableInfo(uint64_t Offset, ValueInfo VI)
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
Kind
Specifies which kind of type check we should emit for this byte array.
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
Struct that holds a reference to a particular GUID in a global value summary.
PointerIntPair< const GlobalValueSummaryMapTy::value_type *, 3, int > RefAndFlags
LLVM_ABI GlobalValue::VisibilityTypes getELFVisibility() const
Returns the most constraining visibility among summaries.
bool isValidAccessSpecifier() const
const GlobalValueSummaryMapTy::value_type * getRef() const
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
StringRef name() const
bool isWriteOnly() const
const GlobalValue * getValue() const
void verifyLocal() const
ValueInfo(bool HaveGVs, const GlobalValueSummaryMapTy::value_type *R)
bool isReadOnly() const
LLVM_ABI bool canAutoHide() const
Checks if all copies are eligible for auto-hiding (have flag set).
unsigned getAccessSpecifier() const
ValueInfo()=default
LLVM_ABI bool isDSOLocal(bool WithDSOLocalPropagation=false) const
Checks if all summaries are DSO local (have the flag set).
GlobalValue::GUID getGUID() const
VirtFuncOffset(ValueInfo VI, uint64_t Offset)
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.
An iterator type that allows iterating over the pointees via some other iterator.
Definition iterator.h:329
This class should be specialized by any type that needs to be converted to/from a YAML mapping.
Definition YAMLTraits.h:63
const GlobalValue * GV
The GlobalValue corresponding to this summary.
StringRef Name
Summary string representation.