• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_ZONE_TYPE_STATS_H_
6 #define V8_ZONE_TYPE_STATS_H_
7 
8 #include <iosfwd>
9 #include <type_traits>
10 #include <typeindex>
11 #include <unordered_map>
12 
13 #include "src/common/globals.h"
14 
15 namespace v8 {
16 namespace internal {
17 
18 class TypeStats;
19 
20 #ifdef V8_ENABLE_PRECISE_ZONE_STATS
21 
22 class TypeStats {
23  public:
24   TypeStats() = default;
25 
26   template <typename TypeTag>
AddAllocated(size_t bytes)27   void AddAllocated(size_t bytes) {
28     StatsEntry& entry = map_[std::type_index(typeid(TypeTag))];
29     entry.allocation_count++;
30     entry.allocated_bytes += bytes;
31     // sizeof(IncompleteType) is not allowed so record size as a sizeof(char).
32     constexpr bool kIsIncomplete =
33         std::is_same<TypeTag, void>::value || std::is_array<TypeTag>::value;
34     using TypeTagForSizeof =
35         typename std::conditional<kIsIncomplete, char, TypeTag>::type;
36     entry.instance_size = sizeof(TypeTagForSizeof);
37   }
38 
39   template <typename TypeTag>
AddDeallocated(size_t bytes)40   void AddDeallocated(size_t bytes) {
41     StatsEntry& entry = map_[std::type_index(typeid(TypeTag))];
42     entry.deallocated_bytes += bytes;
43   }
44 
45   // Merges other stats into this stats object.
46   void MergeWith(const TypeStats& other);
47 
48   // Prints recorded statisticts to stdout.
49   void Dump() const;
50 
51  private:
52   struct StatsEntry {
53     size_t allocation_count = 0;
54     size_t allocated_bytes = 0;
55     size_t deallocated_bytes = 0;
56     size_t instance_size = 0;
57   };
58 
Add(std::type_index type_id,const StatsEntry & other_entry)59   void Add(std::type_index type_id, const StatsEntry& other_entry) {
60     StatsEntry& entry = map_[type_id];
61     entry.allocation_count += other_entry.allocation_count;
62     entry.allocated_bytes += other_entry.allocated_bytes;
63     entry.deallocated_bytes += other_entry.deallocated_bytes;
64     entry.instance_size = other_entry.instance_size;
65   }
66 
67   using HashMap = std::unordered_map<std::type_index, StatsEntry>;
68   HashMap map_;
69 };
70 
71 #endif  // V8_ENABLE_PRECISE_ZONE_STATS
72 
73 }  // namespace internal
74 }  // namespace v8
75 
76 #endif  // V8_ZONE_TYPE_STATS_H_
77