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 INCLUDE_CPPGC_INTERNAL_CAGED_HEAP_LOCAL_DATA_H_
6#define INCLUDE_CPPGC_INTERNAL_CAGED_HEAP_LOCAL_DATA_H_
7
8#include <array>
9#include <cstddef>
10#include <cstdint>
11
12#include "cppgc/internal/api-constants.h"
13#include "cppgc/internal/logging.h"
14#include "cppgc/platform.h"
15#include "v8config.h"  // NOLINT(build/include_directory)
16
17namespace cppgc {
18namespace internal {
19
20class HeapBase;
21
22#if defined(CPPGC_YOUNG_GENERATION)
23
24// AgeTable is the bytemap needed for the fast generation check in the write
25// barrier. AgeTable contains entries that correspond to 512 bytes memory
26// regions (cards). Each entry in the table represents generation of the objects
27// that reside on the corresponding card (young, old or mixed).
28class AgeTable final {
29  static constexpr size_t kRequiredSize = 1 * api_constants::kMB;
30  static constexpr size_t kAllocationGranularity =
31      api_constants::kAllocationGranularity;
32
33 public:
34  enum class Age : uint8_t { kOld, kYoung, kMixed };
35
36  static constexpr size_t kCardSizeInBytes =
37      (api_constants::kCagedHeapReservationSize / kAllocationGranularity) /
38      kRequiredSize;
39
40  void SetAge(uintptr_t cage_offset, Age age) {
41    table_[card(cage_offset)] = age;
42  }
43  V8_INLINE Age GetAge(uintptr_t cage_offset) const {
44    return table_[card(cage_offset)];
45  }
46
47  void Reset(PageAllocator* allocator);
48
49 private:
50  V8_INLINE size_t card(uintptr_t offset) const {
51    constexpr size_t kGranularityBits =
52        __builtin_ctz(static_cast<uint32_t>(kCardSizeInBytes));
53    const size_t entry = offset >> kGranularityBits;
54    CPPGC_DCHECK(table_.size() > entry);
55    return entry;
56  }
57
58  std::array<Age, kRequiredSize> table_;
59};
60
61static_assert(sizeof(AgeTable) == 1 * api_constants::kMB,
62              "Size of AgeTable is 1MB");
63
64#endif  // CPPGC_YOUNG_GENERATION
65
66struct CagedHeapLocalData final {
67  CagedHeapLocalData(HeapBase&, PageAllocator&);
68
69  bool is_incremental_marking_in_progress = false;
70  HeapBase& heap_base;
71#if defined(CPPGC_YOUNG_GENERATION)
72  AgeTable age_table;
73#endif
74};
75
76}  // namespace internal
77}  // namespace cppgc
78
79#endif  // INCLUDE_CPPGC_INTERNAL_CAGED_HEAP_LOCAL_DATA_H_
80