blob: 0fd24ec9a097745168dc75daa069c7985b882b72 [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>
32
33namespace v8 {
34namespace internal {
35
36// ----------------------------------------------------------------------------
37// General helper functions
38
Steve Block3ce2e202009-11-05 08:53:23 +000039// Returns true iff x is a power of 2 (or zero). Cannot be used with the
40// maximally negative value of the type T (the -1 overflows).
Steve Blocka7e24c12009-10-30 11:49:00 +000041template <typename T>
42static inline bool IsPowerOf2(T x) {
43 return (x & (x - 1)) == 0;
44}
45
46
47// The C++ standard leaves the semantics of '>>' undefined for
48// negative signed operands. Most implementations do the right thing,
49// though.
50static 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.
56// This allows conversion of Addresses and integral types into
57// 0-relative int offsets.
58template <typename T>
59static inline intptr_t 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.
65// This allows conversion of 0-relative int offsets into Addresses and
66// integral types.
67template <typename T>
68static inline T AddressFrom(intptr_t x) {
Steve Blockd0582a62009-12-15 09:54:21 +000069 return static_cast<T>(static_cast<T>(0) + x);
Steve Blocka7e24c12009-10-30 11:49:00 +000070}
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
88template <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
105// 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
110template <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,
119 intptr_t alignment,
120 int offset) {
121 intptr_t offs = OffsetFrom(addr + offset);
122 return IsAligned(offs, alignment);
123}
124
125
126// Returns the maximum of the two parameters.
127template <typename T>
128static T Max(T a, T b) {
129 return a < b ? b : a;
130}
131
132
133// Returns the minimum of the two parameters.
134template <typename T>
135static T Min(T a, T b) {
136 return a < b ? a : b;
137}
138
139
Steve Blockd0582a62009-12-15 09:54:21 +0000140inline int StrLength(const char* string) {
141 size_t length = strlen(string);
142 ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
143 return static_cast<int>(length);
144}
145
146
Steve Blocka7e24c12009-10-30 11:49:00 +0000147// ----------------------------------------------------------------------------
148// BitField is a help template for encoding and decode bitfield with
149// unsigned content.
150template<class T, int shift, int size>
151class BitField {
152 public:
153 // Tells whether the provided value fits into the bit field.
154 static bool is_valid(T value) {
155 return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0;
156 }
157
158 // Returns a uint32_t mask of bit field.
159 static uint32_t mask() {
160 return (1U << (size + shift)) - (1U << shift);
161 }
162
163 // Returns a uint32_t with the bit field value encoded.
164 static uint32_t encode(T value) {
165 ASSERT(is_valid(value));
166 return static_cast<uint32_t>(value) << shift;
167 }
168
169 // Extracts the bit field from the value.
170 static T decode(uint32_t value) {
171 return static_cast<T>((value >> shift) & ((1U << (size)) - 1));
172 }
173};
174
175
176// ----------------------------------------------------------------------------
177// Support for compressed, machine-independent encoding
178// and decoding of integer values of arbitrary size.
179
180// Encoding and decoding from/to a buffer at position p;
181// the result is the position after the encoded integer.
182// Small signed integers in the range -64 <= x && x < 64
183// are encoded in 1 byte; larger values are encoded in 2
184// or more bytes. At most sizeof(int) + 1 bytes are used
185// in the worst case.
186byte* EncodeInt(byte* p, int x);
187byte* DecodeInt(byte* p, int* x);
188
189
190// Encoding and decoding from/to a buffer at position p - 1
191// moving backward; the result is the position of the last
192// byte written. These routines are useful to read/write
193// into a buffer starting at the end of the buffer.
194byte* EncodeUnsignedIntBackward(byte* p, unsigned int x);
195
196// The decoding function is inlined since its performance is
197// important to mark-sweep garbage collection.
198inline byte* DecodeUnsignedIntBackward(byte* p, unsigned int* x) {
199 byte b = *--p;
200 if (b >= 128) {
201 *x = static_cast<unsigned int>(b) - 128;
202 return p;
203 }
204 unsigned int r = static_cast<unsigned int>(b);
205 unsigned int s = 7;
206 b = *--p;
207 while (b < 128) {
208 r |= static_cast<unsigned int>(b) << s;
209 s += 7;
210 b = *--p;
211 }
212 // b >= 128
213 *x = r | ((static_cast<unsigned int>(b) - 128) << s);
214 return p;
215}
216
217
218// ----------------------------------------------------------------------------
219// Hash function.
220
221uint32_t ComputeIntegerHash(uint32_t key);
222
223
224// ----------------------------------------------------------------------------
225// I/O support.
226
227// Our version of printf(). Avoids compilation errors that we get
228// with standard printf when attempting to print pointers, etc.
229// (the errors are due to the extra compilation flags, which we
230// want elsewhere).
231void PrintF(const char* format, ...);
232
233// Our version of fflush.
234void Flush();
235
236
237// Read a line of characters after printing the prompt to stdout. The resulting
238// char* needs to be disposed off with DeleteArray by the caller.
239char* ReadLine(const char* prompt);
240
241
242// Read and return the raw bytes in a file. the size of the buffer is returned
243// in size.
244// The returned buffer must be freed by the caller.
245byte* ReadBytes(const char* filename, int* size, bool verbose = true);
246
247
248// Write size chars from str to the file given by filename.
249// The file is overwritten. Returns the number of chars written.
250int WriteChars(const char* filename,
251 const char* str,
252 int size,
253 bool verbose = true);
254
255
256// Write size bytes to the file given by filename.
257// The file is overwritten. Returns the number of bytes written.
258int WriteBytes(const char* filename,
259 const byte* bytes,
260 int size,
261 bool verbose = true);
262
263
264// Write the C code
265// const char* <varname> = "<str>";
266// const int <varname>_len = <len>;
267// to the file given by filename. Only the first len chars are written.
268int WriteAsCFile(const char* filename, const char* varname,
269 const char* str, int size, bool verbose = true);
270
271
272// ----------------------------------------------------------------------------
273// Miscellaneous
274
275// A static resource holds a static instance that can be reserved in
276// a local scope using an instance of Access. Attempts to re-reserve
277// the instance will cause an error.
278template <typename T>
279class StaticResource {
280 public:
281 StaticResource() : is_reserved_(false) {}
282
283 private:
284 template <typename S> friend class Access;
285 T instance_;
286 bool is_reserved_;
287};
288
289
290// Locally scoped access to a static resource.
291template <typename T>
292class Access {
293 public:
294 explicit Access(StaticResource<T>* resource)
295 : resource_(resource)
296 , instance_(&resource->instance_) {
297 ASSERT(!resource->is_reserved_);
298 resource->is_reserved_ = true;
299 }
300
301 ~Access() {
302 resource_->is_reserved_ = false;
303 resource_ = NULL;
304 instance_ = NULL;
305 }
306
307 T* value() { return instance_; }
308 T* operator -> () { return instance_; }
309
310 private:
311 StaticResource<T>* resource_;
312 T* instance_;
313};
314
315
316template <typename T>
317class Vector {
318 public:
319 Vector() : start_(NULL), length_(0) {}
320 Vector(T* data, int length) : start_(data), length_(length) {
321 ASSERT(length == 0 || (length > 0 && data != NULL));
322 }
323
324 static Vector<T> New(int length) {
325 return Vector<T>(NewArray<T>(length), length);
326 }
327
328 // Returns a vector using the same backing storage as this one,
329 // spanning from and including 'from', to but not including 'to'.
330 Vector<T> SubVector(int from, int to) {
331 ASSERT(from < length_);
332 ASSERT(to <= length_);
333 ASSERT(from < to);
334 return Vector<T>(start() + from, to - from);
335 }
336
337 // Returns the length of the vector.
338 int length() const { return length_; }
339
340 // Returns whether or not the vector is empty.
341 bool is_empty() const { return length_ == 0; }
342
343 // Returns the pointer to the start of the data in the vector.
344 T* start() const { return start_; }
345
346 // Access individual vector elements - checks bounds in debug mode.
347 T& operator[](int index) const {
348 ASSERT(0 <= index && index < length_);
349 return start_[index];
350 }
351
352 T& first() { return start_[0]; }
353
354 T& last() { return start_[length_ - 1]; }
355
356 // Returns a clone of this vector with a new backing store.
357 Vector<T> Clone() const {
358 T* result = NewArray<T>(length_);
359 for (int i = 0; i < length_; i++) result[i] = start_[i];
360 return Vector<T>(result, length_);
361 }
362
363 void Sort(int (*cmp)(const T*, const T*)) {
364 typedef int (*RawComparer)(const void*, const void*);
365 qsort(start(),
366 length(),
367 sizeof(T),
368 reinterpret_cast<RawComparer>(cmp));
369 }
370
371 void Sort() {
372 Sort(PointerValueCompare<T>);
373 }
374
375 void Truncate(int length) {
376 ASSERT(length <= length_);
377 length_ = length;
378 }
379
380 // Releases the array underlying this vector. Once disposed the
381 // vector is empty.
382 void Dispose() {
383 if (is_empty()) return;
384 DeleteArray(start_);
385 start_ = NULL;
386 length_ = 0;
387 }
388
389 inline Vector<T> operator+(int offset) {
390 ASSERT(offset < length_);
391 return Vector<T>(start_ + offset, length_ - offset);
392 }
393
394 // Factory method for creating empty vectors.
395 static Vector<T> empty() { return Vector<T>(NULL, 0); }
396
397 protected:
398 void set_start(T* start) { start_ = start; }
399
400 private:
401 T* start_;
402 int length_;
403};
404
405
406// A temporary assignment sets a (non-local) variable to a value on
407// construction and resets it the value on destruction.
408template <typename T>
409class TempAssign {
410 public:
411 TempAssign(T* var, T value): var_(var), old_value_(*var) {
412 *var = value;
413 }
414
415 ~TempAssign() { *var_ = old_value_; }
416
417 private:
418 T* var_;
419 T old_value_;
420};
421
422
423template <typename T, int kSize>
424class EmbeddedVector : public Vector<T> {
425 public:
426 EmbeddedVector() : Vector<T>(buffer_, kSize) { }
427
428 // When copying, make underlying Vector to reference our buffer.
429 EmbeddedVector(const EmbeddedVector& rhs)
430 : Vector<T>(rhs) {
431 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
432 set_start(buffer_);
433 }
434
435 EmbeddedVector& operator=(const EmbeddedVector& rhs) {
436 if (this == &rhs) return *this;
437 Vector<T>::operator=(rhs);
438 memcpy(buffer_, rhs.buffer_, sizeof(T) * kSize);
439 set_start(buffer_);
440 return *this;
441 }
442
443 private:
444 T buffer_[kSize];
445};
446
447
448template <typename T>
449class ScopedVector : public Vector<T> {
450 public:
451 explicit ScopedVector(int length) : Vector<T>(NewArray<T>(length), length) { }
452 ~ScopedVector() {
453 DeleteArray(this->start());
454 }
455};
456
457
458inline Vector<const char> CStrVector(const char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000459 return Vector<const char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000460}
461
462inline Vector<char> MutableCStrVector(char* data) {
Steve Blockd0582a62009-12-15 09:54:21 +0000463 return Vector<char>(data, StrLength(data));
Steve Blocka7e24c12009-10-30 11:49:00 +0000464}
465
466inline Vector<char> MutableCStrVector(char* data, int max) {
Steve Blockd0582a62009-12-15 09:54:21 +0000467 int length = StrLength(data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000468 return Vector<char>(data, (length < max) ? length : max);
469}
470
471template <typename T>
472inline Vector< Handle<Object> > HandleVector(v8::internal::Handle<T>* elms,
473 int length) {
474 return Vector< Handle<Object> >(
475 reinterpret_cast<v8::internal::Handle<Object>*>(elms), length);
476}
477
478
479// Simple support to read a file into a 0-terminated C-string.
480// The returned buffer must be freed by the caller.
481// On return, *exits tells whether the file existed.
482Vector<const char> ReadFile(const char* filename,
483 bool* exists,
484 bool verbose = true);
485
486
487// Simple wrapper that allows an ExternalString to refer to a
488// Vector<const char>. Doesn't assume ownership of the data.
489class AsciiStringAdapter: public v8::String::ExternalAsciiStringResource {
490 public:
491 explicit AsciiStringAdapter(Vector<const char> data) : data_(data) {}
492
493 virtual const char* data() const { return data_.start(); }
494
495 virtual size_t length() const { return data_.length(); }
496
497 private:
498 Vector<const char> data_;
499};
500
501
502// Helper class for building result strings in a character buffer. The
503// purpose of the class is to use safe operations that checks the
504// buffer bounds on all operations in debug mode.
505class StringBuilder {
506 public:
507 // Create a string builder with a buffer of the given size. The
508 // buffer is allocated through NewArray<char> and must be
509 // deallocated by the caller of Finalize().
510 explicit StringBuilder(int size);
511
512 StringBuilder(char* buffer, int size)
513 : buffer_(buffer, size), position_(0) { }
514
515 ~StringBuilder() { if (!is_finalized()) Finalize(); }
516
517 int size() const { return buffer_.length(); }
518
519 // Get the current position in the builder.
520 int position() const {
521 ASSERT(!is_finalized());
522 return position_;
523 }
524
525 // Reset the position.
526 void Reset() { position_ = 0; }
527
528 // Add a single character to the builder. It is not allowed to add
529 // 0-characters; use the Finalize() method to terminate the string
530 // instead.
531 void AddCharacter(char c) {
532 ASSERT(c != '\0');
533 ASSERT(!is_finalized() && position_ < buffer_.length());
534 buffer_[position_++] = c;
535 }
536
537 // Add an entire string to the builder. Uses strlen() internally to
538 // compute the length of the input string.
539 void AddString(const char* s);
540
541 // Add the first 'n' characters of the given string 's' to the
542 // builder. The input string must have enough characters.
543 void AddSubstring(const char* s, int n);
544
545 // Add formatted contents to the builder just like printf().
546 void AddFormatted(const char* format, ...);
547
548 // Add character padding to the builder. If count is non-positive,
549 // nothing is added to the builder.
550 void AddPadding(char c, int count);
551
552 // Finalize the string by 0-terminating it and returning the buffer.
553 char* Finalize();
554
555 private:
556 Vector<char> buffer_;
557 int position_;
558
559 bool is_finalized() const { return position_ < 0; }
560
561 DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
562};
563
564
565// Copy from ASCII/16bit chars to ASCII/16bit chars.
566template <typename sourcechar, typename sinkchar>
567static inline void CopyChars(sinkchar* dest, const sourcechar* src, int chars) {
568 sinkchar* limit = dest + chars;
569#ifdef V8_HOST_CAN_READ_UNALIGNED
570 if (sizeof(*dest) == sizeof(*src)) {
571 // Number of characters in a uint32_t.
572 static const int kStepSize = sizeof(uint32_t) / sizeof(*dest); // NOLINT
573 while (dest <= limit - kStepSize) {
574 *reinterpret_cast<uint32_t*>(dest) =
575 *reinterpret_cast<const uint32_t*>(src);
576 dest += kStepSize;
577 src += kStepSize;
578 }
579 }
580#endif
581 while (dest < limit) {
582 *dest++ = static_cast<sinkchar>(*src++);
583 }
584}
585
586
Steve Blockd0582a62009-12-15 09:54:21 +0000587// Calculate 10^exponent.
588int TenToThe(int exponent);
589
Steve Blocka7e24c12009-10-30 11:49:00 +0000590} } // namespace v8::internal
591
592#endif // V8_UTILS_H_