1 //===- ValueProfileCollector.cpp - determine what to value profile --------===//
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 //
9 // The implementation of the ValueProfileCollector via ValueProfileCollectorImpl
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ValueProfileCollector.h"
14 #include "ValueProfilePlugins.inc"
15 #include "llvm/ProfileData/InstrProf.h"
16 
17 using namespace llvm;
18 
19 namespace {
20 
21 /// A plugin-based class that takes an arbitrary number of Plugin types.
22 /// Each plugin type must satisfy the following API:
23 ///  1) the constructor must take a `Function &f`. Typically, the plugin would
24 ///     scan the function looking for candidates.
25 ///  2) contain a member function with the following signature and name:
26 ///        void run(std::vector<CandidateInfo> &Candidates);
27 ///    such that the plugin would append its result into the vector parameter.
28 ///
29 /// Plugins are defined in ValueProfilePlugins.inc
30 template <class... Ts> class PluginChain;
31 
32 /// The type PluginChainFinal is the final chain of plugins that will be used by
33 /// ValueProfileCollectorImpl.
34 using PluginChainFinal = PluginChain<VP_PLUGIN_LIST>;
35 
36 template <> class PluginChain<> {
37 public:
38   PluginChain(Function &F, TargetLibraryInfo &TLI) {}
39   void get(InstrProfValueKind K, std::vector<CandidateInfo> &Candidates) {}
40 };
41 
42 template <class PluginT, class... Ts>
43 class PluginChain<PluginT, Ts...> : public PluginChain<Ts...> {
44   PluginT Plugin;
45   using Base = PluginChain<Ts...>;
46 
47 public:
48   PluginChain(Function &F, TargetLibraryInfo &TLI)
49       : PluginChain<Ts...>(F, TLI), Plugin(F, TLI) {}
50 
51   void get(InstrProfValueKind K, std::vector<CandidateInfo> &Candidates) {
52     if (K == PluginT::Kind)
53       Plugin.run(Candidates);
54     Base::get(K, Candidates);
55   }
56 };
57 
58 } // end anonymous namespace
59 
60 /// ValueProfileCollectorImpl inherits the API of PluginChainFinal.
61 class ValueProfileCollector::ValueProfileCollectorImpl : public PluginChainFinal {
62 public:
63   using PluginChainFinal::PluginChainFinal;
64 };
65 
66 ValueProfileCollector::ValueProfileCollector(Function &F,
67                                              TargetLibraryInfo &TLI)
68     : PImpl(new ValueProfileCollectorImpl(F, TLI)) {}
69 
70 ValueProfileCollector::~ValueProfileCollector() = default;
71 
72 std::vector<CandidateInfo>
73 ValueProfileCollector::get(InstrProfValueKind Kind) const {
74   std::vector<CandidateInfo> Result;
75   PImpl->get(Kind, Result);
76   return Result;
77 }
78