Debian Codegraph @

js/src/irregexp/util/ZoneShim.h

raw
1 // Copyright 2019 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_UTIL_ZONE_H_
6 #define V8_UTIL_ZONE_H_
7
8 #include <list>
9 #include <map>
10 #include <set>
11 #include <unordered_map>
12 #include <vector>
13
14 #include "ds/LifoAlloc.h"
15 #include "ds/Sort.h"
16 #include "irregexp/util/VectorShim.h"
17
18 namespace v8 {
19 namespace internal {
20
21 // V8::Zone ~= LifoAlloc
22 class Zone {
23 public:
24 Zone(js::LifoAlloc& alloc) : lifoAlloc_(alloc) {}
25
26 template <typename T, typename... Args>
27 T* New(Args&&... args) {
28 js::LifoAlloc::AutoFallibleScope fallible(&lifoAlloc_);
29 js::AutoEnterOOMUnsafeRegion oomUnsafe;
30 void* memory = lifoAlloc_.alloc(sizeof(T));
31 if (!memory) {
32 oomUnsafe.crash("Irregexp Zone::New");
33 }
34 return new (memory) T(std::forward<Args>(args)...);
35 }
36
37 // Allocates uninitialized memory for 'length' number of T instances.
38 template <typename T>
39 T* NewArray(size_t length) {
40 js::LifoAlloc::AutoFallibleScope fallible(&lifoAlloc_);
41 js::AutoEnterOOMUnsafeRegion oomUnsafe;
42 void* memory = lifoAlloc_.alloc(length * sizeof(T));
43 if (!memory) {
44 oomUnsafe.crash("Irregexp Zone::New");
45 }
46 return static_cast<T*>(memory);
47 }
48
49 void DeleteAll() { lifoAlloc_.freeAll(); }
50
51 // Returns true if the total memory allocated exceeds a threshold.
52 static const size_t kExcessLimit = 256 * 1024 * 1024;
53 bool excess_allocation() const {
54 return lifoAlloc_.computedSizeOfExcludingThis() > kExcessLimit;
55 }
56
57 js::LifoAlloc& inner() { return lifoAlloc_; }
58
59 private:
60 js::LifoAlloc& lifoAlloc_;
61 };
62
63 // Superclass for classes allocated in a Zone.
64 // Based on: https://github.com/v8/v8/blob/master/src/zone/zone.h
65 class ZoneObject {
66 public:
67 // new (zone) SomeObject(...) was the old pattern.
68 // Delete the constructor to avoid using it accidentally.
69 void* operator new(size_t size, Zone* zone) = delete;
70
71 // Allow non-allocating placement new
72 void* operator new(size_t size, void* ptr) { return ptr; }
73
74 // Ideally, the delete operator should be private instead of
75 // public, but unfortunately the compiler sometimes synthesizes
76 // (unused) destructors for classes derived from ZoneObject, which
77 // require the operator to be visible. MSVC requires the delete
78 // operator to be public.
79
80 // ZoneObjects should never be deleted individually; use
81 // Zone::DeleteAll() to delete all zone objects in one go.
82 void operator delete(void*, size_t) { MOZ_CRASH("unreachable"); }
83 void operator delete(void* pointer, Zone* zone) { MOZ_CRASH("unreachable"); }
84 };
85
86 // ZoneLists are growable lists with constant-time access to the
87 // elements. The list itself and all its elements are allocated in the
88 // Zone. ZoneLists cannot be deleted individually; you can delete all
89 // objects in the Zone by calling Zone::DeleteAll().
90 // Used throughout irregexp.
91 // Based on: https://github.com/v8/v8/blob/master/src/zone/zone-list.h
92 template <typename T>
93 class ZoneList final : public ZoneObject {
94 public:
95 // Construct a new ZoneList with the given capacity; the length is
96 // always zero. The capacity must be non-negative.
97 ZoneList(int capacity, Zone* zone) : capacity_(capacity) {
98 data_ = (capacity_ > 0) ? zone->NewArray<T>(capacity_) : nullptr;
99 }
100 // Construct a new ZoneList by copying the elements of the given ZoneList.
101 ZoneList(const ZoneList<T>& other, Zone* zone)
102 : ZoneList(other.length(), zone) {
103 AddAll(other, zone);
104 }
105
106 // Construct a new ZoneList by copying the elements of the given vector.
107 ZoneList(const base::Vector<const T>& other, Zone* zone)
108 : ZoneList(other.length(), zone) {
109 AddAll(other, zone);
110 }
111
112 ZoneList(ZoneList<T>&& other) { *this = std::move(other); }
113
114 ZoneList& operator=(ZoneList&& other) {
115 MOZ_ASSERT(!data_);
116 data_ = other.data_;
117 capacity_ = other.capacity_;
118 length_ = other.length_;
119 other.Clear();
120 return *this;
121 }
122
123 // Returns a reference to the element at index i. This reference is not safe
124 // to use after operations that can change the list's backing store
125 // (e.g. Add).
126 inline T& operator[](int i) const {
127 MOZ_ASSERT(i >= 0);
128 MOZ_ASSERT(static_cast<unsigned>(i) < static_cast<unsigned>(length_));
129 return data_[i];
130 }
131 inline T& at(int i) const { return operator[](i); }
132 inline T& last() const { return at(length_ - 1); }
133 inline T& first() const { return at(0); }
134
135 using iterator = T*;
136 inline iterator begin() const { return &data_[0]; }
137 inline iterator end() const { return &data_[length_]; }
138
139 inline bool is_empty() const { return length_ == 0; }
140 inline int length() const { return length_; }
141 inline int capacity() const { return capacity_; }
142
143 base::Vector<T> ToVector() const { return base::Vector<T>(data_, length_); }
144 base::Vector<T> ToVector(int start, int length) const {
145 return base::Vector<T>(data_ + start, std::min(length_ - start, length));
146 }
147
148 base::Vector<const T> ToConstVector() const {
149 return base::Vector<const T>(data_, length_);
150 }
151
152 // Adds a copy of the given 'element' to the end of the list,
153 // expanding the list if necessary.
154 void Add(const T& element, Zone* zone) {
155 if (length_ < capacity_) {
156 data_[length_++] = element;
157 } else {
158 ZoneList<T>::ResizeAdd(element, zone);
159 }
160 }
161 // Add all the elements from the argument list to this list.
162 void AddAll(const ZoneList<T>& other, Zone* zone) {
163 AddAll(other.ToVector(), zone);
164 }
165 // Add all the elements from the vector to this list.
166 void AddAll(const base::Vector<const T>& other, Zone* zone) {
167 int result_length = length_ + other.length();
168 if (capacity_ < result_length) {
169 Resize(result_length, zone);
170 }
171 if (std::is_fundamental<T>()) {
172 memcpy(data_ + length_, other.begin(), sizeof(*data_) * other.length());
173 } else {
174 for (int i = 0; i < other.length(); i++) {
175 data_[length_ + i] = other.at(i);
176 }
177 }
178 length_ = result_length;
179 }
180
181 // Overwrites the element at the specific index.
182 void Set(int index, const T& element) {
183 MOZ_ASSERT(index >= 0 && index <= length_);
184 data_[index] = element;
185 }
186
187 // Removes the i'th element without deleting it even if T is a
188 // pointer type; moves all elements above i "down". Returns the
189 // removed element. This function's complexity is linear in the
190 // size of the list.
191 T Remove(int i) {
192 T element = at(i);
193 length_--;
194 while (i < length_) {
195 data_[i] = data_[i + 1];
196 i++;
197 }
198 return element;
199 }
200
201 // Removes the last element without deleting it even if T is a
202 // pointer type. Returns the removed element.
203 inline T RemoveLast() { return Remove(length_ - 1); }
204
205 // Clears the list, setting the capacity and length to 0.
206 inline void Clear() {
207 data_ = nullptr;
208 capacity_ = 0;
209 length_ = 0;
210 }
211
212 // Drops all but the first 'pos' elements from the list.
213 inline void Rewind(int pos) {
214 MOZ_ASSERT(0 <= pos && pos <= length_);
215 length_ = pos;
216 }
217
218 inline bool Contains(const T& elm) const {
219 for (int i = 0; i < length_; i++) {
220 if (data_[i] == elm) return true;
221 }
222 return false;
223 }
224
225 template <typename CompareFunction>
226 void StableSort(CompareFunction cmp, size_t start, size_t length) {
227 js::AutoEnterOOMUnsafeRegion oomUnsafe;
228 T* scratch = static_cast<T*>(js_malloc(length * sizeof(T)));
229 if (!scratch) {
230 oomUnsafe.crash("Irregexp stable sort scratch space");
231 }
232 auto comparator = [cmp](const T& a, const T& b, bool* lessOrEqual) {
233 *lessOrEqual = cmp(&a, &b) <= 0;
234 return true;
235 };
236 MOZ_ALWAYS_TRUE(
237 js::MergeSort(begin() + start, length, scratch, comparator));
238 js_free(scratch);
239 }
240
241 void operator delete(void* pointer) { MOZ_CRASH("unreachable"); }
242 void operator delete(void* pointer, Zone* zone) { MOZ_CRASH("unreachable"); }
243
244 private:
245 T* data_ = nullptr;
246 int capacity_ = 0;
247 int length_ = 0;
248
249 // Increase the capacity of a full list, and add an element.
250 // List must be full already.
251 void ResizeAdd(const T& element, Zone* zone) {
252 MOZ_ASSERT(length_ >= capacity_);
253 // Grow the list capacity by 100%, but make sure to let it grow
254 // even when the capacity is zero (possible initial case).
255 int new_capacity = 1 + 2 * capacity_;
256 // Since the element reference could be an element of the list, copy
257 // it out of the old backing storage before resizing.
258 T temp = element;
259 Resize(new_capacity, zone);
260 data_[length_++] = temp;
261 }
262
263 // Resize the list.
264 void Resize(int new_capacity, Zone* zone) {
265 MOZ_ASSERT(length_ <= new_capacity);
266 static_assert(std::is_trivially_copyable<T>::value);
267 T* new_data = zone->NewArray<T>(new_capacity);
268 if (length_ > 0) {
269 memcpy(new_data, data_, length_ * sizeof(T));
270 }
271 data_ = new_data;
272 capacity_ = new_capacity;
273 }
274
275 ZoneList& operator=(const ZoneList&) = delete;
276 ZoneList() = delete;
277 ZoneList(const ZoneList&) = delete;
278 };
279
280 // Based on: https://github.com/v8/v8/blob/master/src/zone/zone-allocator.h
281 template <typename T>
282 class ZoneAllocator {
283 public:
284 using pointer = T*;
285 using const_pointer = const T*;
286 using reference = T&;
287 using const_reference = const T&;
288 using value_type = T;
289 using size_type = size_t;
290 using difference_type = ptrdiff_t;
291 template <class O>
292 struct rebind {
293 using other = ZoneAllocator<O>;
294 };
295
296 explicit ZoneAllocator(Zone* zone) : zone_(zone) {}
297 template <typename U>
298 ZoneAllocator(const ZoneAllocator<U>& other)
299 : ZoneAllocator<T>(other.zone_) {}
300 template <typename U>
301 friend class ZoneAllocator;
302
303 T* allocate(size_t n) { return zone_->NewArray<T>(n); }
304 void deallocate(T* p, size_t) {} // noop for zones
305
306 bool operator==(ZoneAllocator const& other) const {
307 return zone_ == other.zone_;
308 }
309 bool operator!=(ZoneAllocator const& other) const {
310 return zone_ != other.zone_;
311 }
312
313 using Policy = js::LifoAllocPolicy<js::Fallible>;
314 Policy policy() const {
315 return js::LifoAllocPolicy<js::Fallible>(zone_->inner());
316 }
317
318 private:
319 Zone* zone_;
320 };
321
322 // Zone wrappers for std containers:
323 // Origin:
324 // https://github.com/v8/v8/blob/5e514a969376dc63517d575b062758efd36cd757/src/zone/zone-containers.h#L25-L169
325
326 // A wrapper subclass for std::vector to make it easy to construct one
327 // that uses a zone allocator.
328 // Used throughout irregexp
329 template <typename T>
330 class ZoneVector : public std::vector<T, ZoneAllocator<T>> {
331 public:
332 ZoneVector(Zone* zone)
333 : std::vector<T, ZoneAllocator<T>>(ZoneAllocator<T>(zone)) {}
334
335 // Constructs a new vector and fills it with {size} elements, each
336 // constructed via the default constructor.
337 ZoneVector(size_t size, Zone* zone)
338 : std::vector<T, ZoneAllocator<T>>(size, T(), ZoneAllocator<T>(zone)) {}
339
340 // Constructs a new vector and fills it with the contents of the range
341 // [first, last).
342 template <class Iter>
343 ZoneVector(Iter first, Iter last, Zone* zone)
344 : std::vector<T, ZoneAllocator<T>>(first, last, ZoneAllocator<T>(zone)) {}
345 };
346
347 // A wrapper subclass for std::list to make it easy to construct one
348 // that uses a zone allocator.
349 // Used in regexp-bytecode-peephole.cc
350 template <typename T>
351 class ZoneLinkedList : public std::list<T, ZoneAllocator<T>> {
352 public:
353 // Constructs an empty list.
354 explicit ZoneLinkedList(Zone* zone)
355 : std::list<T, ZoneAllocator<T>>(ZoneAllocator<T>(zone)) {}
356 };
357
358 // A wrapper subclass for std::set to make it easy to construct one that uses
359 // a zone allocator.
360 // Used in regexp-parser.cc
361 template <typename K, typename Compare = std::less<K>>
362 class ZoneSet : public std::set<K, Compare, ZoneAllocator<K>> {
363 public:
364 // Constructs an empty set.
365 explicit ZoneSet(Zone* zone)
366 : std::set<K, Compare, ZoneAllocator<K>>(Compare(),
367 ZoneAllocator<K>(zone)) {}
368 };
369
370 // A wrapper subclass for std::map to make it easy to construct one that uses
371 // a zone allocator.
372 // Used in regexp-bytecode-peephole.cc
373 template <typename K, typename V, typename Compare = std::less<K>>
374 class ZoneMap
375 : public std::map<K, V, Compare, ZoneAllocator<std::pair<const K, V>>> {
376 public:
377 // Constructs an empty map.
378 explicit ZoneMap(Zone* zone)
379 : std::map<K, V, Compare, ZoneAllocator<std::pair<const K, V>>>(
380 Compare(), ZoneAllocator<std::pair<const K, V>>(zone)) {}
381 };
382
383 // A wrapper subclass for std::unordered_map to make it easy to construct one
384 // that uses a zone allocator.
385 // Used in regexp-bytecode-peephole.cc
386 template <typename K, typename V, typename Hash = std::hash<K>,
387 typename KeyEqual = std::equal_to<K>>
388 class ZoneUnorderedMap
389 : public std::unordered_map<K, V, Hash, KeyEqual,
390 ZoneAllocator<std::pair<const K, V>>> {
391 public:
392 // Constructs an empty map.
393 explicit ZoneUnorderedMap(Zone* zone, size_t bucket_count = 100)
394 : std::unordered_map<K, V, Hash, KeyEqual,
395 ZoneAllocator<std::pair<const K, V>>>(
396 bucket_count, Hash(), KeyEqual(),
397 ZoneAllocator<std::pair<const K, V>>(zone)) {}
398 };
399
400 // A wrapper subclass for base::SmallVector to make it easy to construct one
401 // that uses a zone allocator.
402 template <typename T, size_t kSize>
403 class SmallZoneVector : public base::SmallVector<T, kSize, ZoneAllocator<T>> {
404 public:
405 // Constructs an empty small vector.
406 explicit SmallZoneVector(Zone* zone)
407 : base::SmallVector<T, kSize, ZoneAllocator<T>>(ZoneAllocator<T>(zone)) {}
408
409 explicit SmallZoneVector(size_t size, Zone* zone)
410 : base::SmallVector<T, kSize, ZoneAllocator<T>>(
411 size, ZoneAllocator<T>(ZoneAllocator<T>(zone))) {}
412 };
413
414 } // namespace internal
415 } // namespace v8
416
417 #endif // V8_UTIL_FLAG_H_