ProfileGenerator.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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 "ErrorHandling.h"
  11. #include "PerfReader.h"
  12. #include "ProfiledBinary.h"
  13. #include "llvm/ProfileData/SampleProfWriter.h"
  14. using namespace llvm;
  15. using namespace sampleprof;
  16. namespace llvm {
  17. namespace sampleprof {
  18. class ProfileGenerator {
  19. public:
  20. ProfileGenerator(){};
  21. virtual ~ProfileGenerator() = default;
  22. static std::unique_ptr<ProfileGenerator>
  23. create(const BinarySampleCounterMap &BinarySampleCounters,
  24. enum PerfScriptType SampleType);
  25. virtual void generateProfile() = 0;
  26. // Use SampleProfileWriter to serialize profile map
  27. virtual void write(std::unique_ptr<SampleProfileWriter> Writer,
  28. StringMap<FunctionSamples> &ProfileMap);
  29. void write();
  30. protected:
  31. /*
  32. For each region boundary point, mark if it is begin or end (or both) of
  33. the region. Boundary points are inclusive. Log the sample count as well
  34. so we can use it when we compute the sample count of each disjoint region
  35. later. Note that there might be multiple ranges with different sample
  36. count that share same begin/end point. We need to accumulate the sample
  37. count for the boundary point for such case, because for the example
  38. below,
  39. |<--100-->|
  40. |<------200------>|
  41. A B C
  42. sample count for disjoint region [A,B] would be 300.
  43. */
  44. void findDisjointRanges(RangeSample &DisjointRanges,
  45. const RangeSample &Ranges);
  46. // Used by SampleProfileWriter
  47. StringMap<FunctionSamples> ProfileMap;
  48. };
  49. class CSProfileGenerator : public ProfileGenerator {
  50. protected:
  51. const BinarySampleCounterMap &BinarySampleCounters;
  52. public:
  53. CSProfileGenerator(const BinarySampleCounterMap &Counters)
  54. : BinarySampleCounters(Counters){};
  55. public:
  56. void generateProfile() override {
  57. for (const auto &BI : BinarySampleCounters) {
  58. ProfiledBinary *Binary = BI.first;
  59. for (const auto &CI : BI.second) {
  60. const StringBasedCtxKey *CtxKey =
  61. dyn_cast<StringBasedCtxKey>(CI.first.getPtr());
  62. StringRef ContextId(CtxKey->Context);
  63. // Get or create function profile for the range
  64. FunctionSamples &FunctionProfile =
  65. getFunctionProfileForContext(ContextId);
  66. // Fill in function body samples
  67. populateFunctionBodySamples(FunctionProfile, CI.second.RangeCounter,
  68. Binary);
  69. // Fill in boundary sample counts as well as call site samples for calls
  70. populateFunctionBoundarySamples(ContextId, FunctionProfile,
  71. CI.second.BranchCounter, Binary);
  72. }
  73. }
  74. // Fill in call site value sample for inlined calls and also use context to
  75. // infer missing samples. Since we don't have call count for inlined
  76. // functions, we estimate it from inlinee's profile using the entry of the
  77. // body sample.
  78. populateInferredFunctionSamples();
  79. }
  80. // Remove adjacent repeated context sequences up to a given sequence length,
  81. // -1 means no size limit. Note that repeated sequences are identified based
  82. // on the exact call site, this is finer granularity than function recursion.
  83. template <typename T>
  84. static void compressRecursionContext(SmallVectorImpl<T> &Context,
  85. int32_t CSize = MaxCompressionSize) {
  86. uint32_t I = 1;
  87. uint32_t HS = static_cast<uint32_t>(Context.size() / 2);
  88. uint32_t MaxDedupSize =
  89. CSize == -1 ? HS : std::min(static_cast<uint32_t>(CSize), HS);
  90. auto BeginIter = Context.begin();
  91. // Use an in-place algorithm to save memory copy
  92. // End indicates the end location of current iteration's data
  93. uint32_t End = 0;
  94. // Deduplicate from length 1 to the max possible size of a repeated
  95. // sequence.
  96. while (I <= MaxDedupSize) {
  97. // This is a linear algorithm that deduplicates adjacent repeated
  98. // sequences of size I. The deduplication detection runs on a sliding
  99. // window whose size is 2*I and it keeps sliding the window to deduplicate
  100. // the data inside. Once duplication is detected, deduplicate it by
  101. // skipping the right half part of the window, otherwise just copy back
  102. // the new one by appending them at the back of End pointer(for the next
  103. // iteration).
  104. //
  105. // For example:
  106. // Input: [a1, a2, b1, b2]
  107. // (Added index to distinguish the same char, the origin is [a, a, b,
  108. // b], the size of the dedup window is 2(I = 1) at the beginning)
  109. //
  110. // 1) The initial status is a dummy window[null, a1], then just copy the
  111. // right half of the window(End = 0), then slide the window.
  112. // Result: [a1], a2, b1, b2 (End points to the element right before ],
  113. // after ] is the data of the previous iteration)
  114. //
  115. // 2) Next window is [a1, a2]. Since a1 == a2, then skip the right half of
  116. // the window i.e the duplication happen. Only slide the window.
  117. // Result: [a1], a2, b1, b2
  118. //
  119. // 3) Next window is [a2, b1], copy the right half of the window(b1 is
  120. // new) to the End and slide the window.
  121. // Result: [a1, b1], b1, b2
  122. //
  123. // 4) Next window is [b1, b2], same to 2), skip b2.
  124. // Result: [a1, b1], b1, b2
  125. // After resize, it will be [a, b]
  126. // Use pointers like below to do comparison inside the window
  127. // [a b c a b c]
  128. // | | | | |
  129. // LeftBoundary Left Right Left+I Right+I
  130. // A duplication found if Left < LeftBoundry.
  131. int32_t Right = I - 1;
  132. End = I;
  133. int32_t LeftBoundary = 0;
  134. while (Right + I < Context.size()) {
  135. // To avoids scanning a part of a sequence repeatedly, it finds out
  136. // the common suffix of two hald in the window. The common suffix will
  137. // serve as the common prefix of next possible pair of duplicate
  138. // sequences. The non-common part will be ignored and never scanned
  139. // again.
  140. // For example.
  141. // Input: [a, b1], c1, b2, c2
  142. // I = 2
  143. //
  144. // 1) For the window [a, b1, c1, b2], non-common-suffix for the right
  145. // part is 'c1', copy it and only slide the window 1 step.
  146. // Result: [a, b1, c1], b2, c2
  147. //
  148. // 2) Next window is [b1, c1, b2, c2], so duplication happen.
  149. // Result after resize: [a, b, c]
  150. int32_t Left = Right;
  151. while (Left >= LeftBoundary && Context[Left] == Context[Left + I]) {
  152. // Find the longest suffix inside the window. When stops, Left points
  153. // at the diverging point in the current sequence.
  154. Left--;
  155. }
  156. bool DuplicationFound = (Left < LeftBoundary);
  157. // Don't need to recheck the data before Right
  158. LeftBoundary = Right + 1;
  159. if (DuplicationFound) {
  160. // Duplication found, skip right half of the window.
  161. Right += I;
  162. } else {
  163. // Copy the non-common-suffix part of the adjacent sequence.
  164. std::copy(BeginIter + Right + 1, BeginIter + Left + I + 1,
  165. BeginIter + End);
  166. End += Left + I - Right;
  167. // Only slide the window by the size of non-common-suffix
  168. Right = Left + I;
  169. }
  170. }
  171. // Don't forget the remaining part that's not scanned.
  172. std::copy(BeginIter + Right + 1, Context.end(), BeginIter + End);
  173. End += Context.size() - Right - 1;
  174. I++;
  175. Context.resize(End);
  176. MaxDedupSize = std::min(static_cast<uint32_t>(End / 2), MaxDedupSize);
  177. }
  178. }
  179. protected:
  180. // Lookup or create FunctionSamples for the context
  181. FunctionSamples &getFunctionProfileForContext(StringRef ContextId);
  182. // Merge cold context profile whose total sample is below threshold
  183. // into base profile.
  184. void mergeAndTrimColdProfile(StringMap<FunctionSamples> &ProfileMap);
  185. void write(std::unique_ptr<SampleProfileWriter> Writer,
  186. StringMap<FunctionSamples> &ProfileMap) override;
  187. private:
  188. // Helper function for updating body sample for a leaf location in
  189. // FunctionProfile
  190. void updateBodySamplesforFunctionProfile(FunctionSamples &FunctionProfile,
  191. const FrameLocation &LeafLoc,
  192. uint64_t Count);
  193. void populateFunctionBodySamples(FunctionSamples &FunctionProfile,
  194. const RangeSample &RangeCounters,
  195. ProfiledBinary *Binary);
  196. void populateFunctionBoundarySamples(StringRef ContextId,
  197. FunctionSamples &FunctionProfile,
  198. const BranchSample &BranchCounters,
  199. ProfiledBinary *Binary);
  200. void populateInferredFunctionSamples();
  201. public:
  202. // Deduplicate adjacent repeated context sequences up to a given sequence
  203. // length. -1 means no size limit.
  204. static int32_t MaxCompressionSize;
  205. };
  206. using ProbeCounterMap = std::unordered_map<const PseudoProbe *, uint64_t>;
  207. class PseudoProbeCSProfileGenerator : public CSProfileGenerator {
  208. public:
  209. PseudoProbeCSProfileGenerator(const BinarySampleCounterMap &Counters)
  210. : CSProfileGenerator(Counters) {}
  211. void generateProfile() override;
  212. private:
  213. // Go through each address from range to extract the top frame probe by
  214. // looking up in the Address2ProbeMap
  215. void extractProbesFromRange(const RangeSample &RangeCounter,
  216. ProbeCounterMap &ProbeCounter,
  217. ProfiledBinary *Binary);
  218. // Fill in function body samples from probes
  219. void
  220. populateBodySamplesWithProbes(const RangeSample &RangeCounter,
  221. SmallVectorImpl<std::string> &ContextStrStack,
  222. ProfiledBinary *Binary);
  223. // Fill in boundary samples for a call probe
  224. void populateBoundarySamplesWithProbes(
  225. const BranchSample &BranchCounter,
  226. SmallVectorImpl<std::string> &ContextStrStack, ProfiledBinary *Binary);
  227. // Helper function to get FunctionSamples for the leaf inlined context
  228. FunctionSamples &
  229. getFunctionProfileForLeafProbe(SmallVectorImpl<std::string> &ContextStrStack,
  230. const PseudoProbeFuncDesc *LeafFuncDesc);
  231. // Helper function to get FunctionSamples for the leaf probe
  232. FunctionSamples &
  233. getFunctionProfileForLeafProbe(SmallVectorImpl<std::string> &ContextStrStack,
  234. const PseudoProbe *LeafProbe,
  235. ProfiledBinary *Binary);
  236. };
  237. } // end namespace sampleprof
  238. } // end namespace llvm
  239. #endif