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