1// Copyright 2015 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_ADDRESS_MAP_H_
6#define V8_ADDRESS_MAP_H_
7
8#include "include/v8.h"
9#include "src/assert-scope.h"
10#include "src/base/hashmap.h"
11#include "src/objects/heap-object.h"
12#include "src/roots.h"
13
14namespace v8 {
15namespace internal {
16
17template <typename Type>
18class PointerToIndexHashMap
19 : public base::TemplateHashMapImpl<uintptr_t, uint32_t,
20 base::KeyEqualityMatcher<intptr_t>,
21 base::DefaultAllocationPolicy> {
22 public:
23 typedef base::TemplateHashMapEntry<uintptr_t, uint32_t> Entry;
24
25 inline void Set(Type value, uint32_t index) {
26 uintptr_t key = Key(value);
27 LookupOrInsert(key, Hash(key))->value = index;
28 }
29
30 inline Maybe<uint32_t> Get(Type value) const {
31 uintptr_t key = Key(value);
32 Entry* entry = Lookup(key, Hash(key));
33 if (entry == nullptr) return Nothing<uint32_t>();
34 return Just(entry->value);
35 }
36
37 private:
38 static inline uintptr_t Key(Type value);
39
40 static uint32_t Hash(uintptr_t key) { return static_cast<uint32_t>(key); }
41};
42
43template <>
44inline uintptr_t PointerToIndexHashMap<Address>::Key(Address value) {
45 return static_cast<uintptr_t>(value);
46}
47
48template <>
49inline uintptr_t PointerToIndexHashMap<HeapObject>::Key(HeapObject value) {
50 return value.ptr();
51}
52
53class AddressToIndexHashMap : public PointerToIndexHashMap<Address> {};
54class HeapObjectToIndexHashMap : public PointerToIndexHashMap<HeapObject> {};
55
56class RootIndexMap {
57 public:
58 explicit RootIndexMap(Isolate* isolate);
59
60 // Returns true on successful lookup and sets *|out_root_list|.
61 bool Lookup(HeapObject obj, RootIndex* out_root_list) const {
62 Maybe<uint32_t> maybe_index = map_->Get(obj);
63 if (maybe_index.IsJust()) {
64 *out_root_list = static_cast<RootIndex>(maybe_index.FromJust());
65 return true;
66 }
67 return false;
68 }
69 bool Lookup(Address obj, RootIndex* out_root_list) const;
70
71 private:
72 HeapObjectToIndexHashMap* map_;
73
74 DISALLOW_COPY_AND_ASSIGN(RootIndexMap);
75};
76
77} // namespace internal
78} // namespace v8
79
80#endif // V8_ADDRESS_MAP_H_
81