xref: /freebsd-src/contrib/llvm-project/llvm/lib/Support/Statistic.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
10b57cec5SDimitry Andric //===-- Statistic.cpp - Easy way to expose stats information --------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the 'Statistic' class, which is designed to be an easy
100b57cec5SDimitry Andric // way to expose various success metrics from passes.  These statistics are
110b57cec5SDimitry Andric // printed at the end of a run, when the -stats command line option is enabled
120b57cec5SDimitry Andric // on the command line.
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric // This is useful for reporting information like the number of instructions
150b57cec5SDimitry Andric // simplified, optimized or removed by various transformations, like this:
160b57cec5SDimitry Andric //
170b57cec5SDimitry Andric // static Statistic NumInstEliminated("GCSE", "Number of instructions killed");
180b57cec5SDimitry Andric //
190b57cec5SDimitry Andric // Later, in the code: ++NumInstEliminated;
200b57cec5SDimitry Andric //
210b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
220b57cec5SDimitry Andric 
230b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
24fe6060f1SDimitry Andric 
25fe6060f1SDimitry Andric #include "DebugOptions.h"
26fe6060f1SDimitry Andric 
270b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
280b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
290b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
300b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
310b57cec5SDimitry Andric #include "llvm/Support/Format.h"
320b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h"
330b57cec5SDimitry Andric #include "llvm/Support/Mutex.h"
340b57cec5SDimitry Andric #include "llvm/Support/Timer.h"
350b57cec5SDimitry Andric #include "llvm/Support/YAMLTraits.h"
360b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
370b57cec5SDimitry Andric #include <algorithm>
380b57cec5SDimitry Andric #include <cstring>
390b57cec5SDimitry Andric using namespace llvm;
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric /// -stats - Command line option to cause transformations to emit stats about
420b57cec5SDimitry Andric /// what they did.
430b57cec5SDimitry Andric ///
44fe6060f1SDimitry Andric static bool EnableStats;
45fe6060f1SDimitry Andric static bool StatsAsJSON;
460b57cec5SDimitry Andric static bool Enabled;
470b57cec5SDimitry Andric static bool PrintOnExit;
480b57cec5SDimitry Andric 
initStatisticOptions()49fe6060f1SDimitry Andric void llvm::initStatisticOptions() {
50fe6060f1SDimitry Andric   static cl::opt<bool, true> registerEnableStats{
51fe6060f1SDimitry Andric       "stats",
52fe6060f1SDimitry Andric       cl::desc(
53fe6060f1SDimitry Andric           "Enable statistics output from program (available with Asserts)"),
54fe6060f1SDimitry Andric       cl::location(EnableStats), cl::Hidden};
55fe6060f1SDimitry Andric   static cl::opt<bool, true> registerStatsAsJson{
56fe6060f1SDimitry Andric       "stats-json", cl::desc("Display statistics as json data"),
57fe6060f1SDimitry Andric       cl::location(StatsAsJSON), cl::Hidden};
58fe6060f1SDimitry Andric }
59fe6060f1SDimitry Andric 
600b57cec5SDimitry Andric namespace {
610b57cec5SDimitry Andric /// This class is used in a ManagedStatic so that it is created on demand (when
620b57cec5SDimitry Andric /// the first statistic is bumped) and destroyed only when llvm_shutdown is
630b57cec5SDimitry Andric /// called. We print statistics from the destructor.
640b57cec5SDimitry Andric /// This class is also used to look up statistic values from applications that
650b57cec5SDimitry Andric /// use LLVM.
660b57cec5SDimitry Andric class StatisticInfo {
678bcb0991SDimitry Andric   std::vector<TrackingStatistic *> Stats;
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric   friend void llvm::PrintStatistics();
700b57cec5SDimitry Andric   friend void llvm::PrintStatistics(raw_ostream &OS);
710b57cec5SDimitry Andric   friend void llvm::PrintStatisticsJSON(raw_ostream &OS);
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric   /// Sort statistics by debugtype,name,description.
740b57cec5SDimitry Andric   void sort();
750b57cec5SDimitry Andric public:
768bcb0991SDimitry Andric   using const_iterator = std::vector<TrackingStatistic *>::const_iterator;
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric   StatisticInfo();
790b57cec5SDimitry Andric   ~StatisticInfo();
800b57cec5SDimitry Andric 
addStatistic(TrackingStatistic * S)818bcb0991SDimitry Andric   void addStatistic(TrackingStatistic *S) { Stats.push_back(S); }
820b57cec5SDimitry Andric 
begin() const830b57cec5SDimitry Andric   const_iterator begin() const { return Stats.begin(); }
end() const840b57cec5SDimitry Andric   const_iterator end() const { return Stats.end(); }
statistics() const850b57cec5SDimitry Andric   iterator_range<const_iterator> statistics() const {
860b57cec5SDimitry Andric     return {begin(), end()};
870b57cec5SDimitry Andric   }
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric   void reset();
900b57cec5SDimitry Andric };
910b57cec5SDimitry Andric } // end anonymous namespace
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric static ManagedStatic<StatisticInfo> StatInfo;
940b57cec5SDimitry Andric static ManagedStatic<sys::SmartMutex<true> > StatLock;
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric /// RegisterStatistic - The first time a statistic is bumped, this method is
970b57cec5SDimitry Andric /// called.
RegisterStatistic()988bcb0991SDimitry Andric void TrackingStatistic::RegisterStatistic() {
990b57cec5SDimitry Andric   // If stats are enabled, inform StatInfo that this statistic should be
1000b57cec5SDimitry Andric   // printed.
1010b57cec5SDimitry Andric   // llvm_shutdown calls destructors while holding the ManagedStatic mutex.
1020b57cec5SDimitry Andric   // These destructors end up calling PrintStatistics, which takes StatLock.
1030b57cec5SDimitry Andric   // Since dereferencing StatInfo and StatLock can require taking the
1040b57cec5SDimitry Andric   // ManagedStatic mutex, doing so with StatLock held would lead to a lock
1050b57cec5SDimitry Andric   // order inversion. To avoid that, we dereference the ManagedStatics first,
1060b57cec5SDimitry Andric   // and only take StatLock afterwards.
1070b57cec5SDimitry Andric   if (!Initialized.load(std::memory_order_relaxed)) {
1080b57cec5SDimitry Andric     sys::SmartMutex<true> &Lock = *StatLock;
1090b57cec5SDimitry Andric     StatisticInfo &SI = *StatInfo;
1100b57cec5SDimitry Andric     sys::SmartScopedLock<true> Writer(Lock);
1110b57cec5SDimitry Andric     // Check Initialized again after acquiring the lock.
1120b57cec5SDimitry Andric     if (Initialized.load(std::memory_order_relaxed))
1130b57cec5SDimitry Andric       return;
114480093f4SDimitry Andric     if (EnableStats || Enabled)
1150b57cec5SDimitry Andric       SI.addStatistic(this);
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric     // Remember we have been registered.
1180b57cec5SDimitry Andric     Initialized.store(true, std::memory_order_release);
1190b57cec5SDimitry Andric   }
1200b57cec5SDimitry Andric }
1210b57cec5SDimitry Andric 
StatisticInfo()1220b57cec5SDimitry Andric StatisticInfo::StatisticInfo() {
123*bdd1243dSDimitry Andric   // Ensure that necessary timer global objects are created first so they are
124*bdd1243dSDimitry Andric   // destructed after us.
125*bdd1243dSDimitry Andric   TimerGroup::constructForStatistics();
1260b57cec5SDimitry Andric }
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric // Print information when destroyed, iff command line option is specified.
~StatisticInfo()1290b57cec5SDimitry Andric StatisticInfo::~StatisticInfo() {
130480093f4SDimitry Andric   if (EnableStats || PrintOnExit)
1310b57cec5SDimitry Andric     llvm::PrintStatistics();
1320b57cec5SDimitry Andric }
1330b57cec5SDimitry Andric 
EnableStatistics(bool DoPrintOnExit)134480093f4SDimitry Andric void llvm::EnableStatistics(bool DoPrintOnExit) {
1350b57cec5SDimitry Andric   Enabled = true;
136480093f4SDimitry Andric   PrintOnExit = DoPrintOnExit;
1370b57cec5SDimitry Andric }
1380b57cec5SDimitry Andric 
AreStatisticsEnabled()139fe6060f1SDimitry Andric bool llvm::AreStatisticsEnabled() { return Enabled || EnableStats; }
1400b57cec5SDimitry Andric 
sort()1410b57cec5SDimitry Andric void StatisticInfo::sort() {
1428bcb0991SDimitry Andric   llvm::stable_sort(
1438bcb0991SDimitry Andric       Stats, [](const TrackingStatistic *LHS, const TrackingStatistic *RHS) {
1440b57cec5SDimitry Andric         if (int Cmp = std::strcmp(LHS->getDebugType(), RHS->getDebugType()))
1450b57cec5SDimitry Andric           return Cmp < 0;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric         if (int Cmp = std::strcmp(LHS->getName(), RHS->getName()))
1480b57cec5SDimitry Andric           return Cmp < 0;
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric         return std::strcmp(LHS->getDesc(), RHS->getDesc()) < 0;
1510b57cec5SDimitry Andric       });
1520b57cec5SDimitry Andric }
1530b57cec5SDimitry Andric 
reset()1540b57cec5SDimitry Andric void StatisticInfo::reset() {
1550b57cec5SDimitry Andric   sys::SmartScopedLock<true> Writer(*StatLock);
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric   // Tell each statistic that it isn't registered so it has to register
1580b57cec5SDimitry Andric   // again. We're holding the lock so it won't be able to do so until we're
1590b57cec5SDimitry Andric   // finished. Once we've forced it to re-register (after we return), then zero
1600b57cec5SDimitry Andric   // the value.
1610b57cec5SDimitry Andric   for (auto *Stat : Stats) {
1620b57cec5SDimitry Andric     // Value updates to a statistic that complete before this statement in the
1630b57cec5SDimitry Andric     // iteration for that statistic will be lost as intended.
1640b57cec5SDimitry Andric     Stat->Initialized = false;
1650b57cec5SDimitry Andric     Stat->Value = 0;
1660b57cec5SDimitry Andric   }
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   // Clear the registration list and release the lock once we're done. Any
1690b57cec5SDimitry Andric   // pending updates from other threads will safely take effect after we return.
1700b57cec5SDimitry Andric   // That might not be what the user wants if they're measuring a compilation
1710b57cec5SDimitry Andric   // but it's their responsibility to prevent concurrent compilations to make
1720b57cec5SDimitry Andric   // a single compilation measurable.
1730b57cec5SDimitry Andric   Stats.clear();
1740b57cec5SDimitry Andric }
1750b57cec5SDimitry Andric 
PrintStatistics(raw_ostream & OS)1760b57cec5SDimitry Andric void llvm::PrintStatistics(raw_ostream &OS) {
1770b57cec5SDimitry Andric   StatisticInfo &Stats = *StatInfo;
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   // Figure out how long the biggest Value and Name fields are.
1800b57cec5SDimitry Andric   unsigned MaxDebugTypeLen = 0, MaxValLen = 0;
1810eae32dcSDimitry Andric   for (TrackingStatistic *Stat : Stats.Stats) {
1820eae32dcSDimitry Andric     MaxValLen = std::max(MaxValLen, (unsigned)utostr(Stat->getValue()).size());
1830eae32dcSDimitry Andric     MaxDebugTypeLen =
1840eae32dcSDimitry Andric         std::max(MaxDebugTypeLen, (unsigned)std::strlen(Stat->getDebugType()));
1850b57cec5SDimitry Andric   }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   Stats.sort();
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   // Print out the statistics header...
1900b57cec5SDimitry Andric   OS << "===" << std::string(73, '-') << "===\n"
1910b57cec5SDimitry Andric      << "                          ... Statistics Collected ...\n"
1920b57cec5SDimitry Andric      << "===" << std::string(73, '-') << "===\n\n";
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   // Print all of the statistics.
1950eae32dcSDimitry Andric   for (TrackingStatistic *Stat : Stats.Stats)
19681ad6265SDimitry Andric     OS << format("%*" PRIu64 " %-*s - %s\n", MaxValLen, Stat->getValue(),
1970eae32dcSDimitry Andric                  MaxDebugTypeLen, Stat->getDebugType(), Stat->getDesc());
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric   OS << '\n';  // Flush the output stream.
2000b57cec5SDimitry Andric   OS.flush();
2010b57cec5SDimitry Andric }
2020b57cec5SDimitry Andric 
PrintStatisticsJSON(raw_ostream & OS)2030b57cec5SDimitry Andric void llvm::PrintStatisticsJSON(raw_ostream &OS) {
2040b57cec5SDimitry Andric   sys::SmartScopedLock<true> Reader(*StatLock);
2050b57cec5SDimitry Andric   StatisticInfo &Stats = *StatInfo;
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   Stats.sort();
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric   // Print all of the statistics.
2100b57cec5SDimitry Andric   OS << "{\n";
2110b57cec5SDimitry Andric   const char *delim = "";
2128bcb0991SDimitry Andric   for (const TrackingStatistic *Stat : Stats.Stats) {
2130b57cec5SDimitry Andric     OS << delim;
2140b57cec5SDimitry Andric     assert(yaml::needsQuotes(Stat->getDebugType()) == yaml::QuotingType::None &&
2150b57cec5SDimitry Andric            "Statistic group/type name is simple.");
2160b57cec5SDimitry Andric     assert(yaml::needsQuotes(Stat->getName()) == yaml::QuotingType::None &&
2170b57cec5SDimitry Andric            "Statistic name is simple");
2180b57cec5SDimitry Andric     OS << "\t\"" << Stat->getDebugType() << '.' << Stat->getName() << "\": "
2190b57cec5SDimitry Andric        << Stat->getValue();
2200b57cec5SDimitry Andric     delim = ",\n";
2210b57cec5SDimitry Andric   }
2220b57cec5SDimitry Andric   // Print timers.
2230b57cec5SDimitry Andric   TimerGroup::printAllJSONValues(OS, delim);
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric   OS << "\n}\n";
2260b57cec5SDimitry Andric   OS.flush();
2270b57cec5SDimitry Andric }
2280b57cec5SDimitry Andric 
PrintStatistics()2290b57cec5SDimitry Andric void llvm::PrintStatistics() {
2300b57cec5SDimitry Andric #if LLVM_ENABLE_STATS
2310b57cec5SDimitry Andric   sys::SmartScopedLock<true> Reader(*StatLock);
2320b57cec5SDimitry Andric   StatisticInfo &Stats = *StatInfo;
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric   // Statistics not enabled?
2350b57cec5SDimitry Andric   if (Stats.Stats.empty()) return;
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   // Get the stream to write to.
2380b57cec5SDimitry Andric   std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
2390b57cec5SDimitry Andric   if (StatsAsJSON)
2400b57cec5SDimitry Andric     PrintStatisticsJSON(*OutStream);
2410b57cec5SDimitry Andric   else
2420b57cec5SDimitry Andric     PrintStatistics(*OutStream);
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric #else
2450b57cec5SDimitry Andric   // Check if the -stats option is set instead of checking
2460b57cec5SDimitry Andric   // !Stats.Stats.empty().  In release builds, Statistics operators
2470b57cec5SDimitry Andric   // do nothing, so stats are never Registered.
248480093f4SDimitry Andric   if (EnableStats) {
2490b57cec5SDimitry Andric     // Get the stream to write to.
2500b57cec5SDimitry Andric     std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
2510b57cec5SDimitry Andric     (*OutStream) << "Statistics are disabled.  "
2525ffd83dbSDimitry Andric                  << "Build with asserts or with -DLLVM_FORCE_ENABLE_STATS\n";
2530b57cec5SDimitry Andric   }
2540b57cec5SDimitry Andric #endif
2550b57cec5SDimitry Andric }
2560b57cec5SDimitry Andric 
GetStatistics()257*bdd1243dSDimitry Andric std::vector<std::pair<StringRef, uint64_t>> llvm::GetStatistics() {
2580b57cec5SDimitry Andric   sys::SmartScopedLock<true> Reader(*StatLock);
25981ad6265SDimitry Andric   std::vector<std::pair<StringRef, uint64_t>> ReturnStats;
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric   for (const auto &Stat : StatInfo->statistics())
2620b57cec5SDimitry Andric     ReturnStats.emplace_back(Stat->getName(), Stat->getValue());
2630b57cec5SDimitry Andric   return ReturnStats;
2640b57cec5SDimitry Andric }
2650b57cec5SDimitry Andric 
ResetStatistics()2660b57cec5SDimitry Andric void llvm::ResetStatistics() {
2670b57cec5SDimitry Andric   StatInfo->reset();
2680b57cec5SDimitry Andric }
269