LCOV - code coverage report
Current view: top level - src - counters.h (source / functions) Hit Total Coverage
Test: app.info Lines: 120 132 90.9 %
Date: 2019-02-19 Functions: 27 31 87.1 %

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

Generated by: LCOV version 1.10