ProfileGenerator.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. //===-- ProfileGenerator.h - Profile Generator -----------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef LLVM_TOOLS_LLVM_PROGEN_PROFILEGENERATOR_H
  9. #define LLVM_TOOLS_LLVM_PROGEN_PROFILEGENERATOR_H
  10. #include "CSPreInliner.h"
  11. #include "ErrorHandling.h"
  12. #include "PerfReader.h"
  13. #include "ProfiledBinary.h"
  14. #include "llvm/IR/DebugInfoMetadata.h"
  15. #include "llvm/ProfileData/SampleProfWriter.h"
  16. #include <memory>
  17. #include <unordered_set>
  18. using namespace llvm;
  19. using namespace sampleprof;
  20. namespace llvm {
  21. namespace sampleprof {
  22. using ProbeCounterMap =
  23. std::unordered_map<const MCDecodedPseudoProbe *, uint64_t>;
  24. // This base class for profile generation of sample-based PGO. We reuse all
  25. // structures relating to function profiles and profile writers as seen in
  26. // /ProfileData/SampleProf.h.
  27. class ProfileGeneratorBase {
  28. public:
  29. ProfileGeneratorBase(ProfiledBinary *Binary) : Binary(Binary){};
  30. ProfileGeneratorBase(ProfiledBinary *Binary,
  31. const ContextSampleCounterMap *Counters)
  32. : Binary(Binary), SampleCounters(Counters){};
  33. ProfileGeneratorBase(ProfiledBinary *Binary,
  34. const SampleProfileMap &&Profiles)
  35. : Binary(Binary), ProfileMap(std::move(Profiles)){};
  36. virtual ~ProfileGeneratorBase() = default;
  37. static std::unique_ptr<ProfileGeneratorBase>
  38. create(ProfiledBinary *Binary, const ContextSampleCounterMap *Counters,
  39. bool profileIsCS);
  40. static std::unique_ptr<ProfileGeneratorBase>
  41. create(ProfiledBinary *Binary, SampleProfileMap &ProfileMap,
  42. bool profileIsCS);
  43. virtual void generateProfile() = 0;
  44. void write();
  45. static uint32_t
  46. getDuplicationFactor(unsigned Discriminator,
  47. bool UseFSD = ProfileGeneratorBase::UseFSDiscriminator) {
  48. return UseFSD ? 1
  49. : llvm::DILocation::getDuplicationFactorFromDiscriminator(
  50. Discriminator);
  51. }
  52. static uint32_t
  53. getBaseDiscriminator(unsigned Discriminator,
  54. bool UseFSD = ProfileGeneratorBase::UseFSDiscriminator) {
  55. return UseFSD ? Discriminator
  56. : DILocation::getBaseDiscriminatorFromDiscriminator(
  57. Discriminator, /* IsFSDiscriminator */ false);
  58. }
  59. static bool UseFSDiscriminator;
  60. protected:
  61. // Use SampleProfileWriter to serialize profile map
  62. void write(std::unique_ptr<SampleProfileWriter> Writer,
  63. SampleProfileMap &ProfileMap);
  64. /*
  65. For each region boundary point, mark if it is begin or end (or both) of
  66. the region. Boundary points are inclusive. Log the sample count as well
  67. so we can use it when we compute the sample count of each disjoint region
  68. later. Note that there might be multiple ranges with different sample
  69. count that share same begin/end point. We need to accumulate the sample
  70. count for the boundary point for such case, because for the example
  71. below,
  72. |<--100-->|
  73. |<------200------>|
  74. A B C
  75. sample count for disjoint region [A,B] would be 300.
  76. */
  77. void findDisjointRanges(RangeSample &DisjointRanges,
  78. const RangeSample &Ranges);
  79. // Go through each address from range to extract the top frame probe by
  80. // looking up in the Address2ProbeMap
  81. void extractProbesFromRange(const RangeSample &RangeCounter,
  82. ProbeCounterMap &ProbeCounter,
  83. bool FindDisjointRanges = true);
  84. // Helper function for updating body sample for a leaf location in
  85. // FunctionProfile
  86. void updateBodySamplesforFunctionProfile(FunctionSamples &FunctionProfile,
  87. const SampleContextFrame &LeafLoc,
  88. uint64_t Count);
  89. void updateFunctionSamples();
  90. void updateTotalSamples();
  91. void updateCallsiteSamples();
  92. StringRef getCalleeNameForAddress(uint64_t TargetAddress);
  93. void computeSummaryAndThreshold(SampleProfileMap &ProfileMap);
  94. void calculateAndShowDensity(const SampleProfileMap &Profiles);
  95. double calculateDensity(const SampleProfileMap &Profiles,
  96. uint64_t HotCntThreshold);
  97. void showDensitySuggestion(double Density);
  98. void collectProfiledFunctions();
  99. bool collectFunctionsFromRawProfile(
  100. std::unordered_set<const BinaryFunction *> &ProfiledFunctions);
  101. // Collect profiled Functions for llvm sample profile input.
  102. virtual bool collectFunctionsFromLLVMProfile(
  103. std::unordered_set<const BinaryFunction *> &ProfiledFunctions) = 0;
  104. // Thresholds from profile summary to answer isHotCount/isColdCount queries.
  105. uint64_t HotCountThreshold;
  106. uint64_t ColdCountThreshold;
  107. ProfiledBinary *Binary = nullptr;
  108. std::unique_ptr<ProfileSummary> Summary;
  109. // Used by SampleProfileWriter
  110. SampleProfileMap ProfileMap;
  111. const ContextSampleCounterMap *SampleCounters = nullptr;
  112. };
  113. class ProfileGenerator : public ProfileGeneratorBase {
  114. public:
  115. ProfileGenerator(ProfiledBinary *Binary,
  116. const ContextSampleCounterMap *Counters)
  117. : ProfileGeneratorBase(Binary, Counters){};
  118. ProfileGenerator(ProfiledBinary *Binary, const SampleProfileMap &&Profiles)
  119. : ProfileGeneratorBase(Binary, std::move(Profiles)){};
  120. void generateProfile() override;
  121. private:
  122. void generateLineNumBasedProfile();
  123. void generateProbeBasedProfile();
  124. RangeSample preprocessRangeCounter(const RangeSample &RangeCounter);
  125. FunctionSamples &getTopLevelFunctionProfile(StringRef FuncName);
  126. // Helper function to get the leaf frame's FunctionProfile by traversing the
  127. // inline stack and meanwhile it adds the total samples for each frame's
  128. // function profile.
  129. FunctionSamples &
  130. getLeafProfileAndAddTotalSamples(const SampleContextFrameVector &FrameVec,
  131. uint64_t Count);
  132. void populateBodySamplesForAllFunctions(const RangeSample &RangeCounter);
  133. void
  134. populateBoundarySamplesForAllFunctions(const BranchSample &BranchCounters);
  135. void
  136. populateBodySamplesWithProbesForAllFunctions(const RangeSample &RangeCounter);
  137. void populateBoundarySamplesWithProbesForAllFunctions(
  138. const BranchSample &BranchCounters);
  139. void postProcessProfiles();
  140. void trimColdProfiles(const SampleProfileMap &Profiles,
  141. uint64_t ColdCntThreshold);
  142. bool collectFunctionsFromLLVMProfile(
  143. std::unordered_set<const BinaryFunction *> &ProfiledFunctions) override;
  144. };
  145. class CSProfileGenerator : public ProfileGeneratorBase {
  146. public:
  147. CSProfileGenerator(ProfiledBinary *Binary,
  148. const ContextSampleCounterMap *Counters)
  149. : ProfileGeneratorBase(Binary, Counters){};
  150. CSProfileGenerator(ProfiledBinary *Binary, SampleProfileMap &Profiles)
  151. : ProfileGeneratorBase(Binary), ContextTracker(Profiles, nullptr){};
  152. void generateProfile() override;
  153. // Trim the context stack at a given depth.
  154. template <typename T>
  155. static void trimContext(SmallVectorImpl<T> &S, int Depth = MaxContextDepth) {
  156. if (Depth < 0 || static_cast<size_t>(Depth) >= S.size())
  157. return;
  158. std::copy(S.begin() + S.size() - static_cast<size_t>(Depth), S.end(),
  159. S.begin());
  160. S.resize(Depth);
  161. }
  162. // Remove adjacent repeated context sequences up to a given sequence length,
  163. // -1 means no size limit. Note that repeated sequences are identified based
  164. // on the exact call site, this is finer granularity than function recursion.
  165. template <typename T>
  166. static void compressRecursionContext(SmallVectorImpl<T> &Context,
  167. int32_t CSize = MaxCompressionSize) {
  168. uint32_t I = 1;
  169. uint32_t HS = static_cast<uint32_t>(Context.size() / 2);
  170. uint32_t MaxDedupSize =
  171. CSize == -1 ? HS : std::min(static_cast<uint32_t>(CSize), HS);
  172. auto BeginIter = Context.begin();
  173. // Use an in-place algorithm to save memory copy
  174. // End indicates the end location of current iteration's data
  175. uint32_t End = 0;
  176. // Deduplicate from length 1 to the max possible size of a repeated
  177. // sequence.
  178. while (I <= MaxDedupSize) {
  179. // This is a linear algorithm that deduplicates adjacent repeated
  180. // sequences of size I. The deduplication detection runs on a sliding
  181. // window whose size is 2*I and it keeps sliding the window to deduplicate
  182. // the data inside. Once duplication is detected, deduplicate it by
  183. // skipping the right half part of the window, otherwise just copy back
  184. // the new one by appending them at the back of End pointer(for the next
  185. // iteration).
  186. //
  187. // For example:
  188. // Input: [a1, a2, b1, b2]
  189. // (Added index to distinguish the same char, the origin is [a, a, b,
  190. // b], the size of the dedup window is 2(I = 1) at the beginning)
  191. //
  192. // 1) The initial status is a dummy window[null, a1], then just copy the
  193. // right half of the window(End = 0), then slide the window.
  194. // Result: [a1], a2, b1, b2 (End points to the element right before ],
  195. // after ] is the data of the previous iteration)
  196. //
  197. // 2) Next window is [a1, a2]. Since a1 == a2, then skip the right half of
  198. // the window i.e the duplication happen. Only slide the window.
  199. // Result: [a1], a2, b1, b2
  200. //
  201. // 3) Next window is [a2, b1], copy the right half of the window(b1 is
  202. // new) to the End and slide the window.
  203. // Result: [a1, b1], b1, b2
  204. //
  205. // 4) Next window is [b1, b2], same to 2), skip b2.
  206. // Result: [a1, b1], b1, b2
  207. // After resize, it will be [a, b]
  208. // Use pointers like below to do comparison inside the window
  209. // [a b c a b c]
  210. // | | | | |
  211. // LeftBoundary Left Right Left+I Right+I
  212. // A duplication found if Left < LeftBoundry.
  213. int32_t Right = I - 1;
  214. End = I;
  215. int32_t LeftBoundary = 0;
  216. while (Right + I < Context.size()) {
  217. // To avoids scanning a part of a sequence repeatedly, it finds out
  218. // the common suffix of two hald in the window. The common suffix will
  219. // serve as the common prefix of next possible pair of duplicate
  220. // sequences. The non-common part will be ignored and never scanned
  221. // again.
  222. // For example.
  223. // Input: [a, b1], c1, b2, c2
  224. // I = 2
  225. //
  226. // 1) For the window [a, b1, c1, b2], non-common-suffix for the right
  227. // part is 'c1', copy it and only slide the window 1 step.
  228. // Result: [a, b1, c1], b2, c2
  229. //
  230. // 2) Next window is [b1, c1, b2, c2], so duplication happen.
  231. // Result after resize: [a, b, c]
  232. int32_t Left = Right;
  233. while (Left >= LeftBoundary && Context[Left] == Context[Left + I]) {
  234. // Find the longest suffix inside the window. When stops, Left points
  235. // at the diverging point in the current sequence.
  236. Left--;
  237. }
  238. bool DuplicationFound = (Left < LeftBoundary);
  239. // Don't need to recheck the data before Right
  240. LeftBoundary = Right + 1;
  241. if (DuplicationFound) {
  242. // Duplication found, skip right half of the window.
  243. Right += I;
  244. } else {
  245. // Copy the non-common-suffix part of the adjacent sequence.
  246. std::copy(BeginIter + Right + 1, BeginIter + Left + I + 1,
  247. BeginIter + End);
  248. End += Left + I - Right;
  249. // Only slide the window by the size of non-common-suffix
  250. Right = Left + I;
  251. }
  252. }
  253. // Don't forget the remaining part that's not scanned.
  254. std::copy(BeginIter + Right + 1, Context.end(), BeginIter + End);
  255. End += Context.size() - Right - 1;
  256. I++;
  257. Context.resize(End);
  258. MaxDedupSize = std::min(static_cast<uint32_t>(End / 2), MaxDedupSize);
  259. }
  260. }
  261. private:
  262. void generateLineNumBasedProfile();
  263. FunctionSamples *getOrCreateFunctionSamples(ContextTrieNode *ContextNode,
  264. bool WasLeafInlined = false);
  265. // Lookup or create ContextTrieNode for the context, FunctionSamples is
  266. // created inside this function.
  267. ContextTrieNode *getOrCreateContextNode(const SampleContextFrames Context,
  268. bool WasLeafInlined = false);
  269. // For profiled only functions, on-demand compute their inline context
  270. // function byte size which is used by the pre-inliner.
  271. void computeSizeForProfiledFunctions();
  272. // Post processing for profiles before writing out, such as mermining
  273. // and trimming cold profiles, running preinliner on profiles.
  274. void postProcessProfiles();
  275. void populateBodySamplesForFunction(FunctionSamples &FunctionProfile,
  276. const RangeSample &RangeCounters);
  277. void populateBoundarySamplesForFunction(ContextTrieNode *CallerNode,
  278. const BranchSample &BranchCounters);
  279. void populateInferredFunctionSamples(ContextTrieNode &Node);
  280. void updateFunctionSamples();
  281. void generateProbeBasedProfile();
  282. // Fill in function body samples from probes
  283. void populateBodySamplesWithProbes(const RangeSample &RangeCounter,
  284. const AddrBasedCtxKey *CtxKey);
  285. // Fill in boundary samples for a call probe
  286. void populateBoundarySamplesWithProbes(const BranchSample &BranchCounter,
  287. const AddrBasedCtxKey *CtxKey);
  288. ContextTrieNode *
  289. getContextNodeForLeafProbe(const AddrBasedCtxKey *CtxKey,
  290. const MCDecodedPseudoProbe *LeafProbe);
  291. // Helper function to get FunctionSamples for the leaf probe
  292. FunctionSamples &
  293. getFunctionProfileForLeafProbe(const AddrBasedCtxKey *CtxKey,
  294. const MCDecodedPseudoProbe *LeafProbe);
  295. void convertToProfileMap(ContextTrieNode &Node,
  296. SampleContextFrameVector &Context);
  297. void convertToProfileMap();
  298. void computeSummaryAndThreshold();
  299. bool collectFunctionsFromLLVMProfile(
  300. std::unordered_set<const BinaryFunction *> &ProfiledFunctions) override;
  301. void initializeMissingFrameInferrer();
  302. // Given an input `Context`, output `NewContext` with inferred missing tail
  303. // call frames.
  304. void inferMissingFrames(const SmallVectorImpl<uint64_t> &Context,
  305. SmallVectorImpl<uint64_t> &NewContext);
  306. ContextTrieNode &getRootContext() { return ContextTracker.getRootContext(); };
  307. // The container for holding the FunctionSamples used by context trie.
  308. std::list<FunctionSamples> FSamplesList;
  309. // Underlying context table serves for sample profile writer.
  310. std::unordered_set<SampleContextFrameVector, SampleContextFrameHash> Contexts;
  311. SampleContextTracker ContextTracker;
  312. bool IsProfileValidOnTrie = true;
  313. public:
  314. // Deduplicate adjacent repeated context sequences up to a given sequence
  315. // length. -1 means no size limit.
  316. static int32_t MaxCompressionSize;
  317. static int MaxContextDepth;
  318. };
  319. } // end namespace sampleprof
  320. } // end namespace llvm
  321. #endif