SampleProf.h 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- SampleProf.h - Sampling profiling format support ---------*- 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. // This file contains common definitions used in the reading and writing of
  15. // sample profile data.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_PROFILEDATA_SAMPLEPROF_H
  19. #define LLVM_PROFILEDATA_SAMPLEPROF_H
  20. #include "llvm/ADT/DenseSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/StringMap.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/ADT/StringSet.h"
  25. #include "llvm/IR/Function.h"
  26. #include "llvm/IR/GlobalValue.h"
  27. #include "llvm/IR/Module.h"
  28. #include "llvm/Support/Allocator.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/ErrorOr.h"
  31. #include "llvm/Support/MathExtras.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include <algorithm>
  34. #include <cstdint>
  35. #include <list>
  36. #include <map>
  37. #include <set>
  38. #include <sstream>
  39. #include <string>
  40. #include <system_error>
  41. #include <unordered_map>
  42. #include <utility>
  43. namespace llvm {
  44. const std::error_category &sampleprof_category();
  45. enum class sampleprof_error {
  46. success = 0,
  47. bad_magic,
  48. unsupported_version,
  49. too_large,
  50. truncated,
  51. malformed,
  52. unrecognized_format,
  53. unsupported_writing_format,
  54. truncated_name_table,
  55. not_implemented,
  56. counter_overflow,
  57. ostream_seek_unsupported,
  58. compress_failed,
  59. uncompress_failed,
  60. zlib_unavailable,
  61. hash_mismatch
  62. };
  63. inline std::error_code make_error_code(sampleprof_error E) {
  64. return std::error_code(static_cast<int>(E), sampleprof_category());
  65. }
  66. inline sampleprof_error MergeResult(sampleprof_error &Accumulator,
  67. sampleprof_error Result) {
  68. // Prefer first error encountered as later errors may be secondary effects of
  69. // the initial problem.
  70. if (Accumulator == sampleprof_error::success &&
  71. Result != sampleprof_error::success)
  72. Accumulator = Result;
  73. return Accumulator;
  74. }
  75. } // end namespace llvm
  76. namespace std {
  77. template <>
  78. struct is_error_code_enum<llvm::sampleprof_error> : std::true_type {};
  79. } // end namespace std
  80. namespace llvm {
  81. namespace sampleprof {
  82. enum SampleProfileFormat {
  83. SPF_None = 0,
  84. SPF_Text = 0x1,
  85. SPF_Compact_Binary = 0x2,
  86. SPF_GCC = 0x3,
  87. SPF_Ext_Binary = 0x4,
  88. SPF_Binary = 0xff
  89. };
  90. static inline uint64_t SPMagic(SampleProfileFormat Format = SPF_Binary) {
  91. return uint64_t('S') << (64 - 8) | uint64_t('P') << (64 - 16) |
  92. uint64_t('R') << (64 - 24) | uint64_t('O') << (64 - 32) |
  93. uint64_t('F') << (64 - 40) | uint64_t('4') << (64 - 48) |
  94. uint64_t('2') << (64 - 56) | uint64_t(Format);
  95. }
  96. /// Get the proper representation of a string according to whether the
  97. /// current Format uses MD5 to represent the string.
  98. static inline StringRef getRepInFormat(StringRef Name, bool UseMD5,
  99. std::string &GUIDBuf) {
  100. if (Name.empty() || !UseMD5)
  101. return Name;
  102. GUIDBuf = std::to_string(Function::getGUID(Name));
  103. return GUIDBuf;
  104. }
  105. static inline uint64_t SPVersion() { return 103; }
  106. // Section Type used by SampleProfileExtBinaryBaseReader and
  107. // SampleProfileExtBinaryBaseWriter. Never change the existing
  108. // value of enum. Only append new ones.
  109. enum SecType {
  110. SecInValid = 0,
  111. SecProfSummary = 1,
  112. SecNameTable = 2,
  113. SecProfileSymbolList = 3,
  114. SecFuncOffsetTable = 4,
  115. SecFuncMetadata = 5,
  116. SecCSNameTable = 6,
  117. // marker for the first type of profile.
  118. SecFuncProfileFirst = 32,
  119. SecLBRProfile = SecFuncProfileFirst
  120. };
  121. static inline std::string getSecName(SecType Type) {
  122. switch ((int)Type) { // Avoid -Wcovered-switch-default
  123. case SecInValid:
  124. return "InvalidSection";
  125. case SecProfSummary:
  126. return "ProfileSummarySection";
  127. case SecNameTable:
  128. return "NameTableSection";
  129. case SecProfileSymbolList:
  130. return "ProfileSymbolListSection";
  131. case SecFuncOffsetTable:
  132. return "FuncOffsetTableSection";
  133. case SecFuncMetadata:
  134. return "FunctionMetadata";
  135. case SecCSNameTable:
  136. return "CSNameTableSection";
  137. case SecLBRProfile:
  138. return "LBRProfileSection";
  139. default:
  140. return "UnknownSection";
  141. }
  142. }
  143. // Entry type of section header table used by SampleProfileExtBinaryBaseReader
  144. // and SampleProfileExtBinaryBaseWriter.
  145. struct SecHdrTableEntry {
  146. SecType Type;
  147. uint64_t Flags;
  148. uint64_t Offset;
  149. uint64_t Size;
  150. // The index indicating the location of the current entry in
  151. // SectionHdrLayout table.
  152. uint32_t LayoutIndex;
  153. };
  154. // Flags common for all sections are defined here. In SecHdrTableEntry::Flags,
  155. // common flags will be saved in the lower 32bits and section specific flags
  156. // will be saved in the higher 32 bits.
  157. enum class SecCommonFlags : uint32_t {
  158. SecFlagInValid = 0,
  159. SecFlagCompress = (1 << 0),
  160. // Indicate the section contains only profile without context.
  161. SecFlagFlat = (1 << 1)
  162. };
  163. // Section specific flags are defined here.
  164. // !!!Note: Everytime a new enum class is created here, please add
  165. // a new check in verifySecFlag.
  166. enum class SecNameTableFlags : uint32_t {
  167. SecFlagInValid = 0,
  168. SecFlagMD5Name = (1 << 0),
  169. // Store MD5 in fixed length instead of ULEB128 so NameTable can be
  170. // accessed like an array.
  171. SecFlagFixedLengthMD5 = (1 << 1),
  172. // Profile contains ".__uniq." suffix name. Compiler shouldn't strip
  173. // the suffix when doing profile matching when seeing the flag.
  174. SecFlagUniqSuffix = (1 << 2)
  175. };
  176. enum class SecProfSummaryFlags : uint32_t {
  177. SecFlagInValid = 0,
  178. /// SecFlagPartial means the profile is for common/shared code.
  179. /// The common profile is usually merged from profiles collected
  180. /// from running other targets.
  181. SecFlagPartial = (1 << 0),
  182. /// SecFlagContext means this is context-sensitive flat profile for
  183. /// CSSPGO
  184. SecFlagFullContext = (1 << 1),
  185. /// SecFlagFSDiscriminator means this profile uses flow-sensitive
  186. /// discriminators.
  187. SecFlagFSDiscriminator = (1 << 2),
  188. /// SecFlagIsCSNested means this is context-sensitive nested profile for
  189. /// CSSPGO
  190. SecFlagIsCSNested = (1 << 4),
  191. };
  192. enum class SecFuncMetadataFlags : uint32_t {
  193. SecFlagInvalid = 0,
  194. SecFlagIsProbeBased = (1 << 0),
  195. SecFlagHasAttribute = (1 << 1),
  196. };
  197. enum class SecFuncOffsetFlags : uint32_t {
  198. SecFlagInvalid = 0,
  199. // Store function offsets in an order of contexts. The order ensures that
  200. // callee contexts of a given context laid out next to it.
  201. SecFlagOrdered = (1 << 0),
  202. };
  203. // Verify section specific flag is used for the correct section.
  204. template <class SecFlagType>
  205. static inline void verifySecFlag(SecType Type, SecFlagType Flag) {
  206. // No verification is needed for common flags.
  207. if (std::is_same<SecCommonFlags, SecFlagType>())
  208. return;
  209. // Verification starts here for section specific flag.
  210. bool IsFlagLegal = false;
  211. switch (Type) {
  212. case SecNameTable:
  213. IsFlagLegal = std::is_same<SecNameTableFlags, SecFlagType>();
  214. break;
  215. case SecProfSummary:
  216. IsFlagLegal = std::is_same<SecProfSummaryFlags, SecFlagType>();
  217. break;
  218. case SecFuncMetadata:
  219. IsFlagLegal = std::is_same<SecFuncMetadataFlags, SecFlagType>();
  220. break;
  221. default:
  222. case SecFuncOffsetTable:
  223. IsFlagLegal = std::is_same<SecFuncOffsetFlags, SecFlagType>();
  224. break;
  225. }
  226. if (!IsFlagLegal)
  227. llvm_unreachable("Misuse of a flag in an incompatible section");
  228. }
  229. template <class SecFlagType>
  230. static inline void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag) {
  231. verifySecFlag(Entry.Type, Flag);
  232. auto FVal = static_cast<uint64_t>(Flag);
  233. bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
  234. Entry.Flags |= IsCommon ? FVal : (FVal << 32);
  235. }
  236. template <class SecFlagType>
  237. static inline void removeSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag) {
  238. verifySecFlag(Entry.Type, Flag);
  239. auto FVal = static_cast<uint64_t>(Flag);
  240. bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
  241. Entry.Flags &= ~(IsCommon ? FVal : (FVal << 32));
  242. }
  243. template <class SecFlagType>
  244. static inline bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag) {
  245. verifySecFlag(Entry.Type, Flag);
  246. auto FVal = static_cast<uint64_t>(Flag);
  247. bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
  248. return Entry.Flags & (IsCommon ? FVal : (FVal << 32));
  249. }
  250. /// Represents the relative location of an instruction.
  251. ///
  252. /// Instruction locations are specified by the line offset from the
  253. /// beginning of the function (marked by the line where the function
  254. /// header is) and the discriminator value within that line.
  255. ///
  256. /// The discriminator value is useful to distinguish instructions
  257. /// that are on the same line but belong to different basic blocks
  258. /// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
  259. struct LineLocation {
  260. LineLocation(uint32_t L, uint32_t D) : LineOffset(L), Discriminator(D) {}
  261. void print(raw_ostream &OS) const;
  262. void dump() const;
  263. bool operator<(const LineLocation &O) const {
  264. return LineOffset < O.LineOffset ||
  265. (LineOffset == O.LineOffset && Discriminator < O.Discriminator);
  266. }
  267. bool operator==(const LineLocation &O) const {
  268. return LineOffset == O.LineOffset && Discriminator == O.Discriminator;
  269. }
  270. bool operator!=(const LineLocation &O) const {
  271. return LineOffset != O.LineOffset || Discriminator != O.Discriminator;
  272. }
  273. uint32_t LineOffset;
  274. uint32_t Discriminator;
  275. };
  276. raw_ostream &operator<<(raw_ostream &OS, const LineLocation &Loc);
  277. /// Representation of a single sample record.
  278. ///
  279. /// A sample record is represented by a positive integer value, which
  280. /// indicates how frequently was the associated line location executed.
  281. ///
  282. /// Additionally, if the associated location contains a function call,
  283. /// the record will hold a list of all the possible called targets. For
  284. /// direct calls, this will be the exact function being invoked. For
  285. /// indirect calls (function pointers, virtual table dispatch), this
  286. /// will be a list of one or more functions.
  287. class SampleRecord {
  288. public:
  289. using CallTarget = std::pair<StringRef, uint64_t>;
  290. struct CallTargetComparator {
  291. bool operator()(const CallTarget &LHS, const CallTarget &RHS) const {
  292. if (LHS.second != RHS.second)
  293. return LHS.second > RHS.second;
  294. return LHS.first < RHS.first;
  295. }
  296. };
  297. using SortedCallTargetSet = std::set<CallTarget, CallTargetComparator>;
  298. using CallTargetMap = StringMap<uint64_t>;
  299. SampleRecord() = default;
  300. /// Increment the number of samples for this record by \p S.
  301. /// Optionally scale sample count \p S by \p Weight.
  302. ///
  303. /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
  304. /// around unsigned integers.
  305. sampleprof_error addSamples(uint64_t S, uint64_t Weight = 1) {
  306. bool Overflowed;
  307. NumSamples = SaturatingMultiplyAdd(S, Weight, NumSamples, &Overflowed);
  308. return Overflowed ? sampleprof_error::counter_overflow
  309. : sampleprof_error::success;
  310. }
  311. /// Add called function \p F with samples \p S.
  312. /// Optionally scale sample count \p S by \p Weight.
  313. ///
  314. /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
  315. /// around unsigned integers.
  316. sampleprof_error addCalledTarget(StringRef F, uint64_t S,
  317. uint64_t Weight = 1) {
  318. uint64_t &TargetSamples = CallTargets[F];
  319. bool Overflowed;
  320. TargetSamples =
  321. SaturatingMultiplyAdd(S, Weight, TargetSamples, &Overflowed);
  322. return Overflowed ? sampleprof_error::counter_overflow
  323. : sampleprof_error::success;
  324. }
  325. /// Return true if this sample record contains function calls.
  326. bool hasCalls() const { return !CallTargets.empty(); }
  327. uint64_t getSamples() const { return NumSamples; }
  328. const CallTargetMap &getCallTargets() const { return CallTargets; }
  329. const SortedCallTargetSet getSortedCallTargets() const {
  330. return SortCallTargets(CallTargets);
  331. }
  332. /// Sort call targets in descending order of call frequency.
  333. static const SortedCallTargetSet SortCallTargets(const CallTargetMap &Targets) {
  334. SortedCallTargetSet SortedTargets;
  335. for (const auto &I : Targets) {
  336. SortedTargets.emplace(I.first(), I.second);
  337. }
  338. return SortedTargets;
  339. }
  340. /// Prorate call targets by a distribution factor.
  341. static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets,
  342. float DistributionFactor) {
  343. CallTargetMap AdjustedTargets;
  344. for (const auto &I : Targets) {
  345. AdjustedTargets[I.first()] = I.second * DistributionFactor;
  346. }
  347. return AdjustedTargets;
  348. }
  349. /// Merge the samples in \p Other into this record.
  350. /// Optionally scale sample counts by \p Weight.
  351. sampleprof_error merge(const SampleRecord &Other, uint64_t Weight = 1);
  352. void print(raw_ostream &OS, unsigned Indent) const;
  353. void dump() const;
  354. private:
  355. uint64_t NumSamples = 0;
  356. CallTargetMap CallTargets;
  357. };
  358. raw_ostream &operator<<(raw_ostream &OS, const SampleRecord &Sample);
  359. // State of context associated with FunctionSamples
  360. enum ContextStateMask {
  361. UnknownContext = 0x0, // Profile without context
  362. RawContext = 0x1, // Full context profile from input profile
  363. SyntheticContext = 0x2, // Synthetic context created for context promotion
  364. InlinedContext = 0x4, // Profile for context that is inlined into caller
  365. MergedContext = 0x8 // Profile for context merged into base profile
  366. };
  367. // Attribute of context associated with FunctionSamples
  368. enum ContextAttributeMask {
  369. ContextNone = 0x0,
  370. ContextWasInlined = 0x1, // Leaf of context was inlined in previous build
  371. ContextShouldBeInlined = 0x2, // Leaf of context should be inlined
  372. };
  373. // Represents a context frame with function name and line location
  374. struct SampleContextFrame {
  375. StringRef FuncName;
  376. LineLocation Location;
  377. SampleContextFrame() : Location(0, 0) {}
  378. SampleContextFrame(StringRef FuncName, LineLocation Location)
  379. : FuncName(FuncName), Location(Location) {}
  380. bool operator==(const SampleContextFrame &That) const {
  381. return Location == That.Location && FuncName == That.FuncName;
  382. }
  383. bool operator!=(const SampleContextFrame &That) const {
  384. return !(*this == That);
  385. }
  386. std::string toString(bool OutputLineLocation) const {
  387. std::ostringstream OContextStr;
  388. OContextStr << FuncName.str();
  389. if (OutputLineLocation) {
  390. OContextStr << ":" << Location.LineOffset;
  391. if (Location.Discriminator)
  392. OContextStr << "." << Location.Discriminator;
  393. }
  394. return OContextStr.str();
  395. }
  396. };
  397. static inline hash_code hash_value(const SampleContextFrame &arg) {
  398. return hash_combine(arg.FuncName, arg.Location.LineOffset,
  399. arg.Location.Discriminator);
  400. }
  401. using SampleContextFrameVector = SmallVector<SampleContextFrame, 1>;
  402. using SampleContextFrames = ArrayRef<SampleContextFrame>;
  403. struct SampleContextFrameHash {
  404. uint64_t operator()(const SampleContextFrameVector &S) const {
  405. return hash_combine_range(S.begin(), S.end());
  406. }
  407. };
  408. // Sample context for FunctionSamples. It consists of the calling context,
  409. // the function name and context state. Internally sample context is represented
  410. // using ArrayRef, which is also the input for constructing a `SampleContext`.
  411. // It can accept and represent both full context string as well as context-less
  412. // function name.
  413. // For a CS profile, a full context vector can look like:
  414. // `main:3 _Z5funcAi:1 _Z8funcLeafi`
  415. // For a base CS profile without calling context, the context vector should only
  416. // contain the leaf frame name.
  417. // For a non-CS profile, the context vector should be empty.
  418. class SampleContext {
  419. public:
  420. SampleContext() : State(UnknownContext), Attributes(ContextNone) {}
  421. SampleContext(StringRef Name)
  422. : Name(Name), State(UnknownContext), Attributes(ContextNone) {}
  423. SampleContext(SampleContextFrames Context,
  424. ContextStateMask CState = RawContext)
  425. : Attributes(ContextNone) {
  426. assert(!Context.empty() && "Context is empty");
  427. setContext(Context, CState);
  428. }
  429. // Give a context string, decode and populate internal states like
  430. // Function name, Calling context and context state. Example of input
  431. // `ContextStr`: `[main:3 @ _Z5funcAi:1 @ _Z8funcLeafi]`
  432. SampleContext(StringRef ContextStr,
  433. std::list<SampleContextFrameVector> &CSNameTable,
  434. ContextStateMask CState = RawContext)
  435. : Attributes(ContextNone) {
  436. assert(!ContextStr.empty());
  437. // Note that `[]` wrapped input indicates a full context string, otherwise
  438. // it's treated as context-less function name only.
  439. bool HasContext = ContextStr.startswith("[");
  440. if (!HasContext) {
  441. State = UnknownContext;
  442. Name = ContextStr;
  443. } else {
  444. CSNameTable.emplace_back();
  445. SampleContextFrameVector &Context = CSNameTable.back();
  446. createCtxVectorFromStr(ContextStr, Context);
  447. setContext(Context, CState);
  448. }
  449. }
  450. /// Create a context vector from a given context string and save it in
  451. /// `Context`.
  452. static void createCtxVectorFromStr(StringRef ContextStr,
  453. SampleContextFrameVector &Context) {
  454. // Remove encapsulating '[' and ']' if any
  455. ContextStr = ContextStr.substr(1, ContextStr.size() - 2);
  456. StringRef ContextRemain = ContextStr;
  457. StringRef ChildContext;
  458. StringRef CalleeName;
  459. while (!ContextRemain.empty()) {
  460. auto ContextSplit = ContextRemain.split(" @ ");
  461. ChildContext = ContextSplit.first;
  462. ContextRemain = ContextSplit.second;
  463. LineLocation CallSiteLoc(0, 0);
  464. decodeContextString(ChildContext, CalleeName, CallSiteLoc);
  465. Context.emplace_back(CalleeName, CallSiteLoc);
  466. }
  467. }
  468. // Promote context by removing top frames with the length of
  469. // `ContextFramesToRemove`. Note that with array representation of context,
  470. // the promotion is effectively a slice operation with first
  471. // `ContextFramesToRemove` elements removed from left.
  472. void promoteOnPath(uint32_t ContextFramesToRemove) {
  473. assert(ContextFramesToRemove <= FullContext.size() &&
  474. "Cannot remove more than the whole context");
  475. FullContext = FullContext.drop_front(ContextFramesToRemove);
  476. }
  477. // Decode context string for a frame to get function name and location.
  478. // `ContextStr` is in the form of `FuncName:StartLine.Discriminator`.
  479. static void decodeContextString(StringRef ContextStr, StringRef &FName,
  480. LineLocation &LineLoc) {
  481. // Get function name
  482. auto EntrySplit = ContextStr.split(':');
  483. FName = EntrySplit.first;
  484. LineLoc = {0, 0};
  485. if (!EntrySplit.second.empty()) {
  486. // Get line offset, use signed int for getAsInteger so string will
  487. // be parsed as signed.
  488. int LineOffset = 0;
  489. auto LocSplit = EntrySplit.second.split('.');
  490. LocSplit.first.getAsInteger(10, LineOffset);
  491. LineLoc.LineOffset = LineOffset;
  492. // Get discriminator
  493. if (!LocSplit.second.empty())
  494. LocSplit.second.getAsInteger(10, LineLoc.Discriminator);
  495. }
  496. }
  497. operator SampleContextFrames() const { return FullContext; }
  498. bool hasAttribute(ContextAttributeMask A) { return Attributes & (uint32_t)A; }
  499. void setAttribute(ContextAttributeMask A) { Attributes |= (uint32_t)A; }
  500. uint32_t getAllAttributes() { return Attributes; }
  501. void setAllAttributes(uint32_t A) { Attributes = A; }
  502. bool hasState(ContextStateMask S) { return State & (uint32_t)S; }
  503. void setState(ContextStateMask S) { State |= (uint32_t)S; }
  504. void clearState(ContextStateMask S) { State &= (uint32_t)~S; }
  505. bool hasContext() const { return State != UnknownContext; }
  506. bool isBaseContext() const { return FullContext.size() == 1; }
  507. StringRef getName() const { return Name; }
  508. SampleContextFrames getContextFrames() const { return FullContext; }
  509. static std::string getContextString(SampleContextFrames Context,
  510. bool IncludeLeafLineLocation = false) {
  511. std::ostringstream OContextStr;
  512. for (uint32_t I = 0; I < Context.size(); I++) {
  513. if (OContextStr.str().size()) {
  514. OContextStr << " @ ";
  515. }
  516. OContextStr << Context[I].toString(I != Context.size() - 1 ||
  517. IncludeLeafLineLocation);
  518. }
  519. return OContextStr.str();
  520. }
  521. std::string toString() const {
  522. if (!hasContext())
  523. return Name.str();
  524. return getContextString(FullContext, false);
  525. }
  526. uint64_t getHashCode() const {
  527. return hasContext() ? hash_value(getContextFrames())
  528. : hash_value(getName());
  529. }
  530. /// Set the name of the function and clear the current context.
  531. void setName(StringRef FunctionName) {
  532. Name = FunctionName;
  533. FullContext = SampleContextFrames();
  534. State = UnknownContext;
  535. }
  536. void setContext(SampleContextFrames Context,
  537. ContextStateMask CState = RawContext) {
  538. assert(CState != UnknownContext);
  539. FullContext = Context;
  540. Name = Context.back().FuncName;
  541. State = CState;
  542. }
  543. bool operator==(const SampleContext &That) const {
  544. return State == That.State && Name == That.Name &&
  545. FullContext == That.FullContext;
  546. }
  547. bool operator!=(const SampleContext &That) const { return !(*this == That); }
  548. bool operator<(const SampleContext &That) const {
  549. if (State != That.State)
  550. return State < That.State;
  551. if (!hasContext()) {
  552. return (Name.compare(That.Name)) == -1;
  553. }
  554. uint64_t I = 0;
  555. while (I < std::min(FullContext.size(), That.FullContext.size())) {
  556. auto &Context1 = FullContext[I];
  557. auto &Context2 = That.FullContext[I];
  558. auto V = Context1.FuncName.compare(Context2.FuncName);
  559. if (V)
  560. return V == -1;
  561. if (Context1.Location != Context2.Location)
  562. return Context1.Location < Context2.Location;
  563. I++;
  564. }
  565. return FullContext.size() < That.FullContext.size();
  566. }
  567. struct Hash {
  568. uint64_t operator()(const SampleContext &Context) const {
  569. return Context.getHashCode();
  570. }
  571. };
  572. bool IsPrefixOf(const SampleContext &That) const {
  573. auto ThisContext = FullContext;
  574. auto ThatContext = That.FullContext;
  575. if (ThatContext.size() < ThisContext.size())
  576. return false;
  577. ThatContext = ThatContext.take_front(ThisContext.size());
  578. // Compare Leaf frame first
  579. if (ThisContext.back().FuncName != ThatContext.back().FuncName)
  580. return false;
  581. // Compare leading context
  582. return ThisContext.drop_back() == ThatContext.drop_back();
  583. }
  584. private:
  585. /// Mangled name of the function.
  586. StringRef Name;
  587. // Full context including calling context and leaf function name
  588. SampleContextFrames FullContext;
  589. // State of the associated sample profile
  590. uint32_t State;
  591. // Attribute of the associated sample profile
  592. uint32_t Attributes;
  593. };
  594. static inline hash_code hash_value(const SampleContext &arg) {
  595. return arg.hasContext() ? hash_value(arg.getContextFrames())
  596. : hash_value(arg.getName());
  597. }
  598. class FunctionSamples;
  599. class SampleProfileReaderItaniumRemapper;
  600. using BodySampleMap = std::map<LineLocation, SampleRecord>;
  601. // NOTE: Using a StringMap here makes parsed profiles consume around 17% more
  602. // memory, which is *very* significant for large profiles.
  603. using FunctionSamplesMap = std::map<std::string, FunctionSamples, std::less<>>;
  604. using CallsiteSampleMap = std::map<LineLocation, FunctionSamplesMap>;
  605. /// Representation of the samples collected for a function.
  606. ///
  607. /// This data structure contains all the collected samples for the body
  608. /// of a function. Each sample corresponds to a LineLocation instance
  609. /// within the body of the function.
  610. class FunctionSamples {
  611. public:
  612. FunctionSamples() = default;
  613. void print(raw_ostream &OS = dbgs(), unsigned Indent = 0) const;
  614. void dump() const;
  615. sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight = 1) {
  616. bool Overflowed;
  617. TotalSamples =
  618. SaturatingMultiplyAdd(Num, Weight, TotalSamples, &Overflowed);
  619. return Overflowed ? sampleprof_error::counter_overflow
  620. : sampleprof_error::success;
  621. }
  622. void setTotalSamples(uint64_t Num) { TotalSamples = Num; }
  623. sampleprof_error addHeadSamples(uint64_t Num, uint64_t Weight = 1) {
  624. bool Overflowed;
  625. TotalHeadSamples =
  626. SaturatingMultiplyAdd(Num, Weight, TotalHeadSamples, &Overflowed);
  627. return Overflowed ? sampleprof_error::counter_overflow
  628. : sampleprof_error::success;
  629. }
  630. sampleprof_error addBodySamples(uint32_t LineOffset, uint32_t Discriminator,
  631. uint64_t Num, uint64_t Weight = 1) {
  632. return BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(
  633. Num, Weight);
  634. }
  635. sampleprof_error addCalledTargetSamples(uint32_t LineOffset,
  636. uint32_t Discriminator,
  637. StringRef FName, uint64_t Num,
  638. uint64_t Weight = 1) {
  639. return BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(
  640. FName, Num, Weight);
  641. }
  642. sampleprof_error addBodySamplesForProbe(uint32_t Index, uint64_t Num,
  643. uint64_t Weight = 1) {
  644. SampleRecord S;
  645. S.addSamples(Num, Weight);
  646. return BodySamples[LineLocation(Index, 0)].merge(S, Weight);
  647. }
  648. // Accumulate all body samples to set total samples.
  649. void updateTotalSamples() {
  650. setTotalSamples(0);
  651. for (const auto &I : BodySamples)
  652. addTotalSamples(I.second.getSamples());
  653. for (auto &I : CallsiteSamples) {
  654. for (auto &CS : I.second) {
  655. CS.second.updateTotalSamples();
  656. addTotalSamples(CS.second.getTotalSamples());
  657. }
  658. }
  659. }
  660. // Set current context and all callee contexts to be synthetic.
  661. void SetContextSynthetic() {
  662. Context.setState(SyntheticContext);
  663. for (auto &I : CallsiteSamples) {
  664. for (auto &CS : I.second) {
  665. CS.second.SetContextSynthetic();
  666. }
  667. }
  668. }
  669. /// Return the number of samples collected at the given location.
  670. /// Each location is specified by \p LineOffset and \p Discriminator.
  671. /// If the location is not found in profile, return error.
  672. ErrorOr<uint64_t> findSamplesAt(uint32_t LineOffset,
  673. uint32_t Discriminator) const {
  674. const auto &ret = BodySamples.find(LineLocation(LineOffset, Discriminator));
  675. if (ret == BodySamples.end())
  676. return std::error_code();
  677. return ret->second.getSamples();
  678. }
  679. /// Returns the call target map collected at a given location.
  680. /// Each location is specified by \p LineOffset and \p Discriminator.
  681. /// If the location is not found in profile, return error.
  682. ErrorOr<SampleRecord::CallTargetMap>
  683. findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const {
  684. const auto &ret = BodySamples.find(LineLocation(LineOffset, Discriminator));
  685. if (ret == BodySamples.end())
  686. return std::error_code();
  687. return ret->second.getCallTargets();
  688. }
  689. /// Returns the call target map collected at a given location specified by \p
  690. /// CallSite. If the location is not found in profile, return error.
  691. ErrorOr<SampleRecord::CallTargetMap>
  692. findCallTargetMapAt(const LineLocation &CallSite) const {
  693. const auto &Ret = BodySamples.find(CallSite);
  694. if (Ret == BodySamples.end())
  695. return std::error_code();
  696. return Ret->second.getCallTargets();
  697. }
  698. /// Return the function samples at the given callsite location.
  699. FunctionSamplesMap &functionSamplesAt(const LineLocation &Loc) {
  700. return CallsiteSamples[Loc];
  701. }
  702. /// Returns the FunctionSamplesMap at the given \p Loc.
  703. const FunctionSamplesMap *
  704. findFunctionSamplesMapAt(const LineLocation &Loc) const {
  705. auto iter = CallsiteSamples.find(Loc);
  706. if (iter == CallsiteSamples.end())
  707. return nullptr;
  708. return &iter->second;
  709. }
  710. /// Returns a pointer to FunctionSamples at the given callsite location
  711. /// \p Loc with callee \p CalleeName. If no callsite can be found, relax
  712. /// the restriction to return the FunctionSamples at callsite location
  713. /// \p Loc with the maximum total sample count. If \p Remapper is not
  714. /// nullptr, use \p Remapper to find FunctionSamples with equivalent name
  715. /// as \p CalleeName.
  716. const FunctionSamples *
  717. findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName,
  718. SampleProfileReaderItaniumRemapper *Remapper) const;
  719. bool empty() const { return TotalSamples == 0; }
  720. /// Return the total number of samples collected inside the function.
  721. uint64_t getTotalSamples() const { return TotalSamples; }
  722. /// Return the total number of branch samples that have the function as the
  723. /// branch target. This should be equivalent to the sample of the first
  724. /// instruction of the symbol. But as we directly get this info for raw
  725. /// profile without referring to potentially inaccurate debug info, this
  726. /// gives more accurate profile data and is preferred for standalone symbols.
  727. uint64_t getHeadSamples() const { return TotalHeadSamples; }
  728. /// Return the sample count of the first instruction of the function.
  729. /// The function can be either a standalone symbol or an inlined function.
  730. uint64_t getEntrySamples() const {
  731. if (FunctionSamples::ProfileIsCSFlat && getHeadSamples()) {
  732. // For CS profile, if we already have more accurate head samples
  733. // counted by branch sample from caller, use them as entry samples.
  734. return getHeadSamples();
  735. }
  736. uint64_t Count = 0;
  737. // Use either BodySamples or CallsiteSamples which ever has the smaller
  738. // lineno.
  739. if (!BodySamples.empty() &&
  740. (CallsiteSamples.empty() ||
  741. BodySamples.begin()->first < CallsiteSamples.begin()->first))
  742. Count = BodySamples.begin()->second.getSamples();
  743. else if (!CallsiteSamples.empty()) {
  744. // An indirect callsite may be promoted to several inlined direct calls.
  745. // We need to get the sum of them.
  746. for (const auto &N_FS : CallsiteSamples.begin()->second)
  747. Count += N_FS.second.getEntrySamples();
  748. }
  749. // Return at least 1 if total sample is not 0.
  750. return Count ? Count : TotalSamples > 0;
  751. }
  752. /// Return all the samples collected in the body of the function.
  753. const BodySampleMap &getBodySamples() const { return BodySamples; }
  754. /// Return all the callsite samples collected in the body of the function.
  755. const CallsiteSampleMap &getCallsiteSamples() const {
  756. return CallsiteSamples;
  757. }
  758. /// Return the maximum of sample counts in a function body including functions
  759. /// inlined in it.
  760. uint64_t getMaxCountInside() const {
  761. uint64_t MaxCount = 0;
  762. for (const auto &L : getBodySamples())
  763. MaxCount = std::max(MaxCount, L.second.getSamples());
  764. for (const auto &C : getCallsiteSamples())
  765. for (const FunctionSamplesMap::value_type &F : C.second)
  766. MaxCount = std::max(MaxCount, F.second.getMaxCountInside());
  767. return MaxCount;
  768. }
  769. /// Merge the samples in \p Other into this one.
  770. /// Optionally scale samples by \p Weight.
  771. sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight = 1) {
  772. sampleprof_error Result = sampleprof_error::success;
  773. if (!GUIDToFuncNameMap)
  774. GUIDToFuncNameMap = Other.GUIDToFuncNameMap;
  775. if (Context.getName().empty())
  776. Context = Other.getContext();
  777. if (FunctionHash == 0) {
  778. // Set the function hash code for the target profile.
  779. FunctionHash = Other.getFunctionHash();
  780. } else if (FunctionHash != Other.getFunctionHash()) {
  781. // The two profiles coming with different valid hash codes indicates
  782. // either:
  783. // 1. They are same-named static functions from different compilation
  784. // units (without using -unique-internal-linkage-names), or
  785. // 2. They are really the same function but from different compilations.
  786. // Let's bail out in either case for now, which means one profile is
  787. // dropped.
  788. return sampleprof_error::hash_mismatch;
  789. }
  790. MergeResult(Result, addTotalSamples(Other.getTotalSamples(), Weight));
  791. MergeResult(Result, addHeadSamples(Other.getHeadSamples(), Weight));
  792. for (const auto &I : Other.getBodySamples()) {
  793. const LineLocation &Loc = I.first;
  794. const SampleRecord &Rec = I.second;
  795. MergeResult(Result, BodySamples[Loc].merge(Rec, Weight));
  796. }
  797. for (const auto &I : Other.getCallsiteSamples()) {
  798. const LineLocation &Loc = I.first;
  799. FunctionSamplesMap &FSMap = functionSamplesAt(Loc);
  800. for (const auto &Rec : I.second)
  801. MergeResult(Result, FSMap[Rec.first].merge(Rec.second, Weight));
  802. }
  803. return Result;
  804. }
  805. /// Recursively traverses all children, if the total sample count of the
  806. /// corresponding function is no less than \p Threshold, add its corresponding
  807. /// GUID to \p S. Also traverse the BodySamples to add hot CallTarget's GUID
  808. /// to \p S.
  809. void findInlinedFunctions(DenseSet<GlobalValue::GUID> &S,
  810. const StringMap<Function *> &SymbolMap,
  811. uint64_t Threshold) const {
  812. if (TotalSamples <= Threshold)
  813. return;
  814. auto isDeclaration = [](const Function *F) {
  815. return !F || F->isDeclaration();
  816. };
  817. if (isDeclaration(SymbolMap.lookup(getFuncName()))) {
  818. // Add to the import list only when it's defined out of module.
  819. S.insert(getGUID(getName()));
  820. }
  821. // Import hot CallTargets, which may not be available in IR because full
  822. // profile annotation cannot be done until backend compilation in ThinLTO.
  823. for (const auto &BS : BodySamples)
  824. for (const auto &TS : BS.second.getCallTargets())
  825. if (TS.getValue() > Threshold) {
  826. const Function *Callee = SymbolMap.lookup(getFuncName(TS.getKey()));
  827. if (isDeclaration(Callee))
  828. S.insert(getGUID(TS.getKey()));
  829. }
  830. for (const auto &CS : CallsiteSamples)
  831. for (const auto &NameFS : CS.second)
  832. NameFS.second.findInlinedFunctions(S, SymbolMap, Threshold);
  833. }
  834. /// Set the name of the function.
  835. void setName(StringRef FunctionName) { Context.setName(FunctionName); }
  836. /// Return the function name.
  837. StringRef getName() const { return Context.getName(); }
  838. /// Return the original function name.
  839. StringRef getFuncName() const { return getFuncName(getName()); }
  840. void setFunctionHash(uint64_t Hash) { FunctionHash = Hash; }
  841. uint64_t getFunctionHash() const { return FunctionHash; }
  842. /// Return the canonical name for a function, taking into account
  843. /// suffix elision policy attributes.
  844. static StringRef getCanonicalFnName(const Function &F) {
  845. auto AttrName = "sample-profile-suffix-elision-policy";
  846. auto Attr = F.getFnAttribute(AttrName).getValueAsString();
  847. return getCanonicalFnName(F.getName(), Attr);
  848. }
  849. /// Name suffixes which canonicalization should handle to avoid
  850. /// profile mismatch.
  851. static constexpr const char *LLVMSuffix = ".llvm.";
  852. static constexpr const char *PartSuffix = ".part.";
  853. static constexpr const char *UniqSuffix = ".__uniq.";
  854. static StringRef getCanonicalFnName(StringRef FnName,
  855. StringRef Attr = "selected") {
  856. // Note the sequence of the suffixes in the knownSuffixes array matters.
  857. // If suffix "A" is appended after the suffix "B", "A" should be in front
  858. // of "B" in knownSuffixes.
  859. const char *knownSuffixes[] = {LLVMSuffix, PartSuffix, UniqSuffix};
  860. if (Attr == "" || Attr == "all") {
  861. return FnName.split('.').first;
  862. } else if (Attr == "selected") {
  863. StringRef Cand(FnName);
  864. for (const auto &Suf : knownSuffixes) {
  865. StringRef Suffix(Suf);
  866. // If the profile contains ".__uniq." suffix, don't strip the
  867. // suffix for names in the IR.
  868. if (Suffix == UniqSuffix && FunctionSamples::HasUniqSuffix)
  869. continue;
  870. auto It = Cand.rfind(Suffix);
  871. if (It == StringRef::npos)
  872. continue;
  873. auto Dit = Cand.rfind('.');
  874. if (Dit == It + Suffix.size() - 1)
  875. Cand = Cand.substr(0, It);
  876. }
  877. return Cand;
  878. } else if (Attr == "none") {
  879. return FnName;
  880. } else {
  881. assert(false && "internal error: unknown suffix elision policy");
  882. }
  883. return FnName;
  884. }
  885. /// Translate \p Name into its original name.
  886. /// When profile doesn't use MD5, \p Name needs no translation.
  887. /// When profile uses MD5, \p Name in current FunctionSamples
  888. /// is actually GUID of the original function name. getFuncName will
  889. /// translate \p Name in current FunctionSamples into its original name
  890. /// by looking up in the function map GUIDToFuncNameMap.
  891. /// If the original name doesn't exist in the map, return empty StringRef.
  892. StringRef getFuncName(StringRef Name) const {
  893. if (!UseMD5)
  894. return Name;
  895. assert(GUIDToFuncNameMap && "GUIDToFuncNameMap needs to be populated first");
  896. return GUIDToFuncNameMap->lookup(std::stoull(Name.data()));
  897. }
  898. /// Returns the line offset to the start line of the subprogram.
  899. /// We assume that a single function will not exceed 65535 LOC.
  900. static unsigned getOffset(const DILocation *DIL);
  901. /// Returns a unique call site identifier for a given debug location of a call
  902. /// instruction. This is wrapper of two scenarios, the probe-based profile and
  903. /// regular profile, to hide implementation details from the sample loader and
  904. /// the context tracker.
  905. static LineLocation getCallSiteIdentifier(const DILocation *DIL,
  906. bool ProfileIsFS = false);
  907. /// Returns a unique hash code for a combination of a callsite location and
  908. /// the callee function name.
  909. static uint64_t getCallSiteHash(StringRef CalleeName,
  910. const LineLocation &Callsite);
  911. /// Get the FunctionSamples of the inline instance where DIL originates
  912. /// from.
  913. ///
  914. /// The FunctionSamples of the instruction (Machine or IR) associated to
  915. /// \p DIL is the inlined instance in which that instruction is coming from.
  916. /// We traverse the inline stack of that instruction, and match it with the
  917. /// tree nodes in the profile.
  918. ///
  919. /// \returns the FunctionSamples pointer to the inlined instance.
  920. /// If \p Remapper is not nullptr, it will be used to find matching
  921. /// FunctionSamples with not exactly the same but equivalent name.
  922. const FunctionSamples *findFunctionSamples(
  923. const DILocation *DIL,
  924. SampleProfileReaderItaniumRemapper *Remapper = nullptr) const;
  925. static bool ProfileIsProbeBased;
  926. static bool ProfileIsCSFlat;
  927. static bool ProfileIsCSNested;
  928. SampleContext &getContext() const { return Context; }
  929. void setContext(const SampleContext &FContext) { Context = FContext; }
  930. static SampleProfileFormat Format;
  931. /// Whether the profile uses MD5 to represent string.
  932. static bool UseMD5;
  933. /// Whether the profile contains any ".__uniq." suffix in a name.
  934. static bool HasUniqSuffix;
  935. /// If this profile uses flow sensitive discriminators.
  936. static bool ProfileIsFS;
  937. /// GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
  938. /// all the function symbols defined or declared in current module.
  939. DenseMap<uint64_t, StringRef> *GUIDToFuncNameMap = nullptr;
  940. // Assume the input \p Name is a name coming from FunctionSamples itself.
  941. // If UseMD5 is true, the name is already a GUID and we
  942. // don't want to return the GUID of GUID.
  943. static uint64_t getGUID(StringRef Name) {
  944. return UseMD5 ? std::stoull(Name.data()) : Function::getGUID(Name);
  945. }
  946. // Find all the names in the current FunctionSamples including names in
  947. // all the inline instances and names of call targets.
  948. void findAllNames(DenseSet<StringRef> &NameSet) const;
  949. private:
  950. /// CFG hash value for the function.
  951. uint64_t FunctionHash = 0;
  952. /// Calling context for function profile
  953. mutable SampleContext Context;
  954. /// Total number of samples collected inside this function.
  955. ///
  956. /// Samples are cumulative, they include all the samples collected
  957. /// inside this function and all its inlined callees.
  958. uint64_t TotalSamples = 0;
  959. /// Total number of samples collected at the head of the function.
  960. /// This is an approximation of the number of calls made to this function
  961. /// at runtime.
  962. uint64_t TotalHeadSamples = 0;
  963. /// Map instruction locations to collected samples.
  964. ///
  965. /// Each entry in this map contains the number of samples
  966. /// collected at the corresponding line offset. All line locations
  967. /// are an offset from the start of the function.
  968. BodySampleMap BodySamples;
  969. /// Map call sites to collected samples for the called function.
  970. ///
  971. /// Each entry in this map corresponds to all the samples
  972. /// collected for the inlined function call at the given
  973. /// location. For example, given:
  974. ///
  975. /// void foo() {
  976. /// 1 bar();
  977. /// ...
  978. /// 8 baz();
  979. /// }
  980. ///
  981. /// If the bar() and baz() calls were inlined inside foo(), this
  982. /// map will contain two entries. One for all the samples collected
  983. /// in the call to bar() at line offset 1, the other for all the samples
  984. /// collected in the call to baz() at line offset 8.
  985. CallsiteSampleMap CallsiteSamples;
  986. };
  987. raw_ostream &operator<<(raw_ostream &OS, const FunctionSamples &FS);
  988. using SampleProfileMap =
  989. std::unordered_map<SampleContext, FunctionSamples, SampleContext::Hash>;
  990. using NameFunctionSamples = std::pair<SampleContext, const FunctionSamples *>;
  991. void sortFuncProfiles(const SampleProfileMap &ProfileMap,
  992. std::vector<NameFunctionSamples> &SortedProfiles);
  993. /// Sort a LocationT->SampleT map by LocationT.
  994. ///
  995. /// It produces a sorted list of <LocationT, SampleT> records by ascending
  996. /// order of LocationT.
  997. template <class LocationT, class SampleT> class SampleSorter {
  998. public:
  999. using SamplesWithLoc = std::pair<const LocationT, SampleT>;
  1000. using SamplesWithLocList = SmallVector<const SamplesWithLoc *, 20>;
  1001. SampleSorter(const std::map<LocationT, SampleT> &Samples) {
  1002. for (const auto &I : Samples)
  1003. V.push_back(&I);
  1004. llvm::stable_sort(V, [](const SamplesWithLoc *A, const SamplesWithLoc *B) {
  1005. return A->first < B->first;
  1006. });
  1007. }
  1008. const SamplesWithLocList &get() const { return V; }
  1009. private:
  1010. SamplesWithLocList V;
  1011. };
  1012. /// SampleContextTrimmer impelements helper functions to trim, merge cold
  1013. /// context profiles. It also supports context profile canonicalization to make
  1014. /// sure ProfileMap's key is consistent with FunctionSample's name/context.
  1015. class SampleContextTrimmer {
  1016. public:
  1017. SampleContextTrimmer(SampleProfileMap &Profiles) : ProfileMap(Profiles){};
  1018. // Trim and merge cold context profile when requested. TrimBaseProfileOnly
  1019. // should only be effective when TrimColdContext is true. On top of
  1020. // TrimColdContext, TrimBaseProfileOnly can be used to specify to trim all
  1021. // cold profiles or only cold base profiles. Trimming base profiles only is
  1022. // mainly to honor the preinliner decsion. Note that when MergeColdContext is
  1023. // true, preinliner decsion is not honored anyway so TrimBaseProfileOnly will
  1024. // be ignored.
  1025. void trimAndMergeColdContextProfiles(uint64_t ColdCountThreshold,
  1026. bool TrimColdContext,
  1027. bool MergeColdContext,
  1028. uint32_t ColdContextFrameLength,
  1029. bool TrimBaseProfileOnly);
  1030. // Canonicalize context profile name and attributes.
  1031. void canonicalizeContextProfiles();
  1032. private:
  1033. SampleProfileMap &ProfileMap;
  1034. };
  1035. // CSProfileConverter converts a full context-sensitive flat sample profile into
  1036. // a nested context-sensitive sample profile.
  1037. class CSProfileConverter {
  1038. public:
  1039. CSProfileConverter(SampleProfileMap &Profiles);
  1040. void convertProfiles();
  1041. struct FrameNode {
  1042. FrameNode(StringRef FName = StringRef(),
  1043. FunctionSamples *FSamples = nullptr,
  1044. LineLocation CallLoc = {0, 0})
  1045. : FuncName(FName), FuncSamples(FSamples), CallSiteLoc(CallLoc){};
  1046. // Map line+discriminator location to child frame
  1047. std::map<uint64_t, FrameNode> AllChildFrames;
  1048. // Function name for current frame
  1049. StringRef FuncName;
  1050. // Function Samples for current frame
  1051. FunctionSamples *FuncSamples;
  1052. // Callsite location in parent context
  1053. LineLocation CallSiteLoc;
  1054. FrameNode *getOrCreateChildFrame(const LineLocation &CallSite,
  1055. StringRef CalleeName);
  1056. };
  1057. private:
  1058. // Nest all children profiles into the profile of Node.
  1059. void convertProfiles(FrameNode &Node);
  1060. FrameNode *getOrCreateContextPath(const SampleContext &Context);
  1061. SampleProfileMap &ProfileMap;
  1062. FrameNode RootFrame;
  1063. };
  1064. /// ProfileSymbolList records the list of function symbols shown up
  1065. /// in the binary used to generate the profile. It is useful to
  1066. /// to discriminate a function being so cold as not to shown up
  1067. /// in the profile and a function newly added.
  1068. class ProfileSymbolList {
  1069. public:
  1070. /// copy indicates whether we need to copy the underlying memory
  1071. /// for the input Name.
  1072. void add(StringRef Name, bool copy = false) {
  1073. if (!copy) {
  1074. Syms.insert(Name);
  1075. return;
  1076. }
  1077. Syms.insert(Name.copy(Allocator));
  1078. }
  1079. bool contains(StringRef Name) { return Syms.count(Name); }
  1080. void merge(const ProfileSymbolList &List) {
  1081. for (auto Sym : List.Syms)
  1082. add(Sym, true);
  1083. }
  1084. unsigned size() { return Syms.size(); }
  1085. void setToCompress(bool TC) { ToCompress = TC; }
  1086. bool toCompress() { return ToCompress; }
  1087. std::error_code read(const uint8_t *Data, uint64_t ListSize);
  1088. std::error_code write(raw_ostream &OS);
  1089. void dump(raw_ostream &OS = dbgs()) const;
  1090. private:
  1091. // Determine whether or not to compress the symbol list when
  1092. // writing it into profile. The variable is unused when the symbol
  1093. // list is read from an existing profile.
  1094. bool ToCompress = false;
  1095. DenseSet<StringRef> Syms;
  1096. BumpPtrAllocator Allocator;
  1097. };
  1098. } // end namespace sampleprof
  1099. using namespace sampleprof;
  1100. // Provide DenseMapInfo for SampleContext.
  1101. template <> struct DenseMapInfo<SampleContext> {
  1102. static inline SampleContext getEmptyKey() { return SampleContext(); }
  1103. static inline SampleContext getTombstoneKey() { return SampleContext("@"); }
  1104. static unsigned getHashValue(const SampleContext &Val) {
  1105. return Val.getHashCode();
  1106. }
  1107. static bool isEqual(const SampleContext &LHS, const SampleContext &RHS) {
  1108. return LHS == RHS;
  1109. }
  1110. };
  1111. } // end namespace llvm
  1112. #endif // LLVM_PROFILEDATA_SAMPLEPROF_H
  1113. #ifdef __GNUC__
  1114. #pragma GCC diagnostic pop
  1115. #endif