1// Copyright 2020 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_HEAP_CPPGC_PROCESS_HEAP_STATISTICS_H_
6#define V8_HEAP_CPPGC_PROCESS_HEAP_STATISTICS_H_
7
8#include "include/cppgc/process-heap-statistics.h"
9#include "src/heap/cppgc/stats-collector.h"
10
11namespace cppgc {
12namespace internal {
13
14class ProcessHeapStatisticsUpdater {
15 public:
16  // Allocation observer implementation for heaps should register to contribute
17  // to ProcessHeapStatistics. The heap is responsible for allocating and
18  // registering the observer impl with its stats collector.
19  class AllocationObserverImpl final
20      : public StatsCollector::AllocationObserver {
21   public:
22    void AllocatedObjectSizeIncreased(size_t bytes) final {
23      ProcessHeapStatisticsUpdater::IncreaseTotalAllocatedObjectSize(bytes);
24      object_size_changes_since_last_reset_ += bytes;
25    }
26
27    void AllocatedObjectSizeDecreased(size_t bytes) final {
28      ProcessHeapStatisticsUpdater::DecreaseTotalAllocatedObjectSize(bytes);
29      object_size_changes_since_last_reset_ -= bytes;
30    }
31
32    void ResetAllocatedObjectSize(size_t bytes) final {
33      ProcessHeapStatisticsUpdater::DecreaseTotalAllocatedObjectSize(
34          object_size_changes_since_last_reset_);
35      ProcessHeapStatisticsUpdater::IncreaseTotalAllocatedObjectSize(bytes);
36      object_size_changes_since_last_reset_ = bytes;
37    }
38
39    void AllocatedSizeIncreased(size_t bytes) final {
40      ProcessHeapStatisticsUpdater::IncreaseTotalAllocatedSpace(bytes);
41    }
42
43    void AllocatedSizeDecreased(size_t bytes) final {
44      ProcessHeapStatisticsUpdater::DecreaseTotalAllocatedSpace(bytes);
45    }
46
47   private:
48    size_t object_size_changes_since_last_reset_ = 0;
49  };
50
51  // For cppgc::ProcessHeapStatistics
52  static void IncreaseTotalAllocatedObjectSize(size_t delta) {
53    ::cppgc::ProcessHeapStatistics::total_allocated_object_size_.fetch_add(
54        delta, std::memory_order_relaxed);
55  }
56  static void DecreaseTotalAllocatedObjectSize(size_t delta) {
57    ::cppgc::ProcessHeapStatistics::total_allocated_object_size_.fetch_sub(
58        delta, std::memory_order_relaxed);
59  }
60  static void IncreaseTotalAllocatedSpace(size_t delta) {
61    ::cppgc::ProcessHeapStatistics::total_allocated_space_.fetch_add(
62        delta, std::memory_order_relaxed);
63  }
64  static void DecreaseTotalAllocatedSpace(size_t delta) {
65    ::cppgc::ProcessHeapStatistics::total_allocated_space_.fetch_sub(
66        delta, std::memory_order_relaxed);
67  }
68};
69
70}  // namespace internal
71}  // namespace cppgc
72
73#endif  // V8_HEAP_CPPGC_PROCESS_HEAP_STATISTICS_H_
74