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