blob: cf7819e4a20aac3d353a2c09b7155ff51faf21dc [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
Ben Murdoch2b4ba112012-01-20 14:57:15 +0000240static const uint32_t kZeroHashSeed = 0;
241
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800242// Thomas Wang, Integer Hash Functions.
243// http://www.concentric.net/~Ttwang/tech/inthash.htm
Ben Murdoch2b4ba112012-01-20 14:57:15 +0000244static inline uint32_t ComputeIntegerHash(uint32_t key, uint32_t seed) {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800245 uint32_t hash = key;
Ben Murdoch2b4ba112012-01-20 14:57:15 +0000246 hash = hash ^ seed;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800247 hash = ~hash + (hash << 15); // hash = (hash << 15) - hash - 1;
248 hash = hash ^ (hash >> 12);
249 hash = hash + (hash << 2);
250 hash = hash ^ (hash >> 4);
251 hash = hash * 2057; // hash = (hash + (hash << 3)) + (hash << 11);
252 hash = hash ^ (hash >> 16);
253 return hash;
254}
Steve Blocka7e24c12009-10-30 11:49:00 +0000255
256
Ben Murdoch257744e2011-11-30 15:57:28 +0000257static inline uint32_t ComputePointerHash(void* ptr) {
258 return ComputeIntegerHash(
Ben Murdoch2b4ba112012-01-20 14:57:15 +0000259 static_cast<uint32_t>(reinterpret_cast<intptr_t>(ptr)),
260 v8::internal::kZeroHashSeed);
Ben Murdoch257744e2011-11-30 15:57:28 +0000261}
262
263
Steve Blocka7e24c12009-10-30 11:49:00 +0000264// ----------------------------------------------------------------------------
265// Miscellaneous
266
267// A static resource holds a static instance that can be reserved in
268// a local scope using an instance of Access. Attempts to re-reserve
269// the instance will cause an error.
270template <typename T>
271class StaticResource {
272 public:
273 StaticResource() : is_reserved_(false) {}
274
275 private:
276 template <typename S> friend class Access;
277 T instance_;
278 bool is_reserved_;
279};
280
281
282// Locally scoped access to a static resource.
283template <typename T>
284class Access {
285 public:
286 explicit Access(StaticResource<T>* resource)
287 : resource_(resource)
288 , instance_(&resource->instance_) {
289 ASSERT(!resource->is_reserved_);
290 resource->is_reserved_ = true;
291 }
292
293 ~Access() {
294 resource_->is_reserved_ = false;
295 resource_ = NULL;
296 instance_ = NULL;
297 }
298
299 T* value() { return instance_; }
300 T* operator -> () { return instance_; }
301
302 private:
303 StaticResource<T>* resource_;
304 T* instance_;
305};
306
307
308template <typename T>
309class Vector {
310 public:
311 Vector() : start_(NULL), length_(0) {}
312 Vector(T* data, int length) : start_(data), length_(length) {
313 ASSERT(length == 0 || (length > 0 && data != NULL));
314 }
315
316 static Vector<T> New(int length) {
317 return Vector<T>(NewArray<T>(length), length);
318 }
319
320 // Returns a vector using the same backing storage as this one,
321 // spanning from and including 'from', to but not including 'to'.
322 Vector<T> SubVector(int from, int to) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000323 ASSERT(to <= length_);
324 ASSERT(from < to);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100325 ASSERT(0 <= from);
Steve Blocka7e24c12009-10-30 11:49:00 +0000326 return Vector<T>(start() + from, to - from);
327 }
328
329 // Returns the length of the vector.
330 int length() const { return length_; }
331
332 // Returns whether or not the vector is empty.
333 bool is_empty() const { return length_ == 0; }
334
335 // Returns the pointer to the start of the data in the vector.
336 T* start() const { return start_; }
337
338 // Access individual vector elements - checks bounds in debug mode.
339 T& operator[](int index) const {
340 ASSERT(0 <= index && index < length_);
341 return start_[index];
342 }
343
Ben Murdochb0fe1622011-05-05 13:52:32 +0100344 const T& at(int index) const { return operator[](index); }
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800345
Steve Blocka7e24c12009-10-30 11:49:00 +0000346 T& first() { return start_[0]; }
347
348 T& last() { return start_[length_ - 1]; }
349
350 // Returns a clone of this vector with a new backing store.
351 Vector<T> Clone() const {
352 T* result = NewArray<T>(length_);
353 for (int i = 0; i < length_; i++) result[i] = start_[i];
354 return Vector<T>(result, length_);
355 }
356
357 void Sort(int (*cmp)(const T*, const T*)) {
358 typedef int (*RawComparer)(const void*, const void*);
359 qsort(start(),
360 length(),
361 sizeof(T),
362 reinterpret_cast<RawComparer>(cmp));
363 }
364
365 void Sort() {
366 Sort(PointerValueCompare<T>);
367 }
368
369 void Truncate(int length) {
370 ASSERT(length <= length_);
371 length_ = length;
372 }
373
374 // Releases the array underlying this vector. Once disposed the
375 // vector is empty.
376 void Dispose() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000377 DeleteArray(start_);
378 start_ = NULL;
379 length_ = 0;
380 }
381
382 inline Vector<T> operator+(int offset) {
383 ASSERT(offset < length_);
384 return Vector<T>(start_ + offset, length_ - offset);
385 }
386
387 // Factory method for creating empty vectors.
388 static Vector<T> empty() { return Vector<T>(NULL, 0); }
389
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100390 template<typename S>
391 static Vector<T> cast(Vector<S> input) {
392 return Vector<T>(reinterpret_cast<T*>(input.start()),
393 input.length() * sizeof(S) / sizeof(T));
394 }
395
Steve Blocka7e24c12009-10-30 11:49:00 +0000396 protected:
397 void set_start(T* start) { start_ = start; }
398
399 private:
400 T* start_;
401 int length_;
402};
403
404
Ben Murdochb0fe1622011-05-05 13:52:32 +0100405// A pointer that can only be set once and doesn't allow NULL values.
406template<typename T>
407class SetOncePointer {
408 public:
409 SetOncePointer() : pointer_(NULL) { }
410
411 bool is_set() const { return pointer_ != NULL; }
412
413 T* get() const {
414 ASSERT(pointer_ != NULL);
415 return pointer_;
416 }
417
418 void set(T* value) {
419 ASSERT(pointer_ == NULL && value != NULL);
420 pointer_ = value;
421 }
422
423 private:
424 T* pointer_;
425};
426
427
Steve Blocka7e24c12009-10-30 11:49:00 +0000428template <typename T, int kSize>
429class EmbeddedVector : public Vector<T> {
430 public:
431 EmbeddedVector() : Vector<T>(buffer_, kSize) { }
432
Ben Murdochb0fe1622011-05-05 13:52:32 +0100433 explicit EmbeddedVector(T initial_value) : Vector<T>(buffer_, kSize) {
434 for (int i = 0; i < kSize; ++i) {
435 buffer_[i] = initial_value;
436 }
437 }
438
Steve Blocka7e24c12009-10-30 11:49:00 +0000439 // When copying, make underlying Vector to reference our buffer.
440 EmbeddedVector(const EmbeddedVector& rhs)
441 : Vector<T>(rhs) {
442 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
443 set_start(buffer_);
444 }
445
446 EmbeddedVector& operator=(const EmbeddedVector& rhs) {
447 if (this == &rhs) return *this;
448 Vector<T>::operator=(rhs);
449 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
Steve Block6ded16b2010-05-10 14:33:55 +0100450 this->set_start(buffer_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000451 return *this;
452 }
453
454 private:
455 T buffer_[kSize];
456};
457
458
459template <typename T>
460class ScopedVector : public Vector<T> {
461 public:
462 explicit ScopedVector(int length) : Vector<T>(NewArray<T>(length), length) { }
463 ~ScopedVector() {
464 DeleteArray(this->start());
465 }
Kristian Monsen25f61362010-05-21 11:50:48 +0100466
467 private:
468 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedVector);
Steve Blocka7e24c12009-10-30 11:49:00 +0000469};
470
471
472inline Vector<const char> CStrVector(const char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000473 return Vector<const char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000474}
475
476inline Vector<char> MutableCStrVector(char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000477 return Vector<char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000478}
479
480inline Vector<char> MutableCStrVector(char* data, int max) {
Steve Blockd0582a62009-12-15 09:54:21 +0000481 int length = StrLength(data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000482 return Vector<char>(data, (length < max) ? length : max);
483}
484
Steve Blocka7e24c12009-10-30 11:49:00 +0000485
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100486/*
487 * A class that collects values into a backing store.
488 * Specialized versions of the class can allow access to the backing store
489 * in different ways.
490 * There is no guarantee that the backing store is contiguous (and, as a
491 * consequence, no guarantees that consecutively added elements are adjacent
492 * in memory). The collector may move elements unless it has guaranteed not
493 * to.
494 */
495template <typename T, int growth_factor = 2, int max_growth = 1 * MB>
496class Collector {
497 public:
498 explicit Collector(int initial_capacity = kMinCapacity)
499 : index_(0), size_(0) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100500 current_chunk_ = Vector<T>::New(initial_capacity);
501 }
502
503 virtual ~Collector() {
504 // Free backing store (in reverse allocation order).
505 current_chunk_.Dispose();
506 for (int i = chunks_.length() - 1; i >= 0; i--) {
507 chunks_.at(i).Dispose();
508 }
509 }
510
511 // Add a single element.
512 inline void Add(T value) {
513 if (index_ >= current_chunk_.length()) {
514 Grow(1);
515 }
516 current_chunk_[index_] = value;
517 index_++;
518 size_++;
519 }
520
521 // Add a block of contiguous elements and return a Vector backed by the
522 // memory area.
523 // A basic Collector will keep this vector valid as long as the Collector
524 // is alive.
525 inline Vector<T> AddBlock(int size, T initial_value) {
526 ASSERT(size > 0);
527 if (size > current_chunk_.length() - index_) {
528 Grow(size);
529 }
530 T* position = current_chunk_.start() + index_;
531 index_ += size;
532 size_ += size;
533 for (int i = 0; i < size; i++) {
534 position[i] = initial_value;
535 }
536 return Vector<T>(position, size);
537 }
538
539
Steve Block9fac8402011-05-12 15:51:54 +0100540 // Add a contiguous block of elements and return a vector backed
541 // by the added block.
542 // A basic Collector will keep this vector valid as long as the Collector
543 // is alive.
544 inline Vector<T> AddBlock(Vector<const T> source) {
545 if (source.length() > current_chunk_.length() - index_) {
546 Grow(source.length());
547 }
548 T* position = current_chunk_.start() + index_;
549 index_ += source.length();
550 size_ += source.length();
551 for (int i = 0; i < source.length(); i++) {
552 position[i] = source[i];
553 }
554 return Vector<T>(position, source.length());
555 }
556
557
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100558 // Write the contents of the collector into the provided vector.
559 void WriteTo(Vector<T> destination) {
560 ASSERT(size_ <= destination.length());
561 int position = 0;
562 for (int i = 0; i < chunks_.length(); i++) {
563 Vector<T> chunk = chunks_.at(i);
564 for (int j = 0; j < chunk.length(); j++) {
565 destination[position] = chunk[j];
566 position++;
567 }
568 }
569 for (int i = 0; i < index_; i++) {
570 destination[position] = current_chunk_[i];
571 position++;
572 }
573 }
574
575 // Allocate a single contiguous vector, copy all the collected
576 // elements to the vector, and return it.
577 // The caller is responsible for freeing the memory of the returned
578 // vector (e.g., using Vector::Dispose).
579 Vector<T> ToVector() {
580 Vector<T> new_store = Vector<T>::New(size_);
581 WriteTo(new_store);
582 return new_store;
583 }
584
585 // Resets the collector to be empty.
Ben Murdoch257744e2011-11-30 15:57:28 +0000586 virtual void Reset();
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100587
588 // Total number of elements added to collector so far.
589 inline int size() { return size_; }
590
591 protected:
592 static const int kMinCapacity = 16;
593 List<Vector<T> > chunks_;
594 Vector<T> current_chunk_; // Block of memory currently being written into.
595 int index_; // Current index in current chunk.
596 int size_; // Total number of elements in collector.
597
598 // Creates a new current chunk, and stores the old chunk in the chunks_ list.
599 void Grow(int min_capacity) {
600 ASSERT(growth_factor > 1);
Ben Murdoch589d6972011-11-30 16:04:58 +0000601 int new_capacity;
602 int current_length = current_chunk_.length();
603 if (current_length < kMinCapacity) {
604 // The collector started out as empty.
605 new_capacity = min_capacity * growth_factor;
606 if (new_capacity < kMinCapacity) new_capacity = kMinCapacity;
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100607 } else {
Ben Murdoch589d6972011-11-30 16:04:58 +0000608 int growth = current_length * (growth_factor - 1);
609 if (growth > max_growth) {
610 growth = max_growth;
611 }
612 new_capacity = current_length + growth;
613 if (new_capacity < min_capacity) {
614 new_capacity = min_capacity + growth;
615 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100616 }
Ben Murdoch589d6972011-11-30 16:04:58 +0000617 NewChunk(new_capacity);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100618 ASSERT(index_ + min_capacity <= current_chunk_.length());
619 }
620
621 // Before replacing the current chunk, give a subclass the option to move
622 // some of the current data into the new chunk. The function may update
623 // the current index_ value to represent data no longer in the current chunk.
624 // Returns the initial index of the new chunk (after copied data).
Ben Murdoch589d6972011-11-30 16:04:58 +0000625 virtual void NewChunk(int new_capacity) {
626 Vector<T> new_chunk = Vector<T>::New(new_capacity);
627 if (index_ > 0) {
628 chunks_.Add(current_chunk_.SubVector(0, index_));
629 } else {
630 current_chunk_.Dispose();
631 }
632 current_chunk_ = new_chunk;
633 index_ = 0;
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100634 }
635};
636
637
638/*
639 * A collector that allows sequences of values to be guaranteed to
640 * stay consecutive.
641 * If the backing store grows while a sequence is active, the current
642 * sequence might be moved, but after the sequence is ended, it will
643 * not move again.
644 * NOTICE: Blocks allocated using Collector::AddBlock(int) can move
645 * as well, if inside an active sequence where another element is added.
646 */
647template <typename T, int growth_factor = 2, int max_growth = 1 * MB>
648class SequenceCollector : public Collector<T, growth_factor, max_growth> {
649 public:
650 explicit SequenceCollector(int initial_capacity)
651 : Collector<T, growth_factor, max_growth>(initial_capacity),
652 sequence_start_(kNoSequence) { }
653
654 virtual ~SequenceCollector() {}
655
656 void StartSequence() {
657 ASSERT(sequence_start_ == kNoSequence);
658 sequence_start_ = this->index_;
659 }
660
661 Vector<T> EndSequence() {
662 ASSERT(sequence_start_ != kNoSequence);
663 int sequence_start = sequence_start_;
664 sequence_start_ = kNoSequence;
665 if (sequence_start == this->index_) return Vector<T>();
666 return this->current_chunk_.SubVector(sequence_start, this->index_);
667 }
668
669 // Drops the currently added sequence, and all collected elements in it.
670 void DropSequence() {
671 ASSERT(sequence_start_ != kNoSequence);
672 int sequence_length = this->index_ - sequence_start_;
673 this->index_ = sequence_start_;
674 this->size_ -= sequence_length;
675 sequence_start_ = kNoSequence;
676 }
677
678 virtual void Reset() {
679 sequence_start_ = kNoSequence;
680 this->Collector<T, growth_factor, max_growth>::Reset();
681 }
682
683 private:
684 static const int kNoSequence = -1;
685 int sequence_start_;
686
687 // Move the currently active sequence to the new chunk.
Ben Murdoch589d6972011-11-30 16:04:58 +0000688 virtual void NewChunk(int new_capacity) {
689 if (sequence_start_ == kNoSequence) {
690 // Fall back on default behavior if no sequence has been started.
691 this->Collector<T, growth_factor, max_growth>::NewChunk(new_capacity);
692 return;
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100693 }
Ben Murdoch589d6972011-11-30 16:04:58 +0000694 int sequence_length = this->index_ - sequence_start_;
695 Vector<T> new_chunk = Vector<T>::New(sequence_length + new_capacity);
696 ASSERT(sequence_length < new_chunk.length());
697 for (int i = 0; i < sequence_length; i++) {
698 new_chunk[i] = this->current_chunk_[sequence_start_ + i];
699 }
700 if (sequence_start_ > 0) {
701 this->chunks_.Add(this->current_chunk_.SubVector(0, sequence_start_));
702 } else {
703 this->current_chunk_.Dispose();
704 }
705 this->current_chunk_ = new_chunk;
706 this->index_ = sequence_length;
707 sequence_start_ = 0;
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100708 }
709};
710
711
Steve Block6ded16b2010-05-10 14:33:55 +0100712// Compare ASCII/16bit chars to ASCII/16bit chars.
713template <typename lchar, typename rchar>
714static inline int CompareChars(const lchar* lhs, const rchar* rhs, int chars) {
715 const lchar* limit = lhs + chars;
716#ifdef V8_HOST_CAN_READ_UNALIGNED
717 if (sizeof(*lhs) == sizeof(*rhs)) {
718 // Number of characters in a uintptr_t.
719 static const int kStepSize = sizeof(uintptr_t) / sizeof(*lhs); // NOLINT
720 while (lhs <= limit - kStepSize) {
721 if (*reinterpret_cast<const uintptr_t*>(lhs) !=
722 *reinterpret_cast<const uintptr_t*>(rhs)) {
723 break;
724 }
725 lhs += kStepSize;
726 rhs += kStepSize;
727 }
728 }
729#endif
730 while (lhs < limit) {
731 int r = static_cast<int>(*lhs) - static_cast<int>(*rhs);
732 if (r != 0) return r;
733 ++lhs;
734 ++rhs;
735 }
736 return 0;
737}
738
739
Steve Blockd0582a62009-12-15 09:54:21 +0000740// Calculate 10^exponent.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800741static inline int TenToThe(int exponent) {
742 ASSERT(exponent <= 9);
743 ASSERT(exponent >= 1);
744 int answer = 10;
745 for (int i = 1; i < exponent; i++) answer *= 10;
746 return answer;
747}
Steve Blockd0582a62009-12-15 09:54:21 +0000748
Steve Block6ded16b2010-05-10 14:33:55 +0100749
750// The type-based aliasing rule allows the compiler to assume that pointers of
751// different types (for some definition of different) never alias each other.
752// Thus the following code does not work:
753//
754// float f = foo();
755// int fbits = *(int*)(&f);
756//
757// The compiler 'knows' that the int pointer can't refer to f since the types
758// don't match, so the compiler may cache f in a register, leaving random data
759// in fbits. Using C++ style casts makes no difference, however a pointer to
760// char data is assumed to alias any other pointer. This is the 'memcpy
761// exception'.
762//
763// Bit_cast uses the memcpy exception to move the bits from a variable of one
764// type of a variable of another type. Of course the end result is likely to
765// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
766// will completely optimize BitCast away.
767//
768// There is an additional use for BitCast.
769// Recent gccs will warn when they see casts that may result in breakage due to
770// the type-based aliasing rule. If you have checked that there is no breakage
771// you can use BitCast to cast one pointer type to another. This confuses gcc
772// enough that it can no longer see that you have cast one pointer type to
773// another thus avoiding the warning.
Steve Block1e0659c2011-05-24 12:43:12 +0100774
775// We need different implementations of BitCast for pointer and non-pointer
776// values. We use partial specialization of auxiliary struct to work around
777// issues with template functions overloading.
778template <class Dest, class Source>
779struct BitCastHelper {
780 STATIC_ASSERT(sizeof(Dest) == sizeof(Source));
781
782 INLINE(static Dest cast(const Source& source)) {
783 Dest dest;
784 memcpy(&dest, &source, sizeof(dest));
785 return dest;
786 }
787};
788
789template <class Dest, class Source>
790struct BitCastHelper<Dest, Source*> {
791 INLINE(static Dest cast(Source* source)) {
792 return BitCastHelper<Dest, uintptr_t>::
793 cast(reinterpret_cast<uintptr_t>(source));
794 }
795};
796
Steve Block6ded16b2010-05-10 14:33:55 +0100797template <class Dest, class Source>
Steve Block44f0eee2011-05-26 01:26:41 +0100798INLINE(Dest BitCast(const Source& source));
799
800template <class Dest, class Source>
Steve Block6ded16b2010-05-10 14:33:55 +0100801inline Dest BitCast(const Source& source) {
Steve Block1e0659c2011-05-24 12:43:12 +0100802 return BitCastHelper<Dest, Source>::cast(source);
Iain Merrick75681382010-08-19 15:07:18 +0100803}
Steve Blocka7e24c12009-10-30 11:49:00 +0000804
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000805
806template<typename ElementType, int NumElements>
807class EmbeddedContainer {
808 public:
809 EmbeddedContainer() : elems_() { }
810
811 int length() { return NumElements; }
812 ElementType& operator[](int i) {
813 ASSERT(i < length());
814 return elems_[i];
815 }
816
817 private:
818 ElementType elems_[NumElements];
819};
820
821
822template<typename ElementType>
823class EmbeddedContainer<ElementType, 0> {
824 public:
825 int length() { return 0; }
826 ElementType& operator[](int i) {
827 UNREACHABLE();
828 static ElementType t = 0;
829 return t;
830 }
831};
832
833
834// Helper class for building result strings in a character buffer. The
835// purpose of the class is to use safe operations that checks the
836// buffer bounds on all operations in debug mode.
837// This simple base class does not allow formatted output.
838class SimpleStringBuilder {
839 public:
840 // Create a string builder with a buffer of the given size. The
841 // buffer is allocated through NewArray<char> and must be
842 // deallocated by the caller of Finalize().
843 explicit SimpleStringBuilder(int size);
844
845 SimpleStringBuilder(char* buffer, int size)
846 : buffer_(buffer, size), position_(0) { }
847
848 ~SimpleStringBuilder() { if (!is_finalized()) Finalize(); }
849
850 int size() const { return buffer_.length(); }
851
852 // Get the current position in the builder.
853 int position() const {
854 ASSERT(!is_finalized());
855 return position_;
856 }
857
858 // Reset the position.
859 void Reset() { position_ = 0; }
860
861 // Add a single character to the builder. It is not allowed to add
862 // 0-characters; use the Finalize() method to terminate the string
863 // instead.
864 void AddCharacter(char c) {
865 ASSERT(c != '\0');
866 ASSERT(!is_finalized() && position_ < buffer_.length());
867 buffer_[position_++] = c;
868 }
869
870 // Add an entire string to the builder. Uses strlen() internally to
871 // compute the length of the input string.
872 void AddString(const char* s);
873
874 // Add the first 'n' characters of the given string 's' to the
875 // builder. The input string must have enough characters.
876 void AddSubstring(const char* s, int n);
877
878 // Add character padding to the builder. If count is non-positive,
879 // nothing is added to the builder.
880 void AddPadding(char c, int count);
881
882 // Add the decimal representation of the value.
883 void AddDecimalInteger(int value);
884
885 // Finalize the string by 0-terminating it and returning the buffer.
886 char* Finalize();
887
888 protected:
889 Vector<char> buffer_;
890 int position_;
891
892 bool is_finalized() const { return position_ < 0; }
Ben Murdoch589d6972011-11-30 16:04:58 +0000893
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000894 private:
895 DISALLOW_IMPLICIT_CONSTRUCTORS(SimpleStringBuilder);
896};
897
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000898
899// A poor man's version of STL's bitset: A bit set of enums E (without explicit
900// values), fitting into an integral type T.
901template <class E, class T = int>
902class EnumSet {
903 public:
904 explicit EnumSet(T bits = 0) : bits_(bits) {}
905 bool IsEmpty() const { return bits_ == 0; }
906 bool Contains(E element) const { return (bits_ & Mask(element)) != 0; }
907 void Add(E element) { bits_ |= Mask(element); }
908 void Remove(E element) { bits_ &= ~Mask(element); }
909 T ToIntegral() const { return bits_; }
910
911 private:
912 T Mask(E element) const {
913 // The strange typing in ASSERT is necessary to avoid stupid warnings, see:
914 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43680
915 ASSERT(element < static_cast<int>(sizeof(T) * CHAR_BIT));
916 return 1 << element;
917 }
918
919 T bits_;
920};
921
Iain Merrick75681382010-08-19 15:07:18 +0100922} } // namespace v8::internal
Steve Block6ded16b2010-05-10 14:33:55 +0100923
Steve Blocka7e24c12009-10-30 11:49:00 +0000924#endif // V8_UTILS_H_