xref: /llvm-project/llvm/lib/Support/Statistic.cpp (revision a09751e7791ec6fb9a48969b868caeb1fe56003c)
1 //===-- Statistic.cpp - Easy way to expose stats information --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the 'Statistic' class, which is designed to be an easy
11 // way to expose various success metrics from passes.  These statistics are
12 // printed at the end of a run, when the -stats command line option is enabled
13 // on the command line.
14 //
15 // This is useful for reporting information like the number of instructions
16 // simplified, optimized or removed by various transformations, like this:
17 //
18 // static Statistic NumInstEliminated("GCSE", "Number of instructions killed");
19 //
20 // Later, in the code: ++NumInstEliminated;
21 //
22 //===----------------------------------------------------------------------===//
23 
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/Mutex.h"
32 #include "llvm/Support/Timer.h"
33 #include "llvm/Support/YAMLTraits.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <cstring>
37 using namespace llvm;
38 
39 /// -stats - Command line option to cause transformations to emit stats about
40 /// what they did.
41 ///
42 static cl::opt<bool> Stats(
43     "stats",
44     cl::desc("Enable statistics output from program (available with Asserts)"),
45     cl::Hidden);
46 
47 static cl::opt<bool> StatsAsJSON("stats-json",
48                                  cl::desc("Display statistics as json data"),
49                                  cl::Hidden);
50 
51 static bool Enabled;
52 static bool PrintOnExit;
53 
54 namespace {
55 /// This class is used in a ManagedStatic so that it is created on demand (when
56 /// the first statistic is bumped) and destroyed only when llvm_shutdown is
57 /// called. We print statistics from the destructor.
58 /// This class is also used to look up statistic values from applications that
59 /// use LLVM.
60 class StatisticInfo {
61   std::vector<const Statistic*> Stats;
62 
63   friend void llvm::PrintStatistics();
64   friend void llvm::PrintStatistics(raw_ostream &OS);
65   friend void llvm::PrintStatisticsJSON(raw_ostream &OS);
66 
67   /// Sort statistics by debugtype,name,description.
68   void sort();
69 public:
70   using const_iterator = std::vector<const Statistic *>::const_iterator;
71 
72   StatisticInfo();
73   ~StatisticInfo();
74 
75   void addStatistic(const Statistic *S) {
76     Stats.push_back(S);
77   }
78 
79   const_iterator begin() const { return Stats.begin(); }
80   const_iterator end() const { return Stats.end(); }
81   iterator_range<const_iterator> statistics() const {
82     return {begin(), end()};
83   }
84 };
85 } // end anonymous namespace
86 
87 static ManagedStatic<StatisticInfo> StatInfo;
88 static ManagedStatic<sys::SmartMutex<true> > StatLock;
89 
90 /// RegisterStatistic - The first time a statistic is bumped, this method is
91 /// called.
92 void Statistic::RegisterStatistic() {
93   // If stats are enabled, inform StatInfo that this statistic should be
94   // printed.
95   sys::SmartScopedLock<true> Writer(*StatLock);
96   if (!Initialized.load(std::memory_order_relaxed)) {
97     if (Stats || Enabled)
98       StatInfo->addStatistic(this);
99 
100     // Remember we have been registered.
101     Initialized.store(true, std::memory_order_release);
102   }
103 }
104 
105 StatisticInfo::StatisticInfo() {
106   // Ensure timergroup lists are created first so they are destructed after us.
107   TimerGroup::ConstructTimerLists();
108 }
109 
110 // Print information when destroyed, iff command line option is specified.
111 StatisticInfo::~StatisticInfo() {
112   if (::Stats || PrintOnExit)
113     llvm::PrintStatistics();
114 }
115 
116 void llvm::EnableStatistics(bool PrintOnExit) {
117   Enabled = true;
118   ::PrintOnExit = PrintOnExit;
119 }
120 
121 bool llvm::AreStatisticsEnabled() {
122   return Enabled || Stats;
123 }
124 
125 void StatisticInfo::sort() {
126   std::stable_sort(Stats.begin(), Stats.end(),
127                    [](const Statistic *LHS, const Statistic *RHS) {
128     if (int Cmp = std::strcmp(LHS->getDebugType(), RHS->getDebugType()))
129       return Cmp < 0;
130 
131     if (int Cmp = std::strcmp(LHS->getName(), RHS->getName()))
132       return Cmp < 0;
133 
134     return std::strcmp(LHS->getDesc(), RHS->getDesc()) < 0;
135   });
136 }
137 
138 void llvm::PrintStatistics(raw_ostream &OS) {
139   StatisticInfo &Stats = *StatInfo;
140 
141   // Figure out how long the biggest Value and Name fields are.
142   unsigned MaxDebugTypeLen = 0, MaxValLen = 0;
143   for (size_t i = 0, e = Stats.Stats.size(); i != e; ++i) {
144     MaxValLen = std::max(MaxValLen,
145                          (unsigned)utostr(Stats.Stats[i]->getValue()).size());
146     MaxDebugTypeLen = std::max(MaxDebugTypeLen,
147                          (unsigned)std::strlen(Stats.Stats[i]->getDebugType()));
148   }
149 
150   Stats.sort();
151 
152   // Print out the statistics header...
153   OS << "===" << std::string(73, '-') << "===\n"
154      << "                          ... Statistics Collected ...\n"
155      << "===" << std::string(73, '-') << "===\n\n";
156 
157   // Print all of the statistics.
158   for (size_t i = 0, e = Stats.Stats.size(); i != e; ++i)
159     OS << format("%*u %-*s - %s\n",
160                  MaxValLen, Stats.Stats[i]->getValue(),
161                  MaxDebugTypeLen, Stats.Stats[i]->getDebugType(),
162                  Stats.Stats[i]->getDesc());
163 
164   OS << '\n';  // Flush the output stream.
165   OS.flush();
166 }
167 
168 void llvm::PrintStatisticsJSON(raw_ostream &OS) {
169   StatisticInfo &Stats = *StatInfo;
170 
171   Stats.sort();
172 
173   // Print all of the statistics.
174   OS << "{\n";
175   const char *delim = "";
176   for (const Statistic *Stat : Stats.Stats) {
177     OS << delim;
178     assert(yaml::needsQuotes(Stat->getDebugType()) == yaml::QuotingType::None &&
179            "Statistic group/type name is simple.");
180     assert(yaml::needsQuotes(Stat->getName()) == yaml::QuotingType::None &&
181            "Statistic name is simple");
182     OS << "\t\"" << Stat->getDebugType() << '.' << Stat->getName() << "\": "
183        << Stat->getValue();
184     delim = ",\n";
185   }
186   // Print timers.
187   TimerGroup::printAllJSONValues(OS, delim);
188 
189   OS << "\n}\n";
190   OS.flush();
191 }
192 
193 void llvm::PrintStatistics() {
194 #if LLVM_ENABLE_STATS
195   StatisticInfo &Stats = *StatInfo;
196 
197   // Statistics not enabled?
198   if (Stats.Stats.empty()) return;
199 
200   // Get the stream to write to.
201   std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
202   if (StatsAsJSON)
203     PrintStatisticsJSON(*OutStream);
204   else
205     PrintStatistics(*OutStream);
206 
207 #else
208   // Check if the -stats option is set instead of checking
209   // !Stats.Stats.empty().  In release builds, Statistics operators
210   // do nothing, so stats are never Registered.
211   if (Stats) {
212     // Get the stream to write to.
213     std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
214     (*OutStream) << "Statistics are disabled.  "
215                  << "Build with asserts or with -DLLVM_ENABLE_STATS\n";
216   }
217 #endif
218 }
219 
220 const std::vector<std::pair<StringRef, unsigned>> llvm::GetStatistics() {
221   sys::SmartScopedLock<true> Reader(*StatLock);
222   std::vector<std::pair<StringRef, unsigned>> ReturnStats;
223 
224   for (const auto &Stat : StatInfo->statistics())
225     ReturnStats.emplace_back(Stat->getName(), Stat->getValue());
226   return ReturnStats;
227 }
228