LCOV - code coverage report
Current view: top level - src - counters.h (source / functions) Hit Total Coverage
Test: app.info Lines: 125 134 93.3 %
Date: 2019-03-21 Functions: 19 21 90.5 %

          Line data    Source code
       1             : // Copyright 2012 the V8 project authors. All rights reserved.
       2             : // Use of this source code is governed by a BSD-style license that can be
       3             : // found in the LICENSE file.
       4             : 
       5             : #ifndef V8_COUNTERS_H_
       6             : #define V8_COUNTERS_H_
       7             : 
       8             : #include "include/v8.h"
       9             : #include "src/allocation.h"
      10             : #include "src/base/atomic-utils.h"
      11             : #include "src/base/optional.h"
      12             : #include "src/base/platform/elapsed-timer.h"
      13             : #include "src/base/platform/time.h"
      14             : #include "src/globals.h"
      15             : #include "src/heap-symbols.h"
      16             : #include "src/isolate.h"
      17             : #include "src/objects.h"
      18             : #include "src/runtime/runtime.h"
      19             : #include "src/tracing/trace-event.h"
      20             : #include "src/tracing/traced-value.h"
      21             : #include "src/tracing/tracing-category-observer.h"
      22             : 
      23             : namespace v8 {
      24             : namespace internal {
      25             : 
      26             : // This struct contains a set of flags that can be modified from multiple
      27             : // threads at runtime unlike the normal FLAG_-like flags which are not modified
      28             : // after V8 instance is initialized.
      29             : 
      30             : struct TracingFlags {
      31             :   static V8_EXPORT_PRIVATE std::atomic_uint runtime_stats;
      32             :   static V8_EXPORT_PRIVATE std::atomic_uint gc_stats;
      33             :   static V8_EXPORT_PRIVATE std::atomic_uint ic_stats;
      34             : 
      35             :   static bool is_runtime_stats_enabled() {
      36   195927411 :     return runtime_stats.load(std::memory_order_relaxed) != 0;
      37             :   }
      38             : 
      39             :   static bool is_gc_stats_enabled() {
      40      135489 :     return gc_stats.load(std::memory_order_relaxed) != 0;
      41             :   }
      42             : 
      43             :   static bool is_ic_stats_enabled() {
      44             :     return ic_stats.load(std::memory_order_relaxed) != 0;
      45             :   }
      46             : };
      47             : 
      48             : // StatsCounters is an interface for plugging into external
      49             : // counters for monitoring.  Counters can be looked up and
      50             : // manipulated by name.
      51             : 
      52             : class Counters;
      53             : 
      54             : class StatsTable {
      55             :  public:
      56             :   // Register an application-defined function for recording
      57             :   // subsequent counter statistics.
      58             :   void SetCounterFunction(CounterLookupCallback f);
      59             : 
      60             :   // Register an application-defined function to create histograms for
      61             :   // recording subsequent histogram samples.
      62             :   void SetCreateHistogramFunction(CreateHistogramCallback f) {
      63           8 :     create_histogram_function_ = f;
      64             :   }
      65             : 
      66             :   // Register an application-defined function to add a sample
      67             :   // to a histogram created with CreateHistogram function.
      68             :   void SetAddHistogramSampleFunction(AddHistogramSampleCallback f) {
      69           8 :     add_histogram_sample_function_ = f;
      70             :   }
      71             : 
      72             :   bool HasCounterFunction() const { return lookup_function_ != nullptr; }
      73             : 
      74             :   // Lookup the location of a counter by name.  If the lookup
      75             :   // is successful, returns a non-nullptr pointer for writing the
      76             :   // value of the counter.  Each thread calling this function
      77             :   // may receive a different location to store it's counter.
      78             :   // The return value must not be cached and re-used across
      79             :   // threads, although a single thread is free to cache it.
      80             :   int* FindLocation(const char* name) {
      81     1151715 :     if (!lookup_function_) return nullptr;
      82           0 :     return lookup_function_(name);
      83             :   }
      84             : 
      85             :   // Create a histogram by name. If the create is successful,
      86             :   // returns a non-nullptr pointer for use with AddHistogramSample
      87             :   // function. min and max define the expected minimum and maximum
      88             :   // sample values. buckets is the maximum number of buckets
      89             :   // that the samples will be grouped into.
      90             :   void* CreateHistogram(const char* name,
      91             :                         int min,
      92             :                         int max,
      93             :                         size_t buckets) {
      94         848 :     if (!create_histogram_function_) return nullptr;
      95         318 :     return create_histogram_function_(name, min, max, buckets);
      96             :   }
      97             : 
      98             :   // Add a sample to a histogram created with the CreateHistogram
      99             :   // function.
     100             :   void AddHistogramSample(void* histogram, int sample) {
     101          10 :     if (!add_histogram_sample_function_) return;
     102          10 :     return add_histogram_sample_function_(histogram, sample);
     103             :   }
     104             : 
     105             :  private:
     106             :   friend class Counters;
     107             : 
     108             :   explicit StatsTable(Counters* counters);
     109             : 
     110             :   CounterLookupCallback lookup_function_;
     111             :   CreateHistogramCallback create_histogram_function_;
     112             :   AddHistogramSampleCallback add_histogram_sample_function_;
     113             : 
     114             :   DISALLOW_COPY_AND_ASSIGN(StatsTable);
     115             : };
     116             : 
     117             : // Base class for stats counters.
     118             : class StatsCounterBase {
     119             :  protected:
     120             :   Counters* counters_;
     121             :   const char* name_;
     122             :   int* ptr_;
     123             : 
     124             :   StatsCounterBase() = default;
     125             :   StatsCounterBase(Counters* counters, const char* name)
     126      307670 :       : counters_(counters), name_(name), ptr_(nullptr) {}
     127             : 
     128           0 :   void SetLoc(int* loc, int value) { *loc = value; }
     129           0 :   void IncrementLoc(int* loc) { (*loc)++; }
     130           0 :   void IncrementLoc(int* loc, int value) { (*loc) += value; }
     131           0 :   void DecrementLoc(int* loc) { (*loc)--; }
     132           0 :   void DecrementLoc(int* loc, int value) { (*loc) -= value; }
     133             : 
     134             :   int* FindLocationInStatsTable() const;
     135             : };
     136             : 
     137             : // StatsCounters are dynamically created values which can be tracked in
     138             : // the StatsTable.  They are designed to be lightweight to create and
     139             : // easy to use.
     140             : //
     141             : // Internally, a counter represents a value in a row of a StatsTable.
     142             : // The row has a 32bit value for each process/thread in the table and also
     143             : // a name (stored in the table metadata).  Since the storage location can be
     144             : // thread-specific, this class cannot be shared across threads. Note: This
     145             : // class is not thread safe.
     146             : class StatsCounter : public StatsCounterBase {
     147             :  public:
     148             :   // Sets the counter to a specific value.
     149             :   void Set(int value) {
     150     1877587 :     if (int* loc = GetPtr()) SetLoc(loc, value);
     151             :   }
     152             : 
     153             :   // Increments the counter.
     154   176202551 :   void Increment() {
     155   176202553 :     if (int* loc = GetPtr()) IncrementLoc(loc);
     156   176202553 :   }
     157             : 
     158    19223942 :   void Increment(int value) {
     159    19223942 :     if (int* loc = GetPtr()) IncrementLoc(loc, value);
     160    19223942 :   }
     161             : 
     162             :   // Decrements the counter.
     163     6035823 :   void Decrement() {
     164     6035823 :     if (int* loc = GetPtr()) DecrementLoc(loc);
     165     6035823 :   }
     166             : 
     167     1521026 :   void Decrement(int value) {
     168     1521026 :     if (int* loc = GetPtr()) DecrementLoc(loc, value);
     169     1521026 :   }
     170             : 
     171             :   // Is this counter enabled?
     172             :   // Returns false if table is full.
     173           0 :   bool Enabled() { return GetPtr() != nullptr; }
     174             : 
     175             :   // Get the internal pointer to the counter. This is used
     176             :   // by the code generator to emit code that manipulates a
     177             :   // given counter without calling the runtime system.
     178             :   int* GetInternalPointer() {
     179             :     int* loc = GetPtr();
     180             :     DCHECK_NOT_NULL(loc);
     181             :     return loc;
     182             :   }
     183             : 
     184             :  private:
     185             :   friend class Counters;
     186             : 
     187             :   StatsCounter() = default;
     188             :   StatsCounter(Counters* counters, const char* name)
     189             :       : StatsCounterBase(counters, name), lookup_done_(false) {}
     190             : 
     191             :   // Reset the cached internal pointer.
     192          10 :   void Reset() { lookup_done_ = false; }
     193             : 
     194             :   // Returns the cached address of this counter location.
     195           0 :   int* GetPtr() {
     196   204860929 :     if (lookup_done_) return ptr_;
     197     1151689 :     lookup_done_ = true;
     198     1151689 :     ptr_ = FindLocationInStatsTable();
     199           0 :     return ptr_;
     200             :   }
     201             : 
     202             :   bool lookup_done_;
     203             : };
     204             : 
     205             : // Thread safe version of StatsCounter.
     206       61519 : class StatsCounterThreadSafe : public StatsCounterBase {
     207             :  public:
     208             :   void Set(int Value);
     209             :   void Increment();
     210             :   void Increment(int value);
     211             :   void Decrement();
     212             :   void Decrement(int value);
     213             :   bool Enabled() { return ptr_ != nullptr; }
     214             :   int* GetInternalPointer() {
     215             :     DCHECK_NOT_NULL(ptr_);
     216             :     return ptr_;
     217             :   }
     218             : 
     219             :  private:
     220             :   friend class Counters;
     221             : 
     222             :   StatsCounterThreadSafe(Counters* counters, const char* name);
     223          25 :   void Reset() { ptr_ = FindLocationInStatsTable(); }
     224             : 
     225             :   base::Mutex mutex_;
     226             : 
     227             :   DISALLOW_IMPLICIT_CONSTRUCTORS(StatsCounterThreadSafe);
     228             : };
     229             : 
     230             : // A Histogram represents a dynamically created histogram in the
     231             : // StatsTable.  Note: This class is thread safe.
     232             : class Histogram {
     233             :  public:
     234             :   // Add a single sample to this histogram.
     235             :   void AddSample(int sample);
     236             : 
     237             :   // Returns true if this histogram is enabled.
     238             :   bool Enabled() { return histogram_ != nullptr; }
     239             : 
     240             :   const char* name() { return name_; }
     241             : 
     242             :   int min() const { return min_; }
     243             :   int max() const { return max_; }
     244             :   int num_buckets() const { return num_buckets_; }
     245             : 
     246             :   // Asserts that |expected_counters| are the same as the Counters this
     247             :   // Histogram reports to.
     248             :   void AssertReportsToCounters(Counters* expected_counters) {
     249             :     DCHECK_EQ(counters_, expected_counters);
     250             :   }
     251             : 
     252             :  protected:
     253             :   Histogram() = default;
     254             :   Histogram(const char* name, int min, int max, int num_buckets,
     255             :             Counters* counters)
     256             :       : name_(name),
     257             :         min_(min),
     258             :         max_(max),
     259             :         num_buckets_(num_buckets),
     260             :         histogram_(nullptr),
     261           5 :         counters_(counters) {
     262             :     DCHECK(counters_);
     263             :   }
     264             : 
     265             :   Counters* counters() const { return counters_; }
     266             : 
     267             :   // Reset the cached internal pointer.
     268         848 :   void Reset() { histogram_ = CreateHistogram(); }
     269             : 
     270             :  private:
     271             :   friend class Counters;
     272             : 
     273             :   void* CreateHistogram() const;
     274             : 
     275             :   const char* name_;
     276             :   int min_;
     277             :   int max_;
     278             :   int num_buckets_;
     279             :   void* histogram_;
     280             :   Counters* counters_;
     281             : };
     282             : 
     283             : enum class HistogramTimerResolution { MILLISECOND, MICROSECOND };
     284             : 
     285             : // A thread safe histogram timer. It also allows distributions of
     286             : // nested timed results.
     287             : class TimedHistogram : public Histogram {
     288             :  public:
     289             :   // Start the timer. Log if isolate non-null.
     290             :   void Start(base::ElapsedTimer* timer, Isolate* isolate);
     291             : 
     292             :   // Stop the timer and record the results. Log if isolate non-null.
     293             :   void Stop(base::ElapsedTimer* timer, Isolate* isolate);
     294             : 
     295             :   // Records a TimeDelta::Max() result. Useful to record percentage of tasks
     296             :   // that never got to run in a given scenario. Log if isolate non-null.
     297             :   void RecordAbandon(base::ElapsedTimer* timer, Isolate* isolate);
     298             : 
     299             :  protected:
     300             :   friend class Counters;
     301             :   HistogramTimerResolution resolution_;
     302             : 
     303             :   TimedHistogram() = default;
     304             :   TimedHistogram(const char* name, int min, int max,
     305             :                  HistogramTimerResolution resolution, int num_buckets,
     306             :                  Counters* counters)
     307             :       : Histogram(name, min, max, num_buckets, counters),
     308           5 :         resolution_(resolution) {}
     309             :   void AddTimeSample();
     310             : };
     311             : 
     312             : // Helper class for scoping a TimedHistogram.
     313             : class TimedHistogramScope {
     314             :  public:
     315             :   explicit TimedHistogramScope(TimedHistogram* histogram,
     316             :                                Isolate* isolate = nullptr)
     317     2488782 :       : histogram_(histogram), isolate_(isolate) {
     318     2488782 :     histogram_->Start(&timer_, isolate);
     319             :   }
     320             : 
     321     2483662 :   ~TimedHistogramScope() { histogram_->Stop(&timer_, isolate_); }
     322             : 
     323             :  private:
     324             :   base::ElapsedTimer timer_;
     325             :   TimedHistogram* histogram_;
     326             :   Isolate* isolate_;
     327             : 
     328             :   DISALLOW_IMPLICIT_CONSTRUCTORS(TimedHistogramScope);
     329             : };
     330             : 
     331             : enum class OptionalTimedHistogramScopeMode { TAKE_TIME, DONT_TAKE_TIME };
     332             : 
     333             : // Helper class for scoping a TimedHistogram.
     334             : // It will not take time for mode = DONT_TAKE_TIME.
     335             : class OptionalTimedHistogramScope {
     336             :  public:
     337             :   OptionalTimedHistogramScope(TimedHistogram* histogram, Isolate* isolate,
     338             :                               OptionalTimedHistogramScopeMode mode)
     339       94928 :       : histogram_(histogram), isolate_(isolate), mode_(mode) {
     340       94928 :     if (mode == OptionalTimedHistogramScopeMode::TAKE_TIME) {
     341       94928 :       histogram_->Start(&timer_, isolate);
     342             :     }
     343             :   }
     344             : 
     345       94928 :   ~OptionalTimedHistogramScope() {
     346       94928 :     if (mode_ == OptionalTimedHistogramScopeMode::TAKE_TIME) {
     347       94928 :       histogram_->Stop(&timer_, isolate_);
     348             :     }
     349             :   }
     350             : 
     351             :  private:
     352             :   base::ElapsedTimer timer_;
     353             :   TimedHistogram* const histogram_;
     354             :   Isolate* const isolate_;
     355             :   const OptionalTimedHistogramScopeMode mode_;
     356             :   DISALLOW_IMPLICIT_CONSTRUCTORS(OptionalTimedHistogramScope);
     357             : };
     358             : 
     359             : // Helper class for recording a TimedHistogram asynchronously with manual
     360             : // controls (it will not generate a report if destroyed without explicitly
     361             : // triggering a report). |async_counters| should be a shared_ptr to
     362             : // |histogram->counters()|, making it is safe to report to an
     363             : // AsyncTimedHistogram after the associated isolate has been destroyed.
     364             : // AsyncTimedHistogram can be moved/copied to avoid computing Now() multiple
     365             : // times when the times of multiple tasks are identical; each copy will generate
     366             : // its own report.
     367             : class AsyncTimedHistogram {
     368             :  public:
     369             :   explicit AsyncTimedHistogram(TimedHistogram* histogram,
     370             :                                std::shared_ptr<Counters> async_counters)
     371             :       : histogram_(histogram), async_counters_(std::move(async_counters)) {
     372             :     histogram_->AssertReportsToCounters(async_counters_.get());
     373             :     histogram_->Start(&timer_, nullptr);
     374             :   }
     375             : 
     376             :   // Records the time elapsed to |histogram_| and stops |timer_|.
     377             :   void RecordDone() { histogram_->Stop(&timer_, nullptr); }
     378             : 
     379             :   // Records TimeDelta::Max() to |histogram_| and stops |timer_|.
     380             :   void RecordAbandon() { histogram_->RecordAbandon(&timer_, nullptr); }
     381             : 
     382             :  private:
     383             :   base::ElapsedTimer timer_;
     384             :   TimedHistogram* histogram_;
     385             :   std::shared_ptr<Counters> async_counters_;
     386             : };
     387             : 
     388             : // Helper class for scoping a TimedHistogram, where the histogram is selected at
     389             : // stop time rather than start time.
     390             : // TODO(leszeks): This is heavily reliant on TimedHistogram::Start() doing
     391             : // nothing but starting the timer, and TimedHistogram::Stop() logging the sample
     392             : // correctly even if Start() was not called. This happens to be true iff Stop()
     393             : // is passed a null isolate, but that's an implementation detail of
     394             : // TimedHistogram, and we shouldn't rely on it.
     395             : class LazyTimedHistogramScope {
     396             :  public:
     397      286768 :   LazyTimedHistogramScope() : histogram_(nullptr) { timer_.Start(); }
     398      286767 :   ~LazyTimedHistogramScope() {
     399             :     // We should set the histogram before this scope exits.
     400             :     DCHECK_NOT_NULL(histogram_);
     401      286768 :     histogram_->Stop(&timer_, nullptr);
     402             :   }
     403             : 
     404      286767 :   void set_histogram(TimedHistogram* histogram) { histogram_ = histogram; }
     405             : 
     406             :  private:
     407             :   base::ElapsedTimer timer_;
     408             :   TimedHistogram* histogram_;
     409             : };
     410             : 
     411             : // A HistogramTimer allows distributions of non-nested timed results
     412             : // to be created. WARNING: This class is not thread safe and can only
     413             : // be run on the foreground thread.
     414             : class HistogramTimer : public TimedHistogram {
     415             :  public:
     416             :   // Note: public for testing purposes only.
     417             :   HistogramTimer(const char* name, int min, int max,
     418             :                  HistogramTimerResolution resolution, int num_buckets,
     419             :                  Counters* counters)
     420             :       : TimedHistogram(name, min, max, resolution, num_buckets, counters) {}
     421             : 
     422             :   inline void Start();
     423             :   inline void Stop();
     424             : 
     425             :   // Returns true if the timer is running.
     426             :   bool Running() {
     427             :     return Enabled() && timer_.IsStarted();
     428             :   }
     429             : 
     430             :   // TODO(bmeurer): Remove this when HistogramTimerScope is fixed.
     431             : #ifdef DEBUG
     432             :   base::ElapsedTimer* timer() { return &timer_; }
     433             : #endif
     434             : 
     435             :  private:
     436             :   friend class Counters;
     437             : 
     438             :   base::ElapsedTimer timer_;
     439             : 
     440             :   HistogramTimer() = default;
     441             : };
     442             : 
     443             : // Helper class for scoping a HistogramTimer.
     444             : // TODO(bmeurer): The ifdeffery is an ugly hack around the fact that the
     445             : // Parser is currently reentrant (when it throws an error, we call back
     446             : // into JavaScript and all bets are off), but ElapsedTimer is not
     447             : // reentry-safe. Fix this properly and remove |allow_nesting|.
     448             : class HistogramTimerScope {
     449             :  public:
     450             :   explicit HistogramTimerScope(HistogramTimer* timer,
     451             :                                bool allow_nesting = false)
     452             : #ifdef DEBUG
     453             :       : timer_(timer), skipped_timer_start_(false) {
     454             :     if (timer_->timer()->IsStarted() && allow_nesting) {
     455             :       skipped_timer_start_ = true;
     456             :     } else {
     457             :       timer_->Start();
     458             :     }
     459             :   }
     460             : #else
     461      286771 :       : timer_(timer) {
     462             :     timer_->Start();
     463             :   }
     464             : #endif
     465      286768 :   ~HistogramTimerScope() {
     466             : #ifdef DEBUG
     467             :     if (!skipped_timer_start_) {
     468             :       timer_->Stop();
     469             :     }
     470             : #else
     471      286767 :     timer_->Stop();
     472             : #endif
     473             :   }
     474             : 
     475             :  private:
     476             :   HistogramTimer* timer_;
     477             : #ifdef DEBUG
     478             :   bool skipped_timer_start_;
     479             : #endif
     480             : };
     481             : 
     482             : // A histogram timer that can aggregate events within a larger scope.
     483             : //
     484             : // Intended use of this timer is to have an outer (aggregating) and an inner
     485             : // (to be aggregated) scope, where the inner scope measure the time of events,
     486             : // and all those inner scope measurements will be summed up by the outer scope.
     487             : // An example use might be to aggregate the time spent in lazy compilation
     488             : // while running a script.
     489             : //
     490             : // Helpers:
     491             : // - AggregatingHistogramTimerScope, the "outer" scope within which
     492             : //     times will be summed up.
     493             : // - AggregatedHistogramTimerScope, the "inner" scope which defines the
     494             : //     events to be timed.
     495             : class AggregatableHistogramTimer : public Histogram {
     496             :  public:
     497             :   // Start/stop the "outer" scope.
     498      269207 :   void Start() { time_ = base::TimeDelta(); }
     499      269207 :   void Stop() {
     500      269207 :     if (time_ != base::TimeDelta()) {
     501             :       // Only add non-zero samples, since zero samples represent situations
     502             :       // where there were no aggregated samples added.
     503       45187 :       AddSample(static_cast<int>(time_.InMicroseconds()));
     504             :     }
     505      269207 :   }
     506             : 
     507             :   // Add a time value ("inner" scope).
     508             :   void Add(base::TimeDelta other) { time_ += other; }
     509             : 
     510             :  private:
     511             :   friend class Counters;
     512             : 
     513             :   AggregatableHistogramTimer() = default;
     514             :   AggregatableHistogramTimer(const char* name, int min, int max,
     515             :                              int num_buckets, Counters* counters)
     516             :       : Histogram(name, min, max, num_buckets, counters) {}
     517             : 
     518             :   base::TimeDelta time_;
     519             : };
     520             : 
     521             : // A helper class for use with AggregatableHistogramTimer. This is the
     522             : // // outer-most timer scope used with an AggregatableHistogramTimer. It will
     523             : // // aggregate the information from the inner AggregatedHistogramTimerScope.
     524             : class AggregatingHistogramTimerScope {
     525             :  public:
     526             :   explicit AggregatingHistogramTimerScope(AggregatableHistogramTimer* histogram)
     527             :       : histogram_(histogram) {
     528             :     histogram_->Start();
     529             :   }
     530      269207 :   ~AggregatingHistogramTimerScope() { histogram_->Stop(); }
     531             : 
     532             :  private:
     533             :   AggregatableHistogramTimer* histogram_;
     534             : };
     535             : 
     536             : // A helper class for use with AggregatableHistogramTimer, the "inner" scope
     537             : // // which defines the events to be timed.
     538             : class AggregatedHistogramTimerScope {
     539             :  public:
     540             :   explicit AggregatedHistogramTimerScope(AggregatableHistogramTimer* histogram)
     541             :       : histogram_(histogram) {
     542             :     timer_.Start();
     543             :   }
     544             :   ~AggregatedHistogramTimerScope() { histogram_->Add(timer_.Elapsed()); }
     545             : 
     546             :  private:
     547             :   base::ElapsedTimer timer_;
     548             :   AggregatableHistogramTimer* histogram_;
     549             : };
     550             : 
     551             : 
     552             : // AggretatedMemoryHistogram collects (time, value) sample pairs and turns
     553             : // them into time-uniform samples for the backing historgram, such that the
     554             : // backing histogram receives one sample every T ms, where the T is controlled
     555             : // by the FLAG_histogram_interval.
     556             : //
     557             : // More formally: let F be a real-valued function that maps time to sample
     558             : // values. We define F as a linear interpolation between adjacent samples. For
     559             : // each time interval [x; x + T) the backing histogram gets one sample value
     560             : // that is the average of F(t) in the interval.
     561             : template <typename Histogram>
     562             : class AggregatedMemoryHistogram {
     563             :  public:
     564             :   // Note: public for testing purposes only.
     565             :   explicit AggregatedMemoryHistogram(Histogram* backing_histogram)
     566             :       : AggregatedMemoryHistogram() {
     567          14 :     backing_histogram_ = backing_histogram;
     568             :   }
     569             : 
     570             :   // Invariants that hold before and after AddSample if
     571             :   // is_initialized_ is true:
     572             :   //
     573             :   // 1) For we processed samples that came in before start_ms_ and sent the
     574             :   // corresponding aggregated samples to backing histogram.
     575             :   // 2) (last_ms_, last_value_) is the last received sample.
     576             :   // 3) last_ms_ < start_ms_ + FLAG_histogram_interval.
     577             :   // 4) aggregate_value_ is the average of the function that is constructed by
     578             :   // linearly interpolating samples received between start_ms_ and last_ms_.
     579             :   void AddSample(double current_ms, double current_value);
     580             : 
     581             :  private:
     582             :   friend class Counters;
     583             : 
     584             :   AggregatedMemoryHistogram()
     585             :       : is_initialized_(false),
     586             :         start_ms_(0.0),
     587             :         last_ms_(0.0),
     588             :         aggregate_value_(0.0),
     589             :         last_value_(0.0),
     590          14 :         backing_histogram_(nullptr) {}
     591             :   double Aggregate(double current_ms, double current_value);
     592             : 
     593             :   bool is_initialized_;
     594             :   double start_ms_;
     595             :   double last_ms_;
     596             :   double aggregate_value_;
     597             :   double last_value_;
     598             :   Histogram* backing_histogram_;
     599             : };
     600             : 
     601             : 
     602             : template <typename Histogram>
     603          39 : void AggregatedMemoryHistogram<Histogram>::AddSample(double current_ms,
     604             :                                                      double current_value) {
     605          39 :   if (!is_initialized_) {
     606          14 :     aggregate_value_ = current_value;
     607          14 :     start_ms_ = current_ms;
     608          14 :     last_value_ = current_value;
     609          14 :     last_ms_ = current_ms;
     610          14 :     is_initialized_ = true;
     611             :   } else {
     612             :     const double kEpsilon = 1e-6;
     613             :     const int kMaxSamples = 1000;
     614          25 :     if (current_ms < last_ms_ + kEpsilon) {
     615             :       // Two samples have the same time, remember the last one.
     616           2 :       last_value_ = current_value;
     617             :     } else {
     618          23 :       double sample_interval_ms = FLAG_histogram_interval;
     619          23 :       double end_ms = start_ms_ + sample_interval_ms;
     620          23 :       if (end_ms <= current_ms + kEpsilon) {
     621             :         // Linearly interpolate between the last_ms_ and the current_ms.
     622          18 :         double slope = (current_value - last_value_) / (current_ms - last_ms_);
     623             :         int i;
     624             :         // Send aggregated samples to the backing histogram from the start_ms
     625             :         // to the current_ms.
     626        4058 :         for (i = 0; i < kMaxSamples && end_ms <= current_ms + kEpsilon; i++) {
     627        2020 :           double end_value = last_value_ + (end_ms - last_ms_) * slope;
     628             :           double sample_value;
     629        2020 :           if (i == 0) {
     630             :             // Take aggregate_value_ into account.
     631             :             sample_value = Aggregate(end_ms, end_value);
     632             :           } else {
     633             :             // There is no aggregate_value_ for i > 0.
     634        2002 :             sample_value = (last_value_ + end_value) / 2;
     635             :           }
     636        2020 :           backing_histogram_->AddSample(static_cast<int>(sample_value + 0.5));
     637        2020 :           last_value_ = end_value;
     638        2020 :           last_ms_ = end_ms;
     639        2020 :           end_ms += sample_interval_ms;
     640             :         }
     641          18 :         if (i == kMaxSamples) {
     642             :           // We hit the sample limit, ignore the remaining samples.
     643           2 :           aggregate_value_ = current_value;
     644           2 :           start_ms_ = current_ms;
     645             :         } else {
     646          16 :           aggregate_value_ = last_value_;
     647          16 :           start_ms_ = last_ms_;
     648             :         }
     649             :       }
     650          39 :       aggregate_value_ = current_ms > start_ms_ + kEpsilon
     651             :                              ? Aggregate(current_ms, current_value)
     652             :                              : aggregate_value_;
     653          23 :       last_value_ = current_value;
     654          23 :       last_ms_ = current_ms;
     655             :     }
     656             :   }
     657          39 : }
     658             : 
     659             : 
     660             : template <typename Histogram>
     661             : double AggregatedMemoryHistogram<Histogram>::Aggregate(double current_ms,
     662             :                                                        double current_value) {
     663          25 :   double interval_ms = current_ms - start_ms_;
     664          25 :   double value = (current_value + last_value_) / 2;
     665             :   // The aggregate_value_ is the average for [start_ms_; last_ms_].
     666             :   // The value is the average for [last_ms_; current_ms].
     667             :   // Return the weighted average of the aggregate_value_ and the value.
     668          25 :   return aggregate_value_ * ((last_ms_ - start_ms_) / interval_ms) +
     669          25 :          value * ((current_ms - last_ms_) / interval_ms);
     670             : }
     671             : 
     672             : class RuntimeCallCounter final {
     673             :  public:
     674             :   RuntimeCallCounter() : RuntimeCallCounter(nullptr) {}
     675             :   explicit RuntimeCallCounter(const char* name)
     676    72363447 :       : name_(name), count_(0), time_(0) {}
     677             :   V8_NOINLINE void Reset();
     678             :   V8_NOINLINE void Dump(v8::tracing::TracedValue* value);
     679             :   void Add(RuntimeCallCounter* other);
     680             : 
     681             :   const char* name() const { return name_; }
     682             :   int64_t count() const { return count_; }
     683             :   base::TimeDelta time() const {
     684             :     return base::TimeDelta::FromMicroseconds(time_);
     685             :   }
     686       27437 :   void Increment() { count_++; }
     687       27444 :   void Add(base::TimeDelta delta) { time_ += delta.InMicroseconds(); }
     688             : 
     689             :  private:
     690             :   friend class RuntimeCallStats;
     691             : 
     692             :   const char* name_;
     693             :   int64_t count_;
     694             :   // Stored as int64_t so that its initialization can be deferred.
     695             :   int64_t time_;
     696             : };
     697             : 
     698             : // RuntimeCallTimer is used to keep track of the stack of currently active
     699             : // timers used for properly measuring the own time of a RuntimeCallCounter.
     700   179248068 : class RuntimeCallTimer final {
     701             :  public:
     702             :   RuntimeCallCounter* counter() { return counter_; }
     703          13 :   void set_counter(RuntimeCallCounter* counter) { counter_ = counter; }
     704             :   RuntimeCallTimer* parent() const { return parent_.Value(); }
     705             :   void set_parent(RuntimeCallTimer* timer) { parent_.SetValue(timer); }
     706             :   const char* name() const { return counter_->name(); }
     707             : 
     708             :   inline bool IsStarted();
     709             : 
     710             :   inline void Start(RuntimeCallCounter* counter, RuntimeCallTimer* parent);
     711             :   void Snapshot();
     712             :   inline RuntimeCallTimer* Stop();
     713             : 
     714             :   // Make the time source configurable for testing purposes.
     715             :   V8_EXPORT_PRIVATE static base::TimeTicks (*Now)();
     716             : 
     717             :  private:
     718             :   inline void Pause(base::TimeTicks now);
     719             :   inline void Resume(base::TimeTicks now);
     720             :   inline void CommitTimeToCounter();
     721             : 
     722             :   RuntimeCallCounter* counter_ = nullptr;
     723             :   base::AtomicValue<RuntimeCallTimer*> parent_;
     724             :   base::TimeTicks start_ticks_;
     725             :   base::TimeDelta elapsed_;
     726             : };
     727             : 
     728             : #define FOR_EACH_GC_COUNTER(V) \
     729             :   TRACER_SCOPES(V)             \
     730             :   TRACER_BACKGROUND_SCOPES(V)
     731             : 
     732             : #define FOR_EACH_API_COUNTER(V)                            \
     733             :   V(ArrayBuffer_Cast)                                      \
     734             :   V(ArrayBuffer_Detach)                                    \
     735             :   V(ArrayBuffer_New)                                       \
     736             :   V(Array_CloneElementAt)                                  \
     737             :   V(Array_New)                                             \
     738             :   V(BigInt64Array_New)                                     \
     739             :   V(BigInt_NewFromWords)                                   \
     740             :   V(BigIntObject_BigIntValue)                              \
     741             :   V(BigIntObject_New)                                      \
     742             :   V(BigUint64Array_New)                                    \
     743             :   V(BooleanObject_BooleanValue)                            \
     744             :   V(BooleanObject_New)                                     \
     745             :   V(Context_New)                                           \
     746             :   V(Context_NewRemoteContext)                              \
     747             :   V(DataView_New)                                          \
     748             :   V(Date_New)                                              \
     749             :   V(Date_NumberValue)                                      \
     750             :   V(Debug_Call)                                            \
     751             :   V(debug_GetPrivateFields)                                \
     752             :   V(Error_New)                                             \
     753             :   V(External_New)                                          \
     754             :   V(Float32Array_New)                                      \
     755             :   V(Float64Array_New)                                      \
     756             :   V(Function_Call)                                         \
     757             :   V(Function_New)                                          \
     758             :   V(Function_NewInstance)                                  \
     759             :   V(FunctionTemplate_GetFunction)                          \
     760             :   V(FunctionTemplate_New)                                  \
     761             :   V(FunctionTemplate_NewRemoteInstance)                    \
     762             :   V(FunctionTemplate_NewWithCache)                         \
     763             :   V(FunctionTemplate_NewWithFastHandler)                   \
     764             :   V(Int16Array_New)                                        \
     765             :   V(Int32Array_New)                                        \
     766             :   V(Int8Array_New)                                         \
     767             :   V(Isolate_DateTimeConfigurationChangeNotification)       \
     768             :   V(Isolate_LocaleConfigurationChangeNotification)         \
     769             :   V(JSON_Parse)                                            \
     770             :   V(JSON_Stringify)                                        \
     771             :   V(Map_AsArray)                                           \
     772             :   V(Map_Clear)                                             \
     773             :   V(Map_Delete)                                            \
     774             :   V(Map_Get)                                               \
     775             :   V(Map_Has)                                               \
     776             :   V(Map_New)                                               \
     777             :   V(Map_Set)                                               \
     778             :   V(Message_GetEndColumn)                                  \
     779             :   V(Message_GetLineNumber)                                 \
     780             :   V(Message_GetSourceLine)                                 \
     781             :   V(Message_GetStartColumn)                                \
     782             :   V(Module_Evaluate)                                       \
     783             :   V(Module_InstantiateModule)                              \
     784             :   V(NumberObject_New)                                      \
     785             :   V(NumberObject_NumberValue)                              \
     786             :   V(Object_CallAsConstructor)                              \
     787             :   V(Object_CallAsFunction)                                 \
     788             :   V(Object_CreateDataProperty)                             \
     789             :   V(Object_DefineOwnProperty)                              \
     790             :   V(Object_DefineProperty)                                 \
     791             :   V(Object_Delete)                                         \
     792             :   V(Object_DeleteProperty)                                 \
     793             :   V(Object_ForceSet)                                       \
     794             :   V(Object_Get)                                            \
     795             :   V(Object_GetOwnPropertyDescriptor)                       \
     796             :   V(Object_GetOwnPropertyNames)                            \
     797             :   V(Object_GetPropertyAttributes)                          \
     798             :   V(Object_GetPropertyNames)                               \
     799             :   V(Object_GetRealNamedProperty)                           \
     800             :   V(Object_GetRealNamedPropertyAttributes)                 \
     801             :   V(Object_GetRealNamedPropertyAttributesInPrototypeChain) \
     802             :   V(Object_GetRealNamedPropertyInPrototypeChain)           \
     803             :   V(Object_Has)                                            \
     804             :   V(Object_HasOwnProperty)                                 \
     805             :   V(Object_HasRealIndexedProperty)                         \
     806             :   V(Object_HasRealNamedCallbackProperty)                   \
     807             :   V(Object_HasRealNamedProperty)                           \
     808             :   V(Object_New)                                            \
     809             :   V(Object_ObjectProtoToString)                            \
     810             :   V(Object_Set)                                            \
     811             :   V(Object_SetAccessor)                                    \
     812             :   V(Object_SetIntegrityLevel)                              \
     813             :   V(Object_SetPrivate)                                     \
     814             :   V(Object_SetPrototype)                                   \
     815             :   V(ObjectTemplate_New)                                    \
     816             :   V(ObjectTemplate_NewInstance)                            \
     817             :   V(Object_ToArrayIndex)                                   \
     818             :   V(Object_ToBigInt)                                       \
     819             :   V(Object_ToDetailString)                                 \
     820             :   V(Object_ToInt32)                                        \
     821             :   V(Object_ToInteger)                                      \
     822             :   V(Object_ToNumber)                                       \
     823             :   V(Object_ToObject)                                       \
     824             :   V(Object_ToString)                                       \
     825             :   V(Object_ToUint32)                                       \
     826             :   V(Persistent_New)                                        \
     827             :   V(Private_New)                                           \
     828             :   V(Promise_Catch)                                         \
     829             :   V(Promise_Chain)                                         \
     830             :   V(Promise_HasRejectHandler)                              \
     831             :   V(Promise_Resolver_New)                                  \
     832             :   V(Promise_Resolver_Reject)                               \
     833             :   V(Promise_Resolver_Resolve)                              \
     834             :   V(Promise_Result)                                        \
     835             :   V(Promise_Status)                                        \
     836             :   V(Promise_Then)                                          \
     837             :   V(Proxy_New)                                             \
     838             :   V(RangeError_New)                                        \
     839             :   V(ReferenceError_New)                                    \
     840             :   V(RegExp_New)                                            \
     841             :   V(ScriptCompiler_Compile)                                \
     842             :   V(ScriptCompiler_CompileFunctionInContext)               \
     843             :   V(ScriptCompiler_CompileUnbound)                         \
     844             :   V(Script_Run)                                            \
     845             :   V(Set_Add)                                               \
     846             :   V(Set_AsArray)                                           \
     847             :   V(Set_Clear)                                             \
     848             :   V(Set_Delete)                                            \
     849             :   V(Set_Has)                                               \
     850             :   V(Set_New)                                               \
     851             :   V(SharedArrayBuffer_New)                                 \
     852             :   V(String_Concat)                                         \
     853             :   V(String_NewExternalOneByte)                             \
     854             :   V(String_NewExternalTwoByte)                             \
     855             :   V(String_NewFromOneByte)                                 \
     856             :   V(String_NewFromTwoByte)                                 \
     857             :   V(String_NewFromUtf8)                                    \
     858             :   V(StringObject_New)                                      \
     859             :   V(StringObject_StringValue)                              \
     860             :   V(String_Write)                                          \
     861             :   V(String_WriteUtf8)                                      \
     862             :   V(Symbol_New)                                            \
     863             :   V(SymbolObject_New)                                      \
     864             :   V(SymbolObject_SymbolValue)                              \
     865             :   V(SyntaxError_New)                                       \
     866             :   V(TracedGlobal_New)                                      \
     867             :   V(TryCatch_StackTrace)                                   \
     868             :   V(TypeError_New)                                         \
     869             :   V(Uint16Array_New)                                       \
     870             :   V(Uint32Array_New)                                       \
     871             :   V(Uint8Array_New)                                        \
     872             :   V(Uint8ClampedArray_New)                                 \
     873             :   V(UnboundScript_GetId)                                   \
     874             :   V(UnboundScript_GetLineNumber)                           \
     875             :   V(UnboundScript_GetName)                                 \
     876             :   V(UnboundScript_GetSourceMappingURL)                     \
     877             :   V(UnboundScript_GetSourceURL)                            \
     878             :   V(ValueDeserializer_ReadHeader)                          \
     879             :   V(ValueDeserializer_ReadValue)                           \
     880             :   V(ValueSerializer_WriteValue)                            \
     881             :   V(Value_InstanceOf)                                      \
     882             :   V(Value_Int32Value)                                      \
     883             :   V(Value_IntegerValue)                                    \
     884             :   V(Value_NumberValue)                                     \
     885             :   V(Value_TypeOf)                                          \
     886             :   V(Value_Uint32Value)                                     \
     887             :   V(WeakMap_Get)                                           \
     888             :   V(WeakMap_New)                                           \
     889             :   V(WeakMap_Set)
     890             : 
     891             : #define FOR_EACH_MANUAL_COUNTER(V)             \
     892             :   V(AccessorGetterCallback)                    \
     893             :   V(AccessorSetterCallback)                    \
     894             :   V(ArrayLengthGetter)                         \
     895             :   V(ArrayLengthSetter)                         \
     896             :   V(BoundFunctionLengthGetter)                 \
     897             :   V(BoundFunctionNameGetter)                   \
     898             :   V(CompileAnalyse)                            \
     899             :   V(CompileBackgroundAnalyse)                  \
     900             :   V(CompileBackgroundCompileTask)              \
     901             :   V(CompileBackgroundEval)                     \
     902             :   V(CompileBackgroundFunction)                 \
     903             :   V(CompileBackgroundIgnition)                 \
     904             :   V(CompileBackgroundRewriteReturnResult)      \
     905             :   V(CompileBackgroundScopeAnalysis)            \
     906             :   V(CompileBackgroundScript)                   \
     907             :   V(CompileCollectSourcePositions)             \
     908             :   V(CompileDeserialize)                        \
     909             :   V(CompileEnqueueOnDispatcher)                \
     910             :   V(CompileEval)                               \
     911             :   V(CompileFinalizeBackgroundCompileTask)      \
     912             :   V(CompileFinishNowOnDispatcher)              \
     913             :   V(CompileFunction)                           \
     914             :   V(CompileGetFromOptimizedCodeMap)            \
     915             :   V(CompileIgnition)                           \
     916             :   V(CompileIgnitionFinalization)               \
     917             :   V(CompileRewriteReturnResult)                \
     918             :   V(CompileScopeAnalysis)                      \
     919             :   V(CompileScript)                             \
     920             :   V(CompileSerialize)                          \
     921             :   V(CompileWaitForDispatcher)                  \
     922             :   V(DeoptimizeCode)                            \
     923             :   V(DeserializeContext)                        \
     924             :   V(DeserializeIsolate)                        \
     925             :   V(FunctionCallback)                          \
     926             :   V(FunctionLengthGetter)                      \
     927             :   V(FunctionPrototypeGetter)                   \
     928             :   V(FunctionPrototypeSetter)                   \
     929             :   V(GC_Custom_AllAvailableGarbage)             \
     930             :   V(GC_Custom_IncrementalMarkingObserver)      \
     931             :   V(GC_Custom_SlowAllocateRaw)                 \
     932             :   V(GCEpilogueCallback)                        \
     933             :   V(GCPrologueCallback)                        \
     934             :   V(Genesis)                                   \
     935             :   V(GetMoreDataCallback)                       \
     936             :   V(IndexedDefinerCallback)                    \
     937             :   V(IndexedDeleterCallback)                    \
     938             :   V(IndexedDescriptorCallback)                 \
     939             :   V(IndexedEnumeratorCallback)                 \
     940             :   V(IndexedGetterCallback)                     \
     941             :   V(IndexedQueryCallback)                      \
     942             :   V(IndexedSetterCallback)                     \
     943             :   V(Invoke)                                    \
     944             :   V(InvokeApiFunction)                         \
     945             :   V(InvokeApiInterruptCallbacks)               \
     946             :   V(InvokeFunctionCallback)                    \
     947             :   V(JS_Execution)                              \
     948             :   V(Map_SetPrototype)                          \
     949             :   V(Map_TransitionToAccessorProperty)          \
     950             :   V(Map_TransitionToDataProperty)              \
     951             :   V(MessageListenerCallback)                   \
     952             :   V(NamedDefinerCallback)                      \
     953             :   V(NamedDeleterCallback)                      \
     954             :   V(NamedDescriptorCallback)                   \
     955             :   V(NamedEnumeratorCallback)                   \
     956             :   V(NamedGetterCallback)                       \
     957             :   V(NamedQueryCallback)                        \
     958             :   V(NamedSetterCallback)                       \
     959             :   V(Object_DeleteProperty)                     \
     960             :   V(ObjectVerify)                              \
     961             :   V(OptimizeCode)                              \
     962             :   V(ParseArrowFunctionLiteral)                 \
     963             :   V(ParseBackgroundArrowFunctionLiteral)       \
     964             :   V(ParseBackgroundFunctionLiteral)            \
     965             :   V(ParseBackgroundProgram)                    \
     966             :   V(ParseEval)                                 \
     967             :   V(ParseFunction)                             \
     968             :   V(ParseFunctionLiteral)                      \
     969             :   V(ParseProgram)                              \
     970             :   V(PreParseArrowFunctionLiteral)              \
     971             :   V(PreParseBackgroundArrowFunctionLiteral)    \
     972             :   V(PreParseBackgroundWithVariableResolution)  \
     973             :   V(PreParseWithVariableResolution)            \
     974             :   V(PropertyCallback)                          \
     975             :   V(PrototypeMap_TransitionToAccessorProperty) \
     976             :   V(PrototypeMap_TransitionToDataProperty)     \
     977             :   V(PrototypeObject_DeleteProperty)            \
     978             :   V(RecompileConcurrent)                       \
     979             :   V(RecompileSynchronous)                      \
     980             :   V(ReconfigureToDataProperty)                 \
     981             :   V(StringLengthGetter)                        \
     982             :   V(TestCounter1)                              \
     983             :   V(TestCounter2)                              \
     984             :   V(TestCounter3)
     985             : 
     986             : #define FOR_EACH_HANDLER_COUNTER(V)               \
     987             :   V(KeyedLoadIC_KeyedLoadSloppyArgumentsStub)     \
     988             :   V(KeyedLoadIC_LoadElementDH)                    \
     989             :   V(KeyedLoadIC_LoadIndexedInterceptorStub)       \
     990             :   V(KeyedLoadIC_LoadIndexedStringDH)              \
     991             :   V(KeyedLoadIC_SlowStub)                         \
     992             :   V(KeyedStoreIC_ElementsTransitionAndStoreStub)  \
     993             :   V(KeyedStoreIC_KeyedStoreSloppyArgumentsStub)   \
     994             :   V(KeyedStoreIC_SlowStub)                        \
     995             :   V(KeyedStoreIC_StoreElementStub)                \
     996             :   V(KeyedStoreIC_StoreFastElementStub)            \
     997             :   V(LoadGlobalIC_LoadScriptContextField)          \
     998             :   V(LoadGlobalIC_SlowStub)                        \
     999             :   V(LoadIC_FunctionPrototypeStub)                 \
    1000             :   V(LoadIC_HandlerCacheHit_Accessor)              \
    1001             :   V(LoadIC_LoadAccessorDH)                        \
    1002             :   V(LoadIC_LoadAccessorFromPrototypeDH)           \
    1003             :   V(LoadIC_LoadApiGetterFromPrototypeDH)          \
    1004             :   V(LoadIC_LoadCallback)                          \
    1005             :   V(LoadIC_LoadConstantDH)                        \
    1006             :   V(LoadIC_LoadConstantFromPrototypeDH)           \
    1007             :   V(LoadIC_LoadFieldDH)                           \
    1008             :   V(LoadIC_LoadFieldFromPrototypeDH)              \
    1009             :   V(LoadIC_LoadGlobalDH)                          \
    1010             :   V(LoadIC_LoadGlobalFromPrototypeDH)             \
    1011             :   V(LoadIC_LoadIntegerIndexedExoticDH)            \
    1012             :   V(LoadIC_LoadInterceptorDH)                     \
    1013             :   V(LoadIC_LoadInterceptorFromPrototypeDH)        \
    1014             :   V(LoadIC_LoadNativeDataPropertyDH)              \
    1015             :   V(LoadIC_LoadNativeDataPropertyFromPrototypeDH) \
    1016             :   V(LoadIC_LoadNonexistentDH)                     \
    1017             :   V(LoadIC_LoadNonMaskingInterceptorDH)           \
    1018             :   V(LoadIC_LoadNormalDH)                          \
    1019             :   V(LoadIC_LoadNormalFromPrototypeDH)             \
    1020             :   V(LoadIC_NonReceiver)                           \
    1021             :   V(LoadIC_Premonomorphic)                        \
    1022             :   V(LoadIC_SlowStub)                              \
    1023             :   V(LoadIC_StringLength)                          \
    1024             :   V(LoadIC_StringWrapperLength)                   \
    1025             :   V(StoreGlobalIC_SlowStub)                       \
    1026             :   V(StoreGlobalIC_StoreScriptContextField)        \
    1027             :   V(StoreGlobalIC_Premonomorphic)                 \
    1028             :   V(StoreIC_HandlerCacheHit_Accessor)             \
    1029             :   V(StoreIC_NonReceiver)                          \
    1030             :   V(StoreIC_Premonomorphic)                       \
    1031             :   V(StoreIC_SlowStub)                             \
    1032             :   V(StoreIC_StoreAccessorDH)                      \
    1033             :   V(StoreIC_StoreAccessorOnPrototypeDH)           \
    1034             :   V(StoreIC_StoreApiSetterOnPrototypeDH)          \
    1035             :   V(StoreIC_StoreFieldDH)                         \
    1036             :   V(StoreIC_StoreGlobalDH)                        \
    1037             :   V(StoreIC_StoreGlobalTransitionDH)              \
    1038             :   V(StoreIC_StoreInterceptorStub)                 \
    1039             :   V(StoreIC_StoreNativeDataPropertyDH)            \
    1040             :   V(StoreIC_StoreNativeDataPropertyOnPrototypeDH) \
    1041             :   V(StoreIC_StoreNormalDH)                        \
    1042             :   V(StoreIC_StoreTransitionDH)                    \
    1043             :   V(StoreInArrayLiteralIC_SlowStub)
    1044             : 
    1045             : enum RuntimeCallCounterId {
    1046             : #define CALL_RUNTIME_COUNTER(name) kGC_##name,
    1047             :   FOR_EACH_GC_COUNTER(CALL_RUNTIME_COUNTER)
    1048             : #undef CALL_RUNTIME_COUNTER
    1049             : #define CALL_RUNTIME_COUNTER(name) k##name,
    1050             :       FOR_EACH_MANUAL_COUNTER(CALL_RUNTIME_COUNTER)
    1051             : #undef CALL_RUNTIME_COUNTER
    1052             : #define CALL_RUNTIME_COUNTER(name, nargs, ressize) kRuntime_##name,
    1053             :           FOR_EACH_INTRINSIC(CALL_RUNTIME_COUNTER)
    1054             : #undef CALL_RUNTIME_COUNTER
    1055             : #define CALL_BUILTIN_COUNTER(name) kBuiltin_##name,
    1056             :               BUILTIN_LIST_C(CALL_BUILTIN_COUNTER)
    1057             : #undef CALL_BUILTIN_COUNTER
    1058             : #define CALL_BUILTIN_COUNTER(name) kAPI_##name,
    1059             :                   FOR_EACH_API_COUNTER(CALL_BUILTIN_COUNTER)
    1060             : #undef CALL_BUILTIN_COUNTER
    1061             : #define CALL_BUILTIN_COUNTER(name) kHandler_##name,
    1062             :                       FOR_EACH_HANDLER_COUNTER(CALL_BUILTIN_COUNTER)
    1063             : #undef CALL_BUILTIN_COUNTER
    1064             :                           kNumberOfCounters
    1065             : };
    1066             : 
    1067             : class RuntimeCallStats final {
    1068             :  public:
    1069             :   V8_EXPORT_PRIVATE RuntimeCallStats();
    1070             : 
    1071             :   // Starting measuring the time for a function. This will establish the
    1072             :   // connection to the parent counter for properly calculating the own times.
    1073             :   V8_EXPORT_PRIVATE void Enter(RuntimeCallTimer* timer,
    1074             :                                RuntimeCallCounterId counter_id);
    1075             : 
    1076             :   // Leave a scope for a measured runtime function. This will properly add
    1077             :   // the time delta to the current_counter and subtract the delta from its
    1078             :   // parent.
    1079             :   V8_EXPORT_PRIVATE void Leave(RuntimeCallTimer* timer);
    1080             : 
    1081             :   // Set counter id for the innermost measurement. It can be used to refine
    1082             :   // event kind when a runtime entry counter is too generic.
    1083             :   V8_EXPORT_PRIVATE void CorrectCurrentCounterId(
    1084             :       RuntimeCallCounterId counter_id);
    1085             : 
    1086             :   V8_EXPORT_PRIVATE void Reset();
    1087             :   // Add all entries from another stats object.
    1088             :   void Add(RuntimeCallStats* other);
    1089             :   V8_EXPORT_PRIVATE void Print(std::ostream& os);
    1090             :   V8_EXPORT_PRIVATE void Print();
    1091             :   V8_NOINLINE void Dump(v8::tracing::TracedValue* value);
    1092             : 
    1093             :   ThreadId thread_id() const { return thread_id_; }
    1094             :   RuntimeCallTimer* current_timer() { return current_timer_.Value(); }
    1095             :   RuntimeCallCounter* current_counter() { return current_counter_.Value(); }
    1096             :   bool InUse() { return in_use_; }
    1097             :   bool IsCalledOnTheSameThread();
    1098             : 
    1099             :   static const int kNumberOfCounters =
    1100             :       static_cast<int>(RuntimeCallCounterId::kNumberOfCounters);
    1101             :   RuntimeCallCounter* GetCounter(RuntimeCallCounterId counter_id) {
    1102       27456 :     return &counters_[static_cast<int>(counter_id)];
    1103             :   }
    1104             :   RuntimeCallCounter* GetCounter(int counter_id) {
    1105      904194 :     return &counters_[counter_id];
    1106             :   }
    1107             : 
    1108             :  private:
    1109             :   // Top of a stack of active timers.
    1110             :   base::AtomicValue<RuntimeCallTimer*> current_timer_;
    1111             :   // Active counter object associated with current timer.
    1112             :   base::AtomicValue<RuntimeCallCounter*> current_counter_;
    1113             :   // Used to track nested tracing scopes.
    1114             :   bool in_use_;
    1115             :   ThreadId thread_id_;
    1116             :   RuntimeCallCounter counters_[kNumberOfCounters];
    1117             : };
    1118             : 
    1119             : class WorkerThreadRuntimeCallStats final {
    1120             :  public:
    1121             :   WorkerThreadRuntimeCallStats();
    1122             :   ~WorkerThreadRuntimeCallStats();
    1123             : 
    1124             :   // Returns the TLS key associated with this WorkerThreadRuntimeCallStats.
    1125             :   base::Thread::LocalStorageKey GetKey();
    1126             : 
    1127             :   // Returns a new worker thread runtime call stats table managed by this
    1128             :   // WorkerThreadRuntimeCallStats.
    1129             :   RuntimeCallStats* NewTable();
    1130             : 
    1131             :   // Adds the counters from the worker thread tables to |main_call_stats|.
    1132             :   void AddToMainTable(RuntimeCallStats* main_call_stats);
    1133             : 
    1134             :  private:
    1135             :   base::Mutex mutex_;
    1136             :   std::vector<std::unique_ptr<RuntimeCallStats>> tables_;
    1137             :   base::Optional<base::Thread::LocalStorageKey> tls_key_;
    1138             : };
    1139             : 
    1140             : // Creating a WorkerThreadRuntimeCallStatsScope will provide a thread-local
    1141             : // runtime call stats table, and will dump the table to an immediate trace event
    1142             : // when it is destroyed.
    1143             : class WorkerThreadRuntimeCallStatsScope final {
    1144             :  public:
    1145             :   WorkerThreadRuntimeCallStatsScope(
    1146             :       WorkerThreadRuntimeCallStats* off_thread_stats);
    1147             :   ~WorkerThreadRuntimeCallStatsScope();
    1148             : 
    1149       20461 :   RuntimeCallStats* Get() const { return table_; }
    1150             : 
    1151             :  private:
    1152             :   RuntimeCallStats* table_;
    1153             : };
    1154             : 
    1155             : #define CHANGE_CURRENT_RUNTIME_COUNTER(runtime_call_stats, counter_id) \
    1156             :   do {                                                                 \
    1157             :     if (V8_UNLIKELY(TracingFlags::is_runtime_stats_enabled()) &&       \
    1158             :         runtime_call_stats) {                                          \
    1159             :       runtime_call_stats->CorrectCurrentCounterId(counter_id);         \
    1160             :     }                                                                  \
    1161             :   } while (false)
    1162             : 
    1163             : #define TRACE_HANDLER_STATS(isolate, counter_name) \
    1164             :   CHANGE_CURRENT_RUNTIME_COUNTER(                  \
    1165             :       isolate->counters()->runtime_call_stats(),   \
    1166             :       RuntimeCallCounterId::kHandler_##counter_name)
    1167             : 
    1168             : // A RuntimeCallTimerScopes wraps around a RuntimeCallTimer to measure the
    1169             : // the time of C++ scope.
    1170             : class RuntimeCallTimerScope {
    1171             :  public:
    1172             :   inline RuntimeCallTimerScope(Isolate* isolate,
    1173             :                                RuntimeCallCounterId counter_id);
    1174             :   // This constructor is here just to avoid calling GetIsolate() when the
    1175             :   // stats are disabled and the isolate is not directly available.
    1176             :   inline RuntimeCallTimerScope(Isolate* isolate, HeapObject heap_object,
    1177             :                                RuntimeCallCounterId counter_id);
    1178    17229076 :   inline RuntimeCallTimerScope(RuntimeCallStats* stats,
    1179    17229076 :                                RuntimeCallCounterId counter_id) {
    1180    17229076 :     if (V8_LIKELY(!TracingFlags::is_runtime_stats_enabled() ||
    1181             :                   stats == nullptr))
    1182             :       return;
    1183        8124 :     stats_ = stats;
    1184        8124 :     stats_->Enter(&timer_, counter_id);
    1185             :   }
    1186             : 
    1187   169386948 :   inline ~RuntimeCallTimerScope() {
    1188   169386948 :     if (V8_UNLIKELY(stats_ != nullptr)) {
    1189       27432 :       stats_->Leave(&timer_);
    1190             :     }
    1191             :   }
    1192             : 
    1193             :  private:
    1194             :   RuntimeCallStats* stats_ = nullptr;
    1195             :   RuntimeCallTimer timer_;
    1196             : 
    1197             :   DISALLOW_COPY_AND_ASSIGN(RuntimeCallTimerScope);
    1198             : };
    1199             : 
    1200             : #define HISTOGRAM_RANGE_LIST(HR)                                               \
    1201             :   /* Generic range histograms: HR(name, caption, min, max, num_buckets) */     \
    1202             :   HR(background_marking, V8.GCBackgroundMarking, 0, 10000, 101)                \
    1203             :   HR(background_scavenger, V8.GCBackgroundScavenger, 0, 10000, 101)            \
    1204             :   HR(background_sweeping, V8.GCBackgroundSweeping, 0, 10000, 101)              \
    1205             :   HR(detached_context_age_in_gc, V8.DetachedContextAgeInGC, 0, 20, 21)         \
    1206             :   HR(code_cache_reject_reason, V8.CodeCacheRejectReason, 1, 6, 6)              \
    1207             :   HR(errors_thrown_per_context, V8.ErrorsThrownPerContext, 0, 200, 20)         \
    1208             :   HR(debug_feature_usage, V8.DebugFeatureUsage, 1, 7, 7)                       \
    1209             :   HR(incremental_marking_reason, V8.GCIncrementalMarkingReason, 0, 21, 22)     \
    1210             :   HR(incremental_marking_sum, V8.GCIncrementalMarkingSum, 0, 10000, 101)       \
    1211             :   HR(mark_compact_reason, V8.GCMarkCompactReason, 0, 21, 22)                   \
    1212             :   HR(gc_finalize_clear, V8.GCFinalizeMC.Clear, 0, 10000, 101)                  \
    1213             :   HR(gc_finalize_epilogue, V8.GCFinalizeMC.Epilogue, 0, 10000, 101)            \
    1214             :   HR(gc_finalize_evacuate, V8.GCFinalizeMC.Evacuate, 0, 10000, 101)            \
    1215             :   HR(gc_finalize_finish, V8.GCFinalizeMC.Finish, 0, 10000, 101)                \
    1216             :   HR(gc_finalize_mark, V8.GCFinalizeMC.Mark, 0, 10000, 101)                    \
    1217             :   HR(gc_finalize_prologue, V8.GCFinalizeMC.Prologue, 0, 10000, 101)            \
    1218             :   HR(gc_finalize_sweep, V8.GCFinalizeMC.Sweep, 0, 10000, 101)                  \
    1219             :   HR(gc_scavenger_scavenge_main, V8.GCScavenger.ScavengeMain, 0, 10000, 101)   \
    1220             :   HR(gc_scavenger_scavenge_roots, V8.GCScavenger.ScavengeRoots, 0, 10000, 101) \
    1221             :   HR(gc_mark_compactor, V8.GCMarkCompactor, 0, 10000, 101)                     \
    1222             :   HR(scavenge_reason, V8.GCScavengeReason, 0, 21, 22)                          \
    1223             :   HR(young_generation_handling, V8.GCYoungGenerationHandling, 0, 2, 3)         \
    1224             :   /* Asm/Wasm. */                                                              \
    1225             :   HR(wasm_functions_per_asm_module, V8.WasmFunctionsPerModule.asm, 1, 1000000, \
    1226             :      51)                                                                       \
    1227             :   HR(wasm_functions_per_wasm_module, V8.WasmFunctionsPerModule.wasm, 1,        \
    1228             :      1000000, 51)                                                              \
    1229             :   HR(array_buffer_big_allocations, V8.ArrayBufferLargeAllocations, 0, 4096,    \
    1230             :      13)                                                                       \
    1231             :   HR(array_buffer_new_size_failures, V8.ArrayBufferNewSizeFailures, 0, 4096,   \
    1232             :      13)                                                                       \
    1233             :   HR(shared_array_allocations, V8.SharedArrayAllocationSizes, 0, 4096, 13)     \
    1234             :   HR(wasm_asm_function_size_bytes, V8.WasmFunctionSizeBytes.asm, 1, GB, 51)    \
    1235             :   HR(wasm_wasm_function_size_bytes, V8.WasmFunctionSizeBytes.wasm, 1, GB, 51)  \
    1236             :   HR(wasm_asm_module_size_bytes, V8.WasmModuleSizeBytes.asm, 1, GB, 51)        \
    1237             :   HR(wasm_wasm_module_size_bytes, V8.WasmModuleSizeBytes.wasm, 1, GB, 51)      \
    1238             :   HR(wasm_asm_min_mem_pages_count, V8.WasmMinMemPagesCount.asm, 1, 2 << 16,    \
    1239             :      51)                                                                       \
    1240             :   HR(wasm_wasm_min_mem_pages_count, V8.WasmMinMemPagesCount.wasm, 1, 2 << 16,  \
    1241             :      51)                                                                       \
    1242             :   HR(wasm_wasm_max_mem_pages_count, V8.WasmMaxMemPagesCount.wasm, 1, 2 << 16,  \
    1243             :      51)                                                                       \
    1244             :   HR(wasm_decode_asm_module_peak_memory_bytes,                                 \
    1245             :      V8.WasmDecodeModulePeakMemoryBytes.asm, 1, GB, 51)                        \
    1246             :   HR(wasm_decode_wasm_module_peak_memory_bytes,                                \
    1247             :      V8.WasmDecodeModulePeakMemoryBytes.wasm, 1, GB, 51)                       \
    1248             :   HR(asm_wasm_translation_peak_memory_bytes,                                   \
    1249             :      V8.AsmWasmTranslationPeakMemoryBytes, 1, GB, 51)                          \
    1250             :   HR(wasm_compile_function_peak_memory_bytes,                                  \
    1251             :      V8.WasmCompileFunctionPeakMemoryBytes, 1, GB, 51)                         \
    1252             :   HR(asm_module_size_bytes, V8.AsmModuleSizeBytes, 1, GB, 51)                  \
    1253             :   HR(asm_wasm_translation_throughput, V8.AsmWasmTranslationThroughput, 1, 100, \
    1254             :      20)                                                                       \
    1255             :   HR(wasm_lazy_compilation_throughput, V8.WasmLazyCompilationThroughput, 1,    \
    1256             :      10000, 50)                                                                \
    1257             :   HR(compile_script_cache_behaviour, V8.CompileScript.CacheBehaviour, 0, 20,   \
    1258             :      21)                                                                       \
    1259             :   HR(wasm_memory_allocation_result, V8.WasmMemoryAllocationResult, 0, 3, 4)    \
    1260             :   HR(wasm_address_space_usage_mb, V8.WasmAddressSpaceUsageMiB, 0, 1 << 20,     \
    1261             :      128)                                                                      \
    1262             :   /* code size of live modules, collected on GC */                             \
    1263             :   HR(wasm_module_code_size_mb, V8.WasmModuleCodeSizeMiB, 0, 1024, 64)          \
    1264             :   /* code size of modules after baseline compilation */                        \
    1265             :   HR(wasm_module_code_size_mb_after_baseline,                                  \
    1266             :      V8.WasmModuleCodeSizeBaselineMiB, 0, 1024, 64)                            \
    1267             :   /* code size of modules after top-tier compilation */                        \
    1268             :   HR(wasm_module_code_size_mb_after_top_tier, V8.WasmModuleCodeSizeTopTierMiB, \
    1269             :      0, 1024, 64)
    1270             : 
    1271             : #define HISTOGRAM_TIMER_LIST(HT)                                               \
    1272             :   /* Timer histograms, not thread safe: HT(name, caption, max, unit) */        \
    1273             :   /* Garbage collection timers. */                                             \
    1274             :   HT(gc_context, V8.GCContext, 10000,                                          \
    1275             :      MILLISECOND) /* GC context cleanup time */                                \
    1276             :   HT(gc_idle_notification, V8.GCIdleNotification, 10000, MILLISECOND)          \
    1277             :   HT(gc_incremental_marking, V8.GCIncrementalMarking, 10000, MILLISECOND)      \
    1278             :   HT(gc_incremental_marking_start, V8.GCIncrementalMarkingStart, 10000,        \
    1279             :      MILLISECOND)                                                              \
    1280             :   HT(gc_incremental_marking_finalize, V8.GCIncrementalMarkingFinalize, 10000,  \
    1281             :      MILLISECOND)                                                              \
    1282             :   HT(gc_low_memory_notification, V8.GCLowMemoryNotification, 10000,            \
    1283             :      MILLISECOND)                                                              \
    1284             :   /* Compilation times. */                                                     \
    1285             :   HT(collect_source_positions, V8.CollectSourcePositions, 1000000,             \
    1286             :      MICROSECOND)                                                              \
    1287             :   HT(compile, V8.CompileMicroSeconds, 1000000, MICROSECOND)                    \
    1288             :   HT(compile_eval, V8.CompileEvalMicroSeconds, 1000000, MICROSECOND)           \
    1289             :   /* Serialization as part of compilation (code caching) */                    \
    1290             :   HT(compile_serialize, V8.CompileSerializeMicroSeconds, 100000, MICROSECOND)  \
    1291             :   HT(compile_deserialize, V8.CompileDeserializeMicroSeconds, 1000000,          \
    1292             :      MICROSECOND)                                                              \
    1293             :   /* Total compilation time incl. caching/parsing */                           \
    1294             :   HT(compile_script, V8.CompileScriptMicroSeconds, 1000000, MICROSECOND)       \
    1295             :   /* Total JavaScript execution time (including callbacks and runtime calls */ \
    1296             :   HT(execute, V8.Execute, 1000000, MICROSECOND)                                \
    1297             :   /* Asm/Wasm */                                                               \
    1298             :   HT(asm_wasm_translation_time, V8.AsmWasmTranslationMicroSeconds, 1000000,    \
    1299             :      MICROSECOND)                                                              \
    1300             :   HT(wasm_lazy_compilation_time, V8.WasmLazyCompilationMicroSeconds, 1000000,  \
    1301             :      MICROSECOND)
    1302             : 
    1303             : #define TIMED_HISTOGRAM_LIST(HT)                                               \
    1304             :   /* Timer histograms, thread safe: HT(name, caption, max, unit) */            \
    1305             :   /* Garbage collection timers. */                                             \
    1306             :   HT(gc_compactor, V8.GCCompactor, 10000, MILLISECOND)                         \
    1307             :   HT(gc_compactor_background, V8.GCCompactorBackground, 10000, MILLISECOND)    \
    1308             :   HT(gc_compactor_foreground, V8.GCCompactorForeground, 10000, MILLISECOND)    \
    1309             :   HT(gc_finalize, V8.GCFinalizeMC, 10000, MILLISECOND)                         \
    1310             :   HT(gc_finalize_background, V8.GCFinalizeMCBackground, 10000, MILLISECOND)    \
    1311             :   HT(gc_finalize_foreground, V8.GCFinalizeMCForeground, 10000, MILLISECOND)    \
    1312             :   HT(gc_finalize_reduce_memory, V8.GCFinalizeMCReduceMemory, 10000,            \
    1313             :      MILLISECOND)                                                              \
    1314             :   HT(gc_finalize_reduce_memory_background,                                     \
    1315             :      V8.GCFinalizeMCReduceMemoryBackground, 10000, MILLISECOND)                \
    1316             :   HT(gc_finalize_reduce_memory_foreground,                                     \
    1317             :      V8.GCFinalizeMCReduceMemoryForeground, 10000, MILLISECOND)                \
    1318             :   HT(gc_scavenger, V8.GCScavenger, 10000, MILLISECOND)                         \
    1319             :   HT(gc_scavenger_background, V8.GCScavengerBackground, 10000, MILLISECOND)    \
    1320             :   HT(gc_scavenger_foreground, V8.GCScavengerForeground, 10000, MILLISECOND)    \
    1321             :   /* Wasm timers. */                                                           \
    1322             :   HT(wasm_decode_asm_module_time, V8.WasmDecodeModuleMicroSeconds.asm,         \
    1323             :      1000000, MICROSECOND)                                                     \
    1324             :   HT(wasm_decode_wasm_module_time, V8.WasmDecodeModuleMicroSeconds.wasm,       \
    1325             :      1000000, MICROSECOND)                                                     \
    1326             :   HT(wasm_decode_asm_function_time, V8.WasmDecodeFunctionMicroSeconds.asm,     \
    1327             :      1000000, MICROSECOND)                                                     \
    1328             :   HT(wasm_decode_wasm_function_time, V8.WasmDecodeFunctionMicroSeconds.wasm,   \
    1329             :      1000000, MICROSECOND)                                                     \
    1330             :   HT(wasm_compile_asm_module_time, V8.WasmCompileModuleMicroSeconds.asm,       \
    1331             :      10000000, MICROSECOND)                                                    \
    1332             :   HT(wasm_compile_wasm_module_time, V8.WasmCompileModuleMicroSeconds.wasm,     \
    1333             :      10000000, MICROSECOND)                                                    \
    1334             :   HT(wasm_compile_asm_function_time, V8.WasmCompileFunctionMicroSeconds.asm,   \
    1335             :      1000000, MICROSECOND)                                                     \
    1336             :   HT(wasm_compile_wasm_function_time, V8.WasmCompileFunctionMicroSeconds.wasm, \
    1337             :      1000000, MICROSECOND)                                                     \
    1338             :   HT(liftoff_compile_time, V8.LiftoffCompileMicroSeconds, 10000000,            \
    1339             :      MICROSECOND)                                                              \
    1340             :   HT(wasm_instantiate_wasm_module_time,                                        \
    1341             :      V8.WasmInstantiateModuleMicroSeconds.wasm, 10000000, MICROSECOND)         \
    1342             :   HT(wasm_instantiate_asm_module_time,                                         \
    1343             :      V8.WasmInstantiateModuleMicroSeconds.asm, 10000000, MICROSECOND)          \
    1344             :   /* Total compilation time incl. caching/parsing for various cache states. */ \
    1345             :   HT(compile_script_with_produce_cache,                                        \
    1346             :      V8.CompileScriptMicroSeconds.ProduceCache, 1000000, MICROSECOND)          \
    1347             :   HT(compile_script_with_isolate_cache_hit,                                    \
    1348             :      V8.CompileScriptMicroSeconds.IsolateCacheHit, 1000000, MICROSECOND)       \
    1349             :   HT(compile_script_with_consume_cache,                                        \
    1350             :      V8.CompileScriptMicroSeconds.ConsumeCache, 1000000, MICROSECOND)          \
    1351             :   HT(compile_script_consume_failed,                                            \
    1352             :      V8.CompileScriptMicroSeconds.ConsumeCache.Failed, 1000000, MICROSECOND)   \
    1353             :   HT(compile_script_no_cache_other,                                            \
    1354             :      V8.CompileScriptMicroSeconds.NoCache.Other, 1000000, MICROSECOND)         \
    1355             :   HT(compile_script_no_cache_because_inline_script,                            \
    1356             :      V8.CompileScriptMicroSeconds.NoCache.InlineScript, 1000000, MICROSECOND)  \
    1357             :   HT(compile_script_no_cache_because_script_too_small,                         \
    1358             :      V8.CompileScriptMicroSeconds.NoCache.ScriptTooSmall, 1000000,             \
    1359             :      MICROSECOND)                                                              \
    1360             :   HT(compile_script_no_cache_because_cache_too_cold,                           \
    1361             :      V8.CompileScriptMicroSeconds.NoCache.CacheTooCold, 1000000, MICROSECOND)  \
    1362             :   HT(compile_script_on_background,                                             \
    1363             :      V8.CompileScriptMicroSeconds.BackgroundThread, 1000000, MICROSECOND)      \
    1364             :   HT(compile_function_on_background,                                           \
    1365             :      V8.CompileFunctionMicroSeconds.BackgroundThread, 1000000, MICROSECOND)
    1366             : 
    1367             : #define AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT) \
    1368             :   AHT(compile_lazy, V8.CompileLazyMicroSeconds)
    1369             : 
    1370             : #define HISTOGRAM_PERCENTAGE_LIST(HP)                                          \
    1371             :   /* Heap fragmentation. */                                                    \
    1372             :   HP(external_fragmentation_total, V8.MemoryExternalFragmentationTotal)        \
    1373             :   HP(external_fragmentation_old_space, V8.MemoryExternalFragmentationOldSpace) \
    1374             :   HP(external_fragmentation_code_space,                                        \
    1375             :      V8.MemoryExternalFragmentationCodeSpace)                                  \
    1376             :   HP(external_fragmentation_map_space, V8.MemoryExternalFragmentationMapSpace) \
    1377             :   HP(external_fragmentation_lo_space, V8.MemoryExternalFragmentationLoSpace)
    1378             : 
    1379             : // Note: These use Histogram with options (min=1000, max=500000, buckets=50).
    1380             : #define HISTOGRAM_LEGACY_MEMORY_LIST(HM)                                      \
    1381             :   HM(heap_sample_total_committed, V8.MemoryHeapSampleTotalCommitted)          \
    1382             :   HM(heap_sample_total_used, V8.MemoryHeapSampleTotalUsed)                    \
    1383             :   HM(heap_sample_map_space_committed, V8.MemoryHeapSampleMapSpaceCommitted)   \
    1384             :   HM(heap_sample_code_space_committed, V8.MemoryHeapSampleCodeSpaceCommitted) \
    1385             :   HM(heap_sample_maximum_committed, V8.MemoryHeapSampleMaximumCommitted)
    1386             : 
    1387             : // WARNING: STATS_COUNTER_LIST_* is a very large macro that is causing MSVC
    1388             : // Intellisense to crash.  It was broken into two macros (each of length 40
    1389             : // lines) rather than one macro (of length about 80 lines) to work around
    1390             : // this problem.  Please avoid using recursive macros of this length when
    1391             : // possible.
    1392             : #define STATS_COUNTER_LIST_1(SC)                                    \
    1393             :   /* Global Handle Count*/                                          \
    1394             :   SC(global_handles, V8.GlobalHandles)                              \
    1395             :   /* OS Memory allocated */                                         \
    1396             :   SC(memory_allocated, V8.OsMemoryAllocated)                        \
    1397             :   SC(maps_normalized, V8.MapsNormalized)                            \
    1398             :   SC(maps_created, V8.MapsCreated)                                  \
    1399             :   SC(elements_transitions, V8.ObjectElementsTransitions)            \
    1400             :   SC(props_to_dictionary, V8.ObjectPropertiesToDictionary)          \
    1401             :   SC(elements_to_dictionary, V8.ObjectElementsToDictionary)         \
    1402             :   SC(alive_after_last_gc, V8.AliveAfterLastGC)                      \
    1403             :   SC(objs_since_last_young, V8.ObjsSinceLastYoung)                  \
    1404             :   SC(objs_since_last_full, V8.ObjsSinceLastFull)                    \
    1405             :   SC(string_table_capacity, V8.StringTableCapacity)                 \
    1406             :   SC(number_of_symbols, V8.NumberOfSymbols)                         \
    1407             :   SC(inlined_copied_elements, V8.InlinedCopiedElements)             \
    1408             :   SC(compilation_cache_hits, V8.CompilationCacheHits)               \
    1409             :   SC(compilation_cache_misses, V8.CompilationCacheMisses)           \
    1410             :   /* Amount of evaled source code. */                               \
    1411             :   SC(total_eval_size, V8.TotalEvalSize)                             \
    1412             :   /* Amount of loaded source code. */                               \
    1413             :   SC(total_load_size, V8.TotalLoadSize)                             \
    1414             :   /* Amount of parsed source code. */                               \
    1415             :   SC(total_parse_size, V8.TotalParseSize)                           \
    1416             :   /* Amount of source code skipped over using preparsing. */        \
    1417             :   SC(total_preparse_skipped, V8.TotalPreparseSkipped)               \
    1418             :   /* Amount of compiled source code. */                             \
    1419             :   SC(total_compile_size, V8.TotalCompileSize)                       \
    1420             :   /* Amount of source code compiled with the full codegen. */       \
    1421             :   SC(total_full_codegen_source_size, V8.TotalFullCodegenSourceSize) \
    1422             :   /* Number of contexts created from scratch. */                    \
    1423             :   SC(contexts_created_from_scratch, V8.ContextsCreatedFromScratch)  \
    1424             :   /* Number of contexts created by partial snapshot. */             \
    1425             :   SC(contexts_created_by_snapshot, V8.ContextsCreatedBySnapshot)    \
    1426             :   /* Number of code objects found from pc. */                       \
    1427             :   SC(pc_to_code, V8.PcToCode)                                       \
    1428             :   SC(pc_to_code_cached, V8.PcToCodeCached)                          \
    1429             :   /* The store-buffer implementation of the write barrier. */       \
    1430             :   SC(store_buffer_overflows, V8.StoreBufferOverflows)
    1431             : 
    1432             : #define STATS_COUNTER_LIST_2(SC)                                               \
    1433             :   /* Amount of (JS) compiled code. */                                          \
    1434             :   SC(total_compiled_code_size, V8.TotalCompiledCodeSize)                       \
    1435             :   SC(gc_compactor_caused_by_request, V8.GCCompactorCausedByRequest)            \
    1436             :   SC(gc_compactor_caused_by_promoted_data, V8.GCCompactorCausedByPromotedData) \
    1437             :   SC(gc_compactor_caused_by_oldspace_exhaustion,                               \
    1438             :      V8.GCCompactorCausedByOldspaceExhaustion)                                 \
    1439             :   SC(gc_last_resort_from_js, V8.GCLastResortFromJS)                            \
    1440             :   SC(gc_last_resort_from_handles, V8.GCLastResortFromHandles)                  \
    1441             :   SC(ic_keyed_load_generic_smi, V8.ICKeyedLoadGenericSmi)                      \
    1442             :   SC(ic_keyed_load_generic_symbol, V8.ICKeyedLoadGenericSymbol)                \
    1443             :   SC(ic_keyed_load_generic_slow, V8.ICKeyedLoadGenericSlow)                    \
    1444             :   SC(ic_named_load_global_stub, V8.ICNamedLoadGlobalStub)                      \
    1445             :   SC(ic_store_normal_miss, V8.ICStoreNormalMiss)                               \
    1446             :   SC(ic_store_normal_hit, V8.ICStoreNormalHit)                                 \
    1447             :   SC(ic_binary_op_miss, V8.ICBinaryOpMiss)                                     \
    1448             :   SC(ic_compare_miss, V8.ICCompareMiss)                                        \
    1449             :   SC(ic_call_miss, V8.ICCallMiss)                                              \
    1450             :   SC(ic_keyed_call_miss, V8.ICKeyedCallMiss)                                   \
    1451             :   SC(ic_store_miss, V8.ICStoreMiss)                                            \
    1452             :   SC(ic_keyed_store_miss, V8.ICKeyedStoreMiss)                                 \
    1453             :   SC(cow_arrays_converted, V8.COWArraysConverted)                              \
    1454             :   SC(constructed_objects, V8.ConstructedObjects)                               \
    1455             :   SC(constructed_objects_runtime, V8.ConstructedObjectsRuntime)                \
    1456             :   SC(megamorphic_stub_cache_probes, V8.MegamorphicStubCacheProbes)             \
    1457             :   SC(megamorphic_stub_cache_misses, V8.MegamorphicStubCacheMisses)             \
    1458             :   SC(megamorphic_stub_cache_updates, V8.MegamorphicStubCacheUpdates)           \
    1459             :   SC(enum_cache_hits, V8.EnumCacheHits)                                        \
    1460             :   SC(enum_cache_misses, V8.EnumCacheMisses)                                    \
    1461             :   SC(fast_new_closure_total, V8.FastNewClosureTotal)                           \
    1462             :   SC(string_add_runtime, V8.StringAddRuntime)                                  \
    1463             :   SC(string_add_native, V8.StringAddNative)                                    \
    1464             :   SC(sub_string_runtime, V8.SubStringRuntime)                                  \
    1465             :   SC(sub_string_native, V8.SubStringNative)                                    \
    1466             :   SC(regexp_entry_runtime, V8.RegExpEntryRuntime)                              \
    1467             :   SC(regexp_entry_native, V8.RegExpEntryNative)                                \
    1468             :   SC(math_exp_runtime, V8.MathExpRuntime)                                      \
    1469             :   SC(math_log_runtime, V8.MathLogRuntime)                                      \
    1470             :   SC(math_pow_runtime, V8.MathPowRuntime)                                      \
    1471             :   SC(stack_interrupts, V8.StackInterrupts)                                     \
    1472             :   SC(runtime_profiler_ticks, V8.RuntimeProfilerTicks)                          \
    1473             :   SC(runtime_calls, V8.RuntimeCalls)                                           \
    1474             :   SC(bounds_checks_eliminated, V8.BoundsChecksEliminated)                      \
    1475             :   SC(bounds_checks_hoisted, V8.BoundsChecksHoisted)                            \
    1476             :   SC(soft_deopts_requested, V8.SoftDeoptsRequested)                            \
    1477             :   SC(soft_deopts_inserted, V8.SoftDeoptsInserted)                              \
    1478             :   SC(soft_deopts_executed, V8.SoftDeoptsExecuted)                              \
    1479             :   /* Number of write barriers in generated code. */                            \
    1480             :   SC(write_barriers_dynamic, V8.WriteBarriersDynamic)                          \
    1481             :   SC(write_barriers_static, V8.WriteBarriersStatic)                            \
    1482             :   SC(new_space_bytes_available, V8.MemoryNewSpaceBytesAvailable)               \
    1483             :   SC(new_space_bytes_committed, V8.MemoryNewSpaceBytesCommitted)               \
    1484             :   SC(new_space_bytes_used, V8.MemoryNewSpaceBytesUsed)                         \
    1485             :   SC(old_space_bytes_available, V8.MemoryOldSpaceBytesAvailable)               \
    1486             :   SC(old_space_bytes_committed, V8.MemoryOldSpaceBytesCommitted)               \
    1487             :   SC(old_space_bytes_used, V8.MemoryOldSpaceBytesUsed)                         \
    1488             :   SC(code_space_bytes_available, V8.MemoryCodeSpaceBytesAvailable)             \
    1489             :   SC(code_space_bytes_committed, V8.MemoryCodeSpaceBytesCommitted)             \
    1490             :   SC(code_space_bytes_used, V8.MemoryCodeSpaceBytesUsed)                       \
    1491             :   SC(map_space_bytes_available, V8.MemoryMapSpaceBytesAvailable)               \
    1492             :   SC(map_space_bytes_committed, V8.MemoryMapSpaceBytesCommitted)               \
    1493             :   SC(map_space_bytes_used, V8.MemoryMapSpaceBytesUsed)                         \
    1494             :   SC(lo_space_bytes_available, V8.MemoryLoSpaceBytesAvailable)                 \
    1495             :   SC(lo_space_bytes_committed, V8.MemoryLoSpaceBytesCommitted)                 \
    1496             :   SC(lo_space_bytes_used, V8.MemoryLoSpaceBytesUsed)                           \
    1497             :   /* Total code size (including metadata) of baseline code or bytecode. */     \
    1498             :   SC(total_baseline_code_size, V8.TotalBaselineCodeSize)                       \
    1499             :   /* Total count of functions compiled using the baseline compiler. */         \
    1500             :   SC(total_baseline_compile_count, V8.TotalBaselineCompileCount)
    1501             : 
    1502             : #define STATS_COUNTER_TS_LIST(SC)                                    \
    1503             :   SC(wasm_generated_code_size, V8.WasmGeneratedCodeBytes)            \
    1504             :   SC(wasm_reloc_size, V8.WasmRelocBytes)                             \
    1505             :   SC(wasm_lazily_compiled_functions, V8.WasmLazilyCompiledFunctions) \
    1506             :   SC(liftoff_compiled_functions, V8.LiftoffCompiledFunctions)        \
    1507             :   SC(liftoff_unsupported_functions, V8.LiftoffUnsupportedFunctions)
    1508             : 
    1509             : // This file contains all the v8 counters that are in use.
    1510      123037 : class Counters : public std::enable_shared_from_this<Counters> {
    1511             :  public:
    1512             :   explicit Counters(Isolate* isolate);
    1513             : 
    1514             :   // Register an application-defined function for recording
    1515             :   // subsequent counter statistics. Note: Must be called on the main
    1516             :   // thread.
    1517             :   void ResetCounterFunction(CounterLookupCallback f);
    1518             : 
    1519             :   // Register an application-defined function to create histograms for
    1520             :   // recording subsequent histogram samples. Note: Must be called on
    1521             :   // the main thread.
    1522             :   void ResetCreateHistogramFunction(CreateHistogramCallback f);
    1523             : 
    1524             :   // Register an application-defined function to add a sample
    1525             :   // to a histogram. Will be used in all subsequent sample additions.
    1526             :   // Note: Must be called on the main thread.
    1527             :   void SetAddHistogramSampleFunction(AddHistogramSampleCallback f) {
    1528             :     stats_table_.SetAddHistogramSampleFunction(f);
    1529             :   }
    1530             : 
    1531             : #define HR(name, caption, min, max, num_buckets) \
    1532             :   Histogram* name() { return &name##_; }
    1533     4505244 :   HISTOGRAM_RANGE_LIST(HR)
    1534             : #undef HR
    1535             : 
    1536             : #define HT(name, caption, max, res) \
    1537             :   HistogramTimer* name() { return &name##_; }
    1538     2499491 :   HISTOGRAM_TIMER_LIST(HT)
    1539             : #undef HT
    1540             : 
    1541             : #define HT(name, caption, max, res) \
    1542             :   TimedHistogram* name() { return &name##_; }
    1543     3086287 :   TIMED_HISTOGRAM_LIST(HT)
    1544             : #undef HT
    1545             : 
    1546             : #define AHT(name, caption) \
    1547             :   AggregatableHistogramTimer* name() { return &name##_; }
    1548      837174 :   AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT)
    1549             : #undef AHT
    1550             : 
    1551             : #define HP(name, caption) \
    1552             :   Histogram* name() { return &name##_; }
    1553      398190 :   HISTOGRAM_PERCENTAGE_LIST(HP)
    1554             : #undef HP
    1555             : 
    1556             : #define HM(name, caption) \
    1557             :   Histogram* name() { return &name##_; }
    1558      474640 :   HISTOGRAM_LEGACY_MEMORY_LIST(HM)
    1559             : #undef HM
    1560             : 
    1561             : #define SC(name, caption) \
    1562             :   StatsCounter* name() { return &name##_; }
    1563   175142689 :   STATS_COUNTER_LIST_1(SC)
    1564    27844598 :   STATS_COUNTER_LIST_2(SC)
    1565             : #undef SC
    1566             : 
    1567             : #define SC(name, caption) \
    1568             :   StatsCounterThreadSafe* name() { return &name##_; }
    1569     3158705 :   STATS_COUNTER_TS_LIST(SC)
    1570             : #undef SC
    1571             : 
    1572             :   // clang-format off
    1573             :   enum Id {
    1574             : #define RATE_ID(name, caption, max, res) k_##name,
    1575             :     HISTOGRAM_TIMER_LIST(RATE_ID)
    1576             :     TIMED_HISTOGRAM_LIST(RATE_ID)
    1577             : #undef RATE_ID
    1578             : #define AGGREGATABLE_ID(name, caption) k_##name,
    1579             :     AGGREGATABLE_HISTOGRAM_TIMER_LIST(AGGREGATABLE_ID)
    1580             : #undef AGGREGATABLE_ID
    1581             : #define PERCENTAGE_ID(name, caption) k_##name,
    1582             :     HISTOGRAM_PERCENTAGE_LIST(PERCENTAGE_ID)
    1583             : #undef PERCENTAGE_ID
    1584             : #define MEMORY_ID(name, caption) k_##name,
    1585             :     HISTOGRAM_LEGACY_MEMORY_LIST(MEMORY_ID)
    1586             : #undef MEMORY_ID
    1587             : #define COUNTER_ID(name, caption) k_##name,
    1588             :     STATS_COUNTER_LIST_1(COUNTER_ID)
    1589             :     STATS_COUNTER_LIST_2(COUNTER_ID)
    1590             :     STATS_COUNTER_TS_LIST(COUNTER_ID)
    1591             : #undef COUNTER_ID
    1592             : #define COUNTER_ID(name) kCountOf##name, kSizeOf##name,
    1593             :     INSTANCE_TYPE_LIST(COUNTER_ID)
    1594             : #undef COUNTER_ID
    1595             : #define COUNTER_ID(name) kCountOfCODE_TYPE_##name, \
    1596             :     kSizeOfCODE_TYPE_##name,
    1597             :     CODE_KIND_LIST(COUNTER_ID)
    1598             : #undef COUNTER_ID
    1599             : #define COUNTER_ID(name) kCountOfFIXED_ARRAY__##name, \
    1600             :     kSizeOfFIXED_ARRAY__##name,
    1601             :     FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(COUNTER_ID)
    1602             : #undef COUNTER_ID
    1603             :     stats_counter_count
    1604             :   };
    1605             :   // clang-format on
    1606             : 
    1607     3001787 :   RuntimeCallStats* runtime_call_stats() { return &runtime_call_stats_; }
    1608             : 
    1609             :   WorkerThreadRuntimeCallStats* worker_thread_runtime_call_stats() {
    1610       81937 :     return &worker_thread_runtime_call_stats_;
    1611             :   }
    1612             : 
    1613             :  private:
    1614             :   friend class StatsTable;
    1615             :   friend class StatsCounterBase;
    1616             :   friend class Histogram;
    1617             :   friend class HistogramTimer;
    1618             : 
    1619             :   Isolate* isolate_;
    1620             :   StatsTable stats_table_;
    1621             : 
    1622             :   int* FindLocation(const char* name) {
    1623             :     return stats_table_.FindLocation(name);
    1624             :   }
    1625             : 
    1626             :   void* CreateHistogram(const char* name, int min, int max, size_t buckets) {
    1627             :     return stats_table_.CreateHistogram(name, min, max, buckets);
    1628             :   }
    1629             : 
    1630             :   void AddHistogramSample(void* histogram, int sample) {
    1631             :     stats_table_.AddHistogramSample(histogram, sample);
    1632             :   }
    1633             : 
    1634             :   Isolate* isolate() { return isolate_; }
    1635             : 
    1636             : #define HR(name, caption, min, max, num_buckets) Histogram name##_;
    1637             :   HISTOGRAM_RANGE_LIST(HR)
    1638             : #undef HR
    1639             : 
    1640             : #define HT(name, caption, max, res) HistogramTimer name##_;
    1641             :   HISTOGRAM_TIMER_LIST(HT)
    1642             : #undef HT
    1643             : 
    1644             : #define HT(name, caption, max, res) TimedHistogram name##_;
    1645             :   TIMED_HISTOGRAM_LIST(HT)
    1646             : #undef HT
    1647             : 
    1648             : #define AHT(name, caption) \
    1649             :   AggregatableHistogramTimer name##_;
    1650             :   AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT)
    1651             : #undef AHT
    1652             : 
    1653             : #define HP(name, caption) \
    1654             :   Histogram name##_;
    1655             :   HISTOGRAM_PERCENTAGE_LIST(HP)
    1656             : #undef HP
    1657             : 
    1658             : #define HM(name, caption) \
    1659             :   Histogram name##_;
    1660             :   HISTOGRAM_LEGACY_MEMORY_LIST(HM)
    1661             : #undef HM
    1662             : 
    1663             : #define SC(name, caption) \
    1664             :   StatsCounter name##_;
    1665             :   STATS_COUNTER_LIST_1(SC)
    1666             :   STATS_COUNTER_LIST_2(SC)
    1667             : #undef SC
    1668             : 
    1669             : #define SC(name, caption) StatsCounterThreadSafe name##_;
    1670             :   STATS_COUNTER_TS_LIST(SC)
    1671             : #undef SC
    1672             : 
    1673             : #define SC(name) \
    1674             :   StatsCounter size_of_##name##_; \
    1675             :   StatsCounter count_of_##name##_;
    1676             :   INSTANCE_TYPE_LIST(SC)
    1677             : #undef SC
    1678             : 
    1679             : #define SC(name) \
    1680             :   StatsCounter size_of_CODE_TYPE_##name##_; \
    1681             :   StatsCounter count_of_CODE_TYPE_##name##_;
    1682             :   CODE_KIND_LIST(SC)
    1683             : #undef SC
    1684             : 
    1685             : #define SC(name) \
    1686             :   StatsCounter size_of_FIXED_ARRAY_##name##_; \
    1687             :   StatsCounter count_of_FIXED_ARRAY_##name##_;
    1688             :   FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(SC)
    1689             : #undef SC
    1690             : 
    1691             :   RuntimeCallStats runtime_call_stats_;
    1692             :   WorkerThreadRuntimeCallStats worker_thread_runtime_call_stats_;
    1693             : 
    1694             :   DISALLOW_IMPLICIT_CONSTRUCTORS(Counters);
    1695             : };
    1696             : 
    1697             : void HistogramTimer::Start() {
    1698     2653820 :   TimedHistogram::Start(&timer_, counters()->isolate());
    1699             : }
    1700             : 
    1701             : void HistogramTimer::Stop() {
    1702     2653814 :   TimedHistogram::Stop(&timer_, counters()->isolate());
    1703             : }
    1704             : 
    1705   152157490 : RuntimeCallTimerScope::RuntimeCallTimerScope(Isolate* isolate,
    1706   152157490 :                                              RuntimeCallCounterId counter_id) {
    1707   152157490 :   if (V8_LIKELY(!TracingFlags::is_runtime_stats_enabled())) return;
    1708       19308 :   stats_ = isolate->counters()->runtime_call_stats();
    1709       19308 :   stats_->Enter(&timer_, counter_id);
    1710             : }
    1711             : 
    1712             : }  // namespace internal
    1713             : }  // namespace v8
    1714             : 
    1715             : #endif  // V8_COUNTERS_H_

Generated by: LCOV version 1.10