xref: /freebsd/contrib/llvm-project/llvm/lib/Support/Statistic.cpp (revision ebacd8013fe5f7fdf9f6a5b286f6680dd2891036)
1 //===-- Statistic.cpp - Easy way to expose stats information --------------===//
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 // This file implements the 'Statistic' class, which is designed to be an easy
10 // way to expose various success metrics from passes.  These statistics are
11 // printed at the end of a run, when the -stats command line option is enabled
12 // on the command line.
13 //
14 // This is useful for reporting information like the number of instructions
15 // simplified, optimized or removed by various transformations, like this:
16 //
17 // static Statistic NumInstEliminated("GCSE", "Number of instructions killed");
18 //
19 // Later, in the code: ++NumInstEliminated;
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "llvm/ADT/Statistic.h"
24 
25 #include "DebugOptions.h"
26 
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/Mutex.h"
34 #include "llvm/Support/Timer.h"
35 #include "llvm/Support/YAMLTraits.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <cstring>
39 using namespace llvm;
40 
41 /// -stats - Command line option to cause transformations to emit stats about
42 /// what they did.
43 ///
44 static bool EnableStats;
45 static bool StatsAsJSON;
46 static bool Enabled;
47 static bool PrintOnExit;
48 
49 void llvm::initStatisticOptions() {
50   static cl::opt<bool, true> registerEnableStats{
51       "stats",
52       cl::desc(
53           "Enable statistics output from program (available with Asserts)"),
54       cl::location(EnableStats), cl::Hidden};
55   static cl::opt<bool, true> registerStatsAsJson{
56       "stats-json", cl::desc("Display statistics as json data"),
57       cl::location(StatsAsJSON), cl::Hidden};
58 }
59 
60 namespace {
61 /// This class is used in a ManagedStatic so that it is created on demand (when
62 /// the first statistic is bumped) and destroyed only when llvm_shutdown is
63 /// called. We print statistics from the destructor.
64 /// This class is also used to look up statistic values from applications that
65 /// use LLVM.
66 class StatisticInfo {
67   std::vector<TrackingStatistic *> Stats;
68 
69   friend void llvm::PrintStatistics();
70   friend void llvm::PrintStatistics(raw_ostream &OS);
71   friend void llvm::PrintStatisticsJSON(raw_ostream &OS);
72 
73   /// Sort statistics by debugtype,name,description.
74   void sort();
75 public:
76   using const_iterator = std::vector<TrackingStatistic *>::const_iterator;
77 
78   StatisticInfo();
79   ~StatisticInfo();
80 
81   void addStatistic(TrackingStatistic *S) { Stats.push_back(S); }
82 
83   const_iterator begin() const { return Stats.begin(); }
84   const_iterator end() const { return Stats.end(); }
85   iterator_range<const_iterator> statistics() const {
86     return {begin(), end()};
87   }
88 
89   void reset();
90 };
91 } // end anonymous namespace
92 
93 static ManagedStatic<StatisticInfo> StatInfo;
94 static ManagedStatic<sys::SmartMutex<true> > StatLock;
95 
96 /// RegisterStatistic - The first time a statistic is bumped, this method is
97 /// called.
98 void TrackingStatistic::RegisterStatistic() {
99   // If stats are enabled, inform StatInfo that this statistic should be
100   // printed.
101   // llvm_shutdown calls destructors while holding the ManagedStatic mutex.
102   // These destructors end up calling PrintStatistics, which takes StatLock.
103   // Since dereferencing StatInfo and StatLock can require taking the
104   // ManagedStatic mutex, doing so with StatLock held would lead to a lock
105   // order inversion. To avoid that, we dereference the ManagedStatics first,
106   // and only take StatLock afterwards.
107   if (!Initialized.load(std::memory_order_relaxed)) {
108     sys::SmartMutex<true> &Lock = *StatLock;
109     StatisticInfo &SI = *StatInfo;
110     sys::SmartScopedLock<true> Writer(Lock);
111     // Check Initialized again after acquiring the lock.
112     if (Initialized.load(std::memory_order_relaxed))
113       return;
114     if (EnableStats || Enabled)
115       SI.addStatistic(this);
116 
117     // Remember we have been registered.
118     Initialized.store(true, std::memory_order_release);
119   }
120 }
121 
122 StatisticInfo::StatisticInfo() {
123   // Ensure timergroup lists are created first so they are destructed after us.
124   TimerGroup::ConstructTimerLists();
125 }
126 
127 // Print information when destroyed, iff command line option is specified.
128 StatisticInfo::~StatisticInfo() {
129   if (EnableStats || PrintOnExit)
130     llvm::PrintStatistics();
131 }
132 
133 void llvm::EnableStatistics(bool DoPrintOnExit) {
134   Enabled = true;
135   PrintOnExit = DoPrintOnExit;
136 }
137 
138 bool llvm::AreStatisticsEnabled() { return Enabled || EnableStats; }
139 
140 void StatisticInfo::sort() {
141   llvm::stable_sort(
142       Stats, [](const TrackingStatistic *LHS, const TrackingStatistic *RHS) {
143         if (int Cmp = std::strcmp(LHS->getDebugType(), RHS->getDebugType()))
144           return Cmp < 0;
145 
146         if (int Cmp = std::strcmp(LHS->getName(), RHS->getName()))
147           return Cmp < 0;
148 
149         return std::strcmp(LHS->getDesc(), RHS->getDesc()) < 0;
150       });
151 }
152 
153 void StatisticInfo::reset() {
154   sys::SmartScopedLock<true> Writer(*StatLock);
155 
156   // Tell each statistic that it isn't registered so it has to register
157   // again. We're holding the lock so it won't be able to do so until we're
158   // finished. Once we've forced it to re-register (after we return), then zero
159   // the value.
160   for (auto *Stat : Stats) {
161     // Value updates to a statistic that complete before this statement in the
162     // iteration for that statistic will be lost as intended.
163     Stat->Initialized = false;
164     Stat->Value = 0;
165   }
166 
167   // Clear the registration list and release the lock once we're done. Any
168   // pending updates from other threads will safely take effect after we return.
169   // That might not be what the user wants if they're measuring a compilation
170   // but it's their responsibility to prevent concurrent compilations to make
171   // a single compilation measurable.
172   Stats.clear();
173 }
174 
175 void llvm::PrintStatistics(raw_ostream &OS) {
176   StatisticInfo &Stats = *StatInfo;
177 
178   // Figure out how long the biggest Value and Name fields are.
179   unsigned MaxDebugTypeLen = 0, MaxValLen = 0;
180   for (TrackingStatistic *Stat : Stats.Stats) {
181     MaxValLen = std::max(MaxValLen, (unsigned)utostr(Stat->getValue()).size());
182     MaxDebugTypeLen =
183         std::max(MaxDebugTypeLen, (unsigned)std::strlen(Stat->getDebugType()));
184   }
185 
186   Stats.sort();
187 
188   // Print out the statistics header...
189   OS << "===" << std::string(73, '-') << "===\n"
190      << "                          ... Statistics Collected ...\n"
191      << "===" << std::string(73, '-') << "===\n\n";
192 
193   // Print all of the statistics.
194   for (TrackingStatistic *Stat : Stats.Stats)
195     OS << format("%*" PRIu64 " %-*s - %s\n", MaxValLen, Stat->getValue(),
196                  MaxDebugTypeLen, Stat->getDebugType(), Stat->getDesc());
197 
198   OS << '\n';  // Flush the output stream.
199   OS.flush();
200 }
201 
202 void llvm::PrintStatisticsJSON(raw_ostream &OS) {
203   sys::SmartScopedLock<true> Reader(*StatLock);
204   StatisticInfo &Stats = *StatInfo;
205 
206   Stats.sort();
207 
208   // Print all of the statistics.
209   OS << "{\n";
210   const char *delim = "";
211   for (const TrackingStatistic *Stat : Stats.Stats) {
212     OS << delim;
213     assert(yaml::needsQuotes(Stat->getDebugType()) == yaml::QuotingType::None &&
214            "Statistic group/type name is simple.");
215     assert(yaml::needsQuotes(Stat->getName()) == yaml::QuotingType::None &&
216            "Statistic name is simple");
217     OS << "\t\"" << Stat->getDebugType() << '.' << Stat->getName() << "\": "
218        << Stat->getValue();
219     delim = ",\n";
220   }
221   // Print timers.
222   TimerGroup::printAllJSONValues(OS, delim);
223 
224   OS << "\n}\n";
225   OS.flush();
226 }
227 
228 void llvm::PrintStatistics() {
229 #if LLVM_ENABLE_STATS
230   sys::SmartScopedLock<true> Reader(*StatLock);
231   StatisticInfo &Stats = *StatInfo;
232 
233   // Statistics not enabled?
234   if (Stats.Stats.empty()) return;
235 
236   // Get the stream to write to.
237   std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
238   if (StatsAsJSON)
239     PrintStatisticsJSON(*OutStream);
240   else
241     PrintStatistics(*OutStream);
242 
243 #else
244   // Check if the -stats option is set instead of checking
245   // !Stats.Stats.empty().  In release builds, Statistics operators
246   // do nothing, so stats are never Registered.
247   if (EnableStats) {
248     // Get the stream to write to.
249     std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
250     (*OutStream) << "Statistics are disabled.  "
251                  << "Build with asserts or with -DLLVM_FORCE_ENABLE_STATS\n";
252   }
253 #endif
254 }
255 
256 const std::vector<std::pair<StringRef, uint64_t>> llvm::GetStatistics() {
257   sys::SmartScopedLock<true> Reader(*StatLock);
258   std::vector<std::pair<StringRef, uint64_t>> ReturnStats;
259 
260   for (const auto &Stat : StatInfo->statistics())
261     ReturnStats.emplace_back(Stat->getName(), Stat->getValue());
262   return ReturnStats;
263 }
264 
265 void llvm::ResetStatistics() {
266   StatInfo->reset();
267 }
268