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