LLVM  14.0.0git
Statistic.cpp
Go to the documentation of this file.
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"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Format.h"
33 #include "llvm/Support/Mutex.h"
34 #include "llvm/Support/Timer.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 
50  static cl::opt<bool, true> registerEnableStats{
51  "stats",
52  cl::desc(
53  "Enable statistics output from program (available with Asserts)"),
55  static cl::opt<bool, true> registerStatsAsJson{
56  "stats-json", cl::desc("Display statistics as json data"),
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 
95 
96 /// RegisterStatistic - The first time a statistic is bumped, this method is
97 /// called.
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)) {
109  StatisticInfo &SI = *StatInfo;
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.
125 }
126 
127 // Print information when destroyed, iff command line option is specified.
128 StatisticInfo::~StatisticInfo() {
129  if (EnableStats || PrintOnExit)
131 }
132 
133 void llvm::EnableStatistics(bool DoPrintOnExit) {
134  Enabled = true;
135  PrintOnExit = DoPrintOnExit;
136 }
137 
139 
140 void StatisticInfo::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() {
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 
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 (size_t i = 0, e = Stats.Stats.size(); i != e; ++i) {
181  MaxValLen = std::max(MaxValLen,
182  (unsigned)utostr(Stats.Stats[i]->getValue()).size());
183  MaxDebugTypeLen = std::max(MaxDebugTypeLen,
184  (unsigned)std::strlen(Stats.Stats[i]->getDebugType()));
185  }
186 
187  Stats.sort();
188 
189  // Print out the statistics header...
190  OS << "===" << std::string(73, '-') << "===\n"
191  << " ... Statistics Collected ...\n"
192  << "===" << std::string(73, '-') << "===\n\n";
193 
194  // Print all of the statistics.
195  for (size_t i = 0, e = Stats.Stats.size(); i != e; ++i)
196  OS << format("%*u %-*s - %s\n",
197  MaxValLen, Stats.Stats[i]->getValue(),
198  MaxDebugTypeLen, Stats.Stats[i]->getDebugType(),
199  Stats.Stats[i]->getDesc());
200 
201  OS << '\n'; // Flush the output stream.
202  OS.flush();
203 }
204 
207  StatisticInfo &Stats = *StatInfo;
208 
209  Stats.sort();
210 
211  // Print all of the statistics.
212  OS << "{\n";
213  const char *delim = "";
214  for (const TrackingStatistic *Stat : Stats.Stats) {
215  OS << delim;
216  assert(yaml::needsQuotes(Stat->getDebugType()) == yaml::QuotingType::None &&
217  "Statistic group/type name is simple.");
218  assert(yaml::needsQuotes(Stat->getName()) == yaml::QuotingType::None &&
219  "Statistic name is simple");
220  OS << "\t\"" << Stat->getDebugType() << '.' << Stat->getName() << "\": "
221  << Stat->getValue();
222  delim = ",\n";
223  }
224  // Print timers.
226 
227  OS << "\n}\n";
228  OS.flush();
229 }
230 
232 #if LLVM_ENABLE_STATS
234  StatisticInfo &Stats = *StatInfo;
235 
236  // Statistics not enabled?
237  if (Stats.Stats.empty()) return;
238 
239  // Get the stream to write to.
240  std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
241  if (StatsAsJSON)
242  PrintStatisticsJSON(*OutStream);
243  else
244  PrintStatistics(*OutStream);
245 
246 #else
247  // Check if the -stats option is set instead of checking
248  // !Stats.Stats.empty(). In release builds, Statistics operators
249  // do nothing, so stats are never Registered.
250  if (EnableStats) {
251  // Get the stream to write to.
252  std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
253  (*OutStream) << "Statistics are disabled. "
254  << "Build with asserts or with -DLLVM_FORCE_ENABLE_STATS\n";
255  }
256 #endif
257 }
258 
259 const std::vector<std::pair<StringRef, unsigned>> llvm::GetStatistics() {
261  std::vector<std::pair<StringRef, unsigned>> ReturnStats;
262 
263  for (const auto &Stat : StatInfo->statistics())
264  ReturnStats.emplace_back(Stat->getName(), Stat->getValue());
265  return ReturnStats;
266 }
267 
269  StatInfo->reset();
270 }
i
i
Definition: README.txt:29
llvm
---------------------— PointerInfo ------------------------------------—
Definition: AllocatorList.h:23
llvm::TimerGroup::printAllJSONValues
static const char * printAllJSONValues(raw_ostream &OS, const char *delim)
Prints all timers as JSON key/value pairs.
Definition: Timer.cpp:496
llvm::cl::location
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:459
PrintOnExit
static bool PrintOnExit
Definition: Statistic.cpp:47
Statistic.h
ManagedStatic.h
llvm::cl::Hidden
@ Hidden
Definition: CommandLine.h:143
DebugOptions.h
llvm::sys::path::end
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:233
llvm::sys::path::begin
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:224
llvm::TrackingStatistic::getDebugType
const char * getDebugType() const
Definition: Statistic.h:63
Format.h
llvm::CreateInfoOutputFile
std::unique_ptr< raw_fd_ostream > CreateInfoOutputFile()
Return a file stream to print our output on.
Definition: Timer.cpp:96
llvm::Lock
static sys::Mutex Lock
Definition: NVPTXUtilities.cpp:39
CommandLine.h
llvm::GetStatistics
const std::vector< std::pair< StringRef, unsigned > > GetStatistics()
Get the statistics.
Definition: Statistic.cpp:259
llvm::AreStatisticsEnabled
bool AreStatisticsEnabled()
Check if statistics are enabled.
Definition: Statistic.cpp:138
llvm::TrackingStatistic::RegisterStatistic
void RegisterStatistic()
RegisterStatistic - The first time a statistic is bumped, this method is called.
Definition: Statistic.cpp:98
llvm::ManagedStatic
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:83
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::raw_ostream::flush
void flush()
Definition: raw_ostream.h:186
llvm::TrackingStatistic::getName
const char * getName() const
Definition: Statistic.h:64
llvm::sys::SmartMutex
SmartMutex - A mutex with a compile time constant parameter that indicates whether this mutex should ...
Definition: Mutex.h:28
StatsAsJSON
static bool StatsAsJSON
Definition: Statistic.cpp:45
llvm::None
const NoneType None
Definition: None.h:23
llvm::TrackingStatistic::getValue
unsigned getValue() const
Definition: Statistic.h:67
StatInfo
static ManagedStatic< StatisticInfo > StatInfo
Definition: Statistic.cpp:93
llvm::TimerGroup::ConstructTimerLists
static void ConstructTimerLists()
Ensure global timer group lists are initialized.
Definition: Timer.cpp:503
llvm::TrackingStatistic::getDesc
const char * getDesc() const
Definition: Statistic.h:65
Timer.h
llvm::cl::opt
Definition: CommandLine.h:1434
llvm::PrintStatisticsJSON
void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
Definition: Statistic.cpp:205
EnableStats
static bool EnableStats
-stats - Command line option to cause transformations to emit stats about what they did.
Definition: Statistic.cpp:44
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:57
StringExtras.h
llvm::sys::SmartScopedLock
std::lock_guard< SmartMutex< mt_only > > SmartScopedLock
Definition: Mutex.h:71
llvm::EnableStatistics
void EnableStatistics(bool DoPrintOnExit=true)
Enable the collection and printing of statistics.
Definition: Statistic.cpp:133
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SI
StandardInstrumentations SI(Debug, VerifyEach)
llvm::PrintStatistics
void PrintStatistics()
Print statistics to the file returned by CreateInfoOutputFile().
Definition: Statistic.cpp:231
YAMLTraits.h
StatLock
static ManagedStatic< sys::SmartMutex< true > > StatLock
Definition: Statistic.cpp:94
if
if(llvm_vc STREQUAL "") set(fake_version_inc "$
Definition: CMakeLists.txt:14
Compiler.h
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::format
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
llvm::TrackingStatistic
Definition: Statistic.h:49
Mutex.h
llvm::TrackingStatistic::Initialized
std::atomic< bool > Initialized
Definition: Statistic.h:56
llvm::ResetStatistics
void ResetStatistics()
Reset the statistics.
Definition: Statistic.cpp:268
llvm::stable_sort
void stable_sort(R &&Range)
Definition: STLExtras.h:1686
Stats
block placement Basic Block Placement Stats
Definition: MachineBlockPlacement.cpp:3465
Enabled
static bool Enabled
Definition: Statistic.cpp:46
llvm::sort
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1492
llvm::initStatisticOptions
void initStatisticOptions()
Definition: Statistic.cpp:49
llvm::max
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:340
llvm::iterator_range
A range adaptor for a pair of iterators.
Definition: iterator_range.h:30
llvm::cl::desc
Definition: CommandLine.h:414
raw_ostream.h
Debug.h