blob: 785bc4373c8077b7d1850f117da67df1f13aebc8 [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:
206 // Tells whether the provided value fits into the bit field.
207 static bool is_valid(T value) {
208 return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0;
209 }
210
211 // Returns a uint32_t mask of bit field.
212 static uint32_t mask() {
Andrei Popescu402d9372010-02-26 13:31:12 +0000213 // To use all bits of a uint32 in a bitfield without compiler warnings we
214 // have to compute 2^32 without using a shift count of 32.
215 return ((1U << shift) << size) - (1U << shift);
Steve Blocka7e24c12009-10-30 11:49:00 +0000216 }
217
218 // Returns a uint32_t with the bit field value encoded.
219 static uint32_t encode(T value) {
220 ASSERT(is_valid(value));
221 return static_cast<uint32_t>(value) << shift;
222 }
223
Ben Murdoch257744e2011-11-30 15:57:28 +0000224 // Returns a uint32_t with the bit field value updated.
225 static uint32_t update(uint32_t previous, T value) {
226 return (previous & ~mask()) | encode(value);
227 }
228
Steve Blocka7e24c12009-10-30 11:49:00 +0000229 // Extracts the bit field from the value.
230 static T decode(uint32_t value) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000231 return static_cast<T>((value & mask()) >> shift);
Steve Blocka7e24c12009-10-30 11:49:00 +0000232 }
Ben Murdochb0fe1622011-05-05 13:52:32 +0100233
234 // Value for the field with all bits set.
235 static T max() {
236 return decode(mask());
237 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000238};
239
240
241// ----------------------------------------------------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +0000242// Hash function.
243
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800244// Thomas Wang, Integer Hash Functions.
245// http://www.concentric.net/~Ttwang/tech/inthash.htm
246static inline uint32_t ComputeIntegerHash(uint32_t key) {
247 uint32_t hash = key;
248 hash = ~hash + (hash << 15); // hash = (hash << 15) - hash - 1;
249 hash = hash ^ (hash >> 12);
250 hash = hash + (hash << 2);
251 hash = hash ^ (hash >> 4);
252 hash = hash * 2057; // hash = (hash + (hash << 3)) + (hash << 11);
253 hash = hash ^ (hash >> 16);
254 return hash;
255}
Steve Blocka7e24c12009-10-30 11:49:00 +0000256
257
Ben Murdoch257744e2011-11-30 15:57:28 +0000258static inline uint32_t ComputePointerHash(void* ptr) {
259 return ComputeIntegerHash(
260 static_cast<uint32_t>(reinterpret_cast<intptr_t>(ptr)));
261}
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) {
500 if (initial_capacity < kMinCapacity) {
501 initial_capacity = kMinCapacity;
502 }
503 current_chunk_ = Vector<T>::New(initial_capacity);
504 }
505
506 virtual ~Collector() {
507 // Free backing store (in reverse allocation order).
508 current_chunk_.Dispose();
509 for (int i = chunks_.length() - 1; i >= 0; i--) {
510 chunks_.at(i).Dispose();
511 }
512 }
513
514 // Add a single element.
515 inline void Add(T value) {
516 if (index_ >= current_chunk_.length()) {
517 Grow(1);
518 }
519 current_chunk_[index_] = value;
520 index_++;
521 size_++;
522 }
523
524 // Add a block of contiguous elements and return a Vector backed by the
525 // memory area.
526 // A basic Collector will keep this vector valid as long as the Collector
527 // is alive.
528 inline Vector<T> AddBlock(int size, T initial_value) {
529 ASSERT(size > 0);
530 if (size > current_chunk_.length() - index_) {
531 Grow(size);
532 }
533 T* position = current_chunk_.start() + index_;
534 index_ += size;
535 size_ += size;
536 for (int i = 0; i < size; i++) {
537 position[i] = initial_value;
538 }
539 return Vector<T>(position, size);
540 }
541
542
Steve Block9fac8402011-05-12 15:51:54 +0100543 // Add a contiguous block of elements and return a vector backed
544 // by the added block.
545 // A basic Collector will keep this vector valid as long as the Collector
546 // is alive.
547 inline Vector<T> AddBlock(Vector<const T> source) {
548 if (source.length() > current_chunk_.length() - index_) {
549 Grow(source.length());
550 }
551 T* position = current_chunk_.start() + index_;
552 index_ += source.length();
553 size_ += source.length();
554 for (int i = 0; i < source.length(); i++) {
555 position[i] = source[i];
556 }
557 return Vector<T>(position, source.length());
558 }
559
560
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100561 // Write the contents of the collector into the provided vector.
562 void WriteTo(Vector<T> destination) {
563 ASSERT(size_ <= destination.length());
564 int position = 0;
565 for (int i = 0; i < chunks_.length(); i++) {
566 Vector<T> chunk = chunks_.at(i);
567 for (int j = 0; j < chunk.length(); j++) {
568 destination[position] = chunk[j];
569 position++;
570 }
571 }
572 for (int i = 0; i < index_; i++) {
573 destination[position] = current_chunk_[i];
574 position++;
575 }
576 }
577
578 // Allocate a single contiguous vector, copy all the collected
579 // elements to the vector, and return it.
580 // The caller is responsible for freeing the memory of the returned
581 // vector (e.g., using Vector::Dispose).
582 Vector<T> ToVector() {
583 Vector<T> new_store = Vector<T>::New(size_);
584 WriteTo(new_store);
585 return new_store;
586 }
587
588 // Resets the collector to be empty.
Ben Murdoch257744e2011-11-30 15:57:28 +0000589 virtual void Reset();
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100590
591 // Total number of elements added to collector so far.
592 inline int size() { return size_; }
593
594 protected:
595 static const int kMinCapacity = 16;
596 List<Vector<T> > chunks_;
597 Vector<T> current_chunk_; // Block of memory currently being written into.
598 int index_; // Current index in current chunk.
599 int size_; // Total number of elements in collector.
600
601 // Creates a new current chunk, and stores the old chunk in the chunks_ list.
602 void Grow(int min_capacity) {
603 ASSERT(growth_factor > 1);
604 int growth = current_chunk_.length() * (growth_factor - 1);
605 if (growth > max_growth) {
606 growth = max_growth;
607 }
608 int new_capacity = current_chunk_.length() + growth;
609 if (new_capacity < min_capacity) {
610 new_capacity = min_capacity + growth;
611 }
612 Vector<T> new_chunk = Vector<T>::New(new_capacity);
613 int new_index = PrepareGrow(new_chunk);
614 if (index_ > 0) {
615 chunks_.Add(current_chunk_.SubVector(0, index_));
616 } else {
617 // Can happen if the call to PrepareGrow moves everything into
618 // the new chunk.
619 current_chunk_.Dispose();
620 }
621 current_chunk_ = new_chunk;
622 index_ = new_index;
623 ASSERT(index_ + min_capacity <= current_chunk_.length());
624 }
625
626 // Before replacing the current chunk, give a subclass the option to move
627 // some of the current data into the new chunk. The function may update
628 // the current index_ value to represent data no longer in the current chunk.
629 // Returns the initial index of the new chunk (after copied data).
630 virtual int PrepareGrow(Vector<T> new_chunk) {
631 return 0;
632 }
633};
634
635
636/*
637 * A collector that allows sequences of values to be guaranteed to
638 * stay consecutive.
639 * If the backing store grows while a sequence is active, the current
640 * sequence might be moved, but after the sequence is ended, it will
641 * not move again.
642 * NOTICE: Blocks allocated using Collector::AddBlock(int) can move
643 * as well, if inside an active sequence where another element is added.
644 */
645template <typename T, int growth_factor = 2, int max_growth = 1 * MB>
646class SequenceCollector : public Collector<T, growth_factor, max_growth> {
647 public:
648 explicit SequenceCollector(int initial_capacity)
649 : Collector<T, growth_factor, max_growth>(initial_capacity),
650 sequence_start_(kNoSequence) { }
651
652 virtual ~SequenceCollector() {}
653
654 void StartSequence() {
655 ASSERT(sequence_start_ == kNoSequence);
656 sequence_start_ = this->index_;
657 }
658
659 Vector<T> EndSequence() {
660 ASSERT(sequence_start_ != kNoSequence);
661 int sequence_start = sequence_start_;
662 sequence_start_ = kNoSequence;
663 if (sequence_start == this->index_) return Vector<T>();
664 return this->current_chunk_.SubVector(sequence_start, this->index_);
665 }
666
667 // Drops the currently added sequence, and all collected elements in it.
668 void DropSequence() {
669 ASSERT(sequence_start_ != kNoSequence);
670 int sequence_length = this->index_ - sequence_start_;
671 this->index_ = sequence_start_;
672 this->size_ -= sequence_length;
673 sequence_start_ = kNoSequence;
674 }
675
676 virtual void Reset() {
677 sequence_start_ = kNoSequence;
678 this->Collector<T, growth_factor, max_growth>::Reset();
679 }
680
681 private:
682 static const int kNoSequence = -1;
683 int sequence_start_;
684
685 // Move the currently active sequence to the new chunk.
686 virtual int PrepareGrow(Vector<T> new_chunk) {
687 if (sequence_start_ != kNoSequence) {
688 int sequence_length = this->index_ - sequence_start_;
689 // The new chunk is always larger than the current chunk, so there
690 // is room for the copy.
691 ASSERT(sequence_length < new_chunk.length());
692 for (int i = 0; i < sequence_length; i++) {
693 new_chunk[i] = this->current_chunk_[sequence_start_ + i];
694 }
695 this->index_ = sequence_start_;
696 sequence_start_ = 0;
697 return sequence_length;
698 }
699 return 0;
700 }
701};
702
703
Steve Block6ded16b2010-05-10 14:33:55 +0100704// Compare ASCII/16bit chars to ASCII/16bit chars.
705template <typename lchar, typename rchar>
706static inline int CompareChars(const lchar* lhs, const rchar* rhs, int chars) {
707 const lchar* limit = lhs + chars;
708#ifdef V8_HOST_CAN_READ_UNALIGNED
709 if (sizeof(*lhs) == sizeof(*rhs)) {
710 // Number of characters in a uintptr_t.
711 static const int kStepSize = sizeof(uintptr_t) / sizeof(*lhs); // NOLINT
712 while (lhs <= limit - kStepSize) {
713 if (*reinterpret_cast<const uintptr_t*>(lhs) !=
714 *reinterpret_cast<const uintptr_t*>(rhs)) {
715 break;
716 }
717 lhs += kStepSize;
718 rhs += kStepSize;
719 }
720 }
721#endif
722 while (lhs < limit) {
723 int r = static_cast<int>(*lhs) - static_cast<int>(*rhs);
724 if (r != 0) return r;
725 ++lhs;
726 ++rhs;
727 }
728 return 0;
729}
730
731
Steve Blockd0582a62009-12-15 09:54:21 +0000732// Calculate 10^exponent.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800733static inline int TenToThe(int exponent) {
734 ASSERT(exponent <= 9);
735 ASSERT(exponent >= 1);
736 int answer = 10;
737 for (int i = 1; i < exponent; i++) answer *= 10;
738 return answer;
739}
Steve Blockd0582a62009-12-15 09:54:21 +0000740
Steve Block6ded16b2010-05-10 14:33:55 +0100741
742// The type-based aliasing rule allows the compiler to assume that pointers of
743// different types (for some definition of different) never alias each other.
744// Thus the following code does not work:
745//
746// float f = foo();
747// int fbits = *(int*)(&f);
748//
749// The compiler 'knows' that the int pointer can't refer to f since the types
750// don't match, so the compiler may cache f in a register, leaving random data
751// in fbits. Using C++ style casts makes no difference, however a pointer to
752// char data is assumed to alias any other pointer. This is the 'memcpy
753// exception'.
754//
755// Bit_cast uses the memcpy exception to move the bits from a variable of one
756// type of a variable of another type. Of course the end result is likely to
757// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
758// will completely optimize BitCast away.
759//
760// There is an additional use for BitCast.
761// Recent gccs will warn when they see casts that may result in breakage due to
762// the type-based aliasing rule. If you have checked that there is no breakage
763// you can use BitCast to cast one pointer type to another. This confuses gcc
764// enough that it can no longer see that you have cast one pointer type to
765// another thus avoiding the warning.
Steve Block1e0659c2011-05-24 12:43:12 +0100766
767// We need different implementations of BitCast for pointer and non-pointer
768// values. We use partial specialization of auxiliary struct to work around
769// issues with template functions overloading.
770template <class Dest, class Source>
771struct BitCastHelper {
772 STATIC_ASSERT(sizeof(Dest) == sizeof(Source));
773
774 INLINE(static Dest cast(const Source& source)) {
775 Dest dest;
776 memcpy(&dest, &source, sizeof(dest));
777 return dest;
778 }
779};
780
781template <class Dest, class Source>
782struct BitCastHelper<Dest, Source*> {
783 INLINE(static Dest cast(Source* source)) {
784 return BitCastHelper<Dest, uintptr_t>::
785 cast(reinterpret_cast<uintptr_t>(source));
786 }
787};
788
Steve Block6ded16b2010-05-10 14:33:55 +0100789template <class Dest, class Source>
Steve Block44f0eee2011-05-26 01:26:41 +0100790INLINE(Dest BitCast(const Source& source));
791
792template <class Dest, class Source>
Steve Block6ded16b2010-05-10 14:33:55 +0100793inline Dest BitCast(const Source& source) {
Steve Block1e0659c2011-05-24 12:43:12 +0100794 return BitCastHelper<Dest, Source>::cast(source);
Iain Merrick75681382010-08-19 15:07:18 +0100795}
Steve Blocka7e24c12009-10-30 11:49:00 +0000796
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000797
798template<typename ElementType, int NumElements>
799class EmbeddedContainer {
800 public:
801 EmbeddedContainer() : elems_() { }
802
803 int length() { return NumElements; }
804 ElementType& operator[](int i) {
805 ASSERT(i < length());
806 return elems_[i];
807 }
808
809 private:
810 ElementType elems_[NumElements];
811};
812
813
814template<typename ElementType>
815class EmbeddedContainer<ElementType, 0> {
816 public:
817 int length() { return 0; }
818 ElementType& operator[](int i) {
819 UNREACHABLE();
820 static ElementType t = 0;
821 return t;
822 }
823};
824
825
826// Helper class for building result strings in a character buffer. The
827// purpose of the class is to use safe operations that checks the
828// buffer bounds on all operations in debug mode.
829// This simple base class does not allow formatted output.
830class SimpleStringBuilder {
831 public:
832 // Create a string builder with a buffer of the given size. The
833 // buffer is allocated through NewArray<char> and must be
834 // deallocated by the caller of Finalize().
835 explicit SimpleStringBuilder(int size);
836
837 SimpleStringBuilder(char* buffer, int size)
838 : buffer_(buffer, size), position_(0) { }
839
840 ~SimpleStringBuilder() { if (!is_finalized()) Finalize(); }
841
842 int size() const { return buffer_.length(); }
843
844 // Get the current position in the builder.
845 int position() const {
846 ASSERT(!is_finalized());
847 return position_;
848 }
849
850 // Reset the position.
851 void Reset() { position_ = 0; }
852
853 // Add a single character to the builder. It is not allowed to add
854 // 0-characters; use the Finalize() method to terminate the string
855 // instead.
856 void AddCharacter(char c) {
857 ASSERT(c != '\0');
858 ASSERT(!is_finalized() && position_ < buffer_.length());
859 buffer_[position_++] = c;
860 }
861
862 // Add an entire string to the builder. Uses strlen() internally to
863 // compute the length of the input string.
864 void AddString(const char* s);
865
866 // Add the first 'n' characters of the given string 's' to the
867 // builder. The input string must have enough characters.
868 void AddSubstring(const char* s, int n);
869
870 // Add character padding to the builder. If count is non-positive,
871 // nothing is added to the builder.
872 void AddPadding(char c, int count);
873
874 // Add the decimal representation of the value.
875 void AddDecimalInteger(int value);
876
877 // Finalize the string by 0-terminating it and returning the buffer.
878 char* Finalize();
879
880 protected:
881 Vector<char> buffer_;
882 int position_;
883
884 bool is_finalized() const { return position_ < 0; }
885 private:
886 DISALLOW_IMPLICIT_CONSTRUCTORS(SimpleStringBuilder);
887};
888
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000889
890// A poor man's version of STL's bitset: A bit set of enums E (without explicit
891// values), fitting into an integral type T.
892template <class E, class T = int>
893class EnumSet {
894 public:
895 explicit EnumSet(T bits = 0) : bits_(bits) {}
896 bool IsEmpty() const { return bits_ == 0; }
897 bool Contains(E element) const { return (bits_ & Mask(element)) != 0; }
898 void Add(E element) { bits_ |= Mask(element); }
899 void Remove(E element) { bits_ &= ~Mask(element); }
900 T ToIntegral() const { return bits_; }
901
902 private:
903 T Mask(E element) const {
904 // The strange typing in ASSERT is necessary to avoid stupid warnings, see:
905 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43680
906 ASSERT(element < static_cast<int>(sizeof(T) * CHAR_BIT));
907 return 1 << element;
908 }
909
910 T bits_;
911};
912
Iain Merrick75681382010-08-19 15:07:18 +0100913} } // namespace v8::internal
Steve Block6ded16b2010-05-10 14:33:55 +0100914
Steve Blocka7e24c12009-10-30 11:49:00 +0000915#endif // V8_UTILS_H_