]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/IR/ModuleSummaryIndex.h
Merge ^/head r317808 through r317970.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / IR / ModuleSummaryIndex.h
1 //===-- llvm/ModuleSummaryIndex.h - Module Summary Index --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// @file
11 /// ModuleSummaryIndex.h This file contains the declarations the classes that
12 ///  hold the module index and summary for function importing.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_IR_MODULESUMMARYINDEX_H
17 #define LLVM_IR_MODULESUMMARYINDEX_H
18
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/IR/Module.h"
26
27 #include <array>
28
29 namespace llvm {
30
31 namespace yaml {
32 template <typename T> struct MappingTraits;
33 }
34
35 /// \brief Class to accumulate and hold information about a callee.
36 struct CalleeInfo {
37   enum class HotnessType : uint8_t { Unknown = 0, Cold = 1, None = 2, Hot = 3 };
38   HotnessType Hotness = HotnessType::Unknown;
39
40   CalleeInfo() = default;
41   explicit CalleeInfo(HotnessType Hotness) : Hotness(Hotness) {}
42
43   void updateHotness(const HotnessType OtherHotness) {
44     Hotness = std::max(Hotness, OtherHotness);
45   }
46 };
47
48 class GlobalValueSummary;
49
50 typedef std::vector<std::unique_ptr<GlobalValueSummary>> GlobalValueSummaryList;
51
52 struct GlobalValueSummaryInfo {
53   /// The GlobalValue corresponding to this summary. This is only used in
54   /// per-module summaries.
55   const GlobalValue *GV = nullptr;
56
57   /// List of global value summary structures for a particular value held
58   /// in the GlobalValueMap. Requires a vector in the case of multiple
59   /// COMDAT values of the same name.
60   GlobalValueSummaryList SummaryList;
61 };
62
63 /// Map from global value GUID to corresponding summary structures. Use a
64 /// std::map rather than a DenseMap so that pointers to the map's value_type
65 /// (which are used by ValueInfo) are not invalidated by insertion. Also it will
66 /// likely incur less overhead, as the value type is not very small and the size
67 /// of the map is unknown, resulting in inefficiencies due to repeated
68 /// insertions and resizing.
69 typedef std::map<GlobalValue::GUID, GlobalValueSummaryInfo>
70     GlobalValueSummaryMapTy;
71
72 /// Struct that holds a reference to a particular GUID in a global value
73 /// summary.
74 struct ValueInfo {
75   const GlobalValueSummaryMapTy::value_type *Ref = nullptr;
76   ValueInfo() = default;
77   ValueInfo(const GlobalValueSummaryMapTy::value_type *Ref) : Ref(Ref) {}
78   operator bool() const { return Ref; }
79
80   GlobalValue::GUID getGUID() const { return Ref->first; }
81   const GlobalValue *getValue() const { return Ref->second.GV; }
82   ArrayRef<std::unique_ptr<GlobalValueSummary>> getSummaryList() const {
83     return Ref->second.SummaryList;
84   }
85 };
86
87 template <> struct DenseMapInfo<ValueInfo> {
88   static inline ValueInfo getEmptyKey() {
89     return ValueInfo((GlobalValueSummaryMapTy::value_type *)-1);
90   }
91   static inline ValueInfo getTombstoneKey() {
92     return ValueInfo((GlobalValueSummaryMapTy::value_type *)-2);
93   }
94   static bool isEqual(ValueInfo L, ValueInfo R) { return L.Ref == R.Ref; }
95   static unsigned getHashValue(ValueInfo I) { return (uintptr_t)I.Ref; }
96 };
97
98 /// \brief Function and variable summary information to aid decisions and
99 /// implementation of importing.
100 class GlobalValueSummary {
101 public:
102   /// \brief Sububclass discriminator (for dyn_cast<> et al.)
103   enum SummaryKind : unsigned { AliasKind, FunctionKind, GlobalVarKind };
104
105   /// Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
106   struct GVFlags {
107     /// \brief The linkage type of the associated global value.
108     ///
109     /// One use is to flag values that have local linkage types and need to
110     /// have module identifier appended before placing into the combined
111     /// index, to disambiguate from other values with the same name.
112     /// In the future this will be used to update and optimize linkage
113     /// types based on global summary-based analysis.
114     unsigned Linkage : 4;
115
116     /// Indicate if the global value cannot be imported (e.g. it cannot
117     /// be renamed or references something that can't be renamed).
118     unsigned NotEligibleToImport : 1;
119
120     /// Indicate that the global value must be considered a live root for
121     /// index-based liveness analysis. Used for special LLVM values such as
122     /// llvm.global_ctors that the linker does not know about.
123     unsigned LiveRoot : 1;
124
125     /// Convenience Constructors
126     explicit GVFlags(GlobalValue::LinkageTypes Linkage,
127                      bool NotEligibleToImport, bool LiveRoot)
128         : Linkage(Linkage), NotEligibleToImport(NotEligibleToImport),
129           LiveRoot(LiveRoot) {}
130   };
131
132 private:
133   /// Kind of summary for use in dyn_cast<> et al.
134   SummaryKind Kind;
135
136   GVFlags Flags;
137
138   /// This is the hash of the name of the symbol in the original file. It is
139   /// identical to the GUID for global symbols, but differs for local since the
140   /// GUID includes the module level id in the hash.
141   GlobalValue::GUID OriginalName;
142
143   /// \brief Path of module IR containing value's definition, used to locate
144   /// module during importing.
145   ///
146   /// This is only used during parsing of the combined index, or when
147   /// parsing the per-module index for creation of the combined summary index,
148   /// not during writing of the per-module index which doesn't contain a
149   /// module path string table.
150   StringRef ModulePath;
151
152   /// List of values referenced by this global value's definition
153   /// (either by the initializer of a global variable, or referenced
154   /// from within a function). This does not include functions called, which
155   /// are listed in the derived FunctionSummary object.
156   std::vector<ValueInfo> RefEdgeList;
157
158 protected:
159   GlobalValueSummary(SummaryKind K, GVFlags Flags, std::vector<ValueInfo> Refs)
160       : Kind(K), Flags(Flags), OriginalName(0), RefEdgeList(std::move(Refs)) {}
161
162 public:
163   virtual ~GlobalValueSummary() = default;
164
165   /// Returns the hash of the original name, it is identical to the GUID for
166   /// externally visible symbols, but not for local ones.
167   GlobalValue::GUID getOriginalName() { return OriginalName; }
168
169   /// Initialize the original name hash in this summary.
170   void setOriginalName(GlobalValue::GUID Name) { OriginalName = Name; }
171
172   /// Which kind of summary subclass this is.
173   SummaryKind getSummaryKind() const { return Kind; }
174
175   /// Set the path to the module containing this function, for use in
176   /// the combined index.
177   void setModulePath(StringRef ModPath) { ModulePath = ModPath; }
178
179   /// Get the path to the module containing this function.
180   StringRef modulePath() const { return ModulePath; }
181
182   /// Get the flags for this GlobalValue (see \p struct GVFlags).
183   GVFlags flags() { return Flags; }
184
185   /// Return linkage type recorded for this global value.
186   GlobalValue::LinkageTypes linkage() const {
187     return static_cast<GlobalValue::LinkageTypes>(Flags.Linkage);
188   }
189
190   /// Sets the linkage to the value determined by global summary-based
191   /// optimization. Will be applied in the ThinLTO backends.
192   void setLinkage(GlobalValue::LinkageTypes Linkage) {
193     Flags.Linkage = Linkage;
194   }
195
196   /// Return true if this global value can't be imported.
197   bool notEligibleToImport() const { return Flags.NotEligibleToImport; }
198
199   /// Return true if this global value must be considered a root for live
200   /// value analysis on the index.
201   bool liveRoot() const { return Flags.LiveRoot; }
202
203   /// Flag that this global value must be considered a root for live
204   /// value analysis on the index.
205   void setLiveRoot() { Flags.LiveRoot = true; }
206
207   /// Flag that this global value cannot be imported.
208   void setNotEligibleToImport() { Flags.NotEligibleToImport = true; }
209
210   /// Return the list of values referenced by this global value definition.
211   ArrayRef<ValueInfo> refs() const { return RefEdgeList; }
212 };
213
214 /// \brief Alias summary information.
215 class AliasSummary : public GlobalValueSummary {
216   GlobalValueSummary *AliaseeSummary;
217
218 public:
219   AliasSummary(GVFlags Flags, std::vector<ValueInfo> Refs)
220       : GlobalValueSummary(AliasKind, Flags, std::move(Refs)) {}
221
222   /// Check if this is an alias summary.
223   static bool classof(const GlobalValueSummary *GVS) {
224     return GVS->getSummaryKind() == AliasKind;
225   }
226
227   void setAliasee(GlobalValueSummary *Aliasee) { AliaseeSummary = Aliasee; }
228
229   const GlobalValueSummary &getAliasee() const {
230     assert(AliaseeSummary && "Unexpected missing aliasee summary");
231     return *AliaseeSummary;
232   }
233
234   GlobalValueSummary &getAliasee() {
235     return const_cast<GlobalValueSummary &>(
236                          static_cast<const AliasSummary *>(this)->getAliasee());
237   }
238 };
239
240 /// \brief Function summary information to aid decisions and implementation of
241 /// importing.
242 class FunctionSummary : public GlobalValueSummary {
243 public:
244   /// <CalleeValueInfo, CalleeInfo> call edge pair.
245   typedef std::pair<ValueInfo, CalleeInfo> EdgeTy;
246
247   /// An "identifier" for a virtual function. This contains the type identifier
248   /// represented as a GUID and the offset from the address point to the virtual
249   /// function pointer, where "address point" is as defined in the Itanium ABI:
250   /// https://mentorembedded.github.io/cxx-abi/abi.html#vtable-general
251   struct VFuncId {
252     GlobalValue::GUID GUID;
253     uint64_t Offset;
254   };
255
256   /// A specification for a virtual function call with all constant integer
257   /// arguments. This is used to perform virtual constant propagation on the
258   /// summary.
259   struct ConstVCall {
260     VFuncId VFunc;
261     std::vector<uint64_t> Args;
262   };
263
264 private:
265   /// Number of instructions (ignoring debug instructions, e.g.) computed
266   /// during the initial compile step when the summary index is first built.
267   unsigned InstCount;
268
269   /// List of <CalleeValueInfo, CalleeInfo> call edge pairs from this function.
270   std::vector<EdgeTy> CallGraphEdgeList;
271
272   /// All type identifier related information. Because these fields are
273   /// relatively uncommon we only allocate space for them if necessary.
274   struct TypeIdInfo {
275     /// List of type identifiers used by this function in llvm.type.test
276     /// intrinsics other than by an llvm.assume intrinsic, represented as GUIDs.
277     std::vector<GlobalValue::GUID> TypeTests;
278
279     /// List of virtual calls made by this function using (respectively)
280     /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics that do
281     /// not have all constant integer arguments.
282     std::vector<VFuncId> TypeTestAssumeVCalls, TypeCheckedLoadVCalls;
283
284     /// List of virtual calls made by this function using (respectively)
285     /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics with
286     /// all constant integer arguments.
287     std::vector<ConstVCall> TypeTestAssumeConstVCalls,
288         TypeCheckedLoadConstVCalls;
289   };
290
291   std::unique_ptr<TypeIdInfo> TIdInfo;
292
293 public:
294   FunctionSummary(GVFlags Flags, unsigned NumInsts, std::vector<ValueInfo> Refs,
295                   std::vector<EdgeTy> CGEdges,
296                   std::vector<GlobalValue::GUID> TypeTests,
297                   std::vector<VFuncId> TypeTestAssumeVCalls,
298                   std::vector<VFuncId> TypeCheckedLoadVCalls,
299                   std::vector<ConstVCall> TypeTestAssumeConstVCalls,
300                   std::vector<ConstVCall> TypeCheckedLoadConstVCalls)
301       : GlobalValueSummary(FunctionKind, Flags, std::move(Refs)),
302         InstCount(NumInsts), CallGraphEdgeList(std::move(CGEdges)) {
303     if (!TypeTests.empty() || !TypeTestAssumeVCalls.empty() ||
304         !TypeCheckedLoadVCalls.empty() || !TypeTestAssumeConstVCalls.empty() ||
305         !TypeCheckedLoadConstVCalls.empty())
306       TIdInfo = llvm::make_unique<TypeIdInfo>(TypeIdInfo{
307           std::move(TypeTests), std::move(TypeTestAssumeVCalls),
308           std::move(TypeCheckedLoadVCalls),
309           std::move(TypeTestAssumeConstVCalls),
310           std::move(TypeCheckedLoadConstVCalls)});
311   }
312
313   /// Check if this is a function summary.
314   static bool classof(const GlobalValueSummary *GVS) {
315     return GVS->getSummaryKind() == FunctionKind;
316   }
317
318   /// Get the instruction count recorded for this function.
319   unsigned instCount() const { return InstCount; }
320
321   /// Return the list of <CalleeValueInfo, CalleeInfo> pairs.
322   ArrayRef<EdgeTy> calls() const { return CallGraphEdgeList; }
323
324   /// Returns the list of type identifiers used by this function in
325   /// llvm.type.test intrinsics other than by an llvm.assume intrinsic,
326   /// represented as GUIDs.
327   ArrayRef<GlobalValue::GUID> type_tests() const {
328     if (TIdInfo)
329       return TIdInfo->TypeTests;
330     return {};
331   }
332
333   /// Returns the list of virtual calls made by this function using
334   /// llvm.assume(llvm.type.test) intrinsics that do not have all constant
335   /// integer arguments.
336   ArrayRef<VFuncId> type_test_assume_vcalls() const {
337     if (TIdInfo)
338       return TIdInfo->TypeTestAssumeVCalls;
339     return {};
340   }
341
342   /// Returns the list of virtual calls made by this function using
343   /// llvm.type.checked.load intrinsics that do not have all constant integer
344   /// arguments.
345   ArrayRef<VFuncId> type_checked_load_vcalls() const {
346     if (TIdInfo)
347       return TIdInfo->TypeCheckedLoadVCalls;
348     return {};
349   }
350
351   /// Returns the list of virtual calls made by this function using
352   /// llvm.assume(llvm.type.test) intrinsics with all constant integer
353   /// arguments.
354   ArrayRef<ConstVCall> type_test_assume_const_vcalls() const {
355     if (TIdInfo)
356       return TIdInfo->TypeTestAssumeConstVCalls;
357     return {};
358   }
359
360   /// Returns the list of virtual calls made by this function using
361   /// llvm.type.checked.load intrinsics with all constant integer arguments.
362   ArrayRef<ConstVCall> type_checked_load_const_vcalls() const {
363     if (TIdInfo)
364       return TIdInfo->TypeCheckedLoadConstVCalls;
365     return {};
366   }
367
368   /// Add a type test to the summary. This is used by WholeProgramDevirt if we
369   /// were unable to devirtualize a checked call.
370   void addTypeTest(GlobalValue::GUID Guid) {
371     if (!TIdInfo)
372       TIdInfo = llvm::make_unique<TypeIdInfo>();
373     TIdInfo->TypeTests.push_back(Guid);
374   }
375 };
376
377 template <> struct DenseMapInfo<FunctionSummary::VFuncId> {
378   static FunctionSummary::VFuncId getEmptyKey() { return {0, uint64_t(-1)}; }
379   static FunctionSummary::VFuncId getTombstoneKey() {
380     return {0, uint64_t(-2)};
381   }
382   static bool isEqual(FunctionSummary::VFuncId L, FunctionSummary::VFuncId R) {
383     return L.GUID == R.GUID && L.Offset == R.Offset;
384   }
385   static unsigned getHashValue(FunctionSummary::VFuncId I) { return I.GUID; }
386 };
387
388 template <> struct DenseMapInfo<FunctionSummary::ConstVCall> {
389   static FunctionSummary::ConstVCall getEmptyKey() {
390     return {{0, uint64_t(-1)}, {}};
391   }
392   static FunctionSummary::ConstVCall getTombstoneKey() {
393     return {{0, uint64_t(-2)}, {}};
394   }
395   static bool isEqual(FunctionSummary::ConstVCall L,
396                       FunctionSummary::ConstVCall R) {
397     return DenseMapInfo<FunctionSummary::VFuncId>::isEqual(L.VFunc, R.VFunc) &&
398            L.Args == R.Args;
399   }
400   static unsigned getHashValue(FunctionSummary::ConstVCall I) {
401     return I.VFunc.GUID;
402   }
403 };
404
405 /// \brief Global variable summary information to aid decisions and
406 /// implementation of importing.
407 ///
408 /// Currently this doesn't add anything to the base \p GlobalValueSummary,
409 /// but is a placeholder as additional info may be added to the summary
410 /// for variables.
411 class GlobalVarSummary : public GlobalValueSummary {
412
413 public:
414   GlobalVarSummary(GVFlags Flags, std::vector<ValueInfo> Refs)
415       : GlobalValueSummary(GlobalVarKind, Flags, std::move(Refs)) {}
416
417   /// Check if this is a global variable summary.
418   static bool classof(const GlobalValueSummary *GVS) {
419     return GVS->getSummaryKind() == GlobalVarKind;
420   }
421 };
422
423 struct TypeTestResolution {
424   /// Specifies which kind of type check we should emit for this byte array.
425   /// See http://clang.llvm.org/docs/ControlFlowIntegrityDesign.html for full
426   /// details on each kind of check; the enumerators are described with
427   /// reference to that document.
428   enum Kind {
429     Unsat,     ///< Unsatisfiable type (i.e. no global has this type metadata)
430     ByteArray, ///< Test a byte array (first example)
431     Inline,    ///< Inlined bit vector ("Short Inline Bit Vectors")
432     Single,    ///< Single element (last example in "Short Inline Bit Vectors")
433     AllOnes,   ///< All-ones bit vector ("Eliminating Bit Vector Checks for
434                ///  All-Ones Bit Vectors")
435   } TheKind = Unsat;
436
437   /// Range of size-1 expressed as a bit width. For example, if the size is in
438   /// range [1,256], this number will be 8. This helps generate the most compact
439   /// instruction sequences.
440   unsigned SizeM1BitWidth = 0;
441 };
442
443 struct WholeProgramDevirtResolution {
444   enum Kind {
445     Indir,      ///< Just do a regular virtual call
446     SingleImpl, ///< Single implementation devirtualization
447   } TheKind = Indir;
448
449   std::string SingleImplName;
450
451   struct ByArg {
452     enum Kind {
453       Indir,            ///< Just do a regular virtual call
454       UniformRetVal,    ///< Uniform return value optimization
455       UniqueRetVal,     ///< Unique return value optimization
456       VirtualConstProp, ///< Virtual constant propagation
457     } TheKind = Indir;
458
459     /// Additional information for the resolution:
460     /// - UniformRetVal: the uniform return value.
461     /// - UniqueRetVal: the return value associated with the unique vtable (0 or
462     ///   1).
463     uint64_t Info = 0;
464   };
465
466   /// Resolutions for calls with all constant integer arguments (excluding the
467   /// first argument, "this"), where the key is the argument vector.
468   std::map<std::vector<uint64_t>, ByArg> ResByArg;
469 };
470
471 struct TypeIdSummary {
472   TypeTestResolution TTRes;
473
474   /// Mapping from byte offset to whole-program devirt resolution for that
475   /// (typeid, byte offset) pair.
476   std::map<uint64_t, WholeProgramDevirtResolution> WPDRes;
477 };
478
479 /// 160 bits SHA1
480 typedef std::array<uint32_t, 5> ModuleHash;
481
482 /// Type used for iterating through the global value summary map.
483 typedef GlobalValueSummaryMapTy::const_iterator const_gvsummary_iterator;
484 typedef GlobalValueSummaryMapTy::iterator gvsummary_iterator;
485
486 /// String table to hold/own module path strings, which additionally holds the
487 /// module ID assigned to each module during the plugin step, as well as a hash
488 /// of the module. The StringMap makes a copy of and owns inserted strings.
489 typedef StringMap<std::pair<uint64_t, ModuleHash>> ModulePathStringTableTy;
490
491 /// Map of global value GUID to its summary, used to identify values defined in
492 /// a particular module, and provide efficient access to their summary.
493 typedef std::map<GlobalValue::GUID, GlobalValueSummary *> GVSummaryMapTy;
494
495 /// Class to hold module path string table and global value map,
496 /// and encapsulate methods for operating on them.
497 class ModuleSummaryIndex {
498 private:
499   /// Map from value name to list of summary instances for values of that
500   /// name (may be duplicates in the COMDAT case, e.g.).
501   GlobalValueSummaryMapTy GlobalValueMap;
502
503   /// Holds strings for combined index, mapping to the corresponding module ID.
504   ModulePathStringTableTy ModulePathStringTable;
505
506   /// Mapping from type identifiers to summary information for that type
507   /// identifier.
508   // FIXME: Add bitcode read/write support for this field.
509   std::map<std::string, TypeIdSummary> TypeIdMap;
510
511   /// Mapping from original ID to GUID. If original ID can map to multiple
512   /// GUIDs, it will be mapped to 0.
513   std::map<GlobalValue::GUID, GlobalValue::GUID> OidGuidMap;
514
515   // YAML I/O support.
516   friend yaml::MappingTraits<ModuleSummaryIndex>;
517
518   GlobalValueSummaryMapTy::value_type *
519   getOrInsertValuePtr(GlobalValue::GUID GUID) {
520     return &*GlobalValueMap.emplace(GUID, GlobalValueSummaryInfo{}).first;
521   }
522
523 public:
524   gvsummary_iterator begin() { return GlobalValueMap.begin(); }
525   const_gvsummary_iterator begin() const { return GlobalValueMap.begin(); }
526   gvsummary_iterator end() { return GlobalValueMap.end(); }
527   const_gvsummary_iterator end() const { return GlobalValueMap.end(); }
528   size_t size() const { return GlobalValueMap.size(); }
529
530   /// Return a ValueInfo for GUID if it exists, otherwise return ValueInfo().
531   ValueInfo getValueInfo(GlobalValue::GUID GUID) const {
532     auto I = GlobalValueMap.find(GUID);
533     return ValueInfo(I == GlobalValueMap.end() ? nullptr : &*I);
534   }
535
536   /// Return a ValueInfo for \p GUID.
537   ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID) {
538     return ValueInfo(getOrInsertValuePtr(GUID));
539   }
540
541   /// Return a ValueInfo for \p GV and mark it as belonging to GV.
542   ValueInfo getOrInsertValueInfo(const GlobalValue *GV) {
543     auto VP = getOrInsertValuePtr(GV->getGUID());
544     VP->second.GV = GV;
545     return ValueInfo(VP);
546   }
547
548   /// Return the GUID for \p OriginalId in the OidGuidMap.
549   GlobalValue::GUID getGUIDFromOriginalID(GlobalValue::GUID OriginalID) const {
550     const auto I = OidGuidMap.find(OriginalID);
551     return I == OidGuidMap.end() ? 0 : I->second;
552   }
553
554   /// Add a global value summary for a value of the given name.
555   void addGlobalValueSummary(StringRef ValueName,
556                              std::unique_ptr<GlobalValueSummary> Summary) {
557     addGlobalValueSummary(getOrInsertValueInfo(GlobalValue::getGUID(ValueName)),
558                           std::move(Summary));
559   }
560
561   /// Add a global value summary for the given ValueInfo.
562   void addGlobalValueSummary(ValueInfo VI,
563                              std::unique_ptr<GlobalValueSummary> Summary) {
564     addOriginalName(VI.getGUID(), Summary->getOriginalName());
565     // Here we have a notionally const VI, but the value it points to is owned
566     // by the non-const *this.
567     const_cast<GlobalValueSummaryMapTy::value_type *>(VI.Ref)
568         ->second.SummaryList.push_back(std::move(Summary));
569   }
570
571   /// Add an original name for the value of the given GUID.
572   void addOriginalName(GlobalValue::GUID ValueGUID,
573                        GlobalValue::GUID OrigGUID) {
574     if (OrigGUID == 0 || ValueGUID == OrigGUID)
575       return;
576     if (OidGuidMap.count(OrigGUID) && OidGuidMap[OrigGUID] != ValueGUID)
577       OidGuidMap[OrigGUID] = 0;
578     else
579       OidGuidMap[OrigGUID] = ValueGUID;
580   }
581
582   /// Find the summary for global \p GUID in module \p ModuleId, or nullptr if
583   /// not found.
584   GlobalValueSummary *findSummaryInModule(GlobalValue::GUID ValueGUID,
585                                           StringRef ModuleId) const {
586     auto CalleeInfo = getValueInfo(ValueGUID);
587     if (!CalleeInfo) {
588       return nullptr; // This function does not have a summary
589     }
590     auto Summary =
591         llvm::find_if(CalleeInfo.getSummaryList(),
592                       [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
593                         return Summary->modulePath() == ModuleId;
594                       });
595     if (Summary == CalleeInfo.getSummaryList().end())
596       return nullptr;
597     return Summary->get();
598   }
599
600   /// Returns the first GlobalValueSummary for \p GV, asserting that there
601   /// is only one if \p PerModuleIndex.
602   GlobalValueSummary *getGlobalValueSummary(const GlobalValue &GV,
603                                             bool PerModuleIndex = true) const {
604     assert(GV.hasName() && "Can't get GlobalValueSummary for GV with no name");
605     return getGlobalValueSummary(GlobalValue::getGUID(GV.getName()),
606                                  PerModuleIndex);
607   }
608
609   /// Returns the first GlobalValueSummary for \p ValueGUID, asserting that
610   /// there
611   /// is only one if \p PerModuleIndex.
612   GlobalValueSummary *getGlobalValueSummary(GlobalValue::GUID ValueGUID,
613                                             bool PerModuleIndex = true) const;
614
615   /// Table of modules, containing module hash and id.
616   const StringMap<std::pair<uint64_t, ModuleHash>> &modulePaths() const {
617     return ModulePathStringTable;
618   }
619
620   /// Table of modules, containing hash and id.
621   StringMap<std::pair<uint64_t, ModuleHash>> &modulePaths() {
622     return ModulePathStringTable;
623   }
624
625   /// Get the module ID recorded for the given module path.
626   uint64_t getModuleId(const StringRef ModPath) const {
627     return ModulePathStringTable.lookup(ModPath).first;
628   }
629
630   /// Get the module SHA1 hash recorded for the given module path.
631   const ModuleHash &getModuleHash(const StringRef ModPath) const {
632     auto It = ModulePathStringTable.find(ModPath);
633     assert(It != ModulePathStringTable.end() && "Module not registered");
634     return It->second.second;
635   }
636
637   /// Convenience method for creating a promoted global name
638   /// for the given value name of a local, and its original module's ID.
639   static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash) {
640     SmallString<256> NewName(Name);
641     NewName += ".llvm.";
642     NewName += utohexstr(ModHash[0]); // Take the first 32 bits
643     return NewName.str();
644   }
645
646   /// Helper to obtain the unpromoted name for a global value (or the original
647   /// name if not promoted).
648   static StringRef getOriginalNameBeforePromote(StringRef Name) {
649     std::pair<StringRef, StringRef> Pair = Name.split(".llvm.");
650     return Pair.first;
651   }
652
653   /// Add a new module path with the given \p Hash, mapped to the given \p
654   /// ModID, and return an iterator to the entry in the index.
655   ModulePathStringTableTy::iterator
656   addModulePath(StringRef ModPath, uint64_t ModId,
657                 ModuleHash Hash = ModuleHash{{0}}) {
658     return ModulePathStringTable.insert(std::make_pair(
659                                             ModPath,
660                                             std::make_pair(ModId, Hash))).first;
661   }
662
663   /// Check if the given Module has any functions available for exporting
664   /// in the index. We consider any module present in the ModulePathStringTable
665   /// to have exported functions.
666   bool hasExportedFunctions(const Module &M) const {
667     return ModulePathStringTable.count(M.getModuleIdentifier());
668   }
669
670   const std::map<std::string, TypeIdSummary> &typeIds() const {
671     return TypeIdMap;
672   }
673
674   /// This accessor should only be used when exporting because it can mutate the
675   /// map.
676   TypeIdSummary &getOrInsertTypeIdSummary(StringRef TypeId) {
677     return TypeIdMap[TypeId];
678   }
679
680   /// This returns either a pointer to the type id summary (if present in the
681   /// summary map) or null (if not present). This may be used when importing.
682   const TypeIdSummary *getTypeIdSummary(StringRef TypeId) const {
683     auto I = TypeIdMap.find(TypeId);
684     if (I == TypeIdMap.end())
685       return nullptr;
686     return &I->second;
687   }
688
689   /// Collect for the given module the list of function it defines
690   /// (GUID -> Summary).
691   void collectDefinedFunctionsForModule(StringRef ModulePath,
692                                         GVSummaryMapTy &GVSummaryMap) const;
693
694   /// Collect for each module the list of Summaries it defines (GUID ->
695   /// Summary).
696   void collectDefinedGVSummariesPerModule(
697       StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries) const;
698 };
699
700 } // End llvm namespace
701
702 #endif