Home | History | Annotate | Download | only in IR
      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     assert((K != AliasKind || Refs.empty()) &&
    190            "Expect no references for AliasSummary");
    191   }
    192 
    193 public:
    194   virtual ~GlobalValueSummary() = default;
    195 
    196   /// Returns the hash of the original name, it is identical to the GUID for
    197   /// externally visible symbols, but not for local ones.
    198   GlobalValue::GUID getOriginalName() { return OriginalName; }
    199 
    200   /// Initialize the original name hash in this summary.
    201   void setOriginalName(GlobalValue::GUID Name) { OriginalName = Name; }
    202 
    203   /// Which kind of summary subclass this is.
    204   SummaryKind getSummaryKind() const { return Kind; }
    205 
    206   /// Set the path to the module containing this function, for use in
    207   /// the combined index.
    208   void setModulePath(StringRef ModPath) { ModulePath = ModPath; }
    209 
    210   /// Get the path to the module containing this function.
    211   StringRef modulePath() const { return ModulePath; }
    212 
    213   /// Get the flags for this GlobalValue (see \p struct GVFlags).
    214   GVFlags flags() { return Flags; }
    215 
    216   /// Return linkage type recorded for this global value.
    217   GlobalValue::LinkageTypes linkage() const {
    218     return static_cast<GlobalValue::LinkageTypes>(Flags.Linkage);
    219   }
    220 
    221   /// Sets the linkage to the value determined by global summary-based
    222   /// optimization. Will be applied in the ThinLTO backends.
    223   void setLinkage(GlobalValue::LinkageTypes Linkage) {
    224     Flags.Linkage = Linkage;
    225   }
    226 
    227   /// Return true if this global value can't be imported.
    228   bool notEligibleToImport() const { return Flags.NotEligibleToImport; }
    229 
    230   void setLive(bool Live) { Flags.Live = Live; }
    231 
    232   /// Flag that this global value cannot be imported.
    233   void setNotEligibleToImport() { Flags.NotEligibleToImport = true; }
    234 
    235   /// Return the list of values referenced by this global value definition.
    236   ArrayRef<ValueInfo> refs() const { return RefEdgeList; }
    237 
    238   /// If this is an alias summary, returns the summary of the aliased object (a
    239   /// global variable or function), otherwise returns itself.
    240   GlobalValueSummary *getBaseObject();
    241 
    242   friend class ModuleSummaryIndex;
    243   friend void computeDeadSymbols(class ModuleSummaryIndex &,
    244                                  const DenseSet<GlobalValue::GUID> &);
    245 };
    246 
    247 /// \brief Alias summary information.
    248 class AliasSummary : public GlobalValueSummary {
    249   GlobalValueSummary *AliaseeSummary;
    250 
    251 public:
    252   AliasSummary(GVFlags Flags)
    253       : GlobalValueSummary(AliasKind, Flags, ArrayRef<ValueInfo>{}) {}
    254 
    255   /// Check if this is an alias summary.
    256   static bool classof(const GlobalValueSummary *GVS) {
    257     return GVS->getSummaryKind() == AliasKind;
    258   }
    259 
    260   void setAliasee(GlobalValueSummary *Aliasee) { AliaseeSummary = Aliasee; }
    261 
    262   const GlobalValueSummary &getAliasee() const {
    263     assert(AliaseeSummary && "Unexpected missing aliasee summary");
    264     return *AliaseeSummary;
    265   }
    266 
    267   GlobalValueSummary &getAliasee() {
    268     return const_cast<GlobalValueSummary &>(
    269                          static_cast<const AliasSummary *>(this)->getAliasee());
    270   }
    271 };
    272 
    273 inline GlobalValueSummary *GlobalValueSummary::getBaseObject() {
    274   if (auto *AS = dyn_cast<AliasSummary>(this))
    275     return &AS->getAliasee();
    276   return this;
    277 }
    278 
    279 /// \brief Function summary information to aid decisions and implementation of
    280 /// importing.
    281 class FunctionSummary : public GlobalValueSummary {
    282 public:
    283   /// <CalleeValueInfo, CalleeInfo> call edge pair.
    284   using EdgeTy = std::pair<ValueInfo, CalleeInfo>;
    285 
    286   /// An "identifier" for a virtual function. This contains the type identifier
    287   /// represented as a GUID and the offset from the address point to the virtual
    288   /// function pointer, where "address point" is as defined in the Itanium ABI:
    289   /// https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vtable-general
    290   struct VFuncId {
    291     GlobalValue::GUID GUID;
    292     uint64_t Offset;
    293   };
    294 
    295   /// A specification for a virtual function call with all constant integer
    296   /// arguments. This is used to perform virtual constant propagation on the
    297   /// summary.
    298   struct ConstVCall {
    299     VFuncId VFunc;
    300     std::vector<uint64_t> Args;
    301   };
    302 
    303   /// Function attribute flags. Used to track if a function accesses memory,
    304   /// recurses or aliases.
    305   struct FFlags {
    306     unsigned ReadNone : 1;
    307     unsigned ReadOnly : 1;
    308     unsigned NoRecurse : 1;
    309     unsigned ReturnDoesNotAlias : 1;
    310   };
    311 
    312 private:
    313   /// Number of instructions (ignoring debug instructions, e.g.) computed
    314   /// during the initial compile step when the summary index is first built.
    315   unsigned InstCount;
    316 
    317   /// Function attribute flags. Used to track if a function accesses memory,
    318   /// recurses or aliases.
    319   FFlags FunFlags;
    320 
    321   /// List of <CalleeValueInfo, CalleeInfo> call edge pairs from this function.
    322   std::vector<EdgeTy> CallGraphEdgeList;
    323 
    324   /// All type identifier related information. Because these fields are
    325   /// relatively uncommon we only allocate space for them if necessary.
    326   struct TypeIdInfo {
    327     /// List of type identifiers used by this function in llvm.type.test
    328     /// intrinsics other than by an llvm.assume intrinsic, represented as GUIDs.
    329     std::vector<GlobalValue::GUID> TypeTests;
    330 
    331     /// List of virtual calls made by this function using (respectively)
    332     /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics that do
    333     /// not have all constant integer arguments.
    334     std::vector<VFuncId> TypeTestAssumeVCalls, TypeCheckedLoadVCalls;
    335 
    336     /// List of virtual calls made by this function using (respectively)
    337     /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics with
    338     /// all constant integer arguments.
    339     std::vector<ConstVCall> TypeTestAssumeConstVCalls,
    340         TypeCheckedLoadConstVCalls;
    341   };
    342 
    343   std::unique_ptr<TypeIdInfo> TIdInfo;
    344 
    345 public:
    346   FunctionSummary(GVFlags Flags, unsigned NumInsts, FFlags FunFlags,
    347                   std::vector<ValueInfo> Refs, std::vector<EdgeTy> CGEdges,
    348                   std::vector<GlobalValue::GUID> TypeTests,
    349                   std::vector<VFuncId> TypeTestAssumeVCalls,
    350                   std::vector<VFuncId> TypeCheckedLoadVCalls,
    351                   std::vector<ConstVCall> TypeTestAssumeConstVCalls,
    352                   std::vector<ConstVCall> TypeCheckedLoadConstVCalls)
    353       : GlobalValueSummary(FunctionKind, Flags, std::move(Refs)),
    354         InstCount(NumInsts), FunFlags(FunFlags),
    355         CallGraphEdgeList(std::move(CGEdges)) {
    356     if (!TypeTests.empty() || !TypeTestAssumeVCalls.empty() ||
    357         !TypeCheckedLoadVCalls.empty() || !TypeTestAssumeConstVCalls.empty() ||
    358         !TypeCheckedLoadConstVCalls.empty())
    359       TIdInfo = llvm::make_unique<TypeIdInfo>(TypeIdInfo{
    360           std::move(TypeTests), std::move(TypeTestAssumeVCalls),
    361           std::move(TypeCheckedLoadVCalls),
    362           std::move(TypeTestAssumeConstVCalls),
    363           std::move(TypeCheckedLoadConstVCalls)});
    364   }
    365 
    366   /// Check if this is a function summary.
    367   static bool classof(const GlobalValueSummary *GVS) {
    368     return GVS->getSummaryKind() == FunctionKind;
    369   }
    370 
    371   /// Get function attribute flags.
    372   FFlags &fflags() { return FunFlags; }
    373 
    374   /// Get the instruction count recorded for this function.
    375   unsigned instCount() const { return InstCount; }
    376 
    377   /// Return the list of <CalleeValueInfo, CalleeInfo> pairs.
    378   ArrayRef<EdgeTy> calls() const { return CallGraphEdgeList; }
    379 
    380   /// Returns the list of type identifiers used by this function in
    381   /// llvm.type.test intrinsics other than by an llvm.assume intrinsic,
    382   /// represented as GUIDs.
    383   ArrayRef<GlobalValue::GUID> type_tests() const {
    384     if (TIdInfo)
    385       return TIdInfo->TypeTests;
    386     return {};
    387   }
    388 
    389   /// Returns the list of virtual calls made by this function using
    390   /// llvm.assume(llvm.type.test) intrinsics that do not have all constant
    391   /// integer arguments.
    392   ArrayRef<VFuncId> type_test_assume_vcalls() const {
    393     if (TIdInfo)
    394       return TIdInfo->TypeTestAssumeVCalls;
    395     return {};
    396   }
    397 
    398   /// Returns the list of virtual calls made by this function using
    399   /// llvm.type.checked.load intrinsics that do not have all constant integer
    400   /// arguments.
    401   ArrayRef<VFuncId> type_checked_load_vcalls() const {
    402     if (TIdInfo)
    403       return TIdInfo->TypeCheckedLoadVCalls;
    404     return {};
    405   }
    406 
    407   /// Returns the list of virtual calls made by this function using
    408   /// llvm.assume(llvm.type.test) intrinsics with all constant integer
    409   /// arguments.
    410   ArrayRef<ConstVCall> type_test_assume_const_vcalls() const {
    411     if (TIdInfo)
    412       return TIdInfo->TypeTestAssumeConstVCalls;
    413     return {};
    414   }
    415 
    416   /// Returns the list of virtual calls made by this function using
    417   /// llvm.type.checked.load intrinsics with all constant integer arguments.
    418   ArrayRef<ConstVCall> type_checked_load_const_vcalls() const {
    419     if (TIdInfo)
    420       return TIdInfo->TypeCheckedLoadConstVCalls;
    421     return {};
    422   }
    423 
    424   /// Add a type test to the summary. This is used by WholeProgramDevirt if we
    425   /// were unable to devirtualize a checked call.
    426   void addTypeTest(GlobalValue::GUID Guid) {
    427     if (!TIdInfo)
    428       TIdInfo = llvm::make_unique<TypeIdInfo>();
    429     TIdInfo->TypeTests.push_back(Guid);
    430   }
    431 };
    432 
    433 template <> struct DenseMapInfo<FunctionSummary::VFuncId> {
    434   static FunctionSummary::VFuncId getEmptyKey() { return {0, uint64_t(-1)}; }
    435 
    436   static FunctionSummary::VFuncId getTombstoneKey() {
    437     return {0, uint64_t(-2)};
    438   }
    439 
    440   static bool isEqual(FunctionSummary::VFuncId L, FunctionSummary::VFuncId R) {
    441     return L.GUID == R.GUID && L.Offset == R.Offset;
    442   }
    443 
    444   static unsigned getHashValue(FunctionSummary::VFuncId I) { return I.GUID; }
    445 };
    446 
    447 template <> struct DenseMapInfo<FunctionSummary::ConstVCall> {
    448   static FunctionSummary::ConstVCall getEmptyKey() {
    449     return {{0, uint64_t(-1)}, {}};
    450   }
    451 
    452   static FunctionSummary::ConstVCall getTombstoneKey() {
    453     return {{0, uint64_t(-2)}, {}};
    454   }
    455 
    456   static bool isEqual(FunctionSummary::ConstVCall L,
    457                       FunctionSummary::ConstVCall R) {
    458     return DenseMapInfo<FunctionSummary::VFuncId>::isEqual(L.VFunc, R.VFunc) &&
    459            L.Args == R.Args;
    460   }
    461 
    462   static unsigned getHashValue(FunctionSummary::ConstVCall I) {
    463     return I.VFunc.GUID;
    464   }
    465 };
    466 
    467 /// \brief Global variable summary information to aid decisions and
    468 /// implementation of importing.
    469 ///
    470 /// Currently this doesn't add anything to the base \p GlobalValueSummary,
    471 /// but is a placeholder as additional info may be added to the summary
    472 /// for variables.
    473 class GlobalVarSummary : public GlobalValueSummary {
    474 
    475 public:
    476   GlobalVarSummary(GVFlags Flags, std::vector<ValueInfo> Refs)
    477       : GlobalValueSummary(GlobalVarKind, Flags, std::move(Refs)) {}
    478 
    479   /// Check if this is a global variable summary.
    480   static bool classof(const GlobalValueSummary *GVS) {
    481     return GVS->getSummaryKind() == GlobalVarKind;
    482   }
    483 };
    484 
    485 struct TypeTestResolution {
    486   /// Specifies which kind of type check we should emit for this byte array.
    487   /// See http://clang.llvm.org/docs/ControlFlowIntegrityDesign.html for full
    488   /// details on each kind of check; the enumerators are described with
    489   /// reference to that document.
    490   enum Kind {
    491     Unsat,     ///< Unsatisfiable type (i.e. no global has this type metadata)
    492     ByteArray, ///< Test a byte array (first example)
    493     Inline,    ///< Inlined bit vector ("Short Inline Bit Vectors")
    494     Single,    ///< Single element (last example in "Short Inline Bit Vectors")
    495     AllOnes,   ///< All-ones bit vector ("Eliminating Bit Vector Checks for
    496                ///  All-Ones Bit Vectors")
    497   } TheKind = Unsat;
    498 
    499   /// Range of size-1 expressed as a bit width. For example, if the size is in
    500   /// range [1,256], this number will be 8. This helps generate the most compact
    501   /// instruction sequences.
    502   unsigned SizeM1BitWidth = 0;
    503 
    504   // The following fields are only used if the target does not support the use
    505   // of absolute symbols to store constants. Their meanings are the same as the
    506   // corresponding fields in LowerTypeTestsModule::TypeIdLowering in
    507   // LowerTypeTests.cpp.
    508 
    509   uint64_t AlignLog2 = 0;
    510   uint64_t SizeM1 = 0;
    511   uint8_t BitMask = 0;
    512   uint64_t InlineBits = 0;
    513 };
    514 
    515 struct WholeProgramDevirtResolution {
    516   enum Kind {
    517     Indir,      ///< Just do a regular virtual call
    518     SingleImpl, ///< Single implementation devirtualization
    519   } TheKind = Indir;
    520 
    521   std::string SingleImplName;
    522 
    523   struct ByArg {
    524     enum Kind {
    525       Indir,            ///< Just do a regular virtual call
    526       UniformRetVal,    ///< Uniform return value optimization
    527       UniqueRetVal,     ///< Unique return value optimization
    528       VirtualConstProp, ///< Virtual constant propagation
    529     } TheKind = Indir;
    530 
    531     /// Additional information for the resolution:
    532     /// - UniformRetVal: the uniform return value.
    533     /// - UniqueRetVal: the return value associated with the unique vtable (0 or
    534     ///   1).
    535     uint64_t Info = 0;
    536 
    537     // The following fields are only used if the target does not support the use
    538     // of absolute symbols to store constants.
    539 
    540     uint32_t Byte = 0;
    541     uint32_t Bit = 0;
    542   };
    543 
    544   /// Resolutions for calls with all constant integer arguments (excluding the
    545   /// first argument, "this"), where the key is the argument vector.
    546   std::map<std::vector<uint64_t>, ByArg> ResByArg;
    547 };
    548 
    549 struct TypeIdSummary {
    550   TypeTestResolution TTRes;
    551 
    552   /// Mapping from byte offset to whole-program devirt resolution for that
    553   /// (typeid, byte offset) pair.
    554   std::map<uint64_t, WholeProgramDevirtResolution> WPDRes;
    555 };
    556 
    557 /// 160 bits SHA1
    558 using ModuleHash = std::array<uint32_t, 5>;
    559 
    560 /// Type used for iterating through the global value summary map.
    561 using const_gvsummary_iterator = GlobalValueSummaryMapTy::const_iterator;
    562 using gvsummary_iterator = GlobalValueSummaryMapTy::iterator;
    563 
    564 /// String table to hold/own module path strings, which additionally holds the
    565 /// module ID assigned to each module during the plugin step, as well as a hash
    566 /// of the module. The StringMap makes a copy of and owns inserted strings.
    567 using ModulePathStringTableTy = StringMap<std::pair<uint64_t, ModuleHash>>;
    568 
    569 /// Map of global value GUID to its summary, used to identify values defined in
    570 /// a particular module, and provide efficient access to their summary.
    571 using GVSummaryMapTy = DenseMap<GlobalValue::GUID, GlobalValueSummary *>;
    572 
    573 /// Class to hold module path string table and global value map,
    574 /// and encapsulate methods for operating on them.
    575 class ModuleSummaryIndex {
    576 private:
    577   /// Map from value name to list of summary instances for values of that
    578   /// name (may be duplicates in the COMDAT case, e.g.).
    579   GlobalValueSummaryMapTy GlobalValueMap;
    580 
    581   /// Holds strings for combined index, mapping to the corresponding module ID.
    582   ModulePathStringTableTy ModulePathStringTable;
    583 
    584   /// Mapping from type identifiers to summary information for that type
    585   /// identifier.
    586   // FIXME: Add bitcode read/write support for this field.
    587   std::map<std::string, TypeIdSummary> TypeIdMap;
    588 
    589   /// Mapping from original ID to GUID. If original ID can map to multiple
    590   /// GUIDs, it will be mapped to 0.
    591   std::map<GlobalValue::GUID, GlobalValue::GUID> OidGuidMap;
    592 
    593   /// Indicates that summary-based GlobalValue GC has run, and values with
    594   /// GVFlags::Live==false are really dead. Otherwise, all values must be
    595   /// considered live.
    596   bool WithGlobalValueDeadStripping = false;
    597 
    598   std::set<std::string> CfiFunctionDefs;
    599   std::set<std::string> CfiFunctionDecls;
    600 
    601   // YAML I/O support.
    602   friend yaml::MappingTraits<ModuleSummaryIndex>;
    603 
    604   GlobalValueSummaryMapTy::value_type *
    605   getOrInsertValuePtr(GlobalValue::GUID GUID) {
    606     return &*GlobalValueMap.emplace(GUID, GlobalValueSummaryInfo{}).first;
    607   }
    608 
    609 public:
    610   gvsummary_iterator begin() { return GlobalValueMap.begin(); }
    611   const_gvsummary_iterator begin() const { return GlobalValueMap.begin(); }
    612   gvsummary_iterator end() { return GlobalValueMap.end(); }
    613   const_gvsummary_iterator end() const { return GlobalValueMap.end(); }
    614   size_t size() const { return GlobalValueMap.size(); }
    615 
    616   bool withGlobalValueDeadStripping() const {
    617     return WithGlobalValueDeadStripping;
    618   }
    619   void setWithGlobalValueDeadStripping() {
    620     WithGlobalValueDeadStripping = true;
    621   }
    622 
    623   bool isGlobalValueLive(const GlobalValueSummary *GVS) const {
    624     return !WithGlobalValueDeadStripping || GVS->isLive();
    625   }
    626   bool isGUIDLive(GlobalValue::GUID GUID) const;
    627 
    628   /// Return a ValueInfo for GUID if it exists, otherwise return ValueInfo().
    629   ValueInfo getValueInfo(GlobalValue::GUID GUID) const {
    630     auto I = GlobalValueMap.find(GUID);
    631     return ValueInfo(I == GlobalValueMap.end() ? nullptr : &*I);
    632   }
    633 
    634   /// Return a ValueInfo for \p GUID.
    635   ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID) {
    636     return ValueInfo(getOrInsertValuePtr(GUID));
    637   }
    638 
    639   /// Return a ValueInfo for \p GV and mark it as belonging to GV.
    640   ValueInfo getOrInsertValueInfo(const GlobalValue *GV) {
    641     auto VP = getOrInsertValuePtr(GV->getGUID());
    642     VP->second.GV = GV;
    643     return ValueInfo(VP);
    644   }
    645 
    646   /// Return the GUID for \p OriginalId in the OidGuidMap.
    647   GlobalValue::GUID getGUIDFromOriginalID(GlobalValue::GUID OriginalID) const {
    648     const auto I = OidGuidMap.find(OriginalID);
    649     return I == OidGuidMap.end() ? 0 : I->second;
    650   }
    651 
    652   std::set<std::string> &cfiFunctionDefs() { return CfiFunctionDefs; }
    653   const std::set<std::string> &cfiFunctionDefs() const { return CfiFunctionDefs; }
    654 
    655   std::set<std::string> &cfiFunctionDecls() { return CfiFunctionDecls; }
    656   const std::set<std::string> &cfiFunctionDecls() const { return CfiFunctionDecls; }
    657 
    658   /// Add a global value summary for a value of the given name.
    659   void addGlobalValueSummary(StringRef ValueName,
    660                              std::unique_ptr<GlobalValueSummary> Summary) {
    661     addGlobalValueSummary(getOrInsertValueInfo(GlobalValue::getGUID(ValueName)),
    662                           std::move(Summary));
    663   }
    664 
    665   /// Add a global value summary for the given ValueInfo.
    666   void addGlobalValueSummary(ValueInfo VI,
    667                              std::unique_ptr<GlobalValueSummary> Summary) {
    668     addOriginalName(VI.getGUID(), Summary->getOriginalName());
    669     // Here we have a notionally const VI, but the value it points to is owned
    670     // by the non-const *this.
    671     const_cast<GlobalValueSummaryMapTy::value_type *>(VI.Ref)
    672         ->second.SummaryList.push_back(std::move(Summary));
    673   }
    674 
    675   /// Add an original name for the value of the given GUID.
    676   void addOriginalName(GlobalValue::GUID ValueGUID,
    677                        GlobalValue::GUID OrigGUID) {
    678     if (OrigGUID == 0 || ValueGUID == OrigGUID)
    679       return;
    680     if (OidGuidMap.count(OrigGUID) && OidGuidMap[OrigGUID] != ValueGUID)
    681       OidGuidMap[OrigGUID] = 0;
    682     else
    683       OidGuidMap[OrigGUID] = ValueGUID;
    684   }
    685 
    686   /// Find the summary for global \p GUID in module \p ModuleId, or nullptr if
    687   /// not found.
    688   GlobalValueSummary *findSummaryInModule(GlobalValue::GUID ValueGUID,
    689                                           StringRef ModuleId) const {
    690     auto CalleeInfo = getValueInfo(ValueGUID);
    691     if (!CalleeInfo) {
    692       return nullptr; // This function does not have a summary
    693     }
    694     auto Summary =
    695         llvm::find_if(CalleeInfo.getSummaryList(),
    696                       [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
    697                         return Summary->modulePath() == ModuleId;
    698                       });
    699     if (Summary == CalleeInfo.getSummaryList().end())
    700       return nullptr;
    701     return Summary->get();
    702   }
    703 
    704   /// Returns the first GlobalValueSummary for \p GV, asserting that there
    705   /// is only one if \p PerModuleIndex.
    706   GlobalValueSummary *getGlobalValueSummary(const GlobalValue &GV,
    707                                             bool PerModuleIndex = true) const {
    708     assert(GV.hasName() && "Can't get GlobalValueSummary for GV with no name");
    709     return getGlobalValueSummary(GlobalValue::getGUID(GV.getName()),
    710                                  PerModuleIndex);
    711   }
    712 
    713   /// Returns the first GlobalValueSummary for \p ValueGUID, asserting that
    714   /// there
    715   /// is only one if \p PerModuleIndex.
    716   GlobalValueSummary *getGlobalValueSummary(GlobalValue::GUID ValueGUID,
    717                                             bool PerModuleIndex = true) const;
    718 
    719   /// Table of modules, containing module hash and id.
    720   const StringMap<std::pair<uint64_t, ModuleHash>> &modulePaths() const {
    721     return ModulePathStringTable;
    722   }
    723 
    724   /// Table of modules, containing hash and id.
    725   StringMap<std::pair<uint64_t, ModuleHash>> &modulePaths() {
    726     return ModulePathStringTable;
    727   }
    728 
    729   /// Get the module ID recorded for the given module path.
    730   uint64_t getModuleId(const StringRef ModPath) const {
    731     return ModulePathStringTable.lookup(ModPath).first;
    732   }
    733 
    734   /// Get the module SHA1 hash recorded for the given module path.
    735   const ModuleHash &getModuleHash(const StringRef ModPath) const {
    736     auto It = ModulePathStringTable.find(ModPath);
    737     assert(It != ModulePathStringTable.end() && "Module not registered");
    738     return It->second.second;
    739   }
    740 
    741   /// Convenience method for creating a promoted global name
    742   /// for the given value name of a local, and its original module's ID.
    743   static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash) {
    744     SmallString<256> NewName(Name);
    745     NewName += ".llvm.";
    746     NewName += utostr(ModHash[0]); // Take the first 32 bits
    747     return NewName.str();
    748   }
    749 
    750   /// Helper to obtain the unpromoted name for a global value (or the original
    751   /// name if not promoted).
    752   static StringRef getOriginalNameBeforePromote(StringRef Name) {
    753     std::pair<StringRef, StringRef> Pair = Name.split(".llvm.");
    754     return Pair.first;
    755   }
    756 
    757   typedef ModulePathStringTableTy::value_type ModuleInfo;
    758 
    759   /// Add a new module with the given \p Hash, mapped to the given \p
    760   /// ModID, and return a reference to the module.
    761   ModuleInfo *addModule(StringRef ModPath, uint64_t ModId,
    762                         ModuleHash Hash = ModuleHash{{0}}) {
    763     return &*ModulePathStringTable.insert({ModPath, {ModId, Hash}}).first;
    764   }
    765 
    766   /// Check if the given Module has any functions available for exporting
    767   /// in the index. We consider any module present in the ModulePathStringTable
    768   /// to have exported functions.
    769   bool hasExportedFunctions(const Module &M) const {
    770     return ModulePathStringTable.count(M.getModuleIdentifier());
    771   }
    772 
    773   const std::map<std::string, TypeIdSummary> &typeIds() const {
    774     return TypeIdMap;
    775   }
    776 
    777   /// This accessor should only be used when exporting because it can mutate the
    778   /// map.
    779   TypeIdSummary &getOrInsertTypeIdSummary(StringRef TypeId) {
    780     return TypeIdMap[TypeId];
    781   }
    782 
    783   /// This returns either a pointer to the type id summary (if present in the
    784   /// summary map) or null (if not present). This may be used when importing.
    785   const TypeIdSummary *getTypeIdSummary(StringRef TypeId) const {
    786     auto I = TypeIdMap.find(TypeId);
    787     if (I == TypeIdMap.end())
    788       return nullptr;
    789     return &I->second;
    790   }
    791 
    792   /// Collect for the given module the list of function it defines
    793   /// (GUID -> Summary).
    794   void collectDefinedFunctionsForModule(StringRef ModulePath,
    795                                         GVSummaryMapTy &GVSummaryMap) const;
    796 
    797   /// Collect for each module the list of Summaries it defines (GUID ->
    798   /// Summary).
    799   void collectDefinedGVSummariesPerModule(
    800       StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries) const;
    801 };
    802 
    803 } // end namespace llvm
    804 
    805 #endif // LLVM_IR_MODULESUMMARYINDEX_H
    806