blob: 34478bac1e8d9b8161f047db493322437dff96d4 [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +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
ager@chromium.orga74f0da2008-12-03 16:05:52 +000031#include <stdlib.h>
32
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000033namespace v8 { namespace internal {
34
35// ----------------------------------------------------------------------------
36// General helper functions
37
38// Returns true iff x is a power of 2. Does not work for zero.
39template <typename T>
40static inline bool IsPowerOf2(T x) {
41 return (x & (x - 1)) == 0;
42}
43
44
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000045
46
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000047// The C++ standard leaves the semantics of '>>' undefined for
48// negative signed operands. Most implementations do the right thing,
49// though.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000050static inline int ArithmeticShiftRight(int x, int s) {
51 return x >> s;
52}
53
54
55// Compute the 0-relative offset of some absolute value x of type T.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000056// This allows conversion of Addresses and integral types into
57// 0-relative int offsets.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000058template <typename T>
59static inline int OffsetFrom(T x) {
60 return x - static_cast<T>(0);
61}
62
63
64// Compute the absolute value of type T for some 0-relative offset x.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +000065// This allows conversion of 0-relative int offsets into Addresses and
66// integral types.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000067template <typename T>
68static inline T AddressFrom(int x) {
69 return static_cast<T>(0) + x;
70}
71
72
73// Return the largest multiple of m which is <= x.
74template <typename T>
75static inline T RoundDown(T x, int m) {
76 ASSERT(IsPowerOf2(m));
77 return AddressFrom<T>(OffsetFrom(x) & -m);
78}
79
80
81// Return the smallest multiple of m which is >= x.
82template <typename T>
83static inline T RoundUp(T x, int m) {
84 return RoundDown(x + m - 1, m);
85}
86
87
ager@chromium.orga74f0da2008-12-03 16:05:52 +000088template <typename T>
89static int Compare(const T& a, const T& b) {
90 if (a == b)
91 return 0;
92 else if (a < b)
93 return -1;
94 else
95 return 1;
96}
97
98
99template <typename T>
100static int PointerValueCompare(const T* a, const T* b) {
101 return Compare<T>(*a, *b);
102}
103
104
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000105// Returns the smallest power of two which is >= x. If you pass in a
106// number that is already a power of two, it is returned as is.
107uint32_t RoundUpToPowerOf2(uint32_t x);
108
109
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000110template <typename T>
111static inline bool IsAligned(T value, T alignment) {
112 ASSERT(IsPowerOf2(alignment));
113 return (value & (alignment - 1)) == 0;
114}
115
116
117// Returns true if (addr + offset) is aligned.
118static inline bool IsAddressAligned(Address addr, int alignment, int offset) {
119 int offs = OffsetFrom(addr + offset);
120 return IsAligned(offs, alignment);
121}
122
123
124// Returns the maximum of the two parameters.
125template <typename T>
126static T Max(T a, T b) {
127 return a < b ? b : a;
128}
129
130
131// Returns the minimum of the two parameters.
132template <typename T>
133static T Min(T a, T b) {
134 return a < b ? a : b;
135}
136
137
138// ----------------------------------------------------------------------------
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +0000139// BitField is a help template for encoding and decode bitfield with
140// unsigned content.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000141template<class T, int shift, int size>
142class BitField {
143 public:
144 // Tells whether the provided value fits into the bit field.
145 static bool is_valid(T value) {
146 return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0;
147 }
148
149 // Returns a uint32_t mask of bit field.
150 static uint32_t mask() {
151 return (1U << (size + shift)) - (1U << shift);
152 }
153
154 // Returns a uint32_t with the bit field value encoded.
155 static uint32_t encode(T value) {
156 ASSERT(is_valid(value));
157 return static_cast<uint32_t>(value) << shift;
158 }
159
160 // Extracts the bit field from the value.
161 static T decode(uint32_t value) {
162 return static_cast<T>((value >> shift) & ((1U << (size)) - 1));
163 }
164};
165
166
167// ----------------------------------------------------------------------------
168// Support for compressed, machine-independent encoding
169// and decoding of integer values of arbitrary size.
170
171// Encoding and decoding from/to a buffer at position p;
172// the result is the position after the encoded integer.
173// Small signed integers in the range -64 <= x && x < 64
174// are encoded in 1 byte; larger values are encoded in 2
175// or more bytes. At most sizeof(int) + 1 bytes are used
176// in the worst case.
177byte* EncodeInt(byte* p, int x);
178byte* DecodeInt(byte* p, int* x);
179
180
181// Encoding and decoding from/to a buffer at position p - 1
182// moving backward; the result is the position of the last
183// byte written. These routines are useful to read/write
184// into a buffer starting at the end of the buffer.
185byte* EncodeUnsignedIntBackward(byte* p, unsigned int x);
186
187// The decoding function is inlined since its performance is
188// important to mark-sweep garbage collection.
189inline byte* DecodeUnsignedIntBackward(byte* p, unsigned int* x) {
190 byte b = *--p;
191 if (b >= 128) {
192 *x = static_cast<unsigned int>(b) - 128;
193 return p;
194 }
195 unsigned int r = static_cast<unsigned int>(b);
196 unsigned int s = 7;
197 b = *--p;
198 while (b < 128) {
199 r |= static_cast<unsigned int>(b) << s;
200 s += 7;
201 b = *--p;
202 }
203 // b >= 128
204 *x = r | ((static_cast<unsigned int>(b) - 128) << s);
205 return p;
206}
207
208
209// ----------------------------------------------------------------------------
210// I/O support.
211
212// Our version of printf(). Avoids compilation errors that we get
213// with standard printf when attempting to print pointers, etc.
214// (the errors are due to the extra compilation flags, which we
215// want elsewhere).
216void PrintF(const char* format, ...);
217
218// Our version of fflush.
219void Flush();
220
221
222// Read a line of characters after printing the prompt to stdout. The resulting
223// char* needs to be disposed off with DeleteArray by the caller.
224char* ReadLine(const char* prompt);
225
226
227// Read and return the raw chars in a file. the size of the buffer is returned
228// in size.
229// The returned buffer is not 0-terminated. It must be freed by the caller.
230char* ReadChars(const char* filename, int* size, bool verbose = true);
231
232
233// Write size chars from str to the file given by filename.
234// The file is overwritten. Returns the number of chars written.
235int WriteChars(const char* filename,
236 const char* str,
237 int size,
238 bool verbose = true);
239
240
241// Write the C code
242// const char* <varname> = "<str>";
243// const int <varname>_len = <len>;
244// to the file given by filename. Only the first len chars are written.
245int WriteAsCFile(const char* filename, const char* varname,
246 const char* str, int size, bool verbose = true);
247
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:
kasper.lund7276f142008-07-30 08:49:36 +0000296 Vector() : start_(NULL), length_(0) {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000297 Vector(T* data, int length) : start_(data), length_(length) {
298 ASSERT(length == 0 || (length > 0 && data != NULL));
299 }
300
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000301 static Vector<T> New(int length) {
302 return Vector<T>(NewArray<T>(length), length);
303 }
304
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000305 // 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) {
308 ASSERT(from < length_);
309 ASSERT(to <= length_);
310 ASSERT(from < to);
311 return Vector<T>(start() + from, to - from);
312 }
313
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000314 // 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
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000329 T& first() { return start_[0]; }
330
331 T& last() { return start_[length_ - 1]; }
332
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000333 // Returns a clone of this vector with a new backing store.
334 Vector<T> Clone() const {
335 T* result = NewArray<T>(length_);
336 for (int i = 0; i < length_; i++) result[i] = start_[i];
337 return Vector<T>(result, length_);
338 }
339
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000340 void Sort(int (*cmp)(const T*, const T*)) {
341 typedef int (*RawComparer)(const void*, const void*);
342 qsort(start(),
343 length(),
344 sizeof(T),
345 reinterpret_cast<RawComparer>(cmp));
346 }
347
348 void Sort() {
349 Sort(PointerValueCompare<T>);
350 }
351
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000352 // Releases the array underlying this vector. Once disposed the
353 // vector is empty.
354 void Dispose() {
kasper.lund7276f142008-07-30 08:49:36 +0000355 if (is_empty()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000356 DeleteArray(start_);
357 start_ = NULL;
358 length_ = 0;
359 }
360
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000361 inline Vector<T> operator+(int offset) {
362 ASSERT(offset < length_);
363 return Vector<T>(start_ + offset, length_ - offset);
364 }
365
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000366 // Factory method for creating empty vectors.
367 static Vector<T> empty() { return Vector<T>(NULL, 0); }
368
369 private:
370 T* start_;
371 int length_;
372};
373
374
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000375template <typename T, int kSize>
376class EmbeddedVector : public Vector<T> {
377 public:
378 EmbeddedVector() : Vector<T>(buffer_, kSize) { }
379 private:
380 T buffer_[kSize];
381};
382
383
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000384inline Vector<const char> CStrVector(const char* data) {
385 return Vector<const char>(data, strlen(data));
386}
387
388inline Vector<char> MutableCStrVector(char* data) {
389 return Vector<char>(data, strlen(data));
390}
391
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000392inline Vector<char> MutableCStrVector(char* data, int max) {
393 int length = strlen(data);
394 return Vector<char>(data, (length < max) ? length : max);
395}
396
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000397template <typename T>
398inline Vector< Handle<Object> > HandleVector(v8::internal::Handle<T>* elms,
399 int length) {
400 return Vector< Handle<Object> >(
401 reinterpret_cast<v8::internal::Handle<Object>*>(elms), length);
402}
403
404
405// Simple support to read a file into a 0-terminated C-string.
406// The returned buffer must be freed by the caller.
407// On return, *exits tells whether the file exisited.
408Vector<const char> ReadFile(const char* filename,
409 bool* exists,
410 bool verbose = true);
411
412
413// Simple wrapper that allows an ExternalString to refer to a
414// Vector<const char>. Doesn't assume ownership of the data.
415class AsciiStringAdapter: public v8::String::ExternalAsciiStringResource {
416 public:
417 explicit AsciiStringAdapter(Vector<const char> data) : data_(data) {}
418
419 virtual const char* data() const { return data_.start(); }
420
421 virtual size_t length() const { return data_.length(); }
422
423 private:
424 Vector<const char> data_;
425};
426
427
kasper.lund7276f142008-07-30 08:49:36 +0000428// Helper class for building result strings in a character buffer. The
429// purpose of the class is to use safe operations that checks the
430// buffer bounds on all operations in debug mode.
431class StringBuilder {
432 public:
433 // Create a string builder with a buffer of the given size. The
434 // buffer is allocated through NewArray<char> and must be
435 // deallocated by the caller of Finalize().
436 explicit StringBuilder(int size);
437
438 StringBuilder(char* buffer, int size)
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000439 : buffer_(buffer, size), position_(0) { }
kasper.lund7276f142008-07-30 08:49:36 +0000440
441 ~StringBuilder() { if (!is_finalized()) Finalize(); }
442
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000443 int size() const { return buffer_.length(); }
kasper.lund7276f142008-07-30 08:49:36 +0000444
445 // Get the current position in the builder.
446 int position() const {
447 ASSERT(!is_finalized());
448 return position_;
449 }
450
451 // Reset the position.
452 void Reset() { position_ = 0; }
453
454 // Add a single character to the builder. It is not allowed to add
455 // 0-characters; use the Finalize() method to terminate the string
456 // instead.
457 void AddCharacter(char c) {
458 ASSERT(c != '\0');
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000459 ASSERT(!is_finalized() && position_ < buffer_.length());
kasper.lund7276f142008-07-30 08:49:36 +0000460 buffer_[position_++] = c;
461 }
462
463 // Add an entire string to the builder. Uses strlen() internally to
464 // compute the length of the input string.
465 void AddString(const char* s);
466
467 // Add the first 'n' characters of the given string 's' to the
468 // builder. The input string must have enough characters.
469 void AddSubstring(const char* s, int n);
470
471 // Add formatted contents to the builder just like printf().
472 void AddFormatted(const char* format, ...);
473
474 // Add character padding to the builder. If count is non-positive,
475 // nothing is added to the builder.
476 void AddPadding(char c, int count);
477
478 // Finalize the string by 0-terminating it and returning the buffer.
479 char* Finalize();
480
481 private:
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000482 Vector<char> buffer_;
kasper.lund7276f142008-07-30 08:49:36 +0000483 int position_;
484
485 bool is_finalized() const { return position_ < 0; }
mads.s.ager31e71382008-08-13 09:32:07 +0000486
487 DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
kasper.lund7276f142008-07-30 08:49:36 +0000488};
489
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000490
491// Copy from ASCII/16bit chars to ASCII/16bit chars.
492template <typename sourcechar, typename sinkchar>
493static inline void CopyChars(sinkchar* dest, const sourcechar* src, int chars) {
494 sinkchar* limit = dest + chars;
495#ifdef CAN_READ_UNALIGNED
496 if (sizeof(*dest) == sizeof(*src)) {
497 // Number of characters in a uint32_t.
498 static const int kStepSize = sizeof(uint32_t) / sizeof(*dest); // NOLINT
499 while (dest <= limit - kStepSize) {
500 *reinterpret_cast<uint32_t*>(dest) =
501 *reinterpret_cast<const uint32_t*>(src);
502 dest += kStepSize;
503 src += kStepSize;
504 }
505 }
506#endif
507 while (dest < limit) {
508 *dest++ = static_cast<sinkchar>(*src++);
509 }
510}
511
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000512
513static inline int Load16(const byte* ptr) {
514#ifdef CAN_READ_UNALIGNED
515 return *reinterpret_cast<const uint16_t*>(ptr);
516#else
517 uint32_t word;
518 word = ptr[1];
519 word |= ptr[0] << 8;
520 return word;
521#endif
522}
523
524
525static inline int Load32(const byte* ptr) {
526#ifdef CAN_READ_UNALIGNED
527 return *reinterpret_cast<const uint32_t*>(ptr);
528#else
529 uint32_t word;
530 word = ptr[3];
531 word |= ptr[2] << 8;
532 word |= ptr[1] << 16;
533 word |= ptr[0] << 24;
534 return word;
535#endif
536}
537
538
539static inline void Store16(byte* ptr, uint16_t value) {
540#ifdef CAN_READ_UNALIGNED
541 *reinterpret_cast<uint16_t*>(ptr) = value;
542#else
543 ptr[1] = value;
544 ptr[0] = value >> 8;
545#endif
546}
547
548
549static inline void Store32(byte* ptr, uint32_t value) {
550#ifdef CAN_READ_UNALIGNED
551 *reinterpret_cast<uint32_t*>(ptr) = value;
552#else
553 ptr[3] = value;
554 ptr[2] = value >> 8;
555 ptr[1] = value >> 16;
556 ptr[0] = value >> 24;
557#endif
558}
559
560
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000561} } // namespace v8::internal
562
563#endif // V8_UTILS_H_