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_CODEGEN_ALIGNED_SLOT_ALLOCATOR_H_
6#define V8_CODEGEN_ALIGNED_SLOT_ALLOCATOR_H_
7
8#include "src/base/macros.h"
9#include "src/base/platform/platform.h"
10#include "src/common/globals.h"
11
12namespace v8 {
13namespace internal {
14
15// An aligned slot allocator. Allocates groups of 1, 2, or 4 slots such that the
16// first slot of the group is aligned to the group size. The allocator can also
17// allocate unaligned groups of arbitrary size, and an align the number of slots
18// to 1, 2, or 4 slots. The allocator tries to be as thrifty as possible by
19// reusing alignment padding slots in subsequent smaller slot allocations.
20class V8_EXPORT_PRIVATE AlignedSlotAllocator {
21 public:
22  // Slots are always multiples of pointer-sized units.
23  static constexpr int kSlotSize = kSystemPointerSize;
24
25  static int NumSlotsForWidth(int bytes) {
26    DCHECK_GT(bytes, 0);
27    return (bytes + kSlotSize - 1) / kSlotSize;
28  }
29
30  AlignedSlotAllocator() = default;
31
32  // Allocates |n| slots, where |n| must be 1, 2, or 4. Padding slots may be
33  // inserted for alignment.
34  // Returns the starting index of the slots, which is evenly divisible by |n|.
35  int Allocate(int n);
36
37  // Gets the starting index of the slots that would be returned by Allocate(n).
38  int NextSlot(int n) const;
39
40  // Allocates the given number of slots at the current end of the slot area,
41  // and returns the starting index of the slots. This resets any fragment
42  // slots, so subsequent allocations will be after the end of this one.
43  // AllocateUnaligned(0) can be used to partition the slot area, for example
44  // to make sure tagged values follow untagged values on a Frame.
45  int AllocateUnaligned(int n);
46
47  // Aligns the slot area so that future allocations begin at the alignment.
48  // Returns the number of slots needed to align the slot area.
49  int Align(int n);
50
51  // Returns the size of the slot area, in slots. This will be greater than any
52  // already allocated slot index.
53  int Size() const { return size_; }
54
55 private:
56  static constexpr int kInvalidSlot = -1;
57
58  static bool IsValid(int slot) { return slot > kInvalidSlot; }
59
60  int next1_ = kInvalidSlot;
61  int next2_ = kInvalidSlot;
62  int next4_ = 0;
63  int size_ = 0;
64
65  DISALLOW_NEW_AND_DELETE()
66};
67
68}  // namespace internal
69}  // namespace v8
70
71#endif  // V8_CODEGEN_ALIGNED_SLOT_ALLOCATOR_H_
72