ModuleSummaryIndex.h 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ModuleSummaryIndex.h - Module Summary Index ---------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. /// @file
  15. /// ModuleSummaryIndex.h This file contains the declarations the classes that
  16. /// hold the module index and summary for function importing.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_IR_MODULESUMMARYINDEX_H
  20. #define LLVM_IR_MODULESUMMARYINDEX_H
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringExtras.h"
  27. #include "llvm/ADT/StringMap.h"
  28. #include "llvm/ADT/StringRef.h"
  29. #include "llvm/IR/ConstantRange.h"
  30. #include "llvm/IR/GlobalValue.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/Support/Allocator.h"
  33. #include "llvm/Support/MathExtras.h"
  34. #include "llvm/Support/ScaledNumber.h"
  35. #include "llvm/Support/StringSaver.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include <algorithm>
  38. #include <array>
  39. #include <cassert>
  40. #include <cstddef>
  41. #include <cstdint>
  42. #include <map>
  43. #include <memory>
  44. #include <optional>
  45. #include <set>
  46. #include <string>
  47. #include <utility>
  48. #include <vector>
  49. namespace llvm {
  50. template <class GraphType> struct GraphTraits;
  51. namespace yaml {
  52. template <typename T> struct MappingTraits;
  53. } // end namespace yaml
  54. /// Class to accumulate and hold information about a callee.
  55. struct CalleeInfo {
  56. enum class HotnessType : uint8_t {
  57. Unknown = 0,
  58. Cold = 1,
  59. None = 2,
  60. Hot = 3,
  61. Critical = 4
  62. };
  63. // The size of the bit-field might need to be adjusted if more values are
  64. // added to HotnessType enum.
  65. uint32_t Hotness : 3;
  66. /// The value stored in RelBlockFreq has to be interpreted as the digits of
  67. /// a scaled number with a scale of \p -ScaleShift.
  68. uint32_t RelBlockFreq : 29;
  69. static constexpr int32_t ScaleShift = 8;
  70. static constexpr uint64_t MaxRelBlockFreq = (1 << 29) - 1;
  71. CalleeInfo()
  72. : Hotness(static_cast<uint32_t>(HotnessType::Unknown)), RelBlockFreq(0) {}
  73. explicit CalleeInfo(HotnessType Hotness, uint64_t RelBF)
  74. : Hotness(static_cast<uint32_t>(Hotness)), RelBlockFreq(RelBF) {}
  75. void updateHotness(const HotnessType OtherHotness) {
  76. Hotness = std::max(Hotness, static_cast<uint32_t>(OtherHotness));
  77. }
  78. HotnessType getHotness() const { return HotnessType(Hotness); }
  79. /// Update \p RelBlockFreq from \p BlockFreq and \p EntryFreq
  80. ///
  81. /// BlockFreq is divided by EntryFreq and added to RelBlockFreq. To represent
  82. /// fractional values, the result is represented as a fixed point number with
  83. /// scale of -ScaleShift.
  84. void updateRelBlockFreq(uint64_t BlockFreq, uint64_t EntryFreq) {
  85. if (EntryFreq == 0)
  86. return;
  87. using Scaled64 = ScaledNumber<uint64_t>;
  88. Scaled64 Temp(BlockFreq, ScaleShift);
  89. Temp /= Scaled64::get(EntryFreq);
  90. uint64_t Sum =
  91. SaturatingAdd<uint64_t>(Temp.toInt<uint64_t>(), RelBlockFreq);
  92. Sum = std::min(Sum, uint64_t(MaxRelBlockFreq));
  93. RelBlockFreq = static_cast<uint32_t>(Sum);
  94. }
  95. };
  96. inline const char *getHotnessName(CalleeInfo::HotnessType HT) {
  97. switch (HT) {
  98. case CalleeInfo::HotnessType::Unknown:
  99. return "unknown";
  100. case CalleeInfo::HotnessType::Cold:
  101. return "cold";
  102. case CalleeInfo::HotnessType::None:
  103. return "none";
  104. case CalleeInfo::HotnessType::Hot:
  105. return "hot";
  106. case CalleeInfo::HotnessType::Critical:
  107. return "critical";
  108. }
  109. llvm_unreachable("invalid hotness");
  110. }
  111. class GlobalValueSummary;
  112. using GlobalValueSummaryList = std::vector<std::unique_ptr<GlobalValueSummary>>;
  113. struct alignas(8) GlobalValueSummaryInfo {
  114. union NameOrGV {
  115. NameOrGV(bool HaveGVs) {
  116. if (HaveGVs)
  117. GV = nullptr;
  118. else
  119. Name = "";
  120. }
  121. /// The GlobalValue corresponding to this summary. This is only used in
  122. /// per-module summaries and when the IR is available. E.g. when module
  123. /// analysis is being run, or when parsing both the IR and the summary
  124. /// from assembly.
  125. const GlobalValue *GV;
  126. /// Summary string representation. This StringRef points to BC module
  127. /// string table and is valid until module data is stored in memory.
  128. /// This is guaranteed to happen until runThinLTOBackend function is
  129. /// called, so it is safe to use this field during thin link. This field
  130. /// is only valid if summary index was loaded from BC file.
  131. StringRef Name;
  132. } U;
  133. GlobalValueSummaryInfo(bool HaveGVs) : U(HaveGVs) {}
  134. /// List of global value summary structures for a particular value held
  135. /// in the GlobalValueMap. Requires a vector in the case of multiple
  136. /// COMDAT values of the same name.
  137. GlobalValueSummaryList SummaryList;
  138. };
  139. /// Map from global value GUID to corresponding summary structures. Use a
  140. /// std::map rather than a DenseMap so that pointers to the map's value_type
  141. /// (which are used by ValueInfo) are not invalidated by insertion. Also it will
  142. /// likely incur less overhead, as the value type is not very small and the size
  143. /// of the map is unknown, resulting in inefficiencies due to repeated
  144. /// insertions and resizing.
  145. using GlobalValueSummaryMapTy =
  146. std::map<GlobalValue::GUID, GlobalValueSummaryInfo>;
  147. /// Struct that holds a reference to a particular GUID in a global value
  148. /// summary.
  149. struct ValueInfo {
  150. enum Flags { HaveGV = 1, ReadOnly = 2, WriteOnly = 4 };
  151. PointerIntPair<const GlobalValueSummaryMapTy::value_type *, 3, int>
  152. RefAndFlags;
  153. ValueInfo() = default;
  154. ValueInfo(bool HaveGVs, const GlobalValueSummaryMapTy::value_type *R) {
  155. RefAndFlags.setPointer(R);
  156. RefAndFlags.setInt(HaveGVs);
  157. }
  158. explicit operator bool() const { return getRef(); }
  159. GlobalValue::GUID getGUID() const { return getRef()->first; }
  160. const GlobalValue *getValue() const {
  161. assert(haveGVs());
  162. return getRef()->second.U.GV;
  163. }
  164. ArrayRef<std::unique_ptr<GlobalValueSummary>> getSummaryList() const {
  165. return getRef()->second.SummaryList;
  166. }
  167. StringRef name() const {
  168. return haveGVs() ? getRef()->second.U.GV->getName()
  169. : getRef()->second.U.Name;
  170. }
  171. bool haveGVs() const { return RefAndFlags.getInt() & HaveGV; }
  172. bool isReadOnly() const {
  173. assert(isValidAccessSpecifier());
  174. return RefAndFlags.getInt() & ReadOnly;
  175. }
  176. bool isWriteOnly() const {
  177. assert(isValidAccessSpecifier());
  178. return RefAndFlags.getInt() & WriteOnly;
  179. }
  180. unsigned getAccessSpecifier() const {
  181. assert(isValidAccessSpecifier());
  182. return RefAndFlags.getInt() & (ReadOnly | WriteOnly);
  183. }
  184. bool isValidAccessSpecifier() const {
  185. unsigned BadAccessMask = ReadOnly | WriteOnly;
  186. return (RefAndFlags.getInt() & BadAccessMask) != BadAccessMask;
  187. }
  188. void setReadOnly() {
  189. // We expect ro/wo attribute to set only once during
  190. // ValueInfo lifetime.
  191. assert(getAccessSpecifier() == 0);
  192. RefAndFlags.setInt(RefAndFlags.getInt() | ReadOnly);
  193. }
  194. void setWriteOnly() {
  195. assert(getAccessSpecifier() == 0);
  196. RefAndFlags.setInt(RefAndFlags.getInt() | WriteOnly);
  197. }
  198. const GlobalValueSummaryMapTy::value_type *getRef() const {
  199. return RefAndFlags.getPointer();
  200. }
  201. /// Returns the most constraining visibility among summaries. The
  202. /// visibilities, ordered from least to most constraining, are: default,
  203. /// protected and hidden.
  204. GlobalValue::VisibilityTypes getELFVisibility() const;
  205. /// Checks if all summaries are DSO local (have the flag set). When DSOLocal
  206. /// propagation has been done, set the parameter to enable fast check.
  207. bool isDSOLocal(bool WithDSOLocalPropagation = false) const;
  208. /// Checks if all copies are eligible for auto-hiding (have flag set).
  209. bool canAutoHide() const;
  210. };
  211. inline raw_ostream &operator<<(raw_ostream &OS, const ValueInfo &VI) {
  212. OS << VI.getGUID();
  213. if (!VI.name().empty())
  214. OS << " (" << VI.name() << ")";
  215. return OS;
  216. }
  217. inline bool operator==(const ValueInfo &A, const ValueInfo &B) {
  218. assert(A.getRef() && B.getRef() &&
  219. "Need ValueInfo with non-null Ref for comparison");
  220. return A.getRef() == B.getRef();
  221. }
  222. inline bool operator!=(const ValueInfo &A, const ValueInfo &B) {
  223. assert(A.getRef() && B.getRef() &&
  224. "Need ValueInfo with non-null Ref for comparison");
  225. return A.getRef() != B.getRef();
  226. }
  227. inline bool operator<(const ValueInfo &A, const ValueInfo &B) {
  228. assert(A.getRef() && B.getRef() &&
  229. "Need ValueInfo with non-null Ref to compare GUIDs");
  230. return A.getGUID() < B.getGUID();
  231. }
  232. template <> struct DenseMapInfo<ValueInfo> {
  233. static inline ValueInfo getEmptyKey() {
  234. return ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
  235. }
  236. static inline ValueInfo getTombstoneKey() {
  237. return ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-16);
  238. }
  239. static inline bool isSpecialKey(ValueInfo V) {
  240. return V == getTombstoneKey() || V == getEmptyKey();
  241. }
  242. static bool isEqual(ValueInfo L, ValueInfo R) {
  243. // We are not supposed to mix ValueInfo(s) with different HaveGVs flag
  244. // in a same container.
  245. assert(isSpecialKey(L) || isSpecialKey(R) || (L.haveGVs() == R.haveGVs()));
  246. return L.getRef() == R.getRef();
  247. }
  248. static unsigned getHashValue(ValueInfo I) { return (uintptr_t)I.getRef(); }
  249. };
  250. /// Summary of memprof callsite metadata.
  251. struct CallsiteInfo {
  252. // Actual callee function.
  253. ValueInfo Callee;
  254. // Used to record whole program analysis cloning decisions.
  255. // The ThinLTO backend will need to create as many clones as there are entries
  256. // in the vector (it is expected and should be confirmed that all such
  257. // summaries in the same FunctionSummary have the same number of entries).
  258. // Each index records version info for the corresponding clone of this
  259. // function. The value is the callee clone it calls (becomes the appended
  260. // suffix id). Index 0 is the original version, and a value of 0 calls the
  261. // original callee.
  262. SmallVector<unsigned> Clones{0};
  263. // Represents stack ids in this context, recorded as indices into the
  264. // StackIds vector in the summary index, which in turn holds the full 64-bit
  265. // stack ids. This reduces memory as there are in practice far fewer unique
  266. // stack ids than stack id references.
  267. SmallVector<unsigned> StackIdIndices;
  268. CallsiteInfo(ValueInfo Callee, SmallVector<unsigned> StackIdIndices)
  269. : Callee(Callee), StackIdIndices(std::move(StackIdIndices)) {}
  270. CallsiteInfo(ValueInfo Callee, SmallVector<unsigned> Clones,
  271. SmallVector<unsigned> StackIdIndices)
  272. : Callee(Callee), Clones(std::move(Clones)),
  273. StackIdIndices(std::move(StackIdIndices)) {}
  274. };
  275. // Allocation type assigned to an allocation reached by a given context.
  276. // More can be added but initially this is just noncold and cold.
  277. // Values should be powers of two so that they can be ORed, in particular to
  278. // track allocations that have different behavior with different calling
  279. // contexts.
  280. enum class AllocationType : uint8_t { None = 0, NotCold = 1, Cold = 2 };
  281. /// Summary of a single MIB in a memprof metadata on allocations.
  282. struct MIBInfo {
  283. // The allocation type for this profiled context.
  284. AllocationType AllocType;
  285. // Represents stack ids in this context, recorded as indices into the
  286. // StackIds vector in the summary index, which in turn holds the full 64-bit
  287. // stack ids. This reduces memory as there are in practice far fewer unique
  288. // stack ids than stack id references.
  289. SmallVector<unsigned> StackIdIndices;
  290. MIBInfo(AllocationType AllocType, SmallVector<unsigned> StackIdIndices)
  291. : AllocType(AllocType), StackIdIndices(std::move(StackIdIndices)) {}
  292. };
  293. /// Summary of memprof metadata on allocations.
  294. struct AllocInfo {
  295. // Used to record whole program analysis cloning decisions.
  296. // The ThinLTO backend will need to create as many clones as there are entries
  297. // in the vector (it is expected and should be confirmed that all such
  298. // summaries in the same FunctionSummary have the same number of entries).
  299. // Each index records version info for the corresponding clone of this
  300. // function. The value is the allocation type of the corresponding allocation.
  301. // Index 0 is the original version. Before cloning, index 0 may have more than
  302. // one allocation type.
  303. SmallVector<uint8_t> Versions;
  304. // Vector of MIBs in this memprof metadata.
  305. std::vector<MIBInfo> MIBs;
  306. AllocInfo(std::vector<MIBInfo> MIBs) : MIBs(std::move(MIBs)) {
  307. Versions.push_back(0);
  308. }
  309. AllocInfo(SmallVector<uint8_t> Versions, std::vector<MIBInfo> MIBs)
  310. : Versions(std::move(Versions)), MIBs(std::move(MIBs)) {}
  311. };
  312. /// Function and variable summary information to aid decisions and
  313. /// implementation of importing.
  314. class GlobalValueSummary {
  315. public:
  316. /// Sububclass discriminator (for dyn_cast<> et al.)
  317. enum SummaryKind : unsigned { AliasKind, FunctionKind, GlobalVarKind };
  318. /// Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
  319. struct GVFlags {
  320. /// The linkage type of the associated global value.
  321. ///
  322. /// One use is to flag values that have local linkage types and need to
  323. /// have module identifier appended before placing into the combined
  324. /// index, to disambiguate from other values with the same name.
  325. /// In the future this will be used to update and optimize linkage
  326. /// types based on global summary-based analysis.
  327. unsigned Linkage : 4;
  328. /// Indicates the visibility.
  329. unsigned Visibility : 2;
  330. /// Indicate if the global value cannot be imported (e.g. it cannot
  331. /// be renamed or references something that can't be renamed).
  332. unsigned NotEligibleToImport : 1;
  333. /// In per-module summary, indicate that the global value must be considered
  334. /// a live root for index-based liveness analysis. Used for special LLVM
  335. /// values such as llvm.global_ctors that the linker does not know about.
  336. ///
  337. /// In combined summary, indicate that the global value is live.
  338. unsigned Live : 1;
  339. /// Indicates that the linker resolved the symbol to a definition from
  340. /// within the same linkage unit.
  341. unsigned DSOLocal : 1;
  342. /// In the per-module summary, indicates that the global value is
  343. /// linkonce_odr and global unnamed addr (so eligible for auto-hiding
  344. /// via hidden visibility). In the combined summary, indicates that the
  345. /// prevailing linkonce_odr copy can be auto-hidden via hidden visibility
  346. /// when it is upgraded to weak_odr in the backend. This is legal when
  347. /// all copies are eligible for auto-hiding (i.e. all copies were
  348. /// linkonce_odr global unnamed addr. If any copy is not (e.g. it was
  349. /// originally weak_odr, we cannot auto-hide the prevailing copy as it
  350. /// means the symbol was externally visible.
  351. unsigned CanAutoHide : 1;
  352. /// Convenience Constructors
  353. explicit GVFlags(GlobalValue::LinkageTypes Linkage,
  354. GlobalValue::VisibilityTypes Visibility,
  355. bool NotEligibleToImport, bool Live, bool IsLocal,
  356. bool CanAutoHide)
  357. : Linkage(Linkage), Visibility(Visibility),
  358. NotEligibleToImport(NotEligibleToImport), Live(Live),
  359. DSOLocal(IsLocal), CanAutoHide(CanAutoHide) {}
  360. };
  361. private:
  362. /// Kind of summary for use in dyn_cast<> et al.
  363. SummaryKind Kind;
  364. GVFlags Flags;
  365. /// This is the hash of the name of the symbol in the original file. It is
  366. /// identical to the GUID for global symbols, but differs for local since the
  367. /// GUID includes the module level id in the hash.
  368. GlobalValue::GUID OriginalName = 0;
  369. /// Path of module IR containing value's definition, used to locate
  370. /// module during importing.
  371. ///
  372. /// This is only used during parsing of the combined index, or when
  373. /// parsing the per-module index for creation of the combined summary index,
  374. /// not during writing of the per-module index which doesn't contain a
  375. /// module path string table.
  376. StringRef ModulePath;
  377. /// List of values referenced by this global value's definition
  378. /// (either by the initializer of a global variable, or referenced
  379. /// from within a function). This does not include functions called, which
  380. /// are listed in the derived FunctionSummary object.
  381. std::vector<ValueInfo> RefEdgeList;
  382. protected:
  383. GlobalValueSummary(SummaryKind K, GVFlags Flags, std::vector<ValueInfo> Refs)
  384. : Kind(K), Flags(Flags), RefEdgeList(std::move(Refs)) {
  385. assert((K != AliasKind || Refs.empty()) &&
  386. "Expect no references for AliasSummary");
  387. }
  388. public:
  389. virtual ~GlobalValueSummary() = default;
  390. /// Returns the hash of the original name, it is identical to the GUID for
  391. /// externally visible symbols, but not for local ones.
  392. GlobalValue::GUID getOriginalName() const { return OriginalName; }
  393. /// Initialize the original name hash in this summary.
  394. void setOriginalName(GlobalValue::GUID Name) { OriginalName = Name; }
  395. /// Which kind of summary subclass this is.
  396. SummaryKind getSummaryKind() const { return Kind; }
  397. /// Set the path to the module containing this function, for use in
  398. /// the combined index.
  399. void setModulePath(StringRef ModPath) { ModulePath = ModPath; }
  400. /// Get the path to the module containing this function.
  401. StringRef modulePath() const { return ModulePath; }
  402. /// Get the flags for this GlobalValue (see \p struct GVFlags).
  403. GVFlags flags() const { return Flags; }
  404. /// Return linkage type recorded for this global value.
  405. GlobalValue::LinkageTypes linkage() const {
  406. return static_cast<GlobalValue::LinkageTypes>(Flags.Linkage);
  407. }
  408. /// Sets the linkage to the value determined by global summary-based
  409. /// optimization. Will be applied in the ThinLTO backends.
  410. void setLinkage(GlobalValue::LinkageTypes Linkage) {
  411. Flags.Linkage = Linkage;
  412. }
  413. /// Return true if this global value can't be imported.
  414. bool notEligibleToImport() const { return Flags.NotEligibleToImport; }
  415. bool isLive() const { return Flags.Live; }
  416. void setLive(bool Live) { Flags.Live = Live; }
  417. void setDSOLocal(bool Local) { Flags.DSOLocal = Local; }
  418. bool isDSOLocal() const { return Flags.DSOLocal; }
  419. void setCanAutoHide(bool CanAutoHide) { Flags.CanAutoHide = CanAutoHide; }
  420. bool canAutoHide() const { return Flags.CanAutoHide; }
  421. GlobalValue::VisibilityTypes getVisibility() const {
  422. return (GlobalValue::VisibilityTypes)Flags.Visibility;
  423. }
  424. void setVisibility(GlobalValue::VisibilityTypes Vis) {
  425. Flags.Visibility = (unsigned)Vis;
  426. }
  427. /// Flag that this global value cannot be imported.
  428. void setNotEligibleToImport() { Flags.NotEligibleToImport = true; }
  429. /// Return the list of values referenced by this global value definition.
  430. ArrayRef<ValueInfo> refs() const { return RefEdgeList; }
  431. /// If this is an alias summary, returns the summary of the aliased object (a
  432. /// global variable or function), otherwise returns itself.
  433. GlobalValueSummary *getBaseObject();
  434. const GlobalValueSummary *getBaseObject() const;
  435. friend class ModuleSummaryIndex;
  436. };
  437. /// Alias summary information.
  438. class AliasSummary : public GlobalValueSummary {
  439. ValueInfo AliaseeValueInfo;
  440. /// This is the Aliasee in the same module as alias (could get from VI, trades
  441. /// memory for time). Note that this pointer may be null (and the value info
  442. /// empty) when we have a distributed index where the alias is being imported
  443. /// (as a copy of the aliasee), but the aliasee is not.
  444. GlobalValueSummary *AliaseeSummary;
  445. public:
  446. AliasSummary(GVFlags Flags)
  447. : GlobalValueSummary(AliasKind, Flags, ArrayRef<ValueInfo>{}),
  448. AliaseeSummary(nullptr) {}
  449. /// Check if this is an alias summary.
  450. static bool classof(const GlobalValueSummary *GVS) {
  451. return GVS->getSummaryKind() == AliasKind;
  452. }
  453. void setAliasee(ValueInfo &AliaseeVI, GlobalValueSummary *Aliasee) {
  454. AliaseeValueInfo = AliaseeVI;
  455. AliaseeSummary = Aliasee;
  456. }
  457. bool hasAliasee() const {
  458. assert(!!AliaseeSummary == (AliaseeValueInfo &&
  459. !AliaseeValueInfo.getSummaryList().empty()) &&
  460. "Expect to have both aliasee summary and summary list or neither");
  461. return !!AliaseeSummary;
  462. }
  463. const GlobalValueSummary &getAliasee() const {
  464. assert(AliaseeSummary && "Unexpected missing aliasee summary");
  465. return *AliaseeSummary;
  466. }
  467. GlobalValueSummary &getAliasee() {
  468. return const_cast<GlobalValueSummary &>(
  469. static_cast<const AliasSummary *>(this)->getAliasee());
  470. }
  471. ValueInfo getAliaseeVI() const {
  472. assert(AliaseeValueInfo && "Unexpected missing aliasee");
  473. return AliaseeValueInfo;
  474. }
  475. GlobalValue::GUID getAliaseeGUID() const {
  476. assert(AliaseeValueInfo && "Unexpected missing aliasee");
  477. return AliaseeValueInfo.getGUID();
  478. }
  479. };
  480. const inline GlobalValueSummary *GlobalValueSummary::getBaseObject() const {
  481. if (auto *AS = dyn_cast<AliasSummary>(this))
  482. return &AS->getAliasee();
  483. return this;
  484. }
  485. inline GlobalValueSummary *GlobalValueSummary::getBaseObject() {
  486. if (auto *AS = dyn_cast<AliasSummary>(this))
  487. return &AS->getAliasee();
  488. return this;
  489. }
  490. /// Function summary information to aid decisions and implementation of
  491. /// importing.
  492. class FunctionSummary : public GlobalValueSummary {
  493. public:
  494. /// <CalleeValueInfo, CalleeInfo> call edge pair.
  495. using EdgeTy = std::pair<ValueInfo, CalleeInfo>;
  496. /// Types for -force-summary-edges-cold debugging option.
  497. enum ForceSummaryHotnessType : unsigned {
  498. FSHT_None,
  499. FSHT_AllNonCritical,
  500. FSHT_All
  501. };
  502. /// An "identifier" for a virtual function. This contains the type identifier
  503. /// represented as a GUID and the offset from the address point to the virtual
  504. /// function pointer, where "address point" is as defined in the Itanium ABI:
  505. /// https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vtable-general
  506. struct VFuncId {
  507. GlobalValue::GUID GUID;
  508. uint64_t Offset;
  509. };
  510. /// A specification for a virtual function call with all constant integer
  511. /// arguments. This is used to perform virtual constant propagation on the
  512. /// summary.
  513. struct ConstVCall {
  514. VFuncId VFunc;
  515. std::vector<uint64_t> Args;
  516. };
  517. /// All type identifier related information. Because these fields are
  518. /// relatively uncommon we only allocate space for them if necessary.
  519. struct TypeIdInfo {
  520. /// List of type identifiers used by this function in llvm.type.test
  521. /// intrinsics referenced by something other than an llvm.assume intrinsic,
  522. /// represented as GUIDs.
  523. std::vector<GlobalValue::GUID> TypeTests;
  524. /// List of virtual calls made by this function using (respectively)
  525. /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics that do
  526. /// not have all constant integer arguments.
  527. std::vector<VFuncId> TypeTestAssumeVCalls, TypeCheckedLoadVCalls;
  528. /// List of virtual calls made by this function using (respectively)
  529. /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics with
  530. /// all constant integer arguments.
  531. std::vector<ConstVCall> TypeTestAssumeConstVCalls,
  532. TypeCheckedLoadConstVCalls;
  533. };
  534. /// Flags specific to function summaries.
  535. struct FFlags {
  536. // Function attribute flags. Used to track if a function accesses memory,
  537. // recurses or aliases.
  538. unsigned ReadNone : 1;
  539. unsigned ReadOnly : 1;
  540. unsigned NoRecurse : 1;
  541. unsigned ReturnDoesNotAlias : 1;
  542. // Indicate if the global value cannot be inlined.
  543. unsigned NoInline : 1;
  544. // Indicate if function should be always inlined.
  545. unsigned AlwaysInline : 1;
  546. // Indicate if function never raises an exception. Can be modified during
  547. // thinlink function attribute propagation
  548. unsigned NoUnwind : 1;
  549. // Indicate if function contains instructions that mayThrow
  550. unsigned MayThrow : 1;
  551. // If there are calls to unknown targets (e.g. indirect)
  552. unsigned HasUnknownCall : 1;
  553. // Indicate if a function must be an unreachable function.
  554. //
  555. // This bit is sufficient but not necessary;
  556. // if this bit is on, the function must be regarded as unreachable;
  557. // if this bit is off, the function might be reachable or unreachable.
  558. unsigned MustBeUnreachable : 1;
  559. FFlags &operator&=(const FFlags &RHS) {
  560. this->ReadNone &= RHS.ReadNone;
  561. this->ReadOnly &= RHS.ReadOnly;
  562. this->NoRecurse &= RHS.NoRecurse;
  563. this->ReturnDoesNotAlias &= RHS.ReturnDoesNotAlias;
  564. this->NoInline &= RHS.NoInline;
  565. this->AlwaysInline &= RHS.AlwaysInline;
  566. this->NoUnwind &= RHS.NoUnwind;
  567. this->MayThrow &= RHS.MayThrow;
  568. this->HasUnknownCall &= RHS.HasUnknownCall;
  569. this->MustBeUnreachable &= RHS.MustBeUnreachable;
  570. return *this;
  571. }
  572. bool anyFlagSet() {
  573. return this->ReadNone | this->ReadOnly | this->NoRecurse |
  574. this->ReturnDoesNotAlias | this->NoInline | this->AlwaysInline |
  575. this->NoUnwind | this->MayThrow | this->HasUnknownCall |
  576. this->MustBeUnreachable;
  577. }
  578. operator std::string() {
  579. std::string Output;
  580. raw_string_ostream OS(Output);
  581. OS << "funcFlags: (";
  582. OS << "readNone: " << this->ReadNone;
  583. OS << ", readOnly: " << this->ReadOnly;
  584. OS << ", noRecurse: " << this->NoRecurse;
  585. OS << ", returnDoesNotAlias: " << this->ReturnDoesNotAlias;
  586. OS << ", noInline: " << this->NoInline;
  587. OS << ", alwaysInline: " << this->AlwaysInline;
  588. OS << ", noUnwind: " << this->NoUnwind;
  589. OS << ", mayThrow: " << this->MayThrow;
  590. OS << ", hasUnknownCall: " << this->HasUnknownCall;
  591. OS << ", mustBeUnreachable: " << this->MustBeUnreachable;
  592. OS << ")";
  593. return OS.str();
  594. }
  595. };
  596. /// Describes the uses of a parameter by the function.
  597. struct ParamAccess {
  598. static constexpr uint32_t RangeWidth = 64;
  599. /// Describes the use of a value in a call instruction, specifying the
  600. /// call's target, the value's parameter number, and the possible range of
  601. /// offsets from the beginning of the value that are passed.
  602. struct Call {
  603. uint64_t ParamNo = 0;
  604. ValueInfo Callee;
  605. ConstantRange Offsets{/*BitWidth=*/RangeWidth, /*isFullSet=*/true};
  606. Call() = default;
  607. Call(uint64_t ParamNo, ValueInfo Callee, const ConstantRange &Offsets)
  608. : ParamNo(ParamNo), Callee(Callee), Offsets(Offsets) {}
  609. };
  610. uint64_t ParamNo = 0;
  611. /// The range contains byte offsets from the parameter pointer which
  612. /// accessed by the function. In the per-module summary, it only includes
  613. /// accesses made by the function instructions. In the combined summary, it
  614. /// also includes accesses by nested function calls.
  615. ConstantRange Use{/*BitWidth=*/RangeWidth, /*isFullSet=*/true};
  616. /// In the per-module summary, it summarizes the byte offset applied to each
  617. /// pointer parameter before passing to each corresponding callee.
  618. /// In the combined summary, it's empty and information is propagated by
  619. /// inter-procedural analysis and applied to the Use field.
  620. std::vector<Call> Calls;
  621. ParamAccess() = default;
  622. ParamAccess(uint64_t ParamNo, const ConstantRange &Use)
  623. : ParamNo(ParamNo), Use(Use) {}
  624. };
  625. /// Create an empty FunctionSummary (with specified call edges).
  626. /// Used to represent external nodes and the dummy root node.
  627. static FunctionSummary
  628. makeDummyFunctionSummary(std::vector<FunctionSummary::EdgeTy> Edges) {
  629. return FunctionSummary(
  630. FunctionSummary::GVFlags(
  631. GlobalValue::LinkageTypes::AvailableExternallyLinkage,
  632. GlobalValue::DefaultVisibility,
  633. /*NotEligibleToImport=*/true, /*Live=*/true, /*IsLocal=*/false,
  634. /*CanAutoHide=*/false),
  635. /*NumInsts=*/0, FunctionSummary::FFlags{}, /*EntryCount=*/0,
  636. std::vector<ValueInfo>(), std::move(Edges),
  637. std::vector<GlobalValue::GUID>(),
  638. std::vector<FunctionSummary::VFuncId>(),
  639. std::vector<FunctionSummary::VFuncId>(),
  640. std::vector<FunctionSummary::ConstVCall>(),
  641. std::vector<FunctionSummary::ConstVCall>(),
  642. std::vector<FunctionSummary::ParamAccess>(),
  643. std::vector<CallsiteInfo>(), std::vector<AllocInfo>());
  644. }
  645. /// A dummy node to reference external functions that aren't in the index
  646. static FunctionSummary ExternalNode;
  647. private:
  648. /// Number of instructions (ignoring debug instructions, e.g.) computed
  649. /// during the initial compile step when the summary index is first built.
  650. unsigned InstCount;
  651. /// Function summary specific flags.
  652. FFlags FunFlags;
  653. /// The synthesized entry count of the function.
  654. /// This is only populated during ThinLink phase and remains unused while
  655. /// generating per-module summaries.
  656. uint64_t EntryCount = 0;
  657. /// List of <CalleeValueInfo, CalleeInfo> call edge pairs from this function.
  658. std::vector<EdgeTy> CallGraphEdgeList;
  659. std::unique_ptr<TypeIdInfo> TIdInfo;
  660. /// Uses for every parameter to this function.
  661. using ParamAccessesTy = std::vector<ParamAccess>;
  662. std::unique_ptr<ParamAccessesTy> ParamAccesses;
  663. /// Optional list of memprof callsite metadata summaries. The correspondence
  664. /// between the callsite summary and the callsites in the function is implied
  665. /// by the order in the vector (and can be validated by comparing the stack
  666. /// ids in the CallsiteInfo to those in the instruction callsite metadata).
  667. /// As a memory savings optimization, we only create these for the prevailing
  668. /// copy of a symbol when creating the combined index during LTO.
  669. using CallsitesTy = std::vector<CallsiteInfo>;
  670. std::unique_ptr<CallsitesTy> Callsites;
  671. /// Optional list of allocation memprof metadata summaries. The correspondence
  672. /// between the alloc memprof summary and the allocation callsites in the
  673. /// function is implied by the order in the vector (and can be validated by
  674. /// comparing the stack ids in the AllocInfo to those in the instruction
  675. /// memprof metadata).
  676. /// As a memory savings optimization, we only create these for the prevailing
  677. /// copy of a symbol when creating the combined index during LTO.
  678. using AllocsTy = std::vector<AllocInfo>;
  679. std::unique_ptr<AllocsTy> Allocs;
  680. public:
  681. FunctionSummary(GVFlags Flags, unsigned NumInsts, FFlags FunFlags,
  682. uint64_t EntryCount, std::vector<ValueInfo> Refs,
  683. std::vector<EdgeTy> CGEdges,
  684. std::vector<GlobalValue::GUID> TypeTests,
  685. std::vector<VFuncId> TypeTestAssumeVCalls,
  686. std::vector<VFuncId> TypeCheckedLoadVCalls,
  687. std::vector<ConstVCall> TypeTestAssumeConstVCalls,
  688. std::vector<ConstVCall> TypeCheckedLoadConstVCalls,
  689. std::vector<ParamAccess> Params, CallsitesTy CallsiteList,
  690. AllocsTy AllocList)
  691. : GlobalValueSummary(FunctionKind, Flags, std::move(Refs)),
  692. InstCount(NumInsts), FunFlags(FunFlags), EntryCount(EntryCount),
  693. CallGraphEdgeList(std::move(CGEdges)) {
  694. if (!TypeTests.empty() || !TypeTestAssumeVCalls.empty() ||
  695. !TypeCheckedLoadVCalls.empty() || !TypeTestAssumeConstVCalls.empty() ||
  696. !TypeCheckedLoadConstVCalls.empty())
  697. TIdInfo = std::make_unique<TypeIdInfo>(
  698. TypeIdInfo{std::move(TypeTests), std::move(TypeTestAssumeVCalls),
  699. std::move(TypeCheckedLoadVCalls),
  700. std::move(TypeTestAssumeConstVCalls),
  701. std::move(TypeCheckedLoadConstVCalls)});
  702. if (!Params.empty())
  703. ParamAccesses = std::make_unique<ParamAccessesTy>(std::move(Params));
  704. if (!CallsiteList.empty())
  705. Callsites = std::make_unique<CallsitesTy>(std::move(CallsiteList));
  706. if (!AllocList.empty())
  707. Allocs = std::make_unique<AllocsTy>(std::move(AllocList));
  708. }
  709. // Gets the number of readonly and writeonly refs in RefEdgeList
  710. std::pair<unsigned, unsigned> specialRefCounts() const;
  711. /// Check if this is a function summary.
  712. static bool classof(const GlobalValueSummary *GVS) {
  713. return GVS->getSummaryKind() == FunctionKind;
  714. }
  715. /// Get function summary flags.
  716. FFlags fflags() const { return FunFlags; }
  717. void setNoRecurse() { FunFlags.NoRecurse = true; }
  718. void setNoUnwind() { FunFlags.NoUnwind = true; }
  719. /// Get the instruction count recorded for this function.
  720. unsigned instCount() const { return InstCount; }
  721. /// Get the synthetic entry count for this function.
  722. uint64_t entryCount() const { return EntryCount; }
  723. /// Set the synthetic entry count for this function.
  724. void setEntryCount(uint64_t EC) { EntryCount = EC; }
  725. /// Return the list of <CalleeValueInfo, CalleeInfo> pairs.
  726. ArrayRef<EdgeTy> calls() const { return CallGraphEdgeList; }
  727. std::vector<EdgeTy> &mutableCalls() { return CallGraphEdgeList; }
  728. void addCall(EdgeTy E) { CallGraphEdgeList.push_back(E); }
  729. /// Returns the list of type identifiers used by this function in
  730. /// llvm.type.test intrinsics other than by an llvm.assume intrinsic,
  731. /// represented as GUIDs.
  732. ArrayRef<GlobalValue::GUID> type_tests() const {
  733. if (TIdInfo)
  734. return TIdInfo->TypeTests;
  735. return {};
  736. }
  737. /// Returns the list of virtual calls made by this function using
  738. /// llvm.assume(llvm.type.test) intrinsics that do not have all constant
  739. /// integer arguments.
  740. ArrayRef<VFuncId> type_test_assume_vcalls() const {
  741. if (TIdInfo)
  742. return TIdInfo->TypeTestAssumeVCalls;
  743. return {};
  744. }
  745. /// Returns the list of virtual calls made by this function using
  746. /// llvm.type.checked.load intrinsics that do not have all constant integer
  747. /// arguments.
  748. ArrayRef<VFuncId> type_checked_load_vcalls() const {
  749. if (TIdInfo)
  750. return TIdInfo->TypeCheckedLoadVCalls;
  751. return {};
  752. }
  753. /// Returns the list of virtual calls made by this function using
  754. /// llvm.assume(llvm.type.test) intrinsics with all constant integer
  755. /// arguments.
  756. ArrayRef<ConstVCall> type_test_assume_const_vcalls() const {
  757. if (TIdInfo)
  758. return TIdInfo->TypeTestAssumeConstVCalls;
  759. return {};
  760. }
  761. /// Returns the list of virtual calls made by this function using
  762. /// llvm.type.checked.load intrinsics with all constant integer arguments.
  763. ArrayRef<ConstVCall> type_checked_load_const_vcalls() const {
  764. if (TIdInfo)
  765. return TIdInfo->TypeCheckedLoadConstVCalls;
  766. return {};
  767. }
  768. /// Returns the list of known uses of pointer parameters.
  769. ArrayRef<ParamAccess> paramAccesses() const {
  770. if (ParamAccesses)
  771. return *ParamAccesses;
  772. return {};
  773. }
  774. /// Sets the list of known uses of pointer parameters.
  775. void setParamAccesses(std::vector<ParamAccess> NewParams) {
  776. if (NewParams.empty())
  777. ParamAccesses.reset();
  778. else if (ParamAccesses)
  779. *ParamAccesses = std::move(NewParams);
  780. else
  781. ParamAccesses = std::make_unique<ParamAccessesTy>(std::move(NewParams));
  782. }
  783. /// Add a type test to the summary. This is used by WholeProgramDevirt if we
  784. /// were unable to devirtualize a checked call.
  785. void addTypeTest(GlobalValue::GUID Guid) {
  786. if (!TIdInfo)
  787. TIdInfo = std::make_unique<TypeIdInfo>();
  788. TIdInfo->TypeTests.push_back(Guid);
  789. }
  790. const TypeIdInfo *getTypeIdInfo() const { return TIdInfo.get(); };
  791. ArrayRef<CallsiteInfo> callsites() const {
  792. if (Callsites)
  793. return *Callsites;
  794. return {};
  795. }
  796. ArrayRef<AllocInfo> allocs() const {
  797. if (Allocs)
  798. return *Allocs;
  799. return {};
  800. }
  801. friend struct GraphTraits<ValueInfo>;
  802. };
  803. template <> struct DenseMapInfo<FunctionSummary::VFuncId> {
  804. static FunctionSummary::VFuncId getEmptyKey() { return {0, uint64_t(-1)}; }
  805. static FunctionSummary::VFuncId getTombstoneKey() {
  806. return {0, uint64_t(-2)};
  807. }
  808. static bool isEqual(FunctionSummary::VFuncId L, FunctionSummary::VFuncId R) {
  809. return L.GUID == R.GUID && L.Offset == R.Offset;
  810. }
  811. static unsigned getHashValue(FunctionSummary::VFuncId I) { return I.GUID; }
  812. };
  813. template <> struct DenseMapInfo<FunctionSummary::ConstVCall> {
  814. static FunctionSummary::ConstVCall getEmptyKey() {
  815. return {{0, uint64_t(-1)}, {}};
  816. }
  817. static FunctionSummary::ConstVCall getTombstoneKey() {
  818. return {{0, uint64_t(-2)}, {}};
  819. }
  820. static bool isEqual(FunctionSummary::ConstVCall L,
  821. FunctionSummary::ConstVCall R) {
  822. return DenseMapInfo<FunctionSummary::VFuncId>::isEqual(L.VFunc, R.VFunc) &&
  823. L.Args == R.Args;
  824. }
  825. static unsigned getHashValue(FunctionSummary::ConstVCall I) {
  826. return I.VFunc.GUID;
  827. }
  828. };
  829. /// The ValueInfo and offset for a function within a vtable definition
  830. /// initializer array.
  831. struct VirtFuncOffset {
  832. VirtFuncOffset(ValueInfo VI, uint64_t Offset)
  833. : FuncVI(VI), VTableOffset(Offset) {}
  834. ValueInfo FuncVI;
  835. uint64_t VTableOffset;
  836. };
  837. /// List of functions referenced by a particular vtable definition.
  838. using VTableFuncList = std::vector<VirtFuncOffset>;
  839. /// Global variable summary information to aid decisions and
  840. /// implementation of importing.
  841. ///
  842. /// Global variable summary has two extra flag, telling if it is
  843. /// readonly or writeonly. Both readonly and writeonly variables
  844. /// can be optimized in the backed: readonly variables can be
  845. /// const-folded, while writeonly vars can be completely eliminated
  846. /// together with corresponding stores. We let both things happen
  847. /// by means of internalizing such variables after ThinLTO import.
  848. class GlobalVarSummary : public GlobalValueSummary {
  849. private:
  850. /// For vtable definitions this holds the list of functions and
  851. /// their corresponding offsets within the initializer array.
  852. std::unique_ptr<VTableFuncList> VTableFuncs;
  853. public:
  854. struct GVarFlags {
  855. GVarFlags(bool ReadOnly, bool WriteOnly, bool Constant,
  856. GlobalObject::VCallVisibility Vis)
  857. : MaybeReadOnly(ReadOnly), MaybeWriteOnly(WriteOnly),
  858. Constant(Constant), VCallVisibility(Vis) {}
  859. // If true indicates that this global variable might be accessed
  860. // purely by non-volatile load instructions. This in turn means
  861. // it can be internalized in source and destination modules during
  862. // thin LTO import because it neither modified nor its address
  863. // is taken.
  864. unsigned MaybeReadOnly : 1;
  865. // If true indicates that variable is possibly only written to, so
  866. // its value isn't loaded and its address isn't taken anywhere.
  867. // False, when 'Constant' attribute is set.
  868. unsigned MaybeWriteOnly : 1;
  869. // Indicates that value is a compile-time constant. Global variable
  870. // can be 'Constant' while not being 'ReadOnly' on several occasions:
  871. // - it is volatile, (e.g mapped device address)
  872. // - its address is taken, meaning that unlike 'ReadOnly' vars we can't
  873. // internalize it.
  874. // Constant variables are always imported thus giving compiler an
  875. // opportunity to make some extra optimizations. Readonly constants
  876. // are also internalized.
  877. unsigned Constant : 1;
  878. // Set from metadata on vtable definitions during the module summary
  879. // analysis.
  880. unsigned VCallVisibility : 2;
  881. } VarFlags;
  882. GlobalVarSummary(GVFlags Flags, GVarFlags VarFlags,
  883. std::vector<ValueInfo> Refs)
  884. : GlobalValueSummary(GlobalVarKind, Flags, std::move(Refs)),
  885. VarFlags(VarFlags) {}
  886. /// Check if this is a global variable summary.
  887. static bool classof(const GlobalValueSummary *GVS) {
  888. return GVS->getSummaryKind() == GlobalVarKind;
  889. }
  890. GVarFlags varflags() const { return VarFlags; }
  891. void setReadOnly(bool RO) { VarFlags.MaybeReadOnly = RO; }
  892. void setWriteOnly(bool WO) { VarFlags.MaybeWriteOnly = WO; }
  893. bool maybeReadOnly() const { return VarFlags.MaybeReadOnly; }
  894. bool maybeWriteOnly() const { return VarFlags.MaybeWriteOnly; }
  895. bool isConstant() const { return VarFlags.Constant; }
  896. void setVCallVisibility(GlobalObject::VCallVisibility Vis) {
  897. VarFlags.VCallVisibility = Vis;
  898. }
  899. GlobalObject::VCallVisibility getVCallVisibility() const {
  900. return (GlobalObject::VCallVisibility)VarFlags.VCallVisibility;
  901. }
  902. void setVTableFuncs(VTableFuncList Funcs) {
  903. assert(!VTableFuncs);
  904. VTableFuncs = std::make_unique<VTableFuncList>(std::move(Funcs));
  905. }
  906. ArrayRef<VirtFuncOffset> vTableFuncs() const {
  907. if (VTableFuncs)
  908. return *VTableFuncs;
  909. return {};
  910. }
  911. };
  912. struct TypeTestResolution {
  913. /// Specifies which kind of type check we should emit for this byte array.
  914. /// See http://clang.llvm.org/docs/ControlFlowIntegrityDesign.html for full
  915. /// details on each kind of check; the enumerators are described with
  916. /// reference to that document.
  917. enum Kind {
  918. Unsat, ///< Unsatisfiable type (i.e. no global has this type metadata)
  919. ByteArray, ///< Test a byte array (first example)
  920. Inline, ///< Inlined bit vector ("Short Inline Bit Vectors")
  921. Single, ///< Single element (last example in "Short Inline Bit Vectors")
  922. AllOnes, ///< All-ones bit vector ("Eliminating Bit Vector Checks for
  923. /// All-Ones Bit Vectors")
  924. Unknown, ///< Unknown (analysis not performed, don't lower)
  925. } TheKind = Unknown;
  926. /// Range of size-1 expressed as a bit width. For example, if the size is in
  927. /// range [1,256], this number will be 8. This helps generate the most compact
  928. /// instruction sequences.
  929. unsigned SizeM1BitWidth = 0;
  930. // The following fields are only used if the target does not support the use
  931. // of absolute symbols to store constants. Their meanings are the same as the
  932. // corresponding fields in LowerTypeTestsModule::TypeIdLowering in
  933. // LowerTypeTests.cpp.
  934. uint64_t AlignLog2 = 0;
  935. uint64_t SizeM1 = 0;
  936. uint8_t BitMask = 0;
  937. uint64_t InlineBits = 0;
  938. };
  939. struct WholeProgramDevirtResolution {
  940. enum Kind {
  941. Indir, ///< Just do a regular virtual call
  942. SingleImpl, ///< Single implementation devirtualization
  943. BranchFunnel, ///< When retpoline mitigation is enabled, use a branch funnel
  944. ///< that is defined in the merged module. Otherwise same as
  945. ///< Indir.
  946. } TheKind = Indir;
  947. std::string SingleImplName;
  948. struct ByArg {
  949. enum Kind {
  950. Indir, ///< Just do a regular virtual call
  951. UniformRetVal, ///< Uniform return value optimization
  952. UniqueRetVal, ///< Unique return value optimization
  953. VirtualConstProp, ///< Virtual constant propagation
  954. } TheKind = Indir;
  955. /// Additional information for the resolution:
  956. /// - UniformRetVal: the uniform return value.
  957. /// - UniqueRetVal: the return value associated with the unique vtable (0 or
  958. /// 1).
  959. uint64_t Info = 0;
  960. // The following fields are only used if the target does not support the use
  961. // of absolute symbols to store constants.
  962. uint32_t Byte = 0;
  963. uint32_t Bit = 0;
  964. };
  965. /// Resolutions for calls with all constant integer arguments (excluding the
  966. /// first argument, "this"), where the key is the argument vector.
  967. std::map<std::vector<uint64_t>, ByArg> ResByArg;
  968. };
  969. struct TypeIdSummary {
  970. TypeTestResolution TTRes;
  971. /// Mapping from byte offset to whole-program devirt resolution for that
  972. /// (typeid, byte offset) pair.
  973. std::map<uint64_t, WholeProgramDevirtResolution> WPDRes;
  974. };
  975. /// 160 bits SHA1
  976. using ModuleHash = std::array<uint32_t, 5>;
  977. /// Type used for iterating through the global value summary map.
  978. using const_gvsummary_iterator = GlobalValueSummaryMapTy::const_iterator;
  979. using gvsummary_iterator = GlobalValueSummaryMapTy::iterator;
  980. /// String table to hold/own module path strings, which additionally holds the
  981. /// module ID assigned to each module during the plugin step, as well as a hash
  982. /// of the module. The StringMap makes a copy of and owns inserted strings.
  983. using ModulePathStringTableTy = StringMap<std::pair<uint64_t, ModuleHash>>;
  984. /// Map of global value GUID to its summary, used to identify values defined in
  985. /// a particular module, and provide efficient access to their summary.
  986. using GVSummaryMapTy = DenseMap<GlobalValue::GUID, GlobalValueSummary *>;
  987. /// Map of a type GUID to type id string and summary (multimap used
  988. /// in case of GUID conflicts).
  989. using TypeIdSummaryMapTy =
  990. std::multimap<GlobalValue::GUID, std::pair<std::string, TypeIdSummary>>;
  991. /// The following data structures summarize type metadata information.
  992. /// For type metadata overview see https://llvm.org/docs/TypeMetadata.html.
  993. /// Each type metadata includes both the type identifier and the offset of
  994. /// the address point of the type (the address held by objects of that type
  995. /// which may not be the beginning of the virtual table). Vtable definitions
  996. /// are decorated with type metadata for the types they are compatible with.
  997. ///
  998. /// Holds information about vtable definitions decorated with type metadata:
  999. /// the vtable definition value and its address point offset in a type
  1000. /// identifier metadata it is decorated (compatible) with.
  1001. struct TypeIdOffsetVtableInfo {
  1002. TypeIdOffsetVtableInfo(uint64_t Offset, ValueInfo VI)
  1003. : AddressPointOffset(Offset), VTableVI(VI) {}
  1004. uint64_t AddressPointOffset;
  1005. ValueInfo VTableVI;
  1006. };
  1007. /// List of vtable definitions decorated by a particular type identifier,
  1008. /// and their corresponding offsets in that type identifier's metadata.
  1009. /// Note that each type identifier may be compatible with multiple vtables, due
  1010. /// to inheritance, which is why this is a vector.
  1011. using TypeIdCompatibleVtableInfo = std::vector<TypeIdOffsetVtableInfo>;
  1012. /// Class to hold module path string table and global value map,
  1013. /// and encapsulate methods for operating on them.
  1014. class ModuleSummaryIndex {
  1015. private:
  1016. /// Map from value name to list of summary instances for values of that
  1017. /// name (may be duplicates in the COMDAT case, e.g.).
  1018. GlobalValueSummaryMapTy GlobalValueMap;
  1019. /// Holds strings for combined index, mapping to the corresponding module ID.
  1020. ModulePathStringTableTy ModulePathStringTable;
  1021. /// Mapping from type identifier GUIDs to type identifier and its summary
  1022. /// information. Produced by thin link.
  1023. TypeIdSummaryMapTy TypeIdMap;
  1024. /// Mapping from type identifier to information about vtables decorated
  1025. /// with that type identifier's metadata. Produced by per module summary
  1026. /// analysis and consumed by thin link. For more information, see description
  1027. /// above where TypeIdCompatibleVtableInfo is defined.
  1028. std::map<std::string, TypeIdCompatibleVtableInfo, std::less<>>
  1029. TypeIdCompatibleVtableMap;
  1030. /// Mapping from original ID to GUID. If original ID can map to multiple
  1031. /// GUIDs, it will be mapped to 0.
  1032. std::map<GlobalValue::GUID, GlobalValue::GUID> OidGuidMap;
  1033. /// Indicates that summary-based GlobalValue GC has run, and values with
  1034. /// GVFlags::Live==false are really dead. Otherwise, all values must be
  1035. /// considered live.
  1036. bool WithGlobalValueDeadStripping = false;
  1037. /// Indicates that summary-based attribute propagation has run and
  1038. /// GVarFlags::MaybeReadonly / GVarFlags::MaybeWriteonly are really
  1039. /// read/write only.
  1040. bool WithAttributePropagation = false;
  1041. /// Indicates that summary-based DSOLocal propagation has run and the flag in
  1042. /// every summary of a GV is synchronized.
  1043. bool WithDSOLocalPropagation = false;
  1044. /// Indicates that we have whole program visibility.
  1045. bool WithWholeProgramVisibility = false;
  1046. /// Indicates that summary-based synthetic entry count propagation has run
  1047. bool HasSyntheticEntryCounts = false;
  1048. /// Indicates that distributed backend should skip compilation of the
  1049. /// module. Flag is suppose to be set by distributed ThinLTO indexing
  1050. /// when it detected that the module is not needed during the final
  1051. /// linking. As result distributed backend should just output a minimal
  1052. /// valid object file.
  1053. bool SkipModuleByDistributedBackend = false;
  1054. /// If true then we're performing analysis of IR module, or parsing along with
  1055. /// the IR from assembly. The value of 'false' means we're reading summary
  1056. /// from BC or YAML source. Affects the type of value stored in NameOrGV
  1057. /// union.
  1058. bool HaveGVs;
  1059. // True if the index was created for a module compiled with -fsplit-lto-unit.
  1060. bool EnableSplitLTOUnit;
  1061. // True if some of the modules were compiled with -fsplit-lto-unit and
  1062. // some were not. Set when the combined index is created during the thin link.
  1063. bool PartiallySplitLTOUnits = false;
  1064. /// True if some of the FunctionSummary contains a ParamAccess.
  1065. bool HasParamAccess = false;
  1066. std::set<std::string> CfiFunctionDefs;
  1067. std::set<std::string> CfiFunctionDecls;
  1068. // Used in cases where we want to record the name of a global, but
  1069. // don't have the string owned elsewhere (e.g. the Strtab on a module).
  1070. BumpPtrAllocator Alloc;
  1071. StringSaver Saver;
  1072. // The total number of basic blocks in the module in the per-module summary or
  1073. // the total number of basic blocks in the LTO unit in the combined index.
  1074. uint64_t BlockCount;
  1075. // List of unique stack ids (hashes). We use a 4B index of the id in the
  1076. // stack id lists on the alloc and callsite summaries for memory savings,
  1077. // since the number of unique ids is in practice much smaller than the
  1078. // number of stack id references in the summaries.
  1079. std::vector<uint64_t> StackIds;
  1080. // Temporary map while building StackIds list. Clear when index is completely
  1081. // built via releaseTemporaryMemory.
  1082. std::map<uint64_t, unsigned> StackIdToIndex;
  1083. // YAML I/O support.
  1084. friend yaml::MappingTraits<ModuleSummaryIndex>;
  1085. GlobalValueSummaryMapTy::value_type *
  1086. getOrInsertValuePtr(GlobalValue::GUID GUID) {
  1087. return &*GlobalValueMap.emplace(GUID, GlobalValueSummaryInfo(HaveGVs))
  1088. .first;
  1089. }
  1090. public:
  1091. // See HaveGVs variable comment.
  1092. ModuleSummaryIndex(bool HaveGVs, bool EnableSplitLTOUnit = false)
  1093. : HaveGVs(HaveGVs), EnableSplitLTOUnit(EnableSplitLTOUnit), Saver(Alloc),
  1094. BlockCount(0) {}
  1095. // Current version for the module summary in bitcode files.
  1096. // The BitcodeSummaryVersion should be bumped whenever we introduce changes
  1097. // in the way some record are interpreted, like flags for instance.
  1098. // Note that incrementing this may require changes in both BitcodeReader.cpp
  1099. // and BitcodeWriter.cpp.
  1100. static constexpr uint64_t BitcodeSummaryVersion = 9;
  1101. // Regular LTO module name for ASM writer
  1102. static constexpr const char *getRegularLTOModuleName() {
  1103. return "[Regular LTO]";
  1104. }
  1105. bool haveGVs() const { return HaveGVs; }
  1106. uint64_t getFlags() const;
  1107. void setFlags(uint64_t Flags);
  1108. uint64_t getBlockCount() const { return BlockCount; }
  1109. void addBlockCount(uint64_t C) { BlockCount += C; }
  1110. void setBlockCount(uint64_t C) { BlockCount = C; }
  1111. gvsummary_iterator begin() { return GlobalValueMap.begin(); }
  1112. const_gvsummary_iterator begin() const { return GlobalValueMap.begin(); }
  1113. gvsummary_iterator end() { return GlobalValueMap.end(); }
  1114. const_gvsummary_iterator end() const { return GlobalValueMap.end(); }
  1115. size_t size() const { return GlobalValueMap.size(); }
  1116. const std::vector<uint64_t> &stackIds() const { return StackIds; }
  1117. unsigned addOrGetStackIdIndex(uint64_t StackId) {
  1118. auto Inserted = StackIdToIndex.insert({StackId, StackIds.size()});
  1119. if (Inserted.second)
  1120. StackIds.push_back(StackId);
  1121. return Inserted.first->second;
  1122. }
  1123. uint64_t getStackIdAtIndex(unsigned Index) const {
  1124. assert(StackIds.size() > Index);
  1125. return StackIds[Index];
  1126. }
  1127. // Facility to release memory from data structures only needed during index
  1128. // construction (including while building combined index). Currently this only
  1129. // releases the temporary map used while constructing a correspondence between
  1130. // stack ids and their index in the StackIds vector. Mostly impactful when
  1131. // building a large combined index.
  1132. void releaseTemporaryMemory() {
  1133. assert(StackIdToIndex.size() == StackIds.size());
  1134. StackIdToIndex.clear();
  1135. StackIds.shrink_to_fit();
  1136. }
  1137. /// Convenience function for doing a DFS on a ValueInfo. Marks the function in
  1138. /// the FunctionHasParent map.
  1139. static void discoverNodes(ValueInfo V,
  1140. std::map<ValueInfo, bool> &FunctionHasParent) {
  1141. if (!V.getSummaryList().size())
  1142. return; // skip external functions that don't have summaries
  1143. // Mark discovered if we haven't yet
  1144. auto S = FunctionHasParent.emplace(V, false);
  1145. // Stop if we've already discovered this node
  1146. if (!S.second)
  1147. return;
  1148. FunctionSummary *F =
  1149. dyn_cast<FunctionSummary>(V.getSummaryList().front().get());
  1150. assert(F != nullptr && "Expected FunctionSummary node");
  1151. for (const auto &C : F->calls()) {
  1152. // Insert node if necessary
  1153. auto S = FunctionHasParent.emplace(C.first, true);
  1154. // Skip nodes that we're sure have parents
  1155. if (!S.second && S.first->second)
  1156. continue;
  1157. if (S.second)
  1158. discoverNodes(C.first, FunctionHasParent);
  1159. else
  1160. S.first->second = true;
  1161. }
  1162. }
  1163. // Calculate the callgraph root
  1164. FunctionSummary calculateCallGraphRoot() {
  1165. // Functions that have a parent will be marked in FunctionHasParent pair.
  1166. // Once we've marked all functions, the functions in the map that are false
  1167. // have no parent (so they're the roots)
  1168. std::map<ValueInfo, bool> FunctionHasParent;
  1169. for (auto &S : *this) {
  1170. // Skip external functions
  1171. if (!S.second.SummaryList.size() ||
  1172. !isa<FunctionSummary>(S.second.SummaryList.front().get()))
  1173. continue;
  1174. discoverNodes(ValueInfo(HaveGVs, &S), FunctionHasParent);
  1175. }
  1176. std::vector<FunctionSummary::EdgeTy> Edges;
  1177. // create edges to all roots in the Index
  1178. for (auto &P : FunctionHasParent) {
  1179. if (P.second)
  1180. continue; // skip over non-root nodes
  1181. Edges.push_back(std::make_pair(P.first, CalleeInfo{}));
  1182. }
  1183. if (Edges.empty()) {
  1184. // Failed to find root - return an empty node
  1185. return FunctionSummary::makeDummyFunctionSummary({});
  1186. }
  1187. auto CallGraphRoot = FunctionSummary::makeDummyFunctionSummary(Edges);
  1188. return CallGraphRoot;
  1189. }
  1190. bool withGlobalValueDeadStripping() const {
  1191. return WithGlobalValueDeadStripping;
  1192. }
  1193. void setWithGlobalValueDeadStripping() {
  1194. WithGlobalValueDeadStripping = true;
  1195. }
  1196. bool withAttributePropagation() const { return WithAttributePropagation; }
  1197. void setWithAttributePropagation() {
  1198. WithAttributePropagation = true;
  1199. }
  1200. bool withDSOLocalPropagation() const { return WithDSOLocalPropagation; }
  1201. void setWithDSOLocalPropagation() { WithDSOLocalPropagation = true; }
  1202. bool withWholeProgramVisibility() const { return WithWholeProgramVisibility; }
  1203. void setWithWholeProgramVisibility() { WithWholeProgramVisibility = true; }
  1204. bool isReadOnly(const GlobalVarSummary *GVS) const {
  1205. return WithAttributePropagation && GVS->maybeReadOnly();
  1206. }
  1207. bool isWriteOnly(const GlobalVarSummary *GVS) const {
  1208. return WithAttributePropagation && GVS->maybeWriteOnly();
  1209. }
  1210. bool hasSyntheticEntryCounts() const { return HasSyntheticEntryCounts; }
  1211. void setHasSyntheticEntryCounts() { HasSyntheticEntryCounts = true; }
  1212. bool skipModuleByDistributedBackend() const {
  1213. return SkipModuleByDistributedBackend;
  1214. }
  1215. void setSkipModuleByDistributedBackend() {
  1216. SkipModuleByDistributedBackend = true;
  1217. }
  1218. bool enableSplitLTOUnit() const { return EnableSplitLTOUnit; }
  1219. void setEnableSplitLTOUnit() { EnableSplitLTOUnit = true; }
  1220. bool partiallySplitLTOUnits() const { return PartiallySplitLTOUnits; }
  1221. void setPartiallySplitLTOUnits() { PartiallySplitLTOUnits = true; }
  1222. bool hasParamAccess() const { return HasParamAccess; }
  1223. bool isGlobalValueLive(const GlobalValueSummary *GVS) const {
  1224. return !WithGlobalValueDeadStripping || GVS->isLive();
  1225. }
  1226. bool isGUIDLive(GlobalValue::GUID GUID) const;
  1227. /// Return a ValueInfo for the index value_type (convenient when iterating
  1228. /// index).
  1229. ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const {
  1230. return ValueInfo(HaveGVs, &R);
  1231. }
  1232. /// Return a ValueInfo for GUID if it exists, otherwise return ValueInfo().
  1233. ValueInfo getValueInfo(GlobalValue::GUID GUID) const {
  1234. auto I = GlobalValueMap.find(GUID);
  1235. return ValueInfo(HaveGVs, I == GlobalValueMap.end() ? nullptr : &*I);
  1236. }
  1237. /// Return a ValueInfo for \p GUID.
  1238. ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID) {
  1239. return ValueInfo(HaveGVs, getOrInsertValuePtr(GUID));
  1240. }
  1241. // Save a string in the Index. Use before passing Name to
  1242. // getOrInsertValueInfo when the string isn't owned elsewhere (e.g. on the
  1243. // module's Strtab).
  1244. StringRef saveString(StringRef String) { return Saver.save(String); }
  1245. /// Return a ValueInfo for \p GUID setting value \p Name.
  1246. ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID, StringRef Name) {
  1247. assert(!HaveGVs);
  1248. auto VP = getOrInsertValuePtr(GUID);
  1249. VP->second.U.Name = Name;
  1250. return ValueInfo(HaveGVs, VP);
  1251. }
  1252. /// Return a ValueInfo for \p GV and mark it as belonging to GV.
  1253. ValueInfo getOrInsertValueInfo(const GlobalValue *GV) {
  1254. assert(HaveGVs);
  1255. auto VP = getOrInsertValuePtr(GV->getGUID());
  1256. VP->second.U.GV = GV;
  1257. return ValueInfo(HaveGVs, VP);
  1258. }
  1259. /// Return the GUID for \p OriginalId in the OidGuidMap.
  1260. GlobalValue::GUID getGUIDFromOriginalID(GlobalValue::GUID OriginalID) const {
  1261. const auto I = OidGuidMap.find(OriginalID);
  1262. return I == OidGuidMap.end() ? 0 : I->second;
  1263. }
  1264. std::set<std::string> &cfiFunctionDefs() { return CfiFunctionDefs; }
  1265. const std::set<std::string> &cfiFunctionDefs() const { return CfiFunctionDefs; }
  1266. std::set<std::string> &cfiFunctionDecls() { return CfiFunctionDecls; }
  1267. const std::set<std::string> &cfiFunctionDecls() const { return CfiFunctionDecls; }
  1268. /// Add a global value summary for a value.
  1269. void addGlobalValueSummary(const GlobalValue &GV,
  1270. std::unique_ptr<GlobalValueSummary> Summary) {
  1271. addGlobalValueSummary(getOrInsertValueInfo(&GV), std::move(Summary));
  1272. }
  1273. /// Add a global value summary for a value of the given name.
  1274. void addGlobalValueSummary(StringRef ValueName,
  1275. std::unique_ptr<GlobalValueSummary> Summary) {
  1276. addGlobalValueSummary(getOrInsertValueInfo(GlobalValue::getGUID(ValueName)),
  1277. std::move(Summary));
  1278. }
  1279. /// Add a global value summary for the given ValueInfo.
  1280. void addGlobalValueSummary(ValueInfo VI,
  1281. std::unique_ptr<GlobalValueSummary> Summary) {
  1282. if (const FunctionSummary *FS = dyn_cast<FunctionSummary>(Summary.get()))
  1283. HasParamAccess |= !FS->paramAccesses().empty();
  1284. addOriginalName(VI.getGUID(), Summary->getOriginalName());
  1285. // Here we have a notionally const VI, but the value it points to is owned
  1286. // by the non-const *this.
  1287. const_cast<GlobalValueSummaryMapTy::value_type *>(VI.getRef())
  1288. ->second.SummaryList.push_back(std::move(Summary));
  1289. }
  1290. /// Add an original name for the value of the given GUID.
  1291. void addOriginalName(GlobalValue::GUID ValueGUID,
  1292. GlobalValue::GUID OrigGUID) {
  1293. if (OrigGUID == 0 || ValueGUID == OrigGUID)
  1294. return;
  1295. if (OidGuidMap.count(OrigGUID) && OidGuidMap[OrigGUID] != ValueGUID)
  1296. OidGuidMap[OrigGUID] = 0;
  1297. else
  1298. OidGuidMap[OrigGUID] = ValueGUID;
  1299. }
  1300. /// Find the summary for ValueInfo \p VI in module \p ModuleId, or nullptr if
  1301. /// not found.
  1302. GlobalValueSummary *findSummaryInModule(ValueInfo VI, StringRef ModuleId) const {
  1303. auto SummaryList = VI.getSummaryList();
  1304. auto Summary =
  1305. llvm::find_if(SummaryList,
  1306. [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
  1307. return Summary->modulePath() == ModuleId;
  1308. });
  1309. if (Summary == SummaryList.end())
  1310. return nullptr;
  1311. return Summary->get();
  1312. }
  1313. /// Find the summary for global \p GUID in module \p ModuleId, or nullptr if
  1314. /// not found.
  1315. GlobalValueSummary *findSummaryInModule(GlobalValue::GUID ValueGUID,
  1316. StringRef ModuleId) const {
  1317. auto CalleeInfo = getValueInfo(ValueGUID);
  1318. if (!CalleeInfo)
  1319. return nullptr; // This function does not have a summary
  1320. return findSummaryInModule(CalleeInfo, ModuleId);
  1321. }
  1322. /// Returns the first GlobalValueSummary for \p GV, asserting that there
  1323. /// is only one if \p PerModuleIndex.
  1324. GlobalValueSummary *getGlobalValueSummary(const GlobalValue &GV,
  1325. bool PerModuleIndex = true) const {
  1326. assert(GV.hasName() && "Can't get GlobalValueSummary for GV with no name");
  1327. return getGlobalValueSummary(GV.getGUID(), PerModuleIndex);
  1328. }
  1329. /// Returns the first GlobalValueSummary for \p ValueGUID, asserting that
  1330. /// there
  1331. /// is only one if \p PerModuleIndex.
  1332. GlobalValueSummary *getGlobalValueSummary(GlobalValue::GUID ValueGUID,
  1333. bool PerModuleIndex = true) const;
  1334. /// Table of modules, containing module hash and id.
  1335. const StringMap<std::pair<uint64_t, ModuleHash>> &modulePaths() const {
  1336. return ModulePathStringTable;
  1337. }
  1338. /// Table of modules, containing hash and id.
  1339. StringMap<std::pair<uint64_t, ModuleHash>> &modulePaths() {
  1340. return ModulePathStringTable;
  1341. }
  1342. /// Get the module ID recorded for the given module path.
  1343. uint64_t getModuleId(const StringRef ModPath) const {
  1344. return ModulePathStringTable.lookup(ModPath).first;
  1345. }
  1346. /// Get the module SHA1 hash recorded for the given module path.
  1347. const ModuleHash &getModuleHash(const StringRef ModPath) const {
  1348. auto It = ModulePathStringTable.find(ModPath);
  1349. assert(It != ModulePathStringTable.end() && "Module not registered");
  1350. return It->second.second;
  1351. }
  1352. /// Convenience method for creating a promoted global name
  1353. /// for the given value name of a local, and its original module's ID.
  1354. static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash) {
  1355. std::string Suffix = utostr((uint64_t(ModHash[0]) << 32) |
  1356. ModHash[1]); // Take the first 64 bits
  1357. return getGlobalNameForLocal(Name, Suffix);
  1358. }
  1359. static std::string getGlobalNameForLocal(StringRef Name, StringRef Suffix) {
  1360. SmallString<256> NewName(Name);
  1361. NewName += ".llvm.";
  1362. NewName += Suffix;
  1363. return std::string(NewName.str());
  1364. }
  1365. /// Helper to obtain the unpromoted name for a global value (or the original
  1366. /// name if not promoted). Split off the rightmost ".llvm.${hash}" suffix,
  1367. /// because it is possible in certain clients (not clang at the moment) for
  1368. /// two rounds of ThinLTO optimization and therefore promotion to occur.
  1369. static StringRef getOriginalNameBeforePromote(StringRef Name) {
  1370. std::pair<StringRef, StringRef> Pair = Name.rsplit(".llvm.");
  1371. return Pair.first;
  1372. }
  1373. typedef ModulePathStringTableTy::value_type ModuleInfo;
  1374. /// Add a new module with the given \p Hash, mapped to the given \p
  1375. /// ModID, and return a reference to the module.
  1376. ModuleInfo *addModule(StringRef ModPath, uint64_t ModId,
  1377. ModuleHash Hash = ModuleHash{{0}}) {
  1378. return &*ModulePathStringTable.insert({ModPath, {ModId, Hash}}).first;
  1379. }
  1380. /// Return module entry for module with the given \p ModPath.
  1381. ModuleInfo *getModule(StringRef ModPath) {
  1382. auto It = ModulePathStringTable.find(ModPath);
  1383. assert(It != ModulePathStringTable.end() && "Module not registered");
  1384. return &*It;
  1385. }
  1386. /// Check if the given Module has any functions available for exporting
  1387. /// in the index. We consider any module present in the ModulePathStringTable
  1388. /// to have exported functions.
  1389. bool hasExportedFunctions(const Module &M) const {
  1390. return ModulePathStringTable.count(M.getModuleIdentifier());
  1391. }
  1392. const TypeIdSummaryMapTy &typeIds() const { return TypeIdMap; }
  1393. /// Return an existing or new TypeIdSummary entry for \p TypeId.
  1394. /// This accessor can mutate the map and therefore should not be used in
  1395. /// the ThinLTO backends.
  1396. TypeIdSummary &getOrInsertTypeIdSummary(StringRef TypeId) {
  1397. auto TidIter = TypeIdMap.equal_range(GlobalValue::getGUID(TypeId));
  1398. for (auto It = TidIter.first; It != TidIter.second; ++It)
  1399. if (It->second.first == TypeId)
  1400. return It->second.second;
  1401. auto It = TypeIdMap.insert(
  1402. {GlobalValue::getGUID(TypeId), {std::string(TypeId), TypeIdSummary()}});
  1403. return It->second.second;
  1404. }
  1405. /// This returns either a pointer to the type id summary (if present in the
  1406. /// summary map) or null (if not present). This may be used when importing.
  1407. const TypeIdSummary *getTypeIdSummary(StringRef TypeId) const {
  1408. auto TidIter = TypeIdMap.equal_range(GlobalValue::getGUID(TypeId));
  1409. for (auto It = TidIter.first; It != TidIter.second; ++It)
  1410. if (It->second.first == TypeId)
  1411. return &It->second.second;
  1412. return nullptr;
  1413. }
  1414. TypeIdSummary *getTypeIdSummary(StringRef TypeId) {
  1415. return const_cast<TypeIdSummary *>(
  1416. static_cast<const ModuleSummaryIndex *>(this)->getTypeIdSummary(
  1417. TypeId));
  1418. }
  1419. const auto &typeIdCompatibleVtableMap() const {
  1420. return TypeIdCompatibleVtableMap;
  1421. }
  1422. /// Return an existing or new TypeIdCompatibleVtableMap entry for \p TypeId.
  1423. /// This accessor can mutate the map and therefore should not be used in
  1424. /// the ThinLTO backends.
  1425. TypeIdCompatibleVtableInfo &
  1426. getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId) {
  1427. return TypeIdCompatibleVtableMap[std::string(TypeId)];
  1428. }
  1429. /// For the given \p TypeId, this returns the TypeIdCompatibleVtableMap
  1430. /// entry if present in the summary map. This may be used when importing.
  1431. std::optional<TypeIdCompatibleVtableInfo>
  1432. getTypeIdCompatibleVtableSummary(StringRef TypeId) const {
  1433. auto I = TypeIdCompatibleVtableMap.find(TypeId);
  1434. if (I == TypeIdCompatibleVtableMap.end())
  1435. return std::nullopt;
  1436. return I->second;
  1437. }
  1438. /// Collect for the given module the list of functions it defines
  1439. /// (GUID -> Summary).
  1440. void collectDefinedFunctionsForModule(StringRef ModulePath,
  1441. GVSummaryMapTy &GVSummaryMap) const;
  1442. /// Collect for each module the list of Summaries it defines (GUID ->
  1443. /// Summary).
  1444. template <class Map>
  1445. void
  1446. collectDefinedGVSummariesPerModule(Map &ModuleToDefinedGVSummaries) const {
  1447. for (const auto &GlobalList : *this) {
  1448. auto GUID = GlobalList.first;
  1449. for (const auto &Summary : GlobalList.second.SummaryList) {
  1450. ModuleToDefinedGVSummaries[Summary->modulePath()][GUID] = Summary.get();
  1451. }
  1452. }
  1453. }
  1454. /// Print to an output stream.
  1455. void print(raw_ostream &OS, bool IsForDebug = false) const;
  1456. /// Dump to stderr (for debugging).
  1457. void dump() const;
  1458. /// Export summary to dot file for GraphViz.
  1459. void
  1460. exportToDot(raw_ostream &OS,
  1461. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) const;
  1462. /// Print out strongly connected components for debugging.
  1463. void dumpSCCs(raw_ostream &OS);
  1464. /// Do the access attribute and DSOLocal propagation in combined index.
  1465. void propagateAttributes(const DenseSet<GlobalValue::GUID> &PreservedSymbols);
  1466. /// Checks if we can import global variable from another module.
  1467. bool canImportGlobalVar(GlobalValueSummary *S, bool AnalyzeRefs) const;
  1468. };
  1469. /// GraphTraits definition to build SCC for the index
  1470. template <> struct GraphTraits<ValueInfo> {
  1471. typedef ValueInfo NodeRef;
  1472. using EdgeRef = FunctionSummary::EdgeTy &;
  1473. static NodeRef valueInfoFromEdge(FunctionSummary::EdgeTy &P) {
  1474. return P.first;
  1475. }
  1476. using ChildIteratorType =
  1477. mapped_iterator<std::vector<FunctionSummary::EdgeTy>::iterator,
  1478. decltype(&valueInfoFromEdge)>;
  1479. using ChildEdgeIteratorType = std::vector<FunctionSummary::EdgeTy>::iterator;
  1480. static NodeRef getEntryNode(ValueInfo V) { return V; }
  1481. static ChildIteratorType child_begin(NodeRef N) {
  1482. if (!N.getSummaryList().size()) // handle external function
  1483. return ChildIteratorType(
  1484. FunctionSummary::ExternalNode.CallGraphEdgeList.begin(),
  1485. &valueInfoFromEdge);
  1486. FunctionSummary *F =
  1487. cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
  1488. return ChildIteratorType(F->CallGraphEdgeList.begin(), &valueInfoFromEdge);
  1489. }
  1490. static ChildIteratorType child_end(NodeRef N) {
  1491. if (!N.getSummaryList().size()) // handle external function
  1492. return ChildIteratorType(
  1493. FunctionSummary::ExternalNode.CallGraphEdgeList.end(),
  1494. &valueInfoFromEdge);
  1495. FunctionSummary *F =
  1496. cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
  1497. return ChildIteratorType(F->CallGraphEdgeList.end(), &valueInfoFromEdge);
  1498. }
  1499. static ChildEdgeIteratorType child_edge_begin(NodeRef N) {
  1500. if (!N.getSummaryList().size()) // handle external function
  1501. return FunctionSummary::ExternalNode.CallGraphEdgeList.begin();
  1502. FunctionSummary *F =
  1503. cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
  1504. return F->CallGraphEdgeList.begin();
  1505. }
  1506. static ChildEdgeIteratorType child_edge_end(NodeRef N) {
  1507. if (!N.getSummaryList().size()) // handle external function
  1508. return FunctionSummary::ExternalNode.CallGraphEdgeList.end();
  1509. FunctionSummary *F =
  1510. cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
  1511. return F->CallGraphEdgeList.end();
  1512. }
  1513. static NodeRef edge_dest(EdgeRef E) { return E.first; }
  1514. };
  1515. template <>
  1516. struct GraphTraits<ModuleSummaryIndex *> : public GraphTraits<ValueInfo> {
  1517. static NodeRef getEntryNode(ModuleSummaryIndex *I) {
  1518. std::unique_ptr<GlobalValueSummary> Root =
  1519. std::make_unique<FunctionSummary>(I->calculateCallGraphRoot());
  1520. GlobalValueSummaryInfo G(I->haveGVs());
  1521. G.SummaryList.push_back(std::move(Root));
  1522. static auto P =
  1523. GlobalValueSummaryMapTy::value_type(GlobalValue::GUID(0), std::move(G));
  1524. return ValueInfo(I->haveGVs(), &P);
  1525. }
  1526. };
  1527. } // end namespace llvm
  1528. #endif // LLVM_IR_MODULESUMMARYINDEX_H
  1529. #ifdef __GNUC__
  1530. #pragma GCC diagnostic pop
  1531. #endif