Home | History | Annotate | Download | only in src
      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/builtins/builtins.h"
     14 #include "src/globals.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 StatsTable {
     30  public:
     31   // Register an application-defined function where
     32   // counters can be looked up.
     33   void SetCounterFunction(CounterLookupCallback f) {
     34     lookup_function_ = f;
     35   }
     36 
     37   // Register an application-defined function to create
     38   // a histogram for passing to the AddHistogramSample function
     39   void SetCreateHistogramFunction(CreateHistogramCallback f) {
     40     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     add_histogram_sample_function_ = f;
     47   }
     48 
     49   bool HasCounterFunction() const {
     50     return lookup_function_ != NULL;
     51   }
     52 
     53   // Lookup the location of a counter by name.  If the lookup
     54   // is successful, returns a non-NULL pointer for writing the
     55   // value of the counter.  Each thread calling this function
     56   // may receive a different location to store it's counter.
     57   // The return value must not be cached and re-used across
     58   // threads, although a single thread is free to cache it.
     59   int* FindLocation(const char* name) {
     60     if (!lookup_function_) return NULL;
     61     return lookup_function_(name);
     62   }
     63 
     64   // Create a histogram by name. If the create is successful,
     65   // returns a non-NULL pointer for use with AddHistogramSample
     66   // function. min and max define the expected minimum and maximum
     67   // sample values. buckets is the maximum number of buckets
     68   // that the samples will be grouped into.
     69   void* CreateHistogram(const char* name,
     70                         int min,
     71                         int max,
     72                         size_t buckets) {
     73     if (!create_histogram_function_) return NULL;
     74     return create_histogram_function_(name, min, max, buckets);
     75   }
     76 
     77   // Add a sample to a histogram created with the CreateHistogram
     78   // function.
     79   void AddHistogramSample(void* histogram, int sample) {
     80     if (!add_histogram_sample_function_) return;
     81     return add_histogram_sample_function_(histogram, sample);
     82   }
     83 
     84  private:
     85   StatsTable();
     86 
     87   CounterLookupCallback lookup_function_;
     88   CreateHistogramCallback create_histogram_function_;
     89   AddHistogramSampleCallback add_histogram_sample_function_;
     90 
     91   friend class Isolate;
     92 
     93   DISALLOW_COPY_AND_ASSIGN(StatsTable);
     94 };
     95 
     96 // StatsCounters are dynamically created values which can be tracked in
     97 // the StatsTable.  They are designed to be lightweight to create and
     98 // easy to use.
     99 //
    100 // Internally, a counter represents a value in a row of a StatsTable.
    101 // The row has a 32bit value for each process/thread in the table and also
    102 // a name (stored in the table metadata).  Since the storage location can be
    103 // thread-specific, this class cannot be shared across threads.
    104 class StatsCounter {
    105  public:
    106   StatsCounter() { }
    107   explicit StatsCounter(Isolate* isolate, const char* name)
    108       : isolate_(isolate), name_(name), ptr_(NULL), lookup_done_(false) { }
    109 
    110   // Sets the counter to a specific value.
    111   void Set(int value) {
    112     int* loc = GetPtr();
    113     if (loc) *loc = value;
    114   }
    115 
    116   // Increments the counter.
    117   void Increment() {
    118     int* loc = GetPtr();
    119     if (loc) (*loc)++;
    120   }
    121 
    122   void Increment(int value) {
    123     int* loc = GetPtr();
    124     if (loc)
    125       (*loc) += value;
    126   }
    127 
    128   // Decrements the counter.
    129   void Decrement() {
    130     int* loc = GetPtr();
    131     if (loc) (*loc)--;
    132   }
    133 
    134   void Decrement(int value) {
    135     int* loc = GetPtr();
    136     if (loc) (*loc) -= value;
    137   }
    138 
    139   // Is this counter enabled?
    140   // Returns false if table is full.
    141   bool Enabled() {
    142     return GetPtr() != NULL;
    143   }
    144 
    145   // Get the internal pointer to the counter. This is used
    146   // by the code generator to emit code that manipulates a
    147   // given counter without calling the runtime system.
    148   int* GetInternalPointer() {
    149     int* loc = GetPtr();
    150     DCHECK(loc != NULL);
    151     return loc;
    152   }
    153 
    154   // Reset the cached internal pointer.
    155   void Reset() { lookup_done_ = false; }
    156 
    157  protected:
    158   // Returns the cached address of this counter location.
    159   int* GetPtr() {
    160     if (lookup_done_) return ptr_;
    161     lookup_done_ = true;
    162     ptr_ = FindLocationInStatsTable();
    163     return ptr_;
    164   }
    165 
    166  private:
    167   int* FindLocationInStatsTable() const;
    168 
    169   Isolate* isolate_;
    170   const char* name_;
    171   int* ptr_;
    172   bool lookup_done_;
    173 };
    174 
    175 // A Histogram represents a dynamically created histogram in the StatsTable.
    176 // It will be registered with the histogram system on first use.
    177 class Histogram {
    178  public:
    179   Histogram() { }
    180   Histogram(const char* name,
    181             int min,
    182             int max,
    183             int num_buckets,
    184             Isolate* isolate)
    185       : name_(name),
    186         min_(min),
    187         max_(max),
    188         num_buckets_(num_buckets),
    189         histogram_(NULL),
    190         lookup_done_(false),
    191         isolate_(isolate) { }
    192 
    193   // Add a single sample to this histogram.
    194   void AddSample(int sample);
    195 
    196   // Returns true if this histogram is enabled.
    197   bool Enabled() {
    198     return GetHistogram() != NULL;
    199   }
    200 
    201   // Reset the cached internal pointer.
    202   void Reset() {
    203     lookup_done_ = false;
    204   }
    205 
    206   const char* name() { return name_; }
    207 
    208  protected:
    209   // Returns the handle to the histogram.
    210   void* GetHistogram() {
    211     if (!lookup_done_) {
    212       lookup_done_ = true;
    213       histogram_ = CreateHistogram();
    214     }
    215     return histogram_;
    216   }
    217 
    218   Isolate* isolate() const { return isolate_; }
    219 
    220  private:
    221   void* CreateHistogram() const;
    222 
    223   const char* name_;
    224   int min_;
    225   int max_;
    226   int num_buckets_;
    227   void* histogram_;
    228   bool lookup_done_;
    229   Isolate* isolate_;
    230 };
    231 
    232 // A HistogramTimer allows distributions of results to be created.
    233 class HistogramTimer : public Histogram {
    234  public:
    235   enum Resolution {
    236     MILLISECOND,
    237     MICROSECOND
    238   };
    239 
    240   HistogramTimer() {}
    241   HistogramTimer(const char* name, int min, int max, Resolution resolution,
    242                  int num_buckets, Isolate* isolate)
    243       : Histogram(name, min, max, num_buckets, isolate),
    244         resolution_(resolution) {}
    245 
    246   // Start the timer.
    247   void Start();
    248 
    249   // Stop the timer and record the results.
    250   void Stop();
    251 
    252   // Returns true if the timer is running.
    253   bool Running() {
    254     return Enabled() && timer_.IsStarted();
    255   }
    256 
    257   // TODO(bmeurer): Remove this when HistogramTimerScope is fixed.
    258 #ifdef DEBUG
    259   base::ElapsedTimer* timer() { return &timer_; }
    260 #endif
    261 
    262  private:
    263   base::ElapsedTimer timer_;
    264   Resolution resolution_;
    265 };
    266 
    267 // Helper class for scoping a HistogramTimer.
    268 // TODO(bmeurer): The ifdeffery is an ugly hack around the fact that the
    269 // Parser is currently reentrant (when it throws an error, we call back
    270 // into JavaScript and all bets are off), but ElapsedTimer is not
    271 // reentry-safe. Fix this properly and remove |allow_nesting|.
    272 class HistogramTimerScope BASE_EMBEDDED {
    273  public:
    274   explicit HistogramTimerScope(HistogramTimer* timer,
    275                                bool allow_nesting = false)
    276 #ifdef DEBUG
    277       : timer_(timer),
    278         skipped_timer_start_(false) {
    279     if (timer_->timer()->IsStarted() && allow_nesting) {
    280       skipped_timer_start_ = true;
    281     } else {
    282       timer_->Start();
    283     }
    284   }
    285 #else
    286       : timer_(timer) {
    287     timer_->Start();
    288   }
    289 #endif
    290   ~HistogramTimerScope() {
    291 #ifdef DEBUG
    292     if (!skipped_timer_start_) {
    293       timer_->Stop();
    294     }
    295 #else
    296     timer_->Stop();
    297 #endif
    298   }
    299 
    300  private:
    301   HistogramTimer* timer_;
    302 #ifdef DEBUG
    303   bool skipped_timer_start_;
    304 #endif
    305 };
    306 
    307 
    308 // A histogram timer that can aggregate events within a larger scope.
    309 //
    310 // Intended use of this timer is to have an outer (aggregating) and an inner
    311 // (to be aggregated) scope, where the inner scope measure the time of events,
    312 // and all those inner scope measurements will be summed up by the outer scope.
    313 // An example use might be to aggregate the time spent in lazy compilation
    314 // while running a script.
    315 //
    316 // Helpers:
    317 // - AggregatingHistogramTimerScope, the "outer" scope within which
    318 //     times will be summed up.
    319 // - AggregatedHistogramTimerScope, the "inner" scope which defines the
    320 //     events to be timed.
    321 class AggregatableHistogramTimer : public Histogram {
    322  public:
    323   AggregatableHistogramTimer() {}
    324   AggregatableHistogramTimer(const char* name, int min, int max,
    325                              int num_buckets, Isolate* isolate)
    326       : Histogram(name, min, max, num_buckets, isolate) {}
    327 
    328   // Start/stop the "outer" scope.
    329   void Start() { time_ = base::TimeDelta(); }
    330   void Stop() { AddSample(static_cast<int>(time_.InMicroseconds())); }
    331 
    332   // Add a time value ("inner" scope).
    333   void Add(base::TimeDelta other) { time_ += other; }
    334 
    335  private:
    336   base::TimeDelta time_;
    337 };
    338 
    339 // A helper class for use with AggregatableHistogramTimer. This is the
    340 // // outer-most timer scope used with an AggregatableHistogramTimer. It will
    341 // // aggregate the information from the inner AggregatedHistogramTimerScope.
    342 class AggregatingHistogramTimerScope {
    343  public:
    344   explicit AggregatingHistogramTimerScope(AggregatableHistogramTimer* histogram)
    345       : histogram_(histogram) {
    346     histogram_->Start();
    347   }
    348   ~AggregatingHistogramTimerScope() { histogram_->Stop(); }
    349 
    350  private:
    351   AggregatableHistogramTimer* histogram_;
    352 };
    353 
    354 // A helper class for use with AggregatableHistogramTimer, the "inner" scope
    355 // // which defines the events to be timed.
    356 class AggregatedHistogramTimerScope {
    357  public:
    358   explicit AggregatedHistogramTimerScope(AggregatableHistogramTimer* histogram)
    359       : histogram_(histogram) {
    360     timer_.Start();
    361   }
    362   ~AggregatedHistogramTimerScope() { histogram_->Add(timer_.Elapsed()); }
    363 
    364  private:
    365   base::ElapsedTimer timer_;
    366   AggregatableHistogramTimer* histogram_;
    367 };
    368 
    369 
    370 // AggretatedMemoryHistogram collects (time, value) sample pairs and turns
    371 // them into time-uniform samples for the backing historgram, such that the
    372 // backing histogram receives one sample every T ms, where the T is controlled
    373 // by the FLAG_histogram_interval.
    374 //
    375 // More formally: let F be a real-valued function that maps time to sample
    376 // values. We define F as a linear interpolation between adjacent samples. For
    377 // each time interval [x; x + T) the backing histogram gets one sample value
    378 // that is the average of F(t) in the interval.
    379 template <typename Histogram>
    380 class AggregatedMemoryHistogram {
    381  public:
    382   AggregatedMemoryHistogram()
    383       : is_initialized_(false),
    384         start_ms_(0.0),
    385         last_ms_(0.0),
    386         aggregate_value_(0.0),
    387         last_value_(0.0),
    388         backing_histogram_(NULL) {}
    389 
    390   explicit AggregatedMemoryHistogram(Histogram* backing_histogram)
    391       : AggregatedMemoryHistogram() {
    392     backing_histogram_ = backing_histogram;
    393   }
    394 
    395   // Invariants that hold before and after AddSample if
    396   // is_initialized_ is true:
    397   //
    398   // 1) For we processed samples that came in before start_ms_ and sent the
    399   // corresponding aggregated samples to backing histogram.
    400   // 2) (last_ms_, last_value_) is the last received sample.
    401   // 3) last_ms_ < start_ms_ + FLAG_histogram_interval.
    402   // 4) aggregate_value_ is the average of the function that is constructed by
    403   // linearly interpolating samples received between start_ms_ and last_ms_.
    404   void AddSample(double current_ms, double current_value);
    405 
    406  private:
    407   double Aggregate(double current_ms, double current_value);
    408   bool is_initialized_;
    409   double start_ms_;
    410   double last_ms_;
    411   double aggregate_value_;
    412   double last_value_;
    413   Histogram* backing_histogram_;
    414 };
    415 
    416 
    417 template <typename Histogram>
    418 void AggregatedMemoryHistogram<Histogram>::AddSample(double current_ms,
    419                                                      double current_value) {
    420   if (!is_initialized_) {
    421     aggregate_value_ = current_value;
    422     start_ms_ = current_ms;
    423     last_value_ = current_value;
    424     last_ms_ = current_ms;
    425     is_initialized_ = true;
    426   } else {
    427     const double kEpsilon = 1e-6;
    428     const int kMaxSamples = 1000;
    429     if (current_ms < last_ms_ + kEpsilon) {
    430       // Two samples have the same time, remember the last one.
    431       last_value_ = current_value;
    432     } else {
    433       double sample_interval_ms = FLAG_histogram_interval;
    434       double end_ms = start_ms_ + sample_interval_ms;
    435       if (end_ms <= current_ms + kEpsilon) {
    436         // Linearly interpolate between the last_ms_ and the current_ms.
    437         double slope = (current_value - last_value_) / (current_ms - last_ms_);
    438         int i;
    439         // Send aggregated samples to the backing histogram from the start_ms
    440         // to the current_ms.
    441         for (i = 0; i < kMaxSamples && end_ms <= current_ms + kEpsilon; i++) {
    442           double end_value = last_value_ + (end_ms - last_ms_) * slope;
    443           double sample_value;
    444           if (i == 0) {
    445             // Take aggregate_value_ into account.
    446             sample_value = Aggregate(end_ms, end_value);
    447           } else {
    448             // There is no aggregate_value_ for i > 0.
    449             sample_value = (last_value_ + end_value) / 2;
    450           }
    451           backing_histogram_->AddSample(static_cast<int>(sample_value + 0.5));
    452           last_value_ = end_value;
    453           last_ms_ = end_ms;
    454           end_ms += sample_interval_ms;
    455         }
    456         if (i == kMaxSamples) {
    457           // We hit the sample limit, ignore the remaining samples.
    458           aggregate_value_ = current_value;
    459           start_ms_ = current_ms;
    460         } else {
    461           aggregate_value_ = last_value_;
    462           start_ms_ = last_ms_;
    463         }
    464       }
    465       aggregate_value_ = current_ms > start_ms_ + kEpsilon
    466                              ? Aggregate(current_ms, current_value)
    467                              : aggregate_value_;
    468       last_value_ = current_value;
    469       last_ms_ = current_ms;
    470     }
    471   }
    472 }
    473 
    474 
    475 template <typename Histogram>
    476 double AggregatedMemoryHistogram<Histogram>::Aggregate(double current_ms,
    477                                                        double current_value) {
    478   double interval_ms = current_ms - start_ms_;
    479   double value = (current_value + last_value_) / 2;
    480   // The aggregate_value_ is the average for [start_ms_; last_ms_].
    481   // The value is the average for [last_ms_; current_ms].
    482   // Return the weighted average of the aggregate_value_ and the value.
    483   return aggregate_value_ * ((last_ms_ - start_ms_) / interval_ms) +
    484          value * ((current_ms - last_ms_) / interval_ms);
    485 }
    486 
    487 struct RuntimeCallCounter {
    488   explicit RuntimeCallCounter(const char* name) : name(name) {}
    489   V8_NOINLINE void Reset();
    490   V8_NOINLINE void Dump(v8::tracing::TracedValue* value);
    491   void Add(RuntimeCallCounter* other);
    492 
    493   const char* name;
    494   int64_t count = 0;
    495   base::TimeDelta time;
    496 };
    497 
    498 // RuntimeCallTimer is used to keep track of the stack of currently active
    499 // timers used for properly measuring the own time of a RuntimeCallCounter.
    500 class RuntimeCallTimer {
    501  public:
    502   RuntimeCallCounter* counter() { return counter_; }
    503   base::ElapsedTimer timer() { return timer_; }
    504   RuntimeCallTimer* parent() const { return parent_.Value(); }
    505 
    506  private:
    507   friend class RuntimeCallStats;
    508 
    509   inline void Start(RuntimeCallCounter* counter, RuntimeCallTimer* parent) {
    510     counter_ = counter;
    511     parent_.SetValue(parent);
    512     if (FLAG_runtime_stats !=
    513         v8::tracing::TracingCategoryObserver::ENABLED_BY_SAMPLING) {
    514       timer_.Start();
    515     }
    516   }
    517 
    518   inline RuntimeCallTimer* Stop() {
    519     if (!timer_.IsStarted()) return parent();
    520     base::TimeDelta delta = timer_.Elapsed();
    521     timer_.Stop();
    522     counter_->count++;
    523     counter_->time += delta;
    524     if (parent()) {
    525       // Adjust parent timer so that it does not include sub timer's time.
    526       parent()->counter_->time -= delta;
    527     }
    528     return parent();
    529   }
    530 
    531   inline void Elapsed() {
    532     base::TimeDelta delta = timer_.Elapsed();
    533     counter_->time += delta;
    534     if (parent()) {
    535       parent()->counter_->time -= delta;
    536       parent()->Elapsed();
    537     }
    538     timer_.Restart();
    539   }
    540 
    541   const char* name() { return counter_->name; }
    542 
    543   RuntimeCallCounter* counter_ = nullptr;
    544   base::AtomicValue<RuntimeCallTimer*> parent_;
    545   base::ElapsedTimer timer_;
    546 };
    547 
    548 #define FOR_EACH_API_COUNTER(V)                            \
    549   V(ArrayBuffer_Cast)                                      \
    550   V(ArrayBuffer_Neuter)                                    \
    551   V(ArrayBuffer_New)                                       \
    552   V(Array_CloneElementAt)                                  \
    553   V(Array_New)                                             \
    554   V(BooleanObject_BooleanValue)                            \
    555   V(BooleanObject_New)                                     \
    556   V(Context_New)                                           \
    557   V(Context_NewRemoteContext)                              \
    558   V(DataView_New)                                          \
    559   V(Date_DateTimeConfigurationChangeNotification)          \
    560   V(Date_New)                                              \
    561   V(Date_NumberValue)                                      \
    562   V(Debug_Call)                                            \
    563   V(Debug_GetMirror)                                       \
    564   V(Error_New)                                             \
    565   V(External_New)                                          \
    566   V(Float32Array_New)                                      \
    567   V(Float64Array_New)                                      \
    568   V(Function_Call)                                         \
    569   V(Function_New)                                          \
    570   V(Function_NewInstance)                                  \
    571   V(FunctionTemplate_GetFunction)                          \
    572   V(FunctionTemplate_New)                                  \
    573   V(FunctionTemplate_NewRemoteInstance)                    \
    574   V(FunctionTemplate_NewWithFastHandler)                   \
    575   V(Int16Array_New)                                        \
    576   V(Int32Array_New)                                        \
    577   V(Int8Array_New)                                         \
    578   V(JSON_Parse)                                            \
    579   V(JSON_Stringify)                                        \
    580   V(Map_AsArray)                                           \
    581   V(Map_Clear)                                             \
    582   V(Map_Delete)                                            \
    583   V(Map_Get)                                               \
    584   V(Map_Has)                                               \
    585   V(Map_New)                                               \
    586   V(Map_Set)                                               \
    587   V(Message_GetEndColumn)                                  \
    588   V(Message_GetLineNumber)                                 \
    589   V(Message_GetSourceLine)                                 \
    590   V(Message_GetStartColumn)                                \
    591   V(Module_Evaluate)                                       \
    592   V(Module_Instantiate)                                    \
    593   V(NumberObject_New)                                      \
    594   V(NumberObject_NumberValue)                              \
    595   V(Object_CallAsConstructor)                              \
    596   V(Object_CallAsFunction)                                 \
    597   V(Object_CreateDataProperty)                             \
    598   V(Object_DefineOwnProperty)                              \
    599   V(Object_DefineProperty)                                 \
    600   V(Object_Delete)                                         \
    601   V(Object_DeleteProperty)                                 \
    602   V(Object_ForceSet)                                       \
    603   V(Object_Get)                                            \
    604   V(Object_GetOwnPropertyDescriptor)                       \
    605   V(Object_GetOwnPropertyNames)                            \
    606   V(Object_GetPropertyAttributes)                          \
    607   V(Object_GetPropertyNames)                               \
    608   V(Object_GetRealNamedProperty)                           \
    609   V(Object_GetRealNamedPropertyAttributes)                 \
    610   V(Object_GetRealNamedPropertyAttributesInPrototypeChain) \
    611   V(Object_GetRealNamedPropertyInPrototypeChain)           \
    612   V(Object_HasOwnProperty)                                 \
    613   V(Object_HasRealIndexedProperty)                         \
    614   V(Object_HasRealNamedCallbackProperty)                   \
    615   V(Object_HasRealNamedProperty)                           \
    616   V(Object_Int32Value)                                     \
    617   V(Object_IntegerValue)                                   \
    618   V(Object_New)                                            \
    619   V(Object_NumberValue)                                    \
    620   V(Object_ObjectProtoToString)                            \
    621   V(Object_Set)                                            \
    622   V(Object_SetAccessor)                                    \
    623   V(Object_SetIntegrityLevel)                              \
    624   V(Object_SetPrivate)                                     \
    625   V(Object_SetPrototype)                                   \
    626   V(ObjectTemplate_New)                                    \
    627   V(ObjectTemplate_NewInstance)                            \
    628   V(Object_ToArrayIndex)                                   \
    629   V(Object_ToDetailString)                                 \
    630   V(Object_ToInt32)                                        \
    631   V(Object_ToInteger)                                      \
    632   V(Object_ToNumber)                                       \
    633   V(Object_ToObject)                                       \
    634   V(Object_ToString)                                       \
    635   V(Object_ToUint32)                                       \
    636   V(Object_Uint32Value)                                    \
    637   V(Persistent_New)                                        \
    638   V(Private_New)                                           \
    639   V(Promise_Catch)                                         \
    640   V(Promise_Chain)                                         \
    641   V(Promise_HasRejectHandler)                              \
    642   V(Promise_Resolver_New)                                  \
    643   V(Promise_Resolver_Resolve)                              \
    644   V(Promise_Then)                                          \
    645   V(Proxy_New)                                             \
    646   V(RangeError_New)                                        \
    647   V(ReferenceError_New)                                    \
    648   V(RegExp_New)                                            \
    649   V(ScriptCompiler_Compile)                                \
    650   V(ScriptCompiler_CompileFunctionInContext)               \
    651   V(ScriptCompiler_CompileUnbound)                         \
    652   V(Script_Run)                                            \
    653   V(Set_Add)                                               \
    654   V(Set_AsArray)                                           \
    655   V(Set_Clear)                                             \
    656   V(Set_Delete)                                            \
    657   V(Set_Has)                                               \
    658   V(Set_New)                                               \
    659   V(SharedArrayBuffer_New)                                 \
    660   V(String_Concat)                                         \
    661   V(String_NewExternalOneByte)                             \
    662   V(String_NewExternalTwoByte)                             \
    663   V(String_NewFromOneByte)                                 \
    664   V(String_NewFromTwoByte)                                 \
    665   V(String_NewFromUtf8)                                    \
    666   V(StringObject_New)                                      \
    667   V(StringObject_StringValue)                              \
    668   V(String_Write)                                          \
    669   V(String_WriteUtf8)                                      \
    670   V(Symbol_New)                                            \
    671   V(SymbolObject_New)                                      \
    672   V(SymbolObject_SymbolValue)                              \
    673   V(SyntaxError_New)                                       \
    674   V(TryCatch_StackTrace)                                   \
    675   V(TypeError_New)                                         \
    676   V(Uint16Array_New)                                       \
    677   V(Uint32Array_New)                                       \
    678   V(Uint8Array_New)                                        \
    679   V(Uint8ClampedArray_New)                                 \
    680   V(UnboundScript_GetId)                                   \
    681   V(UnboundScript_GetLineNumber)                           \
    682   V(UnboundScript_GetName)                                 \
    683   V(UnboundScript_GetSourceMappingURL)                     \
    684   V(UnboundScript_GetSourceURL)                            \
    685   V(Value_TypeOf)                                          \
    686   V(ValueDeserializer_ReadHeader)                          \
    687   V(ValueDeserializer_ReadValue)                           \
    688   V(ValueSerializer_WriteValue)
    689 
    690 #define FOR_EACH_MANUAL_COUNTER(V)                  \
    691   V(AccessorGetterCallback)                         \
    692   V(AccessorNameGetterCallback)                     \
    693   V(AccessorNameGetterCallback_ArrayLength)         \
    694   V(AccessorNameGetterCallback_BoundFunctionLength) \
    695   V(AccessorNameGetterCallback_BoundFunctionName)   \
    696   V(AccessorNameGetterCallback_FunctionPrototype)   \
    697   V(AccessorNameGetterCallback_StringLength)        \
    698   V(AccessorNameSetterCallback)                     \
    699   V(Compile)                                        \
    700   V(CompileCode)                                    \
    701   V(CompileCodeLazy)                                \
    702   V(CompileDeserialize)                             \
    703   V(CompileEval)                                    \
    704   V(CompileFullCode)                                \
    705   V(CompileIgnition)                                \
    706   V(CompilerDispatcher)                             \
    707   V(CompileSerialize)                               \
    708   V(DeoptimizeCode)                                 \
    709   V(FunctionCallback)                               \
    710   V(GC)                                             \
    711   V(GenericNamedPropertyDefinerCallback)            \
    712   V(GenericNamedPropertyDeleterCallback)            \
    713   V(GenericNamedPropertyDescriptorCallback)         \
    714   V(GenericNamedPropertyQueryCallback)              \
    715   V(GenericNamedPropertySetterCallback)             \
    716   V(IndexedPropertyDefinerCallback)                 \
    717   V(IndexedPropertyDeleterCallback)                 \
    718   V(IndexedPropertyDescriptorCallback)              \
    719   V(IndexedPropertyGetterCallback)                  \
    720   V(IndexedPropertyQueryCallback)                   \
    721   V(IndexedPropertySetterCallback)                  \
    722   V(InvokeApiInterruptCallbacks)                    \
    723   V(InvokeFunctionCallback)                         \
    724   V(JS_Execution)                                   \
    725   V(Map_SetPrototype)                               \
    726   V(Map_TransitionToAccessorProperty)               \
    727   V(Map_TransitionToDataProperty)                   \
    728   V(Object_DeleteProperty)                          \
    729   V(OptimizeCode)                                   \
    730   V(ParseArrowFunctionLiteral)                      \
    731   V(ParseEval)                                      \
    732   V(ParseFunction)                                  \
    733   V(ParseFunctionLiteral)                           \
    734   V(ParseProgram)                                   \
    735   V(PreParseArrowFunctionLiteral)                   \
    736   V(PreParseNoVariableResolution)                   \
    737   V(PreParseWithVariableResolution)                 \
    738   V(PropertyCallback)                               \
    739   V(PrototypeMap_TransitionToAccessorProperty)      \
    740   V(PrototypeMap_TransitionToDataProperty)          \
    741   V(PrototypeObject_DeleteProperty)                 \
    742   V(RecompileConcurrent)                            \
    743   V(RecompileSynchronous)                           \
    744   /* Dummy counter for the unexpected stub miss. */ \
    745   V(UnexpectedStubMiss)
    746 
    747 #define FOR_EACH_HANDLER_COUNTER(V)              \
    748   V(IC_HandlerCacheHit)                          \
    749   V(KeyedLoadIC_LoadIndexedStringStub)           \
    750   V(KeyedLoadIC_LoadIndexedInterceptorStub)      \
    751   V(KeyedLoadIC_KeyedLoadSloppyArgumentsStub)    \
    752   V(KeyedLoadIC_LoadElementDH)                   \
    753   V(KeyedLoadIC_LoadFastElementStub)             \
    754   V(KeyedLoadIC_LoadDictionaryElementStub)       \
    755   V(KeyedLoadIC_SlowStub)                        \
    756   V(KeyedStoreIC_ElementsTransitionAndStoreStub) \
    757   V(KeyedStoreIC_KeyedStoreSloppyArgumentsStub)  \
    758   V(KeyedStoreIC_SlowStub)                       \
    759   V(KeyedStoreIC_StoreFastElementStub)           \
    760   V(KeyedStoreIC_StoreElementStub)               \
    761   V(LoadIC_FunctionPrototypeStub)                \
    762   V(LoadIC_HandlerCacheHit_AccessCheck)          \
    763   V(LoadIC_HandlerCacheHit_Exotic)               \
    764   V(LoadIC_HandlerCacheHit_Interceptor)          \
    765   V(LoadIC_HandlerCacheHit_JSProxy)              \
    766   V(LoadIC_HandlerCacheHit_NonExistent)          \
    767   V(LoadIC_HandlerCacheHit_Accessor)             \
    768   V(LoadIC_HandlerCacheHit_Data)                 \
    769   V(LoadIC_HandlerCacheHit_Transition)           \
    770   V(LoadIC_LoadApiGetterDH)                      \
    771   V(LoadIC_LoadApiGetterFromPrototypeDH)         \
    772   V(LoadIC_LoadApiGetterStub)                    \
    773   V(LoadIC_LoadCallback)                         \
    774   V(LoadIC_LoadConstantDH)                       \
    775   V(LoadIC_LoadConstantFromPrototypeDH)          \
    776   V(LoadIC_LoadConstant)                         \
    777   V(LoadIC_LoadConstantStub)                     \
    778   V(LoadIC_LoadFieldDH)                          \
    779   V(LoadIC_LoadFieldFromPrototypeDH)             \
    780   V(LoadIC_LoadField)                            \
    781   V(LoadIC_LoadFieldStub)                        \
    782   V(LoadIC_LoadGlobal)                           \
    783   V(LoadIC_LoadInterceptor)                      \
    784   V(LoadIC_LoadNonexistentDH)                    \
    785   V(LoadIC_LoadNonexistent)                      \
    786   V(LoadIC_LoadNormal)                           \
    787   V(LoadIC_LoadScriptContextFieldStub)           \
    788   V(LoadIC_LoadViaGetter)                        \
    789   V(LoadIC_Premonomorphic)                       \
    790   V(LoadIC_SlowStub)                             \
    791   V(LoadIC_StringLengthStub)                     \
    792   V(StoreIC_HandlerCacheHit_AccessCheck)         \
    793   V(StoreIC_HandlerCacheHit_Exotic)              \
    794   V(StoreIC_HandlerCacheHit_Interceptor)         \
    795   V(StoreIC_HandlerCacheHit_JSProxy)             \
    796   V(StoreIC_HandlerCacheHit_NonExistent)         \
    797   V(StoreIC_HandlerCacheHit_Accessor)            \
    798   V(StoreIC_HandlerCacheHit_Data)                \
    799   V(StoreIC_HandlerCacheHit_Transition)          \
    800   V(StoreIC_Premonomorphic)                      \
    801   V(StoreIC_SlowStub)                            \
    802   V(StoreIC_StoreCallback)                       \
    803   V(StoreIC_StoreField)                          \
    804   V(StoreIC_StoreFieldDH)                        \
    805   V(StoreIC_StoreFieldStub)                      \
    806   V(StoreIC_StoreGlobal)                         \
    807   V(StoreIC_StoreGlobalTransition)               \
    808   V(StoreIC_StoreInterceptorStub)                \
    809   V(StoreIC_StoreNormal)                         \
    810   V(StoreIC_StoreScriptContextFieldStub)         \
    811   V(StoreIC_StoreTransition)                     \
    812   V(StoreIC_StoreTransitionDH)                   \
    813   V(StoreIC_StoreViaSetter)
    814 
    815 class RuntimeCallStats : public ZoneObject {
    816  public:
    817   typedef RuntimeCallCounter RuntimeCallStats::*CounterId;
    818 
    819 #define CALL_RUNTIME_COUNTER(name) \
    820   RuntimeCallCounter name = RuntimeCallCounter(#name);
    821   FOR_EACH_MANUAL_COUNTER(CALL_RUNTIME_COUNTER)
    822 #undef CALL_RUNTIME_COUNTER
    823 #define CALL_RUNTIME_COUNTER(name, nargs, ressize) \
    824   RuntimeCallCounter Runtime_##name = RuntimeCallCounter(#name);
    825   FOR_EACH_INTRINSIC(CALL_RUNTIME_COUNTER)
    826 #undef CALL_RUNTIME_COUNTER
    827 #define CALL_BUILTIN_COUNTER(name) \
    828   RuntimeCallCounter Builtin_##name = RuntimeCallCounter(#name);
    829   BUILTIN_LIST_C(CALL_BUILTIN_COUNTER)
    830 #undef CALL_BUILTIN_COUNTER
    831 #define CALL_BUILTIN_COUNTER(name) \
    832   RuntimeCallCounter API_##name = RuntimeCallCounter("API_" #name);
    833   FOR_EACH_API_COUNTER(CALL_BUILTIN_COUNTER)
    834 #undef CALL_BUILTIN_COUNTER
    835 #define CALL_BUILTIN_COUNTER(name) \
    836   RuntimeCallCounter Handler_##name = RuntimeCallCounter(#name);
    837   FOR_EACH_HANDLER_COUNTER(CALL_BUILTIN_COUNTER)
    838 #undef CALL_BUILTIN_COUNTER
    839 
    840   static const CounterId counters[];
    841 
    842   // Starting measuring the time for a function. This will establish the
    843   // connection to the parent counter for properly calculating the own times.
    844   static void Enter(RuntimeCallStats* stats, RuntimeCallTimer* timer,
    845                     CounterId counter_id);
    846 
    847   // Leave a scope for a measured runtime function. This will properly add
    848   // the time delta to the current_counter and subtract the delta from its
    849   // parent.
    850   static void Leave(RuntimeCallStats* stats, RuntimeCallTimer* timer);
    851 
    852   // Set counter id for the innermost measurement. It can be used to refine
    853   // event kind when a runtime entry counter is too generic.
    854   static void CorrectCurrentCounterId(RuntimeCallStats* stats,
    855                                       CounterId counter_id);
    856 
    857   void Reset();
    858   // Add all entries from another stats object.
    859   void Add(RuntimeCallStats* other);
    860   void Print(std::ostream& os);
    861   V8_NOINLINE void Dump(v8::tracing::TracedValue* value);
    862 
    863   RuntimeCallStats() {
    864     Reset();
    865     in_use_ = false;
    866   }
    867 
    868   RuntimeCallTimer* current_timer() { return current_timer_.Value(); }
    869   bool InUse() { return in_use_; }
    870 
    871  private:
    872   // Counter to track recursive time events.
    873   base::AtomicValue<RuntimeCallTimer*> current_timer_;
    874   // Used to track nested tracing scopes.
    875   bool in_use_;
    876 };
    877 
    878 #define CHANGE_CURRENT_RUNTIME_COUNTER(runtime_call_stats, counter_name) \
    879   do {                                                                   \
    880     if (V8_UNLIKELY(FLAG_runtime_stats)) {                               \
    881       RuntimeCallStats::CorrectCurrentCounterId(                         \
    882           runtime_call_stats, &RuntimeCallStats::counter_name);          \
    883     }                                                                    \
    884   } while (false)
    885 
    886 #define TRACE_HANDLER_STATS(isolate, counter_name)                          \
    887   CHANGE_CURRENT_RUNTIME_COUNTER(isolate->counters()->runtime_call_stats(), \
    888                                  Handler_##counter_name)
    889 
    890 #define HISTOGRAM_RANGE_LIST(HR)                                              \
    891   /* Generic range histograms */                                              \
    892   HR(detached_context_age_in_gc, V8.DetachedContextAgeInGC, 0, 20, 21)        \
    893   HR(gc_idle_time_allotted_in_ms, V8.GCIdleTimeAllottedInMS, 0, 10000, 101)   \
    894   HR(gc_idle_time_limit_overshot, V8.GCIdleTimeLimit.Overshot, 0, 10000, 101) \
    895   HR(gc_idle_time_limit_undershot, V8.GCIdleTimeLimit.Undershot, 0, 10000,    \
    896      101)                                                                     \
    897   HR(code_cache_reject_reason, V8.CodeCacheRejectReason, 1, 6, 6)             \
    898   HR(errors_thrown_per_context, V8.ErrorsThrownPerContext, 0, 200, 20)        \
    899   HR(debug_feature_usage, V8.DebugFeatureUsage, 1, 7, 7)                      \
    900   HR(incremental_marking_reason, V8.GCIncrementalMarkingReason, 0, 21, 22)    \
    901   HR(mark_compact_reason, V8.GCMarkCompactReason, 0, 21, 22)                  \
    902   HR(scavenge_reason, V8.GCScavengeReason, 0, 21, 22)                         \
    903   /* Asm/Wasm. */                                                             \
    904   HR(wasm_functions_per_module, V8.WasmFunctionsPerModule, 1, 10000, 51)
    905 
    906 #define HISTOGRAM_TIMER_LIST(HT)                                               \
    907   /* Garbage collection timers. */                                             \
    908   HT(gc_compactor, V8.GCCompactor, 10000, MILLISECOND)                         \
    909   HT(gc_finalize, V8.GCFinalizeMC, 10000, MILLISECOND)                         \
    910   HT(gc_finalize_reduce_memory, V8.GCFinalizeMCReduceMemory, 10000,            \
    911      MILLISECOND)                                                              \
    912   HT(gc_scavenger, V8.GCScavenger, 10000, MILLISECOND)                         \
    913   HT(gc_context, V8.GCContext, 10000,                                          \
    914      MILLISECOND) /* GC context cleanup time */                                \
    915   HT(gc_idle_notification, V8.GCIdleNotification, 10000, MILLISECOND)          \
    916   HT(gc_incremental_marking, V8.GCIncrementalMarking, 10000, MILLISECOND)      \
    917   HT(gc_incremental_marking_start, V8.GCIncrementalMarkingStart, 10000,        \
    918      MILLISECOND)                                                              \
    919   HT(gc_incremental_marking_finalize, V8.GCIncrementalMarkingFinalize, 10000,  \
    920      MILLISECOND)                                                              \
    921   HT(gc_low_memory_notification, V8.GCLowMemoryNotification, 10000,            \
    922      MILLISECOND)                                                              \
    923   /* Compilation times. */                                                     \
    924   HT(compile, V8.CompileMicroSeconds, 1000000, MICROSECOND)                    \
    925   HT(compile_eval, V8.CompileEvalMicroSeconds, 1000000, MICROSECOND)           \
    926   /* Serialization as part of compilation (code caching) */                    \
    927   HT(compile_serialize, V8.CompileSerializeMicroSeconds, 100000, MICROSECOND)  \
    928   HT(compile_deserialize, V8.CompileDeserializeMicroSeconds, 1000000,          \
    929      MICROSECOND)                                                              \
    930   /* Total compilation time incl. caching/parsing */                           \
    931   HT(compile_script, V8.CompileScriptMicroSeconds, 1000000, MICROSECOND)       \
    932   /* Total JavaScript execution time (including callbacks and runtime calls */ \
    933   HT(execute, V8.Execute, 1000000, MICROSECOND)                                \
    934   /* Asm/Wasm */                                                               \
    935   HT(wasm_instantiate_module_time, V8.WasmInstantiateModuleMicroSeconds,       \
    936      1000000, MICROSECOND)                                                     \
    937   HT(wasm_decode_module_time, V8.WasmDecodeModuleMicroSeconds, 1000000,        \
    938      MICROSECOND)                                                              \
    939   HT(wasm_decode_function_time, V8.WasmDecodeFunctionMicroSeconds, 1000000,    \
    940      MICROSECOND)                                                              \
    941   HT(wasm_compile_module_time, V8.WasmCompileModuleMicroSeconds, 1000000,      \
    942      MICROSECOND)                                                              \
    943   HT(wasm_compile_function_time, V8.WasmCompileFunctionMicroSeconds, 1000000,  \
    944      MICROSECOND)
    945 
    946 #define AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT) \
    947   AHT(compile_lazy, V8.CompileLazyMicroSeconds)
    948 
    949 #define HISTOGRAM_PERCENTAGE_LIST(HP)                                          \
    950   /* Heap fragmentation. */                                                    \
    951   HP(external_fragmentation_total, V8.MemoryExternalFragmentationTotal)        \
    952   HP(external_fragmentation_old_space, V8.MemoryExternalFragmentationOldSpace) \
    953   HP(external_fragmentation_code_space,                                        \
    954      V8.MemoryExternalFragmentationCodeSpace)                                  \
    955   HP(external_fragmentation_map_space, V8.MemoryExternalFragmentationMapSpace) \
    956   HP(external_fragmentation_lo_space, V8.MemoryExternalFragmentationLoSpace)   \
    957   /* Percentages of heap committed to each space. */                           \
    958   HP(heap_fraction_new_space, V8.MemoryHeapFractionNewSpace)                   \
    959   HP(heap_fraction_old_space, V8.MemoryHeapFractionOldSpace)                   \
    960   HP(heap_fraction_code_space, V8.MemoryHeapFractionCodeSpace)                 \
    961   HP(heap_fraction_map_space, V8.MemoryHeapFractionMapSpace)                   \
    962   HP(heap_fraction_lo_space, V8.MemoryHeapFractionLoSpace)
    963 
    964 #define HISTOGRAM_LEGACY_MEMORY_LIST(HM)                                      \
    965   HM(heap_sample_total_committed, V8.MemoryHeapSampleTotalCommitted)          \
    966   HM(heap_sample_total_used, V8.MemoryHeapSampleTotalUsed)                    \
    967   HM(heap_sample_map_space_committed, V8.MemoryHeapSampleMapSpaceCommitted)   \
    968   HM(heap_sample_code_space_committed, V8.MemoryHeapSampleCodeSpaceCommitted) \
    969   HM(heap_sample_maximum_committed, V8.MemoryHeapSampleMaximumCommitted)
    970 
    971 #define HISTOGRAM_MEMORY_LIST(HM)                                              \
    972   HM(memory_heap_committed, V8.MemoryHeapCommitted)                            \
    973   HM(memory_heap_used, V8.MemoryHeapUsed)                                      \
    974   /* Asm/Wasm */                                                               \
    975   HM(wasm_decode_module_peak_memory_bytes, V8.WasmDecodeModulePeakMemoryBytes) \
    976   HM(wasm_compile_function_peak_memory_bytes,                                  \
    977      V8.WasmCompileFunctionPeakMemoryBytes)                                    \
    978   HM(wasm_min_mem_pages_count, V8.WasmMinMemPagesCount)                        \
    979   HM(wasm_max_mem_pages_count, V8.WasmMaxMemPagesCount)                        \
    980   HM(wasm_function_size_bytes, V8.WasmFunctionSizeBytes)                       \
    981   HM(wasm_module_size_bytes, V8.WasmModuleSizeBytes)
    982 
    983 // WARNING: STATS_COUNTER_LIST_* is a very large macro that is causing MSVC
    984 // Intellisense to crash.  It was broken into two macros (each of length 40
    985 // lines) rather than one macro (of length about 80 lines) to work around
    986 // this problem.  Please avoid using recursive macros of this length when
    987 // possible.
    988 #define STATS_COUNTER_LIST_1(SC)                                      \
    989   /* Global Handle Count*/                                            \
    990   SC(global_handles, V8.GlobalHandles)                                \
    991   /* OS Memory allocated */                                           \
    992   SC(memory_allocated, V8.OsMemoryAllocated)                          \
    993   SC(maps_normalized, V8.MapsNormalized)                            \
    994   SC(maps_created, V8.MapsCreated)                                  \
    995   SC(elements_transitions, V8.ObjectElementsTransitions)            \
    996   SC(props_to_dictionary, V8.ObjectPropertiesToDictionary)            \
    997   SC(elements_to_dictionary, V8.ObjectElementsToDictionary)           \
    998   SC(alive_after_last_gc, V8.AliveAfterLastGC)                        \
    999   SC(objs_since_last_young, V8.ObjsSinceLastYoung)                    \
   1000   SC(objs_since_last_full, V8.ObjsSinceLastFull)                      \
   1001   SC(string_table_capacity, V8.StringTableCapacity)                   \
   1002   SC(number_of_symbols, V8.NumberOfSymbols)                           \
   1003   SC(script_wrappers, V8.ScriptWrappers)                              \
   1004   SC(inlined_copied_elements, V8.InlinedCopiedElements)               \
   1005   SC(arguments_adaptors, V8.ArgumentsAdaptors)                        \
   1006   SC(compilation_cache_hits, V8.CompilationCacheHits)                 \
   1007   SC(compilation_cache_misses, V8.CompilationCacheMisses)             \
   1008   /* Amount of evaled source code. */                                 \
   1009   SC(total_eval_size, V8.TotalEvalSize)                               \
   1010   /* Amount of loaded source code. */                                 \
   1011   SC(total_load_size, V8.TotalLoadSize)                               \
   1012   /* Amount of parsed source code. */                                 \
   1013   SC(total_parse_size, V8.TotalParseSize)                             \
   1014   /* Amount of source code skipped over using preparsing. */          \
   1015   SC(total_preparse_skipped, V8.TotalPreparseSkipped)                 \
   1016   /* Amount of compiled source code. */                               \
   1017   SC(total_compile_size, V8.TotalCompileSize)                         \
   1018   /* Amount of source code compiled with the full codegen. */         \
   1019   SC(total_full_codegen_source_size, V8.TotalFullCodegenSourceSize)   \
   1020   /* Number of contexts created from scratch. */                      \
   1021   SC(contexts_created_from_scratch, V8.ContextsCreatedFromScratch)    \
   1022   /* Number of contexts created by partial snapshot. */               \
   1023   SC(contexts_created_by_snapshot, V8.ContextsCreatedBySnapshot)      \
   1024   /* Number of code objects found from pc. */                         \
   1025   SC(pc_to_code, V8.PcToCode)                                         \
   1026   SC(pc_to_code_cached, V8.PcToCodeCached)                            \
   1027   /* The store-buffer implementation of the write barrier. */         \
   1028   SC(store_buffer_overflows, V8.StoreBufferOverflows)
   1029 
   1030 #define STATS_COUNTER_LIST_2(SC)                                               \
   1031   /* Number of code stubs. */                                                  \
   1032   SC(code_stubs, V8.CodeStubs)                                                 \
   1033   /* Amount of stub code. */                                                   \
   1034   SC(total_stubs_code_size, V8.TotalStubsCodeSize)                             \
   1035   /* Amount of (JS) compiled code. */                                          \
   1036   SC(total_compiled_code_size, V8.TotalCompiledCodeSize)                       \
   1037   SC(gc_compactor_caused_by_request, V8.GCCompactorCausedByRequest)            \
   1038   SC(gc_compactor_caused_by_promoted_data, V8.GCCompactorCausedByPromotedData) \
   1039   SC(gc_compactor_caused_by_oldspace_exhaustion,                               \
   1040      V8.GCCompactorCausedByOldspaceExhaustion)                                 \
   1041   SC(gc_last_resort_from_js, V8.GCLastResortFromJS)                            \
   1042   SC(gc_last_resort_from_handles, V8.GCLastResortFromHandles)                  \
   1043   SC(ic_keyed_load_generic_smi, V8.ICKeyedLoadGenericSmi)                      \
   1044   SC(ic_keyed_load_generic_symbol, V8.ICKeyedLoadGenericSymbol)                \
   1045   SC(ic_keyed_load_generic_slow, V8.ICKeyedLoadGenericSlow)                    \
   1046   SC(ic_named_load_global_stub, V8.ICNamedLoadGlobalStub)                      \
   1047   SC(ic_store_normal_miss, V8.ICStoreNormalMiss)                               \
   1048   SC(ic_store_normal_hit, V8.ICStoreNormalHit)                                 \
   1049   SC(ic_binary_op_miss, V8.ICBinaryOpMiss)                                     \
   1050   SC(ic_compare_miss, V8.ICCompareMiss)                                        \
   1051   SC(ic_call_miss, V8.ICCallMiss)                                              \
   1052   SC(ic_keyed_call_miss, V8.ICKeyedCallMiss)                                   \
   1053   SC(ic_load_miss, V8.ICLoadMiss)                                              \
   1054   SC(ic_keyed_load_miss, V8.ICKeyedLoadMiss)                                   \
   1055   SC(ic_store_miss, V8.ICStoreMiss)                                            \
   1056   SC(ic_keyed_store_miss, V8.ICKeyedStoreMiss)                                 \
   1057   SC(cow_arrays_created_runtime, V8.COWArraysCreatedRuntime)                   \
   1058   SC(cow_arrays_converted, V8.COWArraysConverted)                              \
   1059   SC(constructed_objects, V8.ConstructedObjects)                               \
   1060   SC(constructed_objects_runtime, V8.ConstructedObjectsRuntime)                \
   1061   SC(negative_lookups, V8.NegativeLookups)                                     \
   1062   SC(negative_lookups_miss, V8.NegativeLookupsMiss)                            \
   1063   SC(megamorphic_stub_cache_probes, V8.MegamorphicStubCacheProbes)             \
   1064   SC(megamorphic_stub_cache_misses, V8.MegamorphicStubCacheMisses)             \
   1065   SC(megamorphic_stub_cache_updates, V8.MegamorphicStubCacheUpdates)           \
   1066   SC(enum_cache_hits, V8.EnumCacheHits)                                        \
   1067   SC(enum_cache_misses, V8.EnumCacheMisses)                                    \
   1068   SC(fast_new_closure_total, V8.FastNewClosureTotal)                           \
   1069   SC(string_add_runtime, V8.StringAddRuntime)                                  \
   1070   SC(string_add_native, V8.StringAddNative)                                    \
   1071   SC(string_add_runtime_ext_to_one_byte, V8.StringAddRuntimeExtToOneByte)      \
   1072   SC(sub_string_runtime, V8.SubStringRuntime)                                  \
   1073   SC(sub_string_native, V8.SubStringNative)                                    \
   1074   SC(string_compare_native, V8.StringCompareNative)                            \
   1075   SC(string_compare_runtime, V8.StringCompareRuntime)                          \
   1076   SC(regexp_entry_runtime, V8.RegExpEntryRuntime)                              \
   1077   SC(regexp_entry_native, V8.RegExpEntryNative)                                \
   1078   SC(number_to_string_native, V8.NumberToStringNative)                         \
   1079   SC(number_to_string_runtime, V8.NumberToStringRuntime)                       \
   1080   SC(math_exp_runtime, V8.MathExpRuntime)                                      \
   1081   SC(math_log_runtime, V8.MathLogRuntime)                                      \
   1082   SC(math_pow_runtime, V8.MathPowRuntime)                                      \
   1083   SC(stack_interrupts, V8.StackInterrupts)                                     \
   1084   SC(runtime_profiler_ticks, V8.RuntimeProfilerTicks)                          \
   1085   SC(runtime_calls, V8.RuntimeCalls)                                           \
   1086   SC(bounds_checks_eliminated, V8.BoundsChecksEliminated)                      \
   1087   SC(bounds_checks_hoisted, V8.BoundsChecksHoisted)                            \
   1088   SC(soft_deopts_requested, V8.SoftDeoptsRequested)                            \
   1089   SC(soft_deopts_inserted, V8.SoftDeoptsInserted)                              \
   1090   SC(soft_deopts_executed, V8.SoftDeoptsExecuted)                              \
   1091   /* Number of write barriers in generated code. */                            \
   1092   SC(write_barriers_dynamic, V8.WriteBarriersDynamic)                          \
   1093   SC(write_barriers_static, V8.WriteBarriersStatic)                            \
   1094   SC(new_space_bytes_available, V8.MemoryNewSpaceBytesAvailable)               \
   1095   SC(new_space_bytes_committed, V8.MemoryNewSpaceBytesCommitted)               \
   1096   SC(new_space_bytes_used, V8.MemoryNewSpaceBytesUsed)                         \
   1097   SC(old_space_bytes_available, V8.MemoryOldSpaceBytesAvailable)               \
   1098   SC(old_space_bytes_committed, V8.MemoryOldSpaceBytesCommitted)               \
   1099   SC(old_space_bytes_used, V8.MemoryOldSpaceBytesUsed)                         \
   1100   SC(code_space_bytes_available, V8.MemoryCodeSpaceBytesAvailable)             \
   1101   SC(code_space_bytes_committed, V8.MemoryCodeSpaceBytesCommitted)             \
   1102   SC(code_space_bytes_used, V8.MemoryCodeSpaceBytesUsed)                       \
   1103   SC(map_space_bytes_available, V8.MemoryMapSpaceBytesAvailable)               \
   1104   SC(map_space_bytes_committed, V8.MemoryMapSpaceBytesCommitted)               \
   1105   SC(map_space_bytes_used, V8.MemoryMapSpaceBytesUsed)                         \
   1106   SC(lo_space_bytes_available, V8.MemoryLoSpaceBytesAvailable)                 \
   1107   SC(lo_space_bytes_committed, V8.MemoryLoSpaceBytesCommitted)                 \
   1108   SC(lo_space_bytes_used, V8.MemoryLoSpaceBytesUsed)                           \
   1109   SC(turbo_escape_allocs_replaced, V8.TurboEscapeAllocsReplaced)               \
   1110   SC(crankshaft_escape_allocs_replaced, V8.CrankshaftEscapeAllocsReplaced)     \
   1111   SC(turbo_escape_loads_replaced, V8.TurboEscapeLoadsReplaced)                 \
   1112   SC(crankshaft_escape_loads_replaced, V8.CrankshaftEscapeLoadsReplaced)       \
   1113   /* Total code size (including metadata) of baseline code or bytecode. */     \
   1114   SC(total_baseline_code_size, V8.TotalBaselineCodeSize)                       \
   1115   /* Total count of functions compiled using the baseline compiler. */         \
   1116   SC(total_baseline_compile_count, V8.TotalBaselineCompileCount)               \
   1117   SC(wasm_generated_code_size, V8.WasmGeneratedCodeBytes)                      \
   1118   SC(wasm_reloc_size, V8.WasmRelocBytes)
   1119 
   1120 // This file contains all the v8 counters that are in use.
   1121 class Counters {
   1122  public:
   1123 #define HR(name, caption, min, max, num_buckets) \
   1124   Histogram* name() { return &name##_; }
   1125   HISTOGRAM_RANGE_LIST(HR)
   1126 #undef HR
   1127 
   1128 #define HT(name, caption, max, res) \
   1129   HistogramTimer* name() { return &name##_; }
   1130   HISTOGRAM_TIMER_LIST(HT)
   1131 #undef HT
   1132 
   1133 #define AHT(name, caption) \
   1134   AggregatableHistogramTimer* name() { return &name##_; }
   1135   AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT)
   1136 #undef AHT
   1137 
   1138 #define HP(name, caption) \
   1139   Histogram* name() { return &name##_; }
   1140   HISTOGRAM_PERCENTAGE_LIST(HP)
   1141 #undef HP
   1142 
   1143 #define HM(name, caption) \
   1144   Histogram* name() { return &name##_; }
   1145   HISTOGRAM_LEGACY_MEMORY_LIST(HM)
   1146   HISTOGRAM_MEMORY_LIST(HM)
   1147 #undef HM
   1148 
   1149 #define HM(name, caption)                                     \
   1150   AggregatedMemoryHistogram<Histogram>* aggregated_##name() { \
   1151     return &aggregated_##name##_;                             \
   1152   }
   1153   HISTOGRAM_MEMORY_LIST(HM)
   1154 #undef HM
   1155 
   1156 #define SC(name, caption) \
   1157   StatsCounter* name() { return &name##_; }
   1158   STATS_COUNTER_LIST_1(SC)
   1159   STATS_COUNTER_LIST_2(SC)
   1160 #undef SC
   1161 
   1162 #define SC(name) \
   1163   StatsCounter* count_of_##name() { return &count_of_##name##_; } \
   1164   StatsCounter* size_of_##name() { return &size_of_##name##_; }
   1165   INSTANCE_TYPE_LIST(SC)
   1166 #undef SC
   1167 
   1168 #define SC(name) \
   1169   StatsCounter* count_of_CODE_TYPE_##name() \
   1170     { return &count_of_CODE_TYPE_##name##_; } \
   1171   StatsCounter* size_of_CODE_TYPE_##name() \
   1172     { return &size_of_CODE_TYPE_##name##_; }
   1173   CODE_KIND_LIST(SC)
   1174 #undef SC
   1175 
   1176 #define SC(name) \
   1177   StatsCounter* count_of_FIXED_ARRAY_##name() \
   1178     { return &count_of_FIXED_ARRAY_##name##_; } \
   1179   StatsCounter* size_of_FIXED_ARRAY_##name() \
   1180     { return &size_of_FIXED_ARRAY_##name##_; }
   1181   FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(SC)
   1182 #undef SC
   1183 
   1184 #define SC(name) \
   1185   StatsCounter* count_of_CODE_AGE_##name() \
   1186     { return &count_of_CODE_AGE_##name##_; } \
   1187   StatsCounter* size_of_CODE_AGE_##name() \
   1188     { return &size_of_CODE_AGE_##name##_; }
   1189   CODE_AGE_LIST_COMPLETE(SC)
   1190 #undef SC
   1191 
   1192   enum Id {
   1193 #define RATE_ID(name, caption, max, res) k_##name,
   1194     HISTOGRAM_TIMER_LIST(RATE_ID)
   1195 #undef RATE_ID
   1196 #define AGGREGATABLE_ID(name, caption) k_##name,
   1197     AGGREGATABLE_HISTOGRAM_TIMER_LIST(AGGREGATABLE_ID)
   1198 #undef AGGREGATABLE_ID
   1199 #define PERCENTAGE_ID(name, caption) k_##name,
   1200     HISTOGRAM_PERCENTAGE_LIST(PERCENTAGE_ID)
   1201 #undef PERCENTAGE_ID
   1202 #define MEMORY_ID(name, caption) k_##name,
   1203     HISTOGRAM_LEGACY_MEMORY_LIST(MEMORY_ID)
   1204     HISTOGRAM_MEMORY_LIST(MEMORY_ID)
   1205 #undef MEMORY_ID
   1206 #define COUNTER_ID(name, caption) k_##name,
   1207     STATS_COUNTER_LIST_1(COUNTER_ID)
   1208     STATS_COUNTER_LIST_2(COUNTER_ID)
   1209 #undef COUNTER_ID
   1210 #define COUNTER_ID(name) kCountOf##name, kSizeOf##name,
   1211     INSTANCE_TYPE_LIST(COUNTER_ID)
   1212 #undef COUNTER_ID
   1213 #define COUNTER_ID(name) kCountOfCODE_TYPE_##name, \
   1214     kSizeOfCODE_TYPE_##name,
   1215     CODE_KIND_LIST(COUNTER_ID)
   1216 #undef COUNTER_ID
   1217 #define COUNTER_ID(name) kCountOfFIXED_ARRAY__##name, \
   1218     kSizeOfFIXED_ARRAY__##name,
   1219     FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(COUNTER_ID)
   1220 #undef COUNTER_ID
   1221 #define COUNTER_ID(name) kCountOfCODE_AGE__##name, \
   1222     kSizeOfCODE_AGE__##name,
   1223     CODE_AGE_LIST_COMPLETE(COUNTER_ID)
   1224 #undef COUNTER_ID
   1225     stats_counter_count
   1226   };
   1227 
   1228   void ResetCounters();
   1229   void ResetHistograms();
   1230   RuntimeCallStats* runtime_call_stats() { return &runtime_call_stats_; }
   1231 
   1232  private:
   1233 #define HR(name, caption, min, max, num_buckets) Histogram name##_;
   1234   HISTOGRAM_RANGE_LIST(HR)
   1235 #undef HR
   1236 
   1237 #define HT(name, caption, max, res) HistogramTimer name##_;
   1238   HISTOGRAM_TIMER_LIST(HT)
   1239 #undef HT
   1240 
   1241 #define AHT(name, caption) \
   1242   AggregatableHistogramTimer name##_;
   1243   AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT)
   1244 #undef AHT
   1245 
   1246 #define HP(name, caption) \
   1247   Histogram name##_;
   1248   HISTOGRAM_PERCENTAGE_LIST(HP)
   1249 #undef HP
   1250 
   1251 #define HM(name, caption) \
   1252   Histogram name##_;
   1253   HISTOGRAM_LEGACY_MEMORY_LIST(HM)
   1254   HISTOGRAM_MEMORY_LIST(HM)
   1255 #undef HM
   1256 
   1257 #define HM(name, caption) \
   1258   AggregatedMemoryHistogram<Histogram> aggregated_##name##_;
   1259   HISTOGRAM_MEMORY_LIST(HM)
   1260 #undef HM
   1261 
   1262 #define SC(name, caption) \
   1263   StatsCounter name##_;
   1264   STATS_COUNTER_LIST_1(SC)
   1265   STATS_COUNTER_LIST_2(SC)
   1266 #undef SC
   1267 
   1268 #define SC(name) \
   1269   StatsCounter size_of_##name##_; \
   1270   StatsCounter count_of_##name##_;
   1271   INSTANCE_TYPE_LIST(SC)
   1272 #undef SC
   1273 
   1274 #define SC(name) \
   1275   StatsCounter size_of_CODE_TYPE_##name##_; \
   1276   StatsCounter count_of_CODE_TYPE_##name##_;
   1277   CODE_KIND_LIST(SC)
   1278 #undef SC
   1279 
   1280 #define SC(name) \
   1281   StatsCounter size_of_FIXED_ARRAY_##name##_; \
   1282   StatsCounter count_of_FIXED_ARRAY_##name##_;
   1283   FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(SC)
   1284 #undef SC
   1285 
   1286 #define SC(name) \
   1287   StatsCounter size_of_CODE_AGE_##name##_; \
   1288   StatsCounter count_of_CODE_AGE_##name##_;
   1289   CODE_AGE_LIST_COMPLETE(SC)
   1290 #undef SC
   1291 
   1292   RuntimeCallStats runtime_call_stats_;
   1293 
   1294   friend class Isolate;
   1295 
   1296   explicit Counters(Isolate* isolate);
   1297 
   1298   DISALLOW_IMPLICIT_CONSTRUCTORS(Counters);
   1299 };
   1300 
   1301 // A RuntimeCallTimerScopes wraps around a RuntimeCallTimer to measure the
   1302 // the time of C++ scope.
   1303 class RuntimeCallTimerScope {
   1304  public:
   1305   inline RuntimeCallTimerScope(Isolate* isolate,
   1306                                RuntimeCallStats::CounterId counter_id);
   1307   // This constructor is here just to avoid calling GetIsolate() when the
   1308   // stats are disabled and the isolate is not directly available.
   1309   inline RuntimeCallTimerScope(HeapObject* heap_object,
   1310                                RuntimeCallStats::CounterId counter_id);
   1311   inline RuntimeCallTimerScope(RuntimeCallStats* stats,
   1312                                RuntimeCallStats::CounterId counter_id);
   1313 
   1314   inline ~RuntimeCallTimerScope() {
   1315     if (V8_UNLIKELY(stats_ != nullptr)) {
   1316       RuntimeCallStats::Leave(stats_, &timer_);
   1317     }
   1318   }
   1319 
   1320  private:
   1321   V8_INLINE void Initialize(RuntimeCallStats* stats,
   1322                             RuntimeCallStats::CounterId counter_id) {
   1323     stats_ = stats;
   1324     RuntimeCallStats::Enter(stats_, &timer_, counter_id);
   1325   }
   1326 
   1327   RuntimeCallStats* stats_ = nullptr;
   1328   RuntimeCallTimer timer_;
   1329 };
   1330 
   1331 }  // namespace internal
   1332 }  // namespace v8
   1333 
   1334 #endif  // V8_COUNTERS_H_
   1335