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_UTILS_ADDRESS_MAP_H_
6 #define V8_UTILS_ADDRESS_MAP_H_
7
8 #include "include/v8.h"
9 #include "src/base/hashmap.h"
10 #include "src/common/assert-scope.h"
11 #include "src/objects/heap-object.h"
12 #include "src/roots/roots.h"
13
14 namespace v8 {
15 namespace internal {
16
17 template <typename Type>
18 class PointerToIndexHashMap
19 : public base::TemplateHashMapImpl<uintptr_t, uint32_t,
20 base::KeyEqualityMatcher<intptr_t>,
21 base::DefaultAllocationPolicy> {
22 public:
23 using Entry = base::TemplateHashMapEntry<uintptr_t, uint32_t>;
24
Set(Type value,uint32_t index)25 inline void Set(Type value, uint32_t index) {
26 uintptr_t key = Key(value);
27 LookupOrInsert(key, Hash(key))->value = index;
28 }
29
Get(Type value)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
Hash(uintptr_t key)40 static uint32_t Hash(uintptr_t key) { return static_cast<uint32_t>(key); }
41 };
42
43 template <>
Key(Address value)44 inline uintptr_t PointerToIndexHashMap<Address>::Key(Address value) {
45 return static_cast<uintptr_t>(value);
46 }
47
48 template <>
Key(HeapObject value)49 inline uintptr_t PointerToIndexHashMap<HeapObject>::Key(HeapObject value) {
50 return value.ptr();
51 }
52
53 class AddressToIndexHashMap : public PointerToIndexHashMap<Address> {};
54 class HeapObjectToIndexHashMap : public PointerToIndexHashMap<HeapObject> {};
55
56 class RootIndexMap {
57 public:
58 explicit RootIndexMap(Isolate* isolate);
59
60 // Returns true on successful lookup and sets *|out_root_list|.
Lookup(HeapObject obj,RootIndex * 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_UTILS_ADDRESS_MAP_H_
81