blob: fa249475aec88b87639cf432573db5e56f60dcde [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
34namespace v8 {
35namespace internal {
36
37// ----------------------------------------------------------------------------
38// General helper functions
39
Steve Block3ce2e202009-11-05 08:53:23 +000040// Returns true iff x is a power of 2 (or zero). Cannot be used with the
41// maximally negative value of the type T (the -1 overflows).
Steve Blocka7e24c12009-10-30 11:49:00 +000042template <typename T>
43static inline bool IsPowerOf2(T x) {
44 return (x & (x - 1)) == 0;
45}
46
47
48// The C++ standard leaves the semantics of '>>' undefined for
49// negative signed operands. Most implementations do the right thing,
50// though.
51static inline int ArithmeticShiftRight(int x, int s) {
52 return x >> s;
53}
54
55
56// Compute the 0-relative offset of some absolute value x of type T.
57// This allows conversion of Addresses and integral types into
58// 0-relative int offsets.
59template <typename T>
60static inline intptr_t OffsetFrom(T x) {
61 return x - static_cast<T>(0);
62}
63
64
65// Compute the absolute value of type T for some 0-relative offset x.
66// This allows conversion of 0-relative int offsets into Addresses and
67// integral types.
68template <typename T>
69static inline T AddressFrom(intptr_t x) {
Steve Blockd0582a62009-12-15 09:54:21 +000070 return static_cast<T>(static_cast<T>(0) + x);
Steve Blocka7e24c12009-10-30 11:49:00 +000071}
72
73
74// Return the largest multiple of m which is <= x.
75template <typename T>
76static inline T RoundDown(T x, int m) {
77 ASSERT(IsPowerOf2(m));
78 return AddressFrom<T>(OffsetFrom(x) & -m);
79}
80
81
82// Return the smallest multiple of m which is >= x.
83template <typename T>
84static inline T RoundUp(T x, int m) {
85 return RoundDown(x + m - 1, m);
86}
87
88
89template <typename T>
90static int Compare(const T& a, const T& b) {
91 if (a == b)
92 return 0;
93 else if (a < b)
94 return -1;
95 else
96 return 1;
97}
98
99
100template <typename T>
101static int PointerValueCompare(const T* a, const T* b) {
102 return Compare<T>(*a, *b);
103}
104
105
106// Returns the smallest power of two which is >= x. If you pass in a
107// number that is already a power of two, it is returned as is.
108uint32_t RoundUpToPowerOf2(uint32_t x);
109
110
111template <typename T>
112static inline bool IsAligned(T value, T alignment) {
113 ASSERT(IsPowerOf2(alignment));
114 return (value & (alignment - 1)) == 0;
115}
116
117
118// Returns true if (addr + offset) is aligned.
119static inline bool IsAddressAligned(Address addr,
120 intptr_t alignment,
121 int offset) {
122 intptr_t offs = OffsetFrom(addr + offset);
123 return IsAligned(offs, alignment);
124}
125
126
127// Returns the maximum of the two parameters.
128template <typename T>
129static T Max(T a, T b) {
130 return a < b ? b : a;
131}
132
133
134// Returns the minimum of the two parameters.
135template <typename T>
136static T Min(T a, T b) {
137 return a < b ? a : b;
138}
139
140
Steve Blockd0582a62009-12-15 09:54:21 +0000141inline int StrLength(const char* string) {
142 size_t length = strlen(string);
143 ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
144 return static_cast<int>(length);
145}
146
147
Steve Blocka7e24c12009-10-30 11:49:00 +0000148// ----------------------------------------------------------------------------
149// BitField is a help template for encoding and decode bitfield with
150// unsigned content.
151template<class T, int shift, int size>
152class BitField {
153 public:
154 // Tells whether the provided value fits into the bit field.
155 static bool is_valid(T value) {
156 return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0;
157 }
158
159 // Returns a uint32_t mask of bit field.
160 static uint32_t mask() {
Andrei Popescu402d9372010-02-26 13:31:12 +0000161 // To use all bits of a uint32 in a bitfield without compiler warnings we
162 // have to compute 2^32 without using a shift count of 32.
163 return ((1U << shift) << size) - (1U << shift);
Steve Blocka7e24c12009-10-30 11:49:00 +0000164 }
165
166 // Returns a uint32_t with the bit field value encoded.
167 static uint32_t encode(T value) {
168 ASSERT(is_valid(value));
169 return static_cast<uint32_t>(value) << shift;
170 }
171
172 // Extracts the bit field from the value.
173 static T decode(uint32_t value) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000174 return static_cast<T>((value & mask()) >> shift);
Steve Blocka7e24c12009-10-30 11:49:00 +0000175 }
176};
177
178
179// ----------------------------------------------------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +0000180// Hash function.
181
182uint32_t ComputeIntegerHash(uint32_t key);
183
184
185// ----------------------------------------------------------------------------
186// I/O support.
187
188// Our version of printf(). Avoids compilation errors that we get
189// with standard printf when attempting to print pointers, etc.
190// (the errors are due to the extra compilation flags, which we
191// want elsewhere).
192void PrintF(const char* format, ...);
193
194// Our version of fflush.
195void Flush();
196
197
198// Read a line of characters after printing the prompt to stdout. The resulting
199// char* needs to be disposed off with DeleteArray by the caller.
200char* ReadLine(const char* prompt);
201
202
203// Read and return the raw bytes in a file. the size of the buffer is returned
204// in size.
205// The returned buffer must be freed by the caller.
206byte* ReadBytes(const char* filename, int* size, bool verbose = true);
207
208
209// Write size chars from str to the file given by filename.
210// The file is overwritten. Returns the number of chars written.
211int WriteChars(const char* filename,
212 const char* str,
213 int size,
214 bool verbose = true);
215
216
217// Write size bytes to the file given by filename.
218// The file is overwritten. Returns the number of bytes written.
219int WriteBytes(const char* filename,
220 const byte* bytes,
221 int size,
222 bool verbose = true);
223
224
225// Write the C code
226// const char* <varname> = "<str>";
227// const int <varname>_len = <len>;
228// to the file given by filename. Only the first len chars are written.
229int WriteAsCFile(const char* filename, const char* varname,
230 const char* str, int size, bool verbose = true);
231
232
233// ----------------------------------------------------------------------------
234// Miscellaneous
235
236// A static resource holds a static instance that can be reserved in
237// a local scope using an instance of Access. Attempts to re-reserve
238// the instance will cause an error.
239template <typename T>
240class StaticResource {
241 public:
242 StaticResource() : is_reserved_(false) {}
243
244 private:
245 template <typename S> friend class Access;
246 T instance_;
247 bool is_reserved_;
248};
249
250
251// Locally scoped access to a static resource.
252template <typename T>
253class Access {
254 public:
255 explicit Access(StaticResource<T>* resource)
256 : resource_(resource)
257 , instance_(&resource->instance_) {
258 ASSERT(!resource->is_reserved_);
259 resource->is_reserved_ = true;
260 }
261
262 ~Access() {
263 resource_->is_reserved_ = false;
264 resource_ = NULL;
265 instance_ = NULL;
266 }
267
268 T* value() { return instance_; }
269 T* operator -> () { return instance_; }
270
271 private:
272 StaticResource<T>* resource_;
273 T* instance_;
274};
275
276
277template <typename T>
278class Vector {
279 public:
280 Vector() : start_(NULL), length_(0) {}
281 Vector(T* data, int length) : start_(data), length_(length) {
282 ASSERT(length == 0 || (length > 0 && data != NULL));
283 }
284
285 static Vector<T> New(int length) {
286 return Vector<T>(NewArray<T>(length), length);
287 }
288
289 // Returns a vector using the same backing storage as this one,
290 // spanning from and including 'from', to but not including 'to'.
291 Vector<T> SubVector(int from, int to) {
292 ASSERT(from < length_);
293 ASSERT(to <= length_);
294 ASSERT(from < to);
295 return Vector<T>(start() + from, to - from);
296 }
297
298 // Returns the length of the vector.
299 int length() const { return length_; }
300
301 // Returns whether or not the vector is empty.
302 bool is_empty() const { return length_ == 0; }
303
304 // Returns the pointer to the start of the data in the vector.
305 T* start() const { return start_; }
306
307 // Access individual vector elements - checks bounds in debug mode.
308 T& operator[](int index) const {
309 ASSERT(0 <= index && index < length_);
310 return start_[index];
311 }
312
313 T& first() { return start_[0]; }
314
315 T& last() { return start_[length_ - 1]; }
316
317 // Returns a clone of this vector with a new backing store.
318 Vector<T> Clone() const {
319 T* result = NewArray<T>(length_);
320 for (int i = 0; i < length_; i++) result[i] = start_[i];
321 return Vector<T>(result, length_);
322 }
323
324 void Sort(int (*cmp)(const T*, const T*)) {
325 typedef int (*RawComparer)(const void*, const void*);
326 qsort(start(),
327 length(),
328 sizeof(T),
329 reinterpret_cast<RawComparer>(cmp));
330 }
331
332 void Sort() {
333 Sort(PointerValueCompare<T>);
334 }
335
336 void Truncate(int length) {
337 ASSERT(length <= length_);
338 length_ = length;
339 }
340
341 // Releases the array underlying this vector. Once disposed the
342 // vector is empty.
343 void Dispose() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000344 DeleteArray(start_);
345 start_ = NULL;
346 length_ = 0;
347 }
348
349 inline Vector<T> operator+(int offset) {
350 ASSERT(offset < length_);
351 return Vector<T>(start_ + offset, length_ - offset);
352 }
353
354 // Factory method for creating empty vectors.
355 static Vector<T> empty() { return Vector<T>(NULL, 0); }
356
357 protected:
358 void set_start(T* start) { start_ = start; }
359
360 private:
361 T* start_;
362 int length_;
363};
364
365
366// A temporary assignment sets a (non-local) variable to a value on
367// construction and resets it the value on destruction.
368template <typename T>
369class TempAssign {
370 public:
371 TempAssign(T* var, T value): var_(var), old_value_(*var) {
372 *var = value;
373 }
374
375 ~TempAssign() { *var_ = old_value_; }
376
377 private:
378 T* var_;
379 T old_value_;
380};
381
382
383template <typename T, int kSize>
384class EmbeddedVector : public Vector<T> {
385 public:
386 EmbeddedVector() : Vector<T>(buffer_, kSize) { }
387
388 // When copying, make underlying Vector to reference our buffer.
389 EmbeddedVector(const EmbeddedVector& rhs)
390 : Vector<T>(rhs) {
391 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
392 set_start(buffer_);
393 }
394
395 EmbeddedVector& operator=(const EmbeddedVector& rhs) {
396 if (this == &rhs) return *this;
397 Vector<T>::operator=(rhs);
398 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
Steve Block6ded16b2010-05-10 14:33:55 +0100399 this->set_start(buffer_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000400 return *this;
401 }
402
403 private:
404 T buffer_[kSize];
405};
406
407
408template <typename T>
409class ScopedVector : public Vector<T> {
410 public:
411 explicit ScopedVector(int length) : Vector<T>(NewArray<T>(length), length) { }
412 ~ScopedVector() {
413 DeleteArray(this->start());
414 }
415};
416
417
418inline Vector<const char> CStrVector(const char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000419 return Vector<const char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000420}
421
422inline Vector<char> MutableCStrVector(char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000423 return Vector<char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000424}
425
426inline Vector<char> MutableCStrVector(char* data, int max) {
Steve Blockd0582a62009-12-15 09:54:21 +0000427 int length = StrLength(data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000428 return Vector<char>(data, (length < max) ? length : max);
429}
430
431template <typename T>
432inline Vector< Handle<Object> > HandleVector(v8::internal::Handle<T>* elms,
433 int length) {
434 return Vector< Handle<Object> >(
435 reinterpret_cast<v8::internal::Handle<Object>*>(elms), length);
436}
437
438
439// Simple support to read a file into a 0-terminated C-string.
440// The returned buffer must be freed by the caller.
441// On return, *exits tells whether the file existed.
442Vector<const char> ReadFile(const char* filename,
443 bool* exists,
444 bool verbose = true);
445
446
447// Simple wrapper that allows an ExternalString to refer to a
448// Vector<const char>. Doesn't assume ownership of the data.
449class AsciiStringAdapter: public v8::String::ExternalAsciiStringResource {
450 public:
451 explicit AsciiStringAdapter(Vector<const char> data) : data_(data) {}
452
453 virtual const char* data() const { return data_.start(); }
454
455 virtual size_t length() const { return data_.length(); }
456
457 private:
458 Vector<const char> data_;
459};
460
461
462// Helper class for building result strings in a character buffer. The
463// purpose of the class is to use safe operations that checks the
464// buffer bounds on all operations in debug mode.
465class StringBuilder {
466 public:
467 // Create a string builder with a buffer of the given size. The
468 // buffer is allocated through NewArray<char> and must be
469 // deallocated by the caller of Finalize().
470 explicit StringBuilder(int size);
471
472 StringBuilder(char* buffer, int size)
473 : buffer_(buffer, size), position_(0) { }
474
475 ~StringBuilder() { if (!is_finalized()) Finalize(); }
476
477 int size() const { return buffer_.length(); }
478
479 // Get the current position in the builder.
480 int position() const {
481 ASSERT(!is_finalized());
482 return position_;
483 }
484
485 // Reset the position.
486 void Reset() { position_ = 0; }
487
488 // Add a single character to the builder. It is not allowed to add
489 // 0-characters; use the Finalize() method to terminate the string
490 // instead.
491 void AddCharacter(char c) {
492 ASSERT(c != '\0');
493 ASSERT(!is_finalized() && position_ < buffer_.length());
494 buffer_[position_++] = c;
495 }
496
497 // Add an entire string to the builder. Uses strlen() internally to
498 // compute the length of the input string.
499 void AddString(const char* s);
500
501 // Add the first 'n' characters of the given string 's' to the
502 // builder. The input string must have enough characters.
503 void AddSubstring(const char* s, int n);
504
505 // Add formatted contents to the builder just like printf().
506 void AddFormatted(const char* format, ...);
507
508 // Add character padding to the builder. If count is non-positive,
509 // nothing is added to the builder.
510 void AddPadding(char c, int count);
511
512 // Finalize the string by 0-terminating it and returning the buffer.
513 char* Finalize();
514
515 private:
516 Vector<char> buffer_;
517 int position_;
518
519 bool is_finalized() const { return position_ < 0; }
520
521 DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
522};
523
524
525// Copy from ASCII/16bit chars to ASCII/16bit chars.
526template <typename sourcechar, typename sinkchar>
527static inline void CopyChars(sinkchar* dest, const sourcechar* src, int chars) {
528 sinkchar* limit = dest + chars;
529#ifdef V8_HOST_CAN_READ_UNALIGNED
530 if (sizeof(*dest) == sizeof(*src)) {
Steve Block6ded16b2010-05-10 14:33:55 +0100531 // Number of characters in a uintptr_t.
532 static const int kStepSize = sizeof(uintptr_t) / sizeof(*dest); // NOLINT
Steve Blocka7e24c12009-10-30 11:49:00 +0000533 while (dest <= limit - kStepSize) {
Steve Block6ded16b2010-05-10 14:33:55 +0100534 *reinterpret_cast<uintptr_t*>(dest) =
535 *reinterpret_cast<const uintptr_t*>(src);
Steve Blocka7e24c12009-10-30 11:49:00 +0000536 dest += kStepSize;
537 src += kStepSize;
538 }
539 }
540#endif
541 while (dest < limit) {
542 *dest++ = static_cast<sinkchar>(*src++);
543 }
544}
545
546
Steve Block6ded16b2010-05-10 14:33:55 +0100547// Compare ASCII/16bit chars to ASCII/16bit chars.
548template <typename lchar, typename rchar>
549static inline int CompareChars(const lchar* lhs, const rchar* rhs, int chars) {
550 const lchar* limit = lhs + chars;
551#ifdef V8_HOST_CAN_READ_UNALIGNED
552 if (sizeof(*lhs) == sizeof(*rhs)) {
553 // Number of characters in a uintptr_t.
554 static const int kStepSize = sizeof(uintptr_t) / sizeof(*lhs); // NOLINT
555 while (lhs <= limit - kStepSize) {
556 if (*reinterpret_cast<const uintptr_t*>(lhs) !=
557 *reinterpret_cast<const uintptr_t*>(rhs)) {
558 break;
559 }
560 lhs += kStepSize;
561 rhs += kStepSize;
562 }
563 }
564#endif
565 while (lhs < limit) {
566 int r = static_cast<int>(*lhs) - static_cast<int>(*rhs);
567 if (r != 0) return r;
568 ++lhs;
569 ++rhs;
570 }
571 return 0;
572}
573
574
575template <typename T>
576static inline void MemsetPointer(T** dest, T* value, int counter) {
577#if defined(V8_HOST_ARCH_IA32)
578#define STOS "stosl"
579#elif defined(V8_HOST_ARCH_X64)
580#define STOS "stosq"
581#endif
582
583#if defined(__GNUC__) && defined(STOS)
584 asm volatile(
585 "cld;"
586 "rep ; " STOS
587 : "+&c" (counter), "+&D" (dest)
588 : "a" (value)
589 : "memory", "cc");
590#else
591 for (int i = 0; i < counter; i++) {
592 dest[i] = value;
593 }
594#endif
595
596#undef STOS
597}
598
599
600// Copies data from |src| to |dst|. The data spans MUST not overlap.
601inline void CopyWords(Object** dst, Object** src, int num_words) {
602 ASSERT(Min(dst, src) + num_words <= Max(dst, src));
603 ASSERT(num_words > 0);
604
605 // Use block copying memcpy if the segment we're copying is
606 // enough to justify the extra call/setup overhead.
607 static const int kBlockCopyLimit = 16;
608
609 if (num_words >= kBlockCopyLimit) {
610 memcpy(dst, src, num_words * kPointerSize);
611 } else {
612 int remaining = num_words;
613 do {
614 remaining--;
615 *dst++ = *src++;
616 } while (remaining > 0);
617 }
618}
619
620
Steve Blockd0582a62009-12-15 09:54:21 +0000621// Calculate 10^exponent.
622int TenToThe(int exponent);
623
Steve Block6ded16b2010-05-10 14:33:55 +0100624
625// The type-based aliasing rule allows the compiler to assume that pointers of
626// different types (for some definition of different) never alias each other.
627// Thus the following code does not work:
628//
629// float f = foo();
630// int fbits = *(int*)(&f);
631//
632// The compiler 'knows' that the int pointer can't refer to f since the types
633// don't match, so the compiler may cache f in a register, leaving random data
634// in fbits. Using C++ style casts makes no difference, however a pointer to
635// char data is assumed to alias any other pointer. This is the 'memcpy
636// exception'.
637//
638// Bit_cast uses the memcpy exception to move the bits from a variable of one
639// type of a variable of another type. Of course the end result is likely to
640// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
641// will completely optimize BitCast away.
642//
643// There is an additional use for BitCast.
644// Recent gccs will warn when they see casts that may result in breakage due to
645// the type-based aliasing rule. If you have checked that there is no breakage
646// you can use BitCast to cast one pointer type to another. This confuses gcc
647// enough that it can no longer see that you have cast one pointer type to
648// another thus avoiding the warning.
649template <class Dest, class Source>
650inline Dest BitCast(const Source& source) {
651 // Compile time assertion: sizeof(Dest) == sizeof(Source)
652 // A compile error here means your Dest and Source have different sizes.
653 typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1];
654
655 Dest dest;
656 memcpy(&dest, &source, sizeof(dest));
657 return dest;
658}
659
Steve Blocka7e24c12009-10-30 11:49:00 +0000660} } // namespace v8::internal
661
Steve Block6ded16b2010-05-10 14:33:55 +0100662
Steve Blocka7e24c12009-10-30 11:49:00 +0000663#endif // V8_UTILS_H_