LCOV - code coverage report
Current view: top level - src - counters.h (source / functions) Hit Total Coverage
Test: app.info Lines: 126 136 92.6 %
Date: 2019-01-20 Functions: 17 20 85.0 %

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

Generated by: LCOV version 1.10