blob: 26c522b89f2025e06f56ffd4878aabdf51d42dbc [file] [log] [blame]
Ben Murdoch257744e2011-11-30 15:57:28 +00001// Copyright 2011 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#ifndef V8_UTILS_H_
29#define V8_UTILS_H_
30
31#include <stdlib.h>
Steve Block6ded16b2010-05-10 14:33:55 +010032#include <string.h>
Ben Murdoch69a99ed2011-11-30 16:03:39 +000033#include <climits>
Steve Blocka7e24c12009-10-30 11:49:00 +000034
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080035#include "globals.h"
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080036#include "checks.h"
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080037#include "allocation.h"
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080038
Steve Blocka7e24c12009-10-30 11:49:00 +000039namespace v8 {
40namespace internal {
41
42// ----------------------------------------------------------------------------
43// General helper functions
44
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010045#define IS_POWER_OF_TWO(x) (((x) & ((x) - 1)) == 0)
46
Steve Block3ce2e202009-11-05 08:53:23 +000047// Returns true iff x is a power of 2 (or zero). Cannot be used with the
48// maximally negative value of the type T (the -1 overflows).
Steve Blocka7e24c12009-10-30 11:49:00 +000049template <typename T>
50static inline bool IsPowerOf2(T x) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010051 return IS_POWER_OF_TWO(x);
Steve Blocka7e24c12009-10-30 11:49:00 +000052}
53
54
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010055// X must be a power of 2. Returns the number of trailing zeros.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000056static inline int WhichPowerOf2(uint32_t x) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010057 ASSERT(IsPowerOf2(x));
58 ASSERT(x != 0);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010059 int bits = 0;
60#ifdef DEBUG
61 int original_x = x;
62#endif
63 if (x >= 0x10000) {
64 bits += 16;
65 x >>= 16;
66 }
67 if (x >= 0x100) {
68 bits += 8;
69 x >>= 8;
70 }
71 if (x >= 0x10) {
72 bits += 4;
73 x >>= 4;
74 }
75 switch (x) {
76 default: UNREACHABLE();
77 case 8: bits++; // Fall through.
78 case 4: bits++; // Fall through.
79 case 2: bits++; // Fall through.
80 case 1: break;
81 }
82 ASSERT_EQ(1 << bits, original_x);
83 return bits;
84 return 0;
85}
86
87
Steve Blocka7e24c12009-10-30 11:49:00 +000088// The C++ standard leaves the semantics of '>>' undefined for
89// negative signed operands. Most implementations do the right thing,
90// though.
91static inline int ArithmeticShiftRight(int x, int s) {
92 return x >> s;
93}
94
95
96// Compute the 0-relative offset of some absolute value x of type T.
97// This allows conversion of Addresses and integral types into
98// 0-relative int offsets.
99template <typename T>
100static inline intptr_t OffsetFrom(T x) {
101 return x - static_cast<T>(0);
102}
103
104
105// Compute the absolute value of type T for some 0-relative offset x.
106// This allows conversion of 0-relative int offsets into Addresses and
107// integral types.
108template <typename T>
109static inline T AddressFrom(intptr_t x) {
Steve Blockd0582a62009-12-15 09:54:21 +0000110 return static_cast<T>(static_cast<T>(0) + x);
Steve Blocka7e24c12009-10-30 11:49:00 +0000111}
112
113
114// Return the largest multiple of m which is <= x.
115template <typename T>
116static inline T RoundDown(T x, int m) {
117 ASSERT(IsPowerOf2(m));
118 return AddressFrom<T>(OffsetFrom(x) & -m);
119}
120
121
122// Return the smallest multiple of m which is >= x.
123template <typename T>
124static inline T RoundUp(T x, int m) {
125 return RoundDown(x + m - 1, m);
126}
127
128
129template <typename T>
130static int Compare(const T& a, const T& b) {
131 if (a == b)
132 return 0;
133 else if (a < b)
134 return -1;
135 else
136 return 1;
137}
138
139
140template <typename T>
141static int PointerValueCompare(const T* a, const T* b) {
142 return Compare<T>(*a, *b);
143}
144
145
146// Returns the smallest power of two which is >= x. If you pass in a
147// number that is already a power of two, it is returned as is.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800148// Implementation is from "Hacker's Delight" by Henry S. Warren, Jr.,
149// figure 3-3, page 48, where the function is called clp2.
150static inline uint32_t RoundUpToPowerOf2(uint32_t x) {
151 ASSERT(x <= 0x80000000u);
152 x = x - 1;
153 x = x | (x >> 1);
154 x = x | (x >> 2);
155 x = x | (x >> 4);
156 x = x | (x >> 8);
157 x = x | (x >> 16);
158 return x + 1;
159}
160
Steve Blocka7e24c12009-10-30 11:49:00 +0000161
162
163template <typename T>
164static inline bool IsAligned(T value, T alignment) {
165 ASSERT(IsPowerOf2(alignment));
166 return (value & (alignment - 1)) == 0;
167}
168
169
170// Returns true if (addr + offset) is aligned.
171static inline bool IsAddressAligned(Address addr,
172 intptr_t alignment,
173 int offset) {
174 intptr_t offs = OffsetFrom(addr + offset);
175 return IsAligned(offs, alignment);
176}
177
178
179// Returns the maximum of the two parameters.
180template <typename T>
181static T Max(T a, T b) {
182 return a < b ? b : a;
183}
184
185
186// Returns the minimum of the two parameters.
187template <typename T>
188static T Min(T a, T b) {
189 return a < b ? a : b;
190}
191
192
Steve Blockd0582a62009-12-15 09:54:21 +0000193inline int StrLength(const char* string) {
194 size_t length = strlen(string);
195 ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
196 return static_cast<int>(length);
197}
198
199
Steve Blocka7e24c12009-10-30 11:49:00 +0000200// ----------------------------------------------------------------------------
201// BitField is a help template for encoding and decode bitfield with
202// unsigned content.
203template<class T, int shift, int size>
204class BitField {
205 public:
Ben Murdoch589d6972011-11-30 16:04:58 +0000206 // A uint32_t mask of bit field. To use all bits of a uint32 in a
207 // bitfield without compiler warnings we have to compute 2^32 without
208 // using a shift count of 32.
209 static const uint32_t kMask = ((1U << shift) << size) - (1U << shift);
210
211 // Value for the field with all bits set.
212 static const T kMax = static_cast<T>((1U << size) - 1);
213
Steve Blocka7e24c12009-10-30 11:49:00 +0000214 // Tells whether the provided value fits into the bit field.
215 static bool is_valid(T value) {
Ben Murdoch589d6972011-11-30 16:04:58 +0000216 return (static_cast<uint32_t>(value) & ~static_cast<uint32_t>(kMax)) == 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000217 }
218
219 // Returns a uint32_t with the bit field value encoded.
220 static uint32_t encode(T value) {
221 ASSERT(is_valid(value));
222 return static_cast<uint32_t>(value) << shift;
223 }
224
Ben Murdoch257744e2011-11-30 15:57:28 +0000225 // Returns a uint32_t with the bit field value updated.
226 static uint32_t update(uint32_t previous, T value) {
Ben Murdoch589d6972011-11-30 16:04:58 +0000227 return (previous & ~kMask) | encode(value);
Ben Murdoch257744e2011-11-30 15:57:28 +0000228 }
229
Steve Blocka7e24c12009-10-30 11:49:00 +0000230 // Extracts the bit field from the value.
231 static T decode(uint32_t value) {
Ben Murdoch589d6972011-11-30 16:04:58 +0000232 return static_cast<T>((value & kMask) >> shift);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100233 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000234};
235
236
237// ----------------------------------------------------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +0000238// Hash function.
239
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800240// Thomas Wang, Integer Hash Functions.
241// http://www.concentric.net/~Ttwang/tech/inthash.htm
242static inline uint32_t ComputeIntegerHash(uint32_t key) {
243 uint32_t hash = key;
244 hash = ~hash + (hash << 15); // hash = (hash << 15) - hash - 1;
245 hash = hash ^ (hash >> 12);
246 hash = hash + (hash << 2);
247 hash = hash ^ (hash >> 4);
248 hash = hash * 2057; // hash = (hash + (hash << 3)) + (hash << 11);
249 hash = hash ^ (hash >> 16);
250 return hash;
251}
Steve Blocka7e24c12009-10-30 11:49:00 +0000252
253
Ben Murdoch257744e2011-11-30 15:57:28 +0000254static inline uint32_t ComputePointerHash(void* ptr) {
255 return ComputeIntegerHash(
256 static_cast<uint32_t>(reinterpret_cast<intptr_t>(ptr)));
257}
258
259
Steve Blocka7e24c12009-10-30 11:49:00 +0000260// ----------------------------------------------------------------------------
261// Miscellaneous
262
263// A static resource holds a static instance that can be reserved in
264// a local scope using an instance of Access. Attempts to re-reserve
265// the instance will cause an error.
266template <typename T>
267class StaticResource {
268 public:
269 StaticResource() : is_reserved_(false) {}
270
271 private:
272 template <typename S> friend class Access;
273 T instance_;
274 bool is_reserved_;
275};
276
277
278// Locally scoped access to a static resource.
279template <typename T>
280class Access {
281 public:
282 explicit Access(StaticResource<T>* resource)
283 : resource_(resource)
284 , instance_(&resource->instance_) {
285 ASSERT(!resource->is_reserved_);
286 resource->is_reserved_ = true;
287 }
288
289 ~Access() {
290 resource_->is_reserved_ = false;
291 resource_ = NULL;
292 instance_ = NULL;
293 }
294
295 T* value() { return instance_; }
296 T* operator -> () { return instance_; }
297
298 private:
299 StaticResource<T>* resource_;
300 T* instance_;
301};
302
303
304template <typename T>
305class Vector {
306 public:
307 Vector() : start_(NULL), length_(0) {}
308 Vector(T* data, int length) : start_(data), length_(length) {
309 ASSERT(length == 0 || (length > 0 && data != NULL));
310 }
311
312 static Vector<T> New(int length) {
313 return Vector<T>(NewArray<T>(length), length);
314 }
315
316 // Returns a vector using the same backing storage as this one,
317 // spanning from and including 'from', to but not including 'to'.
318 Vector<T> SubVector(int from, int to) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000319 ASSERT(to <= length_);
320 ASSERT(from < to);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100321 ASSERT(0 <= from);
Steve Blocka7e24c12009-10-30 11:49:00 +0000322 return Vector<T>(start() + from, to - from);
323 }
324
325 // Returns the length of the vector.
326 int length() const { return length_; }
327
328 // Returns whether or not the vector is empty.
329 bool is_empty() const { return length_ == 0; }
330
331 // Returns the pointer to the start of the data in the vector.
332 T* start() const { return start_; }
333
334 // Access individual vector elements - checks bounds in debug mode.
335 T& operator[](int index) const {
336 ASSERT(0 <= index && index < length_);
337 return start_[index];
338 }
339
Ben Murdochb0fe1622011-05-05 13:52:32 +0100340 const T& at(int index) const { return operator[](index); }
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800341
Steve Blocka7e24c12009-10-30 11:49:00 +0000342 T& first() { return start_[0]; }
343
344 T& last() { return start_[length_ - 1]; }
345
346 // Returns a clone of this vector with a new backing store.
347 Vector<T> Clone() const {
348 T* result = NewArray<T>(length_);
349 for (int i = 0; i < length_; i++) result[i] = start_[i];
350 return Vector<T>(result, length_);
351 }
352
353 void Sort(int (*cmp)(const T*, const T*)) {
354 typedef int (*RawComparer)(const void*, const void*);
355 qsort(start(),
356 length(),
357 sizeof(T),
358 reinterpret_cast<RawComparer>(cmp));
359 }
360
361 void Sort() {
362 Sort(PointerValueCompare<T>);
363 }
364
365 void Truncate(int length) {
366 ASSERT(length <= length_);
367 length_ = length;
368 }
369
370 // Releases the array underlying this vector. Once disposed the
371 // vector is empty.
372 void Dispose() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000373 DeleteArray(start_);
374 start_ = NULL;
375 length_ = 0;
376 }
377
378 inline Vector<T> operator+(int offset) {
379 ASSERT(offset < length_);
380 return Vector<T>(start_ + offset, length_ - offset);
381 }
382
383 // Factory method for creating empty vectors.
384 static Vector<T> empty() { return Vector<T>(NULL, 0); }
385
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100386 template<typename S>
387 static Vector<T> cast(Vector<S> input) {
388 return Vector<T>(reinterpret_cast<T*>(input.start()),
389 input.length() * sizeof(S) / sizeof(T));
390 }
391
Steve Blocka7e24c12009-10-30 11:49:00 +0000392 protected:
393 void set_start(T* start) { start_ = start; }
394
395 private:
396 T* start_;
397 int length_;
398};
399
400
Ben Murdochb0fe1622011-05-05 13:52:32 +0100401// A pointer that can only be set once and doesn't allow NULL values.
402template<typename T>
403class SetOncePointer {
404 public:
405 SetOncePointer() : pointer_(NULL) { }
406
407 bool is_set() const { return pointer_ != NULL; }
408
409 T* get() const {
410 ASSERT(pointer_ != NULL);
411 return pointer_;
412 }
413
414 void set(T* value) {
415 ASSERT(pointer_ == NULL && value != NULL);
416 pointer_ = value;
417 }
418
419 private:
420 T* pointer_;
421};
422
423
Steve Blocka7e24c12009-10-30 11:49:00 +0000424template <typename T, int kSize>
425class EmbeddedVector : public Vector<T> {
426 public:
427 EmbeddedVector() : Vector<T>(buffer_, kSize) { }
428
Ben Murdochb0fe1622011-05-05 13:52:32 +0100429 explicit EmbeddedVector(T initial_value) : Vector<T>(buffer_, kSize) {
430 for (int i = 0; i < kSize; ++i) {
431 buffer_[i] = initial_value;
432 }
433 }
434
Steve Blocka7e24c12009-10-30 11:49:00 +0000435 // When copying, make underlying Vector to reference our buffer.
436 EmbeddedVector(const EmbeddedVector& rhs)
437 : Vector<T>(rhs) {
438 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
439 set_start(buffer_);
440 }
441
442 EmbeddedVector& operator=(const EmbeddedVector& rhs) {
443 if (this == &rhs) return *this;
444 Vector<T>::operator=(rhs);
445 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
Steve Block6ded16b2010-05-10 14:33:55 +0100446 this->set_start(buffer_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000447 return *this;
448 }
449
450 private:
451 T buffer_[kSize];
452};
453
454
455template <typename T>
456class ScopedVector : public Vector<T> {
457 public:
458 explicit ScopedVector(int length) : Vector<T>(NewArray<T>(length), length) { }
459 ~ScopedVector() {
460 DeleteArray(this->start());
461 }
Kristian Monsen25f61362010-05-21 11:50:48 +0100462
463 private:
464 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedVector);
Steve Blocka7e24c12009-10-30 11:49:00 +0000465};
466
467
468inline Vector<const char> CStrVector(const char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000469 return Vector<const char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000470}
471
472inline Vector<char> MutableCStrVector(char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000473 return Vector<char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000474}
475
476inline Vector<char> MutableCStrVector(char* data, int max) {
Steve Blockd0582a62009-12-15 09:54:21 +0000477 int length = StrLength(data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000478 return Vector<char>(data, (length < max) ? length : max);
479}
480
Steve Blocka7e24c12009-10-30 11:49:00 +0000481
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100482/*
483 * A class that collects values into a backing store.
484 * Specialized versions of the class can allow access to the backing store
485 * in different ways.
486 * There is no guarantee that the backing store is contiguous (and, as a
487 * consequence, no guarantees that consecutively added elements are adjacent
488 * in memory). The collector may move elements unless it has guaranteed not
489 * to.
490 */
491template <typename T, int growth_factor = 2, int max_growth = 1 * MB>
492class Collector {
493 public:
494 explicit Collector(int initial_capacity = kMinCapacity)
495 : index_(0), size_(0) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100496 current_chunk_ = Vector<T>::New(initial_capacity);
497 }
498
499 virtual ~Collector() {
500 // Free backing store (in reverse allocation order).
501 current_chunk_.Dispose();
502 for (int i = chunks_.length() - 1; i >= 0; i--) {
503 chunks_.at(i).Dispose();
504 }
505 }
506
507 // Add a single element.
508 inline void Add(T value) {
509 if (index_ >= current_chunk_.length()) {
510 Grow(1);
511 }
512 current_chunk_[index_] = value;
513 index_++;
514 size_++;
515 }
516
517 // Add a block of contiguous elements and return a Vector backed by the
518 // memory area.
519 // A basic Collector will keep this vector valid as long as the Collector
520 // is alive.
521 inline Vector<T> AddBlock(int size, T initial_value) {
522 ASSERT(size > 0);
523 if (size > current_chunk_.length() - index_) {
524 Grow(size);
525 }
526 T* position = current_chunk_.start() + index_;
527 index_ += size;
528 size_ += size;
529 for (int i = 0; i < size; i++) {
530 position[i] = initial_value;
531 }
532 return Vector<T>(position, size);
533 }
534
535
Steve Block9fac8402011-05-12 15:51:54 +0100536 // Add a contiguous block of elements and return a vector backed
537 // by the added block.
538 // A basic Collector will keep this vector valid as long as the Collector
539 // is alive.
540 inline Vector<T> AddBlock(Vector<const T> source) {
541 if (source.length() > current_chunk_.length() - index_) {
542 Grow(source.length());
543 }
544 T* position = current_chunk_.start() + index_;
545 index_ += source.length();
546 size_ += source.length();
547 for (int i = 0; i < source.length(); i++) {
548 position[i] = source[i];
549 }
550 return Vector<T>(position, source.length());
551 }
552
553
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100554 // Write the contents of the collector into the provided vector.
555 void WriteTo(Vector<T> destination) {
556 ASSERT(size_ <= destination.length());
557 int position = 0;
558 for (int i = 0; i < chunks_.length(); i++) {
559 Vector<T> chunk = chunks_.at(i);
560 for (int j = 0; j < chunk.length(); j++) {
561 destination[position] = chunk[j];
562 position++;
563 }
564 }
565 for (int i = 0; i < index_; i++) {
566 destination[position] = current_chunk_[i];
567 position++;
568 }
569 }
570
571 // Allocate a single contiguous vector, copy all the collected
572 // elements to the vector, and return it.
573 // The caller is responsible for freeing the memory of the returned
574 // vector (e.g., using Vector::Dispose).
575 Vector<T> ToVector() {
576 Vector<T> new_store = Vector<T>::New(size_);
577 WriteTo(new_store);
578 return new_store;
579 }
580
581 // Resets the collector to be empty.
Ben Murdoch257744e2011-11-30 15:57:28 +0000582 virtual void Reset();
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100583
584 // Total number of elements added to collector so far.
585 inline int size() { return size_; }
586
587 protected:
588 static const int kMinCapacity = 16;
589 List<Vector<T> > chunks_;
590 Vector<T> current_chunk_; // Block of memory currently being written into.
591 int index_; // Current index in current chunk.
592 int size_; // Total number of elements in collector.
593
594 // Creates a new current chunk, and stores the old chunk in the chunks_ list.
595 void Grow(int min_capacity) {
596 ASSERT(growth_factor > 1);
Ben Murdoch589d6972011-11-30 16:04:58 +0000597 int new_capacity;
598 int current_length = current_chunk_.length();
599 if (current_length < kMinCapacity) {
600 // The collector started out as empty.
601 new_capacity = min_capacity * growth_factor;
602 if (new_capacity < kMinCapacity) new_capacity = kMinCapacity;
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100603 } else {
Ben Murdoch589d6972011-11-30 16:04:58 +0000604 int growth = current_length * (growth_factor - 1);
605 if (growth > max_growth) {
606 growth = max_growth;
607 }
608 new_capacity = current_length + growth;
609 if (new_capacity < min_capacity) {
610 new_capacity = min_capacity + growth;
611 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100612 }
Ben Murdoch589d6972011-11-30 16:04:58 +0000613 NewChunk(new_capacity);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100614 ASSERT(index_ + min_capacity <= current_chunk_.length());
615 }
616
617 // Before replacing the current chunk, give a subclass the option to move
618 // some of the current data into the new chunk. The function may update
619 // the current index_ value to represent data no longer in the current chunk.
620 // Returns the initial index of the new chunk (after copied data).
Ben Murdoch589d6972011-11-30 16:04:58 +0000621 virtual void NewChunk(int new_capacity) {
622 Vector<T> new_chunk = Vector<T>::New(new_capacity);
623 if (index_ > 0) {
624 chunks_.Add(current_chunk_.SubVector(0, index_));
625 } else {
626 current_chunk_.Dispose();
627 }
628 current_chunk_ = new_chunk;
629 index_ = 0;
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100630 }
631};
632
633
634/*
635 * A collector that allows sequences of values to be guaranteed to
636 * stay consecutive.
637 * If the backing store grows while a sequence is active, the current
638 * sequence might be moved, but after the sequence is ended, it will
639 * not move again.
640 * NOTICE: Blocks allocated using Collector::AddBlock(int) can move
641 * as well, if inside an active sequence where another element is added.
642 */
643template <typename T, int growth_factor = 2, int max_growth = 1 * MB>
644class SequenceCollector : public Collector<T, growth_factor, max_growth> {
645 public:
646 explicit SequenceCollector(int initial_capacity)
647 : Collector<T, growth_factor, max_growth>(initial_capacity),
648 sequence_start_(kNoSequence) { }
649
650 virtual ~SequenceCollector() {}
651
652 void StartSequence() {
653 ASSERT(sequence_start_ == kNoSequence);
654 sequence_start_ = this->index_;
655 }
656
657 Vector<T> EndSequence() {
658 ASSERT(sequence_start_ != kNoSequence);
659 int sequence_start = sequence_start_;
660 sequence_start_ = kNoSequence;
661 if (sequence_start == this->index_) return Vector<T>();
662 return this->current_chunk_.SubVector(sequence_start, this->index_);
663 }
664
665 // Drops the currently added sequence, and all collected elements in it.
666 void DropSequence() {
667 ASSERT(sequence_start_ != kNoSequence);
668 int sequence_length = this->index_ - sequence_start_;
669 this->index_ = sequence_start_;
670 this->size_ -= sequence_length;
671 sequence_start_ = kNoSequence;
672 }
673
674 virtual void Reset() {
675 sequence_start_ = kNoSequence;
676 this->Collector<T, growth_factor, max_growth>::Reset();
677 }
678
679 private:
680 static const int kNoSequence = -1;
681 int sequence_start_;
682
683 // Move the currently active sequence to the new chunk.
Ben Murdoch589d6972011-11-30 16:04:58 +0000684 virtual void NewChunk(int new_capacity) {
685 if (sequence_start_ == kNoSequence) {
686 // Fall back on default behavior if no sequence has been started.
687 this->Collector<T, growth_factor, max_growth>::NewChunk(new_capacity);
688 return;
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100689 }
Ben Murdoch589d6972011-11-30 16:04:58 +0000690 int sequence_length = this->index_ - sequence_start_;
691 Vector<T> new_chunk = Vector<T>::New(sequence_length + new_capacity);
692 ASSERT(sequence_length < new_chunk.length());
693 for (int i = 0; i < sequence_length; i++) {
694 new_chunk[i] = this->current_chunk_[sequence_start_ + i];
695 }
696 if (sequence_start_ > 0) {
697 this->chunks_.Add(this->current_chunk_.SubVector(0, sequence_start_));
698 } else {
699 this->current_chunk_.Dispose();
700 }
701 this->current_chunk_ = new_chunk;
702 this->index_ = sequence_length;
703 sequence_start_ = 0;
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100704 }
705};
706
707
Steve Block6ded16b2010-05-10 14:33:55 +0100708// Compare ASCII/16bit chars to ASCII/16bit chars.
709template <typename lchar, typename rchar>
710static inline int CompareChars(const lchar* lhs, const rchar* rhs, int chars) {
711 const lchar* limit = lhs + chars;
712#ifdef V8_HOST_CAN_READ_UNALIGNED
713 if (sizeof(*lhs) == sizeof(*rhs)) {
714 // Number of characters in a uintptr_t.
715 static const int kStepSize = sizeof(uintptr_t) / sizeof(*lhs); // NOLINT
716 while (lhs <= limit - kStepSize) {
717 if (*reinterpret_cast<const uintptr_t*>(lhs) !=
718 *reinterpret_cast<const uintptr_t*>(rhs)) {
719 break;
720 }
721 lhs += kStepSize;
722 rhs += kStepSize;
723 }
724 }
725#endif
726 while (lhs < limit) {
727 int r = static_cast<int>(*lhs) - static_cast<int>(*rhs);
728 if (r != 0) return r;
729 ++lhs;
730 ++rhs;
731 }
732 return 0;
733}
734
735
Steve Blockd0582a62009-12-15 09:54:21 +0000736// Calculate 10^exponent.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800737static inline int TenToThe(int exponent) {
738 ASSERT(exponent <= 9);
739 ASSERT(exponent >= 1);
740 int answer = 10;
741 for (int i = 1; i < exponent; i++) answer *= 10;
742 return answer;
743}
Steve Blockd0582a62009-12-15 09:54:21 +0000744
Steve Block6ded16b2010-05-10 14:33:55 +0100745
746// The type-based aliasing rule allows the compiler to assume that pointers of
747// different types (for some definition of different) never alias each other.
748// Thus the following code does not work:
749//
750// float f = foo();
751// int fbits = *(int*)(&f);
752//
753// The compiler 'knows' that the int pointer can't refer to f since the types
754// don't match, so the compiler may cache f in a register, leaving random data
755// in fbits. Using C++ style casts makes no difference, however a pointer to
756// char data is assumed to alias any other pointer. This is the 'memcpy
757// exception'.
758//
759// Bit_cast uses the memcpy exception to move the bits from a variable of one
760// type of a variable of another type. Of course the end result is likely to
761// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
762// will completely optimize BitCast away.
763//
764// There is an additional use for BitCast.
765// Recent gccs will warn when they see casts that may result in breakage due to
766// the type-based aliasing rule. If you have checked that there is no breakage
767// you can use BitCast to cast one pointer type to another. This confuses gcc
768// enough that it can no longer see that you have cast one pointer type to
769// another thus avoiding the warning.
Steve Block1e0659c2011-05-24 12:43:12 +0100770
771// We need different implementations of BitCast for pointer and non-pointer
772// values. We use partial specialization of auxiliary struct to work around
773// issues with template functions overloading.
774template <class Dest, class Source>
775struct BitCastHelper {
776 STATIC_ASSERT(sizeof(Dest) == sizeof(Source));
777
778 INLINE(static Dest cast(const Source& source)) {
779 Dest dest;
780 memcpy(&dest, &source, sizeof(dest));
781 return dest;
782 }
783};
784
785template <class Dest, class Source>
786struct BitCastHelper<Dest, Source*> {
787 INLINE(static Dest cast(Source* source)) {
788 return BitCastHelper<Dest, uintptr_t>::
789 cast(reinterpret_cast<uintptr_t>(source));
790 }
791};
792
Steve Block6ded16b2010-05-10 14:33:55 +0100793template <class Dest, class Source>
Steve Block44f0eee2011-05-26 01:26:41 +0100794INLINE(Dest BitCast(const Source& source));
795
796template <class Dest, class Source>
Steve Block6ded16b2010-05-10 14:33:55 +0100797inline Dest BitCast(const Source& source) {
Steve Block1e0659c2011-05-24 12:43:12 +0100798 return BitCastHelper<Dest, Source>::cast(source);
Iain Merrick75681382010-08-19 15:07:18 +0100799}
Steve Blocka7e24c12009-10-30 11:49:00 +0000800
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000801
802template<typename ElementType, int NumElements>
803class EmbeddedContainer {
804 public:
805 EmbeddedContainer() : elems_() { }
806
807 int length() { return NumElements; }
808 ElementType& operator[](int i) {
809 ASSERT(i < length());
810 return elems_[i];
811 }
812
813 private:
814 ElementType elems_[NumElements];
815};
816
817
818template<typename ElementType>
819class EmbeddedContainer<ElementType, 0> {
820 public:
821 int length() { return 0; }
822 ElementType& operator[](int i) {
823 UNREACHABLE();
824 static ElementType t = 0;
825 return t;
826 }
827};
828
829
830// Helper class for building result strings in a character buffer. The
831// purpose of the class is to use safe operations that checks the
832// buffer bounds on all operations in debug mode.
833// This simple base class does not allow formatted output.
834class SimpleStringBuilder {
835 public:
836 // Create a string builder with a buffer of the given size. The
837 // buffer is allocated through NewArray<char> and must be
838 // deallocated by the caller of Finalize().
839 explicit SimpleStringBuilder(int size);
840
841 SimpleStringBuilder(char* buffer, int size)
842 : buffer_(buffer, size), position_(0) { }
843
844 ~SimpleStringBuilder() { if (!is_finalized()) Finalize(); }
845
846 int size() const { return buffer_.length(); }
847
848 // Get the current position in the builder.
849 int position() const {
850 ASSERT(!is_finalized());
851 return position_;
852 }
853
854 // Reset the position.
855 void Reset() { position_ = 0; }
856
857 // Add a single character to the builder. It is not allowed to add
858 // 0-characters; use the Finalize() method to terminate the string
859 // instead.
860 void AddCharacter(char c) {
861 ASSERT(c != '\0');
862 ASSERT(!is_finalized() && position_ < buffer_.length());
863 buffer_[position_++] = c;
864 }
865
866 // Add an entire string to the builder. Uses strlen() internally to
867 // compute the length of the input string.
868 void AddString(const char* s);
869
870 // Add the first 'n' characters of the given string 's' to the
871 // builder. The input string must have enough characters.
872 void AddSubstring(const char* s, int n);
873
874 // Add character padding to the builder. If count is non-positive,
875 // nothing is added to the builder.
876 void AddPadding(char c, int count);
877
878 // Add the decimal representation of the value.
879 void AddDecimalInteger(int value);
880
881 // Finalize the string by 0-terminating it and returning the buffer.
882 char* Finalize();
883
884 protected:
885 Vector<char> buffer_;
886 int position_;
887
888 bool is_finalized() const { return position_ < 0; }
Ben Murdoch589d6972011-11-30 16:04:58 +0000889
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000890 private:
891 DISALLOW_IMPLICIT_CONSTRUCTORS(SimpleStringBuilder);
892};
893
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000894
895// A poor man's version of STL's bitset: A bit set of enums E (without explicit
896// values), fitting into an integral type T.
897template <class E, class T = int>
898class EnumSet {
899 public:
900 explicit EnumSet(T bits = 0) : bits_(bits) {}
901 bool IsEmpty() const { return bits_ == 0; }
902 bool Contains(E element) const { return (bits_ & Mask(element)) != 0; }
903 void Add(E element) { bits_ |= Mask(element); }
904 void Remove(E element) { bits_ &= ~Mask(element); }
905 T ToIntegral() const { return bits_; }
906
907 private:
908 T Mask(E element) const {
909 // The strange typing in ASSERT is necessary to avoid stupid warnings, see:
910 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43680
911 ASSERT(element < static_cast<int>(sizeof(T) * CHAR_BIT));
912 return 1 << element;
913 }
914
915 T bits_;
916};
917
Iain Merrick75681382010-08-19 15:07:18 +0100918} } // namespace v8::internal
Steve Block6ded16b2010-05-10 14:33:55 +0100919
Steve Blocka7e24c12009-10-30 11:49:00 +0000920#endif // V8_UTILS_H_