blob: 69c062fb9bba00722db0d22afe295ae0eda1b070 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 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>
Steve Block6ded16b2010-05-10 14:33:55 +010032#include <string.h>
Steve Blocka7e24c12009-10-30 11:49:00 +000033
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080034#include "globals.h"
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080035#include "checks.h"
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080036#include "allocation.h"
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080037
Steve Blocka7e24c12009-10-30 11:49:00 +000038namespace v8 {
39namespace internal {
40
41// ----------------------------------------------------------------------------
42// General helper functions
43
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010044#define IS_POWER_OF_TWO(x) (((x) & ((x) - 1)) == 0)
45
Steve Block3ce2e202009-11-05 08:53:23 +000046// Returns true iff x is a power of 2 (or zero). Cannot be used with the
47// maximally negative value of the type T (the -1 overflows).
Steve Blocka7e24c12009-10-30 11:49:00 +000048template <typename T>
49static inline bool IsPowerOf2(T x) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010050 return IS_POWER_OF_TWO(x);
Steve Blocka7e24c12009-10-30 11:49:00 +000051}
52
53
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010054// X must be a power of 2. Returns the number of trailing zeros.
55template <typename T>
56static inline int WhichPowerOf2(T x) {
57 ASSERT(IsPowerOf2(x));
58 ASSERT(x != 0);
59 if (x < 0) return 31;
60 int bits = 0;
61#ifdef DEBUG
62 int original_x = x;
63#endif
64 if (x >= 0x10000) {
65 bits += 16;
66 x >>= 16;
67 }
68 if (x >= 0x100) {
69 bits += 8;
70 x >>= 8;
71 }
72 if (x >= 0x10) {
73 bits += 4;
74 x >>= 4;
75 }
76 switch (x) {
77 default: UNREACHABLE();
78 case 8: bits++; // Fall through.
79 case 4: bits++; // Fall through.
80 case 2: bits++; // Fall through.
81 case 1: break;
82 }
83 ASSERT_EQ(1 << bits, original_x);
84 return bits;
85 return 0;
86}
87
88
Steve Blocka7e24c12009-10-30 11:49:00 +000089// The C++ standard leaves the semantics of '>>' undefined for
90// negative signed operands. Most implementations do the right thing,
91// though.
92static inline int ArithmeticShiftRight(int x, int s) {
93 return x >> s;
94}
95
96
97// Compute the 0-relative offset of some absolute value x of type T.
98// This allows conversion of Addresses and integral types into
99// 0-relative int offsets.
100template <typename T>
101static inline intptr_t OffsetFrom(T x) {
102 return x - static_cast<T>(0);
103}
104
105
106// Compute the absolute value of type T for some 0-relative offset x.
107// This allows conversion of 0-relative int offsets into Addresses and
108// integral types.
109template <typename T>
110static inline T AddressFrom(intptr_t x) {
Steve Blockd0582a62009-12-15 09:54:21 +0000111 return static_cast<T>(static_cast<T>(0) + x);
Steve Blocka7e24c12009-10-30 11:49:00 +0000112}
113
114
115// Return the largest multiple of m which is <= x.
116template <typename T>
117static inline T RoundDown(T x, int m) {
118 ASSERT(IsPowerOf2(m));
119 return AddressFrom<T>(OffsetFrom(x) & -m);
120}
121
122
123// Return the smallest multiple of m which is >= x.
124template <typename T>
125static inline T RoundUp(T x, int m) {
126 return RoundDown(x + m - 1, m);
127}
128
129
130template <typename T>
131static int Compare(const T& a, const T& b) {
132 if (a == b)
133 return 0;
134 else if (a < b)
135 return -1;
136 else
137 return 1;
138}
139
140
141template <typename T>
142static int PointerValueCompare(const T* a, const T* b) {
143 return Compare<T>(*a, *b);
144}
145
146
147// Returns the smallest power of two which is >= x. If you pass in a
148// number that is already a power of two, it is returned as is.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800149// Implementation is from "Hacker's Delight" by Henry S. Warren, Jr.,
150// figure 3-3, page 48, where the function is called clp2.
151static inline uint32_t RoundUpToPowerOf2(uint32_t x) {
152 ASSERT(x <= 0x80000000u);
153 x = x - 1;
154 x = x | (x >> 1);
155 x = x | (x >> 2);
156 x = x | (x >> 4);
157 x = x | (x >> 8);
158 x = x | (x >> 16);
159 return x + 1;
160}
161
Steve Blocka7e24c12009-10-30 11:49:00 +0000162
163
164template <typename T>
165static inline bool IsAligned(T value, T alignment) {
166 ASSERT(IsPowerOf2(alignment));
167 return (value & (alignment - 1)) == 0;
168}
169
170
171// Returns true if (addr + offset) is aligned.
172static inline bool IsAddressAligned(Address addr,
173 intptr_t alignment,
174 int offset) {
175 intptr_t offs = OffsetFrom(addr + offset);
176 return IsAligned(offs, alignment);
177}
178
179
180// Returns the maximum of the two parameters.
181template <typename T>
182static T Max(T a, T b) {
183 return a < b ? b : a;
184}
185
186
187// Returns the minimum of the two parameters.
188template <typename T>
189static T Min(T a, T b) {
190 return a < b ? a : b;
191}
192
193
Steve Blockd0582a62009-12-15 09:54:21 +0000194inline int StrLength(const char* string) {
195 size_t length = strlen(string);
196 ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
197 return static_cast<int>(length);
198}
199
200
Steve Blocka7e24c12009-10-30 11:49:00 +0000201// ----------------------------------------------------------------------------
202// BitField is a help template for encoding and decode bitfield with
203// unsigned content.
204template<class T, int shift, int size>
205class BitField {
206 public:
207 // Tells whether the provided value fits into the bit field.
208 static bool is_valid(T value) {
209 return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0;
210 }
211
212 // Returns a uint32_t mask of bit field.
213 static uint32_t mask() {
Andrei Popescu402d9372010-02-26 13:31:12 +0000214 // To use all bits of a uint32 in a bitfield without compiler warnings we
215 // have to compute 2^32 without using a shift count of 32.
216 return ((1U << shift) << size) - (1U << shift);
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
225 // Extracts the bit field from the value.
226 static T decode(uint32_t value) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000227 return static_cast<T>((value & mask()) >> shift);
Steve Blocka7e24c12009-10-30 11:49:00 +0000228 }
229};
230
231
232// ----------------------------------------------------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +0000233// Hash function.
234
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800235// Thomas Wang, Integer Hash Functions.
236// http://www.concentric.net/~Ttwang/tech/inthash.htm
237static inline uint32_t ComputeIntegerHash(uint32_t key) {
238 uint32_t hash = key;
239 hash = ~hash + (hash << 15); // hash = (hash << 15) - hash - 1;
240 hash = hash ^ (hash >> 12);
241 hash = hash + (hash << 2);
242 hash = hash ^ (hash >> 4);
243 hash = hash * 2057; // hash = (hash + (hash << 3)) + (hash << 11);
244 hash = hash ^ (hash >> 16);
245 return hash;
246}
Steve Blocka7e24c12009-10-30 11:49:00 +0000247
248
249// ----------------------------------------------------------------------------
250// Miscellaneous
251
252// A static resource holds a static instance that can be reserved in
253// a local scope using an instance of Access. Attempts to re-reserve
254// the instance will cause an error.
255template <typename T>
256class StaticResource {
257 public:
258 StaticResource() : is_reserved_(false) {}
259
260 private:
261 template <typename S> friend class Access;
262 T instance_;
263 bool is_reserved_;
264};
265
266
267// Locally scoped access to a static resource.
268template <typename T>
269class Access {
270 public:
271 explicit Access(StaticResource<T>* resource)
272 : resource_(resource)
273 , instance_(&resource->instance_) {
274 ASSERT(!resource->is_reserved_);
275 resource->is_reserved_ = true;
276 }
277
278 ~Access() {
279 resource_->is_reserved_ = false;
280 resource_ = NULL;
281 instance_ = NULL;
282 }
283
284 T* value() { return instance_; }
285 T* operator -> () { return instance_; }
286
287 private:
288 StaticResource<T>* resource_;
289 T* instance_;
290};
291
292
293template <typename T>
294class Vector {
295 public:
296 Vector() : start_(NULL), length_(0) {}
297 Vector(T* data, int length) : start_(data), length_(length) {
298 ASSERT(length == 0 || (length > 0 && data != NULL));
299 }
300
301 static Vector<T> New(int length) {
302 return Vector<T>(NewArray<T>(length), length);
303 }
304
305 // Returns a vector using the same backing storage as this one,
306 // spanning from and including 'from', to but not including 'to'.
307 Vector<T> SubVector(int from, int to) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000308 ASSERT(to <= length_);
309 ASSERT(from < to);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100310 ASSERT(0 <= from);
Steve Blocka7e24c12009-10-30 11:49:00 +0000311 return Vector<T>(start() + from, to - from);
312 }
313
314 // Returns the length of the vector.
315 int length() const { return length_; }
316
317 // Returns whether or not the vector is empty.
318 bool is_empty() const { return length_ == 0; }
319
320 // Returns the pointer to the start of the data in the vector.
321 T* start() const { return start_; }
322
323 // Access individual vector elements - checks bounds in debug mode.
324 T& operator[](int index) const {
325 ASSERT(0 <= index && index < length_);
326 return start_[index];
327 }
328
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800329 T& at(int i) const { return operator[](i); }
330
Steve Blocka7e24c12009-10-30 11:49:00 +0000331 T& first() { return start_[0]; }
332
333 T& last() { return start_[length_ - 1]; }
334
335 // Returns a clone of this vector with a new backing store.
336 Vector<T> Clone() const {
337 T* result = NewArray<T>(length_);
338 for (int i = 0; i < length_; i++) result[i] = start_[i];
339 return Vector<T>(result, length_);
340 }
341
342 void Sort(int (*cmp)(const T*, const T*)) {
343 typedef int (*RawComparer)(const void*, const void*);
344 qsort(start(),
345 length(),
346 sizeof(T),
347 reinterpret_cast<RawComparer>(cmp));
348 }
349
350 void Sort() {
351 Sort(PointerValueCompare<T>);
352 }
353
354 void Truncate(int length) {
355 ASSERT(length <= length_);
356 length_ = length;
357 }
358
359 // Releases the array underlying this vector. Once disposed the
360 // vector is empty.
361 void Dispose() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000362 DeleteArray(start_);
363 start_ = NULL;
364 length_ = 0;
365 }
366
367 inline Vector<T> operator+(int offset) {
368 ASSERT(offset < length_);
369 return Vector<T>(start_ + offset, length_ - offset);
370 }
371
372 // Factory method for creating empty vectors.
373 static Vector<T> empty() { return Vector<T>(NULL, 0); }
374
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100375 template<typename S>
376 static Vector<T> cast(Vector<S> input) {
377 return Vector<T>(reinterpret_cast<T*>(input.start()),
378 input.length() * sizeof(S) / sizeof(T));
379 }
380
Steve Blocka7e24c12009-10-30 11:49:00 +0000381 protected:
382 void set_start(T* start) { start_ = start; }
383
384 private:
385 T* start_;
386 int length_;
387};
388
389
Steve Blocka7e24c12009-10-30 11:49:00 +0000390template <typename T, int kSize>
391class EmbeddedVector : public Vector<T> {
392 public:
393 EmbeddedVector() : Vector<T>(buffer_, kSize) { }
394
395 // When copying, make underlying Vector to reference our buffer.
396 EmbeddedVector(const EmbeddedVector& rhs)
397 : Vector<T>(rhs) {
398 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
399 set_start(buffer_);
400 }
401
402 EmbeddedVector& operator=(const EmbeddedVector& rhs) {
403 if (this == &rhs) return *this;
404 Vector<T>::operator=(rhs);
405 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
Steve Block6ded16b2010-05-10 14:33:55 +0100406 this->set_start(buffer_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000407 return *this;
408 }
409
410 private:
411 T buffer_[kSize];
412};
413
414
415template <typename T>
416class ScopedVector : public Vector<T> {
417 public:
418 explicit ScopedVector(int length) : Vector<T>(NewArray<T>(length), length) { }
419 ~ScopedVector() {
420 DeleteArray(this->start());
421 }
Kristian Monsen25f61362010-05-21 11:50:48 +0100422
423 private:
424 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedVector);
Steve Blocka7e24c12009-10-30 11:49:00 +0000425};
426
427
428inline Vector<const char> CStrVector(const char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000429 return Vector<const char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000430}
431
432inline Vector<char> MutableCStrVector(char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000433 return Vector<char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000434}
435
436inline Vector<char> MutableCStrVector(char* data, int max) {
Steve Blockd0582a62009-12-15 09:54:21 +0000437 int length = StrLength(data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000438 return Vector<char>(data, (length < max) ? length : max);
439}
440
Steve Blocka7e24c12009-10-30 11:49:00 +0000441
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100442/*
443 * A class that collects values into a backing store.
444 * Specialized versions of the class can allow access to the backing store
445 * in different ways.
446 * There is no guarantee that the backing store is contiguous (and, as a
447 * consequence, no guarantees that consecutively added elements are adjacent
448 * in memory). The collector may move elements unless it has guaranteed not
449 * to.
450 */
451template <typename T, int growth_factor = 2, int max_growth = 1 * MB>
452class Collector {
453 public:
454 explicit Collector(int initial_capacity = kMinCapacity)
455 : index_(0), size_(0) {
456 if (initial_capacity < kMinCapacity) {
457 initial_capacity = kMinCapacity;
458 }
459 current_chunk_ = Vector<T>::New(initial_capacity);
460 }
461
462 virtual ~Collector() {
463 // Free backing store (in reverse allocation order).
464 current_chunk_.Dispose();
465 for (int i = chunks_.length() - 1; i >= 0; i--) {
466 chunks_.at(i).Dispose();
467 }
468 }
469
470 // Add a single element.
471 inline void Add(T value) {
472 if (index_ >= current_chunk_.length()) {
473 Grow(1);
474 }
475 current_chunk_[index_] = value;
476 index_++;
477 size_++;
478 }
479
480 // Add a block of contiguous elements and return a Vector backed by the
481 // memory area.
482 // A basic Collector will keep this vector valid as long as the Collector
483 // is alive.
484 inline Vector<T> AddBlock(int size, T initial_value) {
485 ASSERT(size > 0);
486 if (size > current_chunk_.length() - index_) {
487 Grow(size);
488 }
489 T* position = current_chunk_.start() + index_;
490 index_ += size;
491 size_ += size;
492 for (int i = 0; i < size; i++) {
493 position[i] = initial_value;
494 }
495 return Vector<T>(position, size);
496 }
497
498
499 // Write the contents of the collector into the provided vector.
500 void WriteTo(Vector<T> destination) {
501 ASSERT(size_ <= destination.length());
502 int position = 0;
503 for (int i = 0; i < chunks_.length(); i++) {
504 Vector<T> chunk = chunks_.at(i);
505 for (int j = 0; j < chunk.length(); j++) {
506 destination[position] = chunk[j];
507 position++;
508 }
509 }
510 for (int i = 0; i < index_; i++) {
511 destination[position] = current_chunk_[i];
512 position++;
513 }
514 }
515
516 // Allocate a single contiguous vector, copy all the collected
517 // elements to the vector, and return it.
518 // The caller is responsible for freeing the memory of the returned
519 // vector (e.g., using Vector::Dispose).
520 Vector<T> ToVector() {
521 Vector<T> new_store = Vector<T>::New(size_);
522 WriteTo(new_store);
523 return new_store;
524 }
525
526 // Resets the collector to be empty.
527 virtual void Reset() {
528 for (int i = chunks_.length() - 1; i >= 0; i--) {
529 chunks_.at(i).Dispose();
530 }
531 chunks_.Rewind(0);
532 index_ = 0;
533 size_ = 0;
534 }
535
536 // Total number of elements added to collector so far.
537 inline int size() { return size_; }
538
539 protected:
540 static const int kMinCapacity = 16;
541 List<Vector<T> > chunks_;
542 Vector<T> current_chunk_; // Block of memory currently being written into.
543 int index_; // Current index in current chunk.
544 int size_; // Total number of elements in collector.
545
546 // Creates a new current chunk, and stores the old chunk in the chunks_ list.
547 void Grow(int min_capacity) {
548 ASSERT(growth_factor > 1);
549 int growth = current_chunk_.length() * (growth_factor - 1);
550 if (growth > max_growth) {
551 growth = max_growth;
552 }
553 int new_capacity = current_chunk_.length() + growth;
554 if (new_capacity < min_capacity) {
555 new_capacity = min_capacity + growth;
556 }
557 Vector<T> new_chunk = Vector<T>::New(new_capacity);
558 int new_index = PrepareGrow(new_chunk);
559 if (index_ > 0) {
560 chunks_.Add(current_chunk_.SubVector(0, index_));
561 } else {
562 // Can happen if the call to PrepareGrow moves everything into
563 // the new chunk.
564 current_chunk_.Dispose();
565 }
566 current_chunk_ = new_chunk;
567 index_ = new_index;
568 ASSERT(index_ + min_capacity <= current_chunk_.length());
569 }
570
571 // Before replacing the current chunk, give a subclass the option to move
572 // some of the current data into the new chunk. The function may update
573 // the current index_ value to represent data no longer in the current chunk.
574 // Returns the initial index of the new chunk (after copied data).
575 virtual int PrepareGrow(Vector<T> new_chunk) {
576 return 0;
577 }
578};
579
580
581/*
582 * A collector that allows sequences of values to be guaranteed to
583 * stay consecutive.
584 * If the backing store grows while a sequence is active, the current
585 * sequence might be moved, but after the sequence is ended, it will
586 * not move again.
587 * NOTICE: Blocks allocated using Collector::AddBlock(int) can move
588 * as well, if inside an active sequence where another element is added.
589 */
590template <typename T, int growth_factor = 2, int max_growth = 1 * MB>
591class SequenceCollector : public Collector<T, growth_factor, max_growth> {
592 public:
593 explicit SequenceCollector(int initial_capacity)
594 : Collector<T, growth_factor, max_growth>(initial_capacity),
595 sequence_start_(kNoSequence) { }
596
597 virtual ~SequenceCollector() {}
598
599 void StartSequence() {
600 ASSERT(sequence_start_ == kNoSequence);
601 sequence_start_ = this->index_;
602 }
603
604 Vector<T> EndSequence() {
605 ASSERT(sequence_start_ != kNoSequence);
606 int sequence_start = sequence_start_;
607 sequence_start_ = kNoSequence;
608 if (sequence_start == this->index_) return Vector<T>();
609 return this->current_chunk_.SubVector(sequence_start, this->index_);
610 }
611
612 // Drops the currently added sequence, and all collected elements in it.
613 void DropSequence() {
614 ASSERT(sequence_start_ != kNoSequence);
615 int sequence_length = this->index_ - sequence_start_;
616 this->index_ = sequence_start_;
617 this->size_ -= sequence_length;
618 sequence_start_ = kNoSequence;
619 }
620
621 virtual void Reset() {
622 sequence_start_ = kNoSequence;
623 this->Collector<T, growth_factor, max_growth>::Reset();
624 }
625
626 private:
627 static const int kNoSequence = -1;
628 int sequence_start_;
629
630 // Move the currently active sequence to the new chunk.
631 virtual int PrepareGrow(Vector<T> new_chunk) {
632 if (sequence_start_ != kNoSequence) {
633 int sequence_length = this->index_ - sequence_start_;
634 // The new chunk is always larger than the current chunk, so there
635 // is room for the copy.
636 ASSERT(sequence_length < new_chunk.length());
637 for (int i = 0; i < sequence_length; i++) {
638 new_chunk[i] = this->current_chunk_[sequence_start_ + i];
639 }
640 this->index_ = sequence_start_;
641 sequence_start_ = 0;
642 return sequence_length;
643 }
644 return 0;
645 }
646};
647
648
Steve Block6ded16b2010-05-10 14:33:55 +0100649// Compare ASCII/16bit chars to ASCII/16bit chars.
650template <typename lchar, typename rchar>
651static inline int CompareChars(const lchar* lhs, const rchar* rhs, int chars) {
652 const lchar* limit = lhs + chars;
653#ifdef V8_HOST_CAN_READ_UNALIGNED
654 if (sizeof(*lhs) == sizeof(*rhs)) {
655 // Number of characters in a uintptr_t.
656 static const int kStepSize = sizeof(uintptr_t) / sizeof(*lhs); // NOLINT
657 while (lhs <= limit - kStepSize) {
658 if (*reinterpret_cast<const uintptr_t*>(lhs) !=
659 *reinterpret_cast<const uintptr_t*>(rhs)) {
660 break;
661 }
662 lhs += kStepSize;
663 rhs += kStepSize;
664 }
665 }
666#endif
667 while (lhs < limit) {
668 int r = static_cast<int>(*lhs) - static_cast<int>(*rhs);
669 if (r != 0) return r;
670 ++lhs;
671 ++rhs;
672 }
673 return 0;
674}
675
676
Steve Blockd0582a62009-12-15 09:54:21 +0000677// Calculate 10^exponent.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800678static inline int TenToThe(int exponent) {
679 ASSERT(exponent <= 9);
680 ASSERT(exponent >= 1);
681 int answer = 10;
682 for (int i = 1; i < exponent; i++) answer *= 10;
683 return answer;
684}
Steve Blockd0582a62009-12-15 09:54:21 +0000685
Steve Block6ded16b2010-05-10 14:33:55 +0100686
687// The type-based aliasing rule allows the compiler to assume that pointers of
688// different types (for some definition of different) never alias each other.
689// Thus the following code does not work:
690//
691// float f = foo();
692// int fbits = *(int*)(&f);
693//
694// The compiler 'knows' that the int pointer can't refer to f since the types
695// don't match, so the compiler may cache f in a register, leaving random data
696// in fbits. Using C++ style casts makes no difference, however a pointer to
697// char data is assumed to alias any other pointer. This is the 'memcpy
698// exception'.
699//
700// Bit_cast uses the memcpy exception to move the bits from a variable of one
701// type of a variable of another type. Of course the end result is likely to
702// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
703// will completely optimize BitCast away.
704//
705// There is an additional use for BitCast.
706// Recent gccs will warn when they see casts that may result in breakage due to
707// the type-based aliasing rule. If you have checked that there is no breakage
708// you can use BitCast to cast one pointer type to another. This confuses gcc
709// enough that it can no longer see that you have cast one pointer type to
710// another thus avoiding the warning.
711template <class Dest, class Source>
712inline Dest BitCast(const Source& source) {
713 // Compile time assertion: sizeof(Dest) == sizeof(Source)
714 // A compile error here means your Dest and Source have different sizes.
715 typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1];
716
717 Dest dest;
718 memcpy(&dest, &source, sizeof(dest));
719 return dest;
720}
721
Iain Merrick75681382010-08-19 15:07:18 +0100722template <class Dest, class Source>
Steve Block791712a2010-08-27 10:21:07 +0100723inline Dest BitCast(Source* source) {
724 return BitCast<Dest>(reinterpret_cast<uintptr_t>(source));
Iain Merrick75681382010-08-19 15:07:18 +0100725}
Steve Blocka7e24c12009-10-30 11:49:00 +0000726
Iain Merrick75681382010-08-19 15:07:18 +0100727} } // namespace v8::internal
Steve Block6ded16b2010-05-10 14:33:55 +0100728
Steve Blocka7e24c12009-10-30 11:49:00 +0000729#endif // V8_UTILS_H_