Statistic.cpp 8.9 KB

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