• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // 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>
32 #include <string.h>
33 #include <climits>
34 
35 #include "globals.h"
36 #include "checks.h"
37 #include "allocation.h"
38 
39 namespace v8 {
40 namespace internal {
41 
42 // ----------------------------------------------------------------------------
43 // General helper functions
44 
45 #define IS_POWER_OF_TWO(x) (((x) & ((x) - 1)) == 0)
46 
47 // 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).
49 template <typename T>
IsPowerOf2(T x)50 inline bool IsPowerOf2(T x) {
51   return IS_POWER_OF_TWO(x);
52 }
53 
54 
55 // X must be a power of 2.  Returns the number of trailing zeros.
WhichPowerOf2(uint32_t x)56 inline int WhichPowerOf2(uint32_t x) {
57   ASSERT(IsPowerOf2(x));
58   ASSERT(x != 0);
59   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 
88 // The C++ standard leaves the semantics of '>>' undefined for
89 // negative signed operands. Most implementations do the right thing,
90 // though.
ArithmeticShiftRight(int x,int s)91 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.
99 template <typename T>
OffsetFrom(T x)100 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.
108 template <typename T>
AddressFrom(intptr_t x)109 inline T AddressFrom(intptr_t x) {
110   return static_cast<T>(static_cast<T>(0) + x);
111 }
112 
113 
114 // Return the largest multiple of m which is <= x.
115 template <typename T>
RoundDown(T x,intptr_t m)116 inline T RoundDown(T x, intptr_t 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.
123 template <typename T>
RoundUp(T x,intptr_t m)124 inline T RoundUp(T x, intptr_t m) {
125   return RoundDown<T>(static_cast<T>(x + m - 1), m);
126 }
127 
128 
129 template <typename T>
Compare(const T & a,const T & b)130 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 
140 template <typename T>
PointerValueCompare(const T * a,const T * b)141 int PointerValueCompare(const T* a, const T* b) {
142   return Compare<T>(*a, *b);
143 }
144 
145 
146 // Compare function to compare the object pointer value of two
147 // handlified objects. The handles are passed as pointers to the
148 // handles.
149 template<typename T> class Handle;  // Forward declaration.
150 template <typename T>
HandleObjectPointerCompare(const Handle<T> * a,const Handle<T> * b)151 int HandleObjectPointerCompare(const Handle<T>* a, const Handle<T>* b) {
152   return Compare<T*>(*(*a), *(*b));
153 }
154 
155 
156 // Returns the smallest power of two which is >= x. If you pass in a
157 // number that is already a power of two, it is returned as is.
158 // Implementation is from "Hacker's Delight" by Henry S. Warren, Jr.,
159 // figure 3-3, page 48, where the function is called clp2.
RoundUpToPowerOf2(uint32_t x)160 inline uint32_t RoundUpToPowerOf2(uint32_t x) {
161   ASSERT(x <= 0x80000000u);
162   x = x - 1;
163   x = x | (x >> 1);
164   x = x | (x >> 2);
165   x = x | (x >> 4);
166   x = x | (x >> 8);
167   x = x | (x >> 16);
168   return x + 1;
169 }
170 
171 
RoundDownToPowerOf2(uint32_t x)172 inline uint32_t RoundDownToPowerOf2(uint32_t x) {
173   uint32_t rounded_up = RoundUpToPowerOf2(x);
174   if (rounded_up > x) return rounded_up >> 1;
175   return rounded_up;
176 }
177 
178 
179 template <typename T, typename U>
IsAligned(T value,U alignment)180 inline bool IsAligned(T value, U alignment) {
181   return (value & (alignment - 1)) == 0;
182 }
183 
184 
185 // Returns true if (addr + offset) is aligned.
186 inline bool IsAddressAligned(Address addr,
187                              intptr_t alignment,
188                              int offset = 0) {
189   intptr_t offs = OffsetFrom(addr + offset);
190   return IsAligned(offs, alignment);
191 }
192 
193 
194 // Returns the maximum of the two parameters.
195 template <typename T>
Max(T a,T b)196 T Max(T a, T b) {
197   return a < b ? b : a;
198 }
199 
200 
201 // Returns the minimum of the two parameters.
202 template <typename T>
Min(T a,T b)203 T Min(T a, T b) {
204   return a < b ? a : b;
205 }
206 
207 
StrLength(const char * string)208 inline int StrLength(const char* string) {
209   size_t length = strlen(string);
210   ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
211   return static_cast<int>(length);
212 }
213 
214 
215 // ----------------------------------------------------------------------------
216 // BitField is a help template for encoding and decode bitfield with
217 // unsigned content.
218 template<class T, int shift, int size>
219 class BitField {
220  public:
221   // A uint32_t mask of bit field.  To use all bits of a uint32 in a
222   // bitfield without compiler warnings we have to compute 2^32 without
223   // using a shift count of 32.
224   static const uint32_t kMask = ((1U << shift) << size) - (1U << shift);
225 
226   // Value for the field with all bits set.
227   static const T kMax = static_cast<T>((1U << size) - 1);
228 
229   // Tells whether the provided value fits into the bit field.
is_valid(T value)230   static bool is_valid(T value) {
231     return (static_cast<uint32_t>(value) & ~static_cast<uint32_t>(kMax)) == 0;
232   }
233 
234   // Returns a uint32_t with the bit field value encoded.
encode(T value)235   static uint32_t encode(T value) {
236     ASSERT(is_valid(value));
237     return static_cast<uint32_t>(value) << shift;
238   }
239 
240   // Returns a uint32_t with the bit field value updated.
update(uint32_t previous,T value)241   static uint32_t update(uint32_t previous, T value) {
242     return (previous & ~kMask) | encode(value);
243   }
244 
245   // Extracts the bit field from the value.
decode(uint32_t value)246   static T decode(uint32_t value) {
247     return static_cast<T>((value & kMask) >> shift);
248   }
249 };
250 
251 
252 // ----------------------------------------------------------------------------
253 // Hash function.
254 
255 static const uint32_t kZeroHashSeed = 0;
256 
257 // Thomas Wang, Integer Hash Functions.
258 // http://www.concentric.net/~Ttwang/tech/inthash.htm
ComputeIntegerHash(uint32_t key,uint32_t seed)259 inline uint32_t ComputeIntegerHash(uint32_t key, uint32_t seed) {
260   uint32_t hash = key;
261   hash = hash ^ seed;
262   hash = ~hash + (hash << 15);  // hash = (hash << 15) - hash - 1;
263   hash = hash ^ (hash >> 12);
264   hash = hash + (hash << 2);
265   hash = hash ^ (hash >> 4);
266   hash = hash * 2057;  // hash = (hash + (hash << 3)) + (hash << 11);
267   hash = hash ^ (hash >> 16);
268   return hash;
269 }
270 
271 
ComputeLongHash(uint64_t key)272 inline uint32_t ComputeLongHash(uint64_t key) {
273   uint64_t hash = key;
274   hash = ~hash + (hash << 18);  // hash = (hash << 18) - hash - 1;
275   hash = hash ^ (hash >> 31);
276   hash = hash * 21;  // hash = (hash + (hash << 2)) + (hash << 4);
277   hash = hash ^ (hash >> 11);
278   hash = hash + (hash << 6);
279   hash = hash ^ (hash >> 22);
280   return (uint32_t) hash;
281 }
282 
283 
ComputePointerHash(void * ptr)284 inline uint32_t ComputePointerHash(void* ptr) {
285   return ComputeIntegerHash(
286       static_cast<uint32_t>(reinterpret_cast<intptr_t>(ptr)),
287       v8::internal::kZeroHashSeed);
288 }
289 
290 
291 // ----------------------------------------------------------------------------
292 // Miscellaneous
293 
294 // A static resource holds a static instance that can be reserved in
295 // a local scope using an instance of Access.  Attempts to re-reserve
296 // the instance will cause an error.
297 template <typename T>
298 class StaticResource {
299  public:
StaticResource()300   StaticResource() : is_reserved_(false)  {}
301 
302  private:
303   template <typename S> friend class Access;
304   T instance_;
305   bool is_reserved_;
306 };
307 
308 
309 // Locally scoped access to a static resource.
310 template <typename T>
311 class Access {
312  public:
Access(StaticResource<T> * resource)313   explicit Access(StaticResource<T>* resource)
314     : resource_(resource)
315     , instance_(&resource->instance_) {
316     ASSERT(!resource->is_reserved_);
317     resource->is_reserved_ = true;
318   }
319 
~Access()320   ~Access() {
321     resource_->is_reserved_ = false;
322     resource_ = NULL;
323     instance_ = NULL;
324   }
325 
value()326   T* value()  { return instance_; }
327   T* operator -> ()  { return instance_; }
328 
329  private:
330   StaticResource<T>* resource_;
331   T* instance_;
332 };
333 
334 
335 template <typename T>
336 class Vector {
337  public:
Vector()338   Vector() : start_(NULL), length_(0) {}
Vector(T * data,int length)339   Vector(T* data, int length) : start_(data), length_(length) {
340     ASSERT(length == 0 || (length > 0 && data != NULL));
341   }
342 
New(int length)343   static Vector<T> New(int length) {
344     return Vector<T>(NewArray<T>(length), length);
345   }
346 
347   // Returns a vector using the same backing storage as this one,
348   // spanning from and including 'from', to but not including 'to'.
SubVector(int from,int to)349   Vector<T> SubVector(int from, int to) {
350     ASSERT(to <= length_);
351     ASSERT(from < to);
352     ASSERT(0 <= from);
353     return Vector<T>(start() + from, to - from);
354   }
355 
356   // Returns the length of the vector.
length()357   int length() const { return length_; }
358 
359   // Returns whether or not the vector is empty.
is_empty()360   bool is_empty() const { return length_ == 0; }
361 
362   // Returns the pointer to the start of the data in the vector.
start()363   T* start() const { return start_; }
364 
365   // Access individual vector elements - checks bounds in debug mode.
366   T& operator[](int index) const {
367     ASSERT(0 <= index && index < length_);
368     return start_[index];
369   }
370 
at(int index)371   const T& at(int index) const { return operator[](index); }
372 
first()373   T& first() { return start_[0]; }
374 
last()375   T& last() { return start_[length_ - 1]; }
376 
377   // Returns a clone of this vector with a new backing store.
Clone()378   Vector<T> Clone() const {
379     T* result = NewArray<T>(length_);
380     for (int i = 0; i < length_; i++) result[i] = start_[i];
381     return Vector<T>(result, length_);
382   }
383 
Sort(int (* cmp)(const T *,const T *))384   void Sort(int (*cmp)(const T*, const T*)) {
385     typedef int (*RawComparer)(const void*, const void*);
386     qsort(start(),
387           length(),
388           sizeof(T),
389           reinterpret_cast<RawComparer>(cmp));
390   }
391 
Sort()392   void Sort() {
393     Sort(PointerValueCompare<T>);
394   }
395 
Truncate(int length)396   void Truncate(int length) {
397     ASSERT(length <= length_);
398     length_ = length;
399   }
400 
401   // Releases the array underlying this vector. Once disposed the
402   // vector is empty.
Dispose()403   void Dispose() {
404     DeleteArray(start_);
405     start_ = NULL;
406     length_ = 0;
407   }
408 
409   inline Vector<T> operator+(int offset) {
410     ASSERT(offset < length_);
411     return Vector<T>(start_ + offset, length_ - offset);
412   }
413 
414   // Factory method for creating empty vectors.
empty()415   static Vector<T> empty() { return Vector<T>(NULL, 0); }
416 
417   template<typename S>
cast(Vector<S> input)418   static Vector<T> cast(Vector<S> input) {
419     return Vector<T>(reinterpret_cast<T*>(input.start()),
420                      input.length() * sizeof(S) / sizeof(T));
421   }
422 
423  protected:
set_start(T * start)424   void set_start(T* start) { start_ = start; }
425 
426  private:
427   T* start_;
428   int length_;
429 };
430 
431 
432 // A pointer that can only be set once and doesn't allow NULL values.
433 template<typename T>
434 class SetOncePointer {
435  public:
SetOncePointer()436   SetOncePointer() : pointer_(NULL) { }
437 
is_set()438   bool is_set() const { return pointer_ != NULL; }
439 
get()440   T* get() const {
441     ASSERT(pointer_ != NULL);
442     return pointer_;
443   }
444 
set(T * value)445   void set(T* value) {
446     ASSERT(pointer_ == NULL && value != NULL);
447     pointer_ = value;
448   }
449 
450  private:
451   T* pointer_;
452 };
453 
454 
455 template <typename T, int kSize>
456 class EmbeddedVector : public Vector<T> {
457  public:
EmbeddedVector()458   EmbeddedVector() : Vector<T>(buffer_, kSize) { }
459 
EmbeddedVector(T initial_value)460   explicit EmbeddedVector(T initial_value) : Vector<T>(buffer_, kSize) {
461     for (int i = 0; i < kSize; ++i) {
462       buffer_[i] = initial_value;
463     }
464   }
465 
466   // When copying, make underlying Vector to reference our buffer.
EmbeddedVector(const EmbeddedVector & rhs)467   EmbeddedVector(const EmbeddedVector& rhs)
468       : Vector<T>(rhs) {
469     memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
470     set_start(buffer_);
471   }
472 
473   EmbeddedVector& operator=(const EmbeddedVector& rhs) {
474     if (this == &rhs) return *this;
475     Vector<T>::operator=(rhs);
476     memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
477     this->set_start(buffer_);
478     return *this;
479   }
480 
481  private:
482   T buffer_[kSize];
483 };
484 
485 
486 template <typename T>
487 class ScopedVector : public Vector<T> {
488  public:
ScopedVector(int length)489   explicit ScopedVector(int length) : Vector<T>(NewArray<T>(length), length) { }
~ScopedVector()490   ~ScopedVector() {
491     DeleteArray(this->start());
492   }
493 
494  private:
495   DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedVector);
496 };
497 
498 
CStrVector(const char * data)499 inline Vector<const char> CStrVector(const char* data) {
500   return Vector<const char>(data, StrLength(data));
501 }
502 
MutableCStrVector(char * data)503 inline Vector<char> MutableCStrVector(char* data) {
504   return Vector<char>(data, StrLength(data));
505 }
506 
MutableCStrVector(char * data,int max)507 inline Vector<char> MutableCStrVector(char* data, int max) {
508   int length = StrLength(data);
509   return Vector<char>(data, (length < max) ? length : max);
510 }
511 
512 
513 /*
514  * A class that collects values into a backing store.
515  * Specialized versions of the class can allow access to the backing store
516  * in different ways.
517  * There is no guarantee that the backing store is contiguous (and, as a
518  * consequence, no guarantees that consecutively added elements are adjacent
519  * in memory). The collector may move elements unless it has guaranteed not
520  * to.
521  */
522 template <typename T, int growth_factor = 2, int max_growth = 1 * MB>
523 class Collector {
524  public:
525   explicit Collector(int initial_capacity = kMinCapacity)
526       : index_(0), size_(0) {
527     current_chunk_ = Vector<T>::New(initial_capacity);
528   }
529 
~Collector()530   virtual ~Collector() {
531     // Free backing store (in reverse allocation order).
532     current_chunk_.Dispose();
533     for (int i = chunks_.length() - 1; i >= 0; i--) {
534       chunks_.at(i).Dispose();
535     }
536   }
537 
538   // Add a single element.
Add(T value)539   inline void Add(T value) {
540     if (index_ >= current_chunk_.length()) {
541       Grow(1);
542     }
543     current_chunk_[index_] = value;
544     index_++;
545     size_++;
546   }
547 
548   // Add a block of contiguous elements and return a Vector backed by the
549   // memory area.
550   // A basic Collector will keep this vector valid as long as the Collector
551   // is alive.
AddBlock(int size,T initial_value)552   inline Vector<T> AddBlock(int size, T initial_value) {
553     ASSERT(size > 0);
554     if (size > current_chunk_.length() - index_) {
555       Grow(size);
556     }
557     T* position = current_chunk_.start() + index_;
558     index_ += size;
559     size_ += size;
560     for (int i = 0; i < size; i++) {
561       position[i] = initial_value;
562     }
563     return Vector<T>(position, size);
564   }
565 
566 
567   // Add a contiguous block of elements and return a vector backed
568   // by the added block.
569   // A basic Collector will keep this vector valid as long as the Collector
570   // is alive.
AddBlock(Vector<const T> source)571   inline Vector<T> AddBlock(Vector<const T> source) {
572     if (source.length() > current_chunk_.length() - index_) {
573       Grow(source.length());
574     }
575     T* position = current_chunk_.start() + index_;
576     index_ += source.length();
577     size_ += source.length();
578     for (int i = 0; i < source.length(); i++) {
579       position[i] = source[i];
580     }
581     return Vector<T>(position, source.length());
582   }
583 
584 
585   // Write the contents of the collector into the provided vector.
WriteTo(Vector<T> destination)586   void WriteTo(Vector<T> destination) {
587     ASSERT(size_ <= destination.length());
588     int position = 0;
589     for (int i = 0; i < chunks_.length(); i++) {
590       Vector<T> chunk = chunks_.at(i);
591       for (int j = 0; j < chunk.length(); j++) {
592         destination[position] = chunk[j];
593         position++;
594       }
595     }
596     for (int i = 0; i < index_; i++) {
597       destination[position] = current_chunk_[i];
598       position++;
599     }
600   }
601 
602   // Allocate a single contiguous vector, copy all the collected
603   // elements to the vector, and return it.
604   // The caller is responsible for freeing the memory of the returned
605   // vector (e.g., using Vector::Dispose).
ToVector()606   Vector<T> ToVector() {
607     Vector<T> new_store = Vector<T>::New(size_);
608     WriteTo(new_store);
609     return new_store;
610   }
611 
612   // Resets the collector to be empty.
613   virtual void Reset();
614 
615   // Total number of elements added to collector so far.
size()616   inline int size() { return size_; }
617 
618  protected:
619   static const int kMinCapacity = 16;
620   List<Vector<T> > chunks_;
621   Vector<T> current_chunk_;  // Block of memory currently being written into.
622   int index_;  // Current index in current chunk.
623   int size_;  // Total number of elements in collector.
624 
625   // Creates a new current chunk, and stores the old chunk in the chunks_ list.
Grow(int min_capacity)626   void Grow(int min_capacity) {
627     ASSERT(growth_factor > 1);
628     int new_capacity;
629     int current_length = current_chunk_.length();
630     if (current_length < kMinCapacity) {
631       // The collector started out as empty.
632       new_capacity = min_capacity * growth_factor;
633       if (new_capacity < kMinCapacity) new_capacity = kMinCapacity;
634     } else {
635       int growth = current_length * (growth_factor - 1);
636       if (growth > max_growth) {
637         growth = max_growth;
638       }
639       new_capacity = current_length + growth;
640       if (new_capacity < min_capacity) {
641         new_capacity = min_capacity + growth;
642       }
643     }
644     NewChunk(new_capacity);
645     ASSERT(index_ + min_capacity <= current_chunk_.length());
646   }
647 
648   // Before replacing the current chunk, give a subclass the option to move
649   // some of the current data into the new chunk. The function may update
650   // the current index_ value to represent data no longer in the current chunk.
651   // Returns the initial index of the new chunk (after copied data).
NewChunk(int new_capacity)652   virtual void NewChunk(int new_capacity)  {
653     Vector<T> new_chunk = Vector<T>::New(new_capacity);
654     if (index_ > 0) {
655       chunks_.Add(current_chunk_.SubVector(0, index_));
656     } else {
657       current_chunk_.Dispose();
658     }
659     current_chunk_ = new_chunk;
660     index_ = 0;
661   }
662 };
663 
664 
665 /*
666  * A collector that allows sequences of values to be guaranteed to
667  * stay consecutive.
668  * If the backing store grows while a sequence is active, the current
669  * sequence might be moved, but after the sequence is ended, it will
670  * not move again.
671  * NOTICE: Blocks allocated using Collector::AddBlock(int) can move
672  * as well, if inside an active sequence where another element is added.
673  */
674 template <typename T, int growth_factor = 2, int max_growth = 1 * MB>
675 class SequenceCollector : public Collector<T, growth_factor, max_growth> {
676  public:
SequenceCollector(int initial_capacity)677   explicit SequenceCollector(int initial_capacity)
678       : Collector<T, growth_factor, max_growth>(initial_capacity),
679         sequence_start_(kNoSequence) { }
680 
~SequenceCollector()681   virtual ~SequenceCollector() {}
682 
StartSequence()683   void StartSequence() {
684     ASSERT(sequence_start_ == kNoSequence);
685     sequence_start_ = this->index_;
686   }
687 
EndSequence()688   Vector<T> EndSequence() {
689     ASSERT(sequence_start_ != kNoSequence);
690     int sequence_start = sequence_start_;
691     sequence_start_ = kNoSequence;
692     if (sequence_start == this->index_) return Vector<T>();
693     return this->current_chunk_.SubVector(sequence_start, this->index_);
694   }
695 
696   // Drops the currently added sequence, and all collected elements in it.
DropSequence()697   void DropSequence() {
698     ASSERT(sequence_start_ != kNoSequence);
699     int sequence_length = this->index_ - sequence_start_;
700     this->index_ = sequence_start_;
701     this->size_ -= sequence_length;
702     sequence_start_ = kNoSequence;
703   }
704 
Reset()705   virtual void Reset() {
706     sequence_start_ = kNoSequence;
707     this->Collector<T, growth_factor, max_growth>::Reset();
708   }
709 
710  private:
711   static const int kNoSequence = -1;
712   int sequence_start_;
713 
714   // Move the currently active sequence to the new chunk.
NewChunk(int new_capacity)715   virtual void NewChunk(int new_capacity) {
716     if (sequence_start_ == kNoSequence) {
717       // Fall back on default behavior if no sequence has been started.
718       this->Collector<T, growth_factor, max_growth>::NewChunk(new_capacity);
719       return;
720     }
721     int sequence_length = this->index_ - sequence_start_;
722     Vector<T> new_chunk = Vector<T>::New(sequence_length + new_capacity);
723     ASSERT(sequence_length < new_chunk.length());
724     for (int i = 0; i < sequence_length; i++) {
725       new_chunk[i] = this->current_chunk_[sequence_start_ + i];
726     }
727     if (sequence_start_ > 0) {
728       this->chunks_.Add(this->current_chunk_.SubVector(0, sequence_start_));
729     } else {
730       this->current_chunk_.Dispose();
731     }
732     this->current_chunk_ = new_chunk;
733     this->index_ = sequence_length;
734     sequence_start_ = 0;
735   }
736 };
737 
738 
739 // Compare ASCII/16bit chars to ASCII/16bit chars.
740 template <typename lchar, typename rchar>
CompareChars(const lchar * lhs,const rchar * rhs,int chars)741 inline int CompareChars(const lchar* lhs, const rchar* rhs, int chars) {
742   const lchar* limit = lhs + chars;
743 #ifdef V8_HOST_CAN_READ_UNALIGNED
744   if (sizeof(*lhs) == sizeof(*rhs)) {
745     // Number of characters in a uintptr_t.
746     static const int kStepSize = sizeof(uintptr_t) / sizeof(*lhs);  // NOLINT
747     while (lhs <= limit - kStepSize) {
748       if (*reinterpret_cast<const uintptr_t*>(lhs) !=
749           *reinterpret_cast<const uintptr_t*>(rhs)) {
750         break;
751       }
752       lhs += kStepSize;
753       rhs += kStepSize;
754     }
755   }
756 #endif
757   while (lhs < limit) {
758     int r = static_cast<int>(*lhs) - static_cast<int>(*rhs);
759     if (r != 0) return r;
760     ++lhs;
761     ++rhs;
762   }
763   return 0;
764 }
765 
766 
767 // Calculate 10^exponent.
TenToThe(int exponent)768 inline int TenToThe(int exponent) {
769   ASSERT(exponent <= 9);
770   ASSERT(exponent >= 1);
771   int answer = 10;
772   for (int i = 1; i < exponent; i++) answer *= 10;
773   return answer;
774 }
775 
776 
777 // The type-based aliasing rule allows the compiler to assume that pointers of
778 // different types (for some definition of different) never alias each other.
779 // Thus the following code does not work:
780 //
781 // float f = foo();
782 // int fbits = *(int*)(&f);
783 //
784 // The compiler 'knows' that the int pointer can't refer to f since the types
785 // don't match, so the compiler may cache f in a register, leaving random data
786 // in fbits.  Using C++ style casts makes no difference, however a pointer to
787 // char data is assumed to alias any other pointer.  This is the 'memcpy
788 // exception'.
789 //
790 // Bit_cast uses the memcpy exception to move the bits from a variable of one
791 // type of a variable of another type.  Of course the end result is likely to
792 // be implementation dependent.  Most compilers (gcc-4.2 and MSVC 2005)
793 // will completely optimize BitCast away.
794 //
795 // There is an additional use for BitCast.
796 // Recent gccs will warn when they see casts that may result in breakage due to
797 // the type-based aliasing rule.  If you have checked that there is no breakage
798 // you can use BitCast to cast one pointer type to another.  This confuses gcc
799 // enough that it can no longer see that you have cast one pointer type to
800 // another thus avoiding the warning.
801 
802 // We need different implementations of BitCast for pointer and non-pointer
803 // values. We use partial specialization of auxiliary struct to work around
804 // issues with template functions overloading.
805 template <class Dest, class Source>
806 struct BitCastHelper {
807   STATIC_ASSERT(sizeof(Dest) == sizeof(Source));
808 
INLINEBitCastHelper809   INLINE(static Dest cast(const Source& source)) {
810     Dest dest;
811     memcpy(&dest, &source, sizeof(dest));
812     return dest;
813   }
814 };
815 
816 template <class Dest, class Source>
817 struct BitCastHelper<Dest, Source*> {
818   INLINE(static Dest cast(Source* source)) {
819     return BitCastHelper<Dest, uintptr_t>::
820         cast(reinterpret_cast<uintptr_t>(source));
821   }
822 };
823 
824 template <class Dest, class Source>
825 INLINE(Dest BitCast(const Source& source));
826 
827 template <class Dest, class Source>
828 inline Dest BitCast(const Source& source) {
829   return BitCastHelper<Dest, Source>::cast(source);
830 }
831 
832 
833 template<typename ElementType, int NumElements>
834 class EmbeddedContainer {
835  public:
836   EmbeddedContainer() : elems_() { }
837 
838   int length() { return NumElements; }
839   ElementType& operator[](int i) {
840     ASSERT(i < length());
841     return elems_[i];
842   }
843 
844  private:
845   ElementType elems_[NumElements];
846 };
847 
848 
849 template<typename ElementType>
850 class EmbeddedContainer<ElementType, 0> {
851  public:
852   int length() { return 0; }
853   ElementType& operator[](int i) {
854     UNREACHABLE();
855     static ElementType t = 0;
856     return t;
857   }
858 };
859 
860 
861 // Helper class for building result strings in a character buffer. The
862 // purpose of the class is to use safe operations that checks the
863 // buffer bounds on all operations in debug mode.
864 // This simple base class does not allow formatted output.
865 class SimpleStringBuilder {
866  public:
867   // Create a string builder with a buffer of the given size. The
868   // buffer is allocated through NewArray<char> and must be
869   // deallocated by the caller of Finalize().
870   explicit SimpleStringBuilder(int size);
871 
872   SimpleStringBuilder(char* buffer, int size)
873       : buffer_(buffer, size), position_(0) { }
874 
875   ~SimpleStringBuilder() { if (!is_finalized()) Finalize(); }
876 
877   int size() const { return buffer_.length(); }
878 
879   // Get the current position in the builder.
880   int position() const {
881     ASSERT(!is_finalized());
882     return position_;
883   }
884 
885   // Reset the position.
886   void Reset() { position_ = 0; }
887 
888   // Add a single character to the builder. It is not allowed to add
889   // 0-characters; use the Finalize() method to terminate the string
890   // instead.
891   void AddCharacter(char c) {
892     ASSERT(c != '\0');
893     ASSERT(!is_finalized() && position_ < buffer_.length());
894     buffer_[position_++] = c;
895   }
896 
897   // Add an entire string to the builder. Uses strlen() internally to
898   // compute the length of the input string.
899   void AddString(const char* s);
900 
901   // Add the first 'n' characters of the given string 's' to the
902   // builder. The input string must have enough characters.
903   void AddSubstring(const char* s, int n);
904 
905   // Add character padding to the builder. If count is non-positive,
906   // nothing is added to the builder.
907   void AddPadding(char c, int count);
908 
909   // Add the decimal representation of the value.
910   void AddDecimalInteger(int value);
911 
912   // Finalize the string by 0-terminating it and returning the buffer.
913   char* Finalize();
914 
915  protected:
916   Vector<char> buffer_;
917   int position_;
918 
919   bool is_finalized() const { return position_ < 0; }
920 
921  private:
922   DISALLOW_IMPLICIT_CONSTRUCTORS(SimpleStringBuilder);
923 };
924 
925 
926 // A poor man's version of STL's bitset: A bit set of enums E (without explicit
927 // values), fitting into an integral type T.
928 template <class E, class T = int>
929 class EnumSet {
930  public:
931   explicit EnumSet(T bits = 0) : bits_(bits) {}
932   bool IsEmpty() const { return bits_ == 0; }
933   bool Contains(E element) const { return (bits_ & Mask(element)) != 0; }
934   bool ContainsAnyOf(const EnumSet& set) const {
935     return (bits_ & set.bits_) != 0;
936   }
937   void Add(E element) { bits_ |= Mask(element); }
938   void Add(const EnumSet& set) { bits_ |= set.bits_; }
939   void Remove(E element) { bits_ &= ~Mask(element); }
940   void Remove(const EnumSet& set) { bits_ &= ~set.bits_; }
941   void RemoveAll() { bits_ = 0; }
942   void Intersect(const EnumSet& set) { bits_ &= set.bits_; }
943   T ToIntegral() const { return bits_; }
944   bool operator==(const EnumSet& set) { return bits_ == set.bits_; }
945 
946  private:
947   T Mask(E element) const {
948     // The strange typing in ASSERT is necessary to avoid stupid warnings, see:
949     // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43680
950     ASSERT(element < static_cast<int>(sizeof(T) * CHAR_BIT));
951     return 1 << element;
952   }
953 
954   T bits_;
955 };
956 
957 } }  // namespace v8::internal
958 
959 #endif  // V8_UTILS_H_
960