objects-inl.h 209 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4 5 6 7 8 9 10
//
// Review notes:
//
// - The use of macros in these inline functions may seem superfluous
// but it is absolutely needed to make sure gcc generates optimal
// code. gcc is not happy when attempting to inline too deep.
//
11 12 13 14

#ifndef V8_OBJECTS_INL_H_
#define V8_OBJECTS_INL_H_

15
#include "src/base/atomicops.h"
16 17
#include "src/contexts.h"
#include "src/conversions-inl.h"
18 19
#include "src/elements.h"
#include "src/factory.h"
20
#include "src/field-index-inl.h"
21
#include "src/heap-inl.h"
22
#include "src/heap.h"
23
#include "src/incremental-marking.h"
24
#include "src/isolate.h"
25 26 27
#include "src/lookup.h"
#include "src/objects.h"
#include "src/objects-visiting.h"
28 29 30 31
#include "src/property.h"
#include "src/spaces.h"
#include "src/store-buffer.h"
#include "src/transitions-inl.h"
32
#include "src/v8memory.h"
33

34 35
namespace v8 {
namespace internal {
36 37 38 39 40 41

PropertyDetails::PropertyDetails(Smi* smi) {
  value_ = smi->value();
}


42
Smi* PropertyDetails::AsSmi() const {
43 44 45 46
  // Ensure the upper 2 bits have the same value by sign extending it. This is
  // necessary to be able to use the 31st bit of the property details.
  int value = value_ << 1;
  return Smi::FromInt(value >> 1);
47 48 49
}


50
PropertyDetails PropertyDetails::AsDeleted() const {
51
  Smi* smi = Smi::FromInt(value_ | DeletedField::encode(1));
52 53 54 55
  return PropertyDetails(smi);
}


56
#define TYPE_CHECKER(type, instancetype)                                \
57
  bool Object::Is##type() const {                                       \
58 59 60 61 62
  return Object::IsHeapObject() &&                                      \
      HeapObject::cast(this)->map()->instance_type() == instancetype;   \
  }


63 64 65 66 67 68
#define CAST_ACCESSOR(type)                       \
  type* type::cast(Object* object) {              \
    SLOW_ASSERT(object->Is##type());              \
    return reinterpret_cast<type*>(object);       \
  }                                               \
  const type* type::cast(const Object* object) {  \
69
    SLOW_ASSERT(object->Is##type());              \
70
    return reinterpret_cast<const type*>(object); \
71 72 73
  }


74 75
#define INT_ACCESSORS(holder, name, offset)                                   \
  int holder::name() const { return READ_INT_FIELD(this, offset); }           \
76 77 78
  void holder::set_##name(int value) { WRITE_INT_FIELD(this, offset, value); }


79 80 81 82 83
#define ACCESSORS(holder, name, type, offset)                                 \
  type* holder::name() const { return type::cast(READ_FIELD(this, offset)); } \
  void holder::set_##name(type* value, WriteBarrierMode mode) {               \
    WRITE_FIELD(this, offset, value);                                         \
    CONDITIONAL_WRITE_BARRIER(GetHeap(), this, offset, value, mode);          \
84 85 86
  }


87
// Getter that returns a tagged Smi and setter that writes a tagged Smi.
88 89 90 91
#define ACCESSORS_TO_SMI(holder, name, offset)                              \
  Smi* holder::name() const { return Smi::cast(READ_FIELD(this, offset)); } \
  void holder::set_##name(Smi* value, WriteBarrierMode mode) {              \
    WRITE_FIELD(this, offset, value);                                       \
92 93 94 95
  }


// Getter that returns a Smi as an int and writes an int as a Smi.
96
#define SMI_ACCESSORS(holder, name, offset)             \
97
  int holder::name() const {                            \
98 99 100 101 102 103 104
    Object* value = READ_FIELD(this, offset);           \
    return Smi::cast(value)->value();                   \
  }                                                     \
  void holder::set_##name(int value) {                  \
    WRITE_FIELD(this, offset, Smi::FromInt(value));     \
  }

105
#define SYNCHRONIZED_SMI_ACCESSORS(holder, name, offset)    \
106
  int holder::synchronized_##name() const {                 \
107 108 109 110 111 112 113
    Object* value = ACQUIRE_READ_FIELD(this, offset);       \
    return Smi::cast(value)->value();                       \
  }                                                         \
  void holder::synchronized_set_##name(int value) {         \
    RELEASE_WRITE_FIELD(this, offset, Smi::FromInt(value)); \
  }

114
#define NOBARRIER_SMI_ACCESSORS(holder, name, offset)          \
115
  int holder::nobarrier_##name() const {                       \
116 117 118 119 120 121
    Object* value = NOBARRIER_READ_FIELD(this, offset);        \
    return Smi::cast(value)->value();                          \
  }                                                            \
  void holder::nobarrier_set_##name(int value) {               \
    NOBARRIER_WRITE_FIELD(this, offset, Smi::FromInt(value));  \
  }
122

123
#define BOOL_GETTER(holder, field, name, offset)           \
124
  bool holder::name() const {                              \
125 126 127 128 129
    return BooleanBit::get(field(), offset);               \
  }                                                        \


#define BOOL_ACCESSORS(holder, field, name, offset)        \
130
  bool holder::name() const {                              \
131 132 133 134 135 136 137
    return BooleanBit::get(field(), offset);               \
  }                                                        \
  void holder::set_##name(bool value) {                    \
    set_##field(BooleanBit::set(field(), offset, value));  \
  }


138
bool Object::IsFixedArrayBase() const {
139 140
  return IsFixedArray() || IsFixedDoubleArray() || IsConstantPoolArray() ||
         IsFixedTypedArrayBase() || IsExternalArray();
141 142 143
}


144
// External objects are not extensible, so the map check is enough.
145
bool Object::IsExternal() const {
146 147 148 149 150 151
  return Object::IsHeapObject() &&
      HeapObject::cast(this)->map() ==
      HeapObject::cast(this)->GetHeap()->external_map();
}


152
bool Object::IsAccessorInfo() const {
153 154 155 156
  return IsExecutableAccessorInfo() || IsDeclaredAccessorInfo();
}


157
bool Object::IsSmi() const {
158 159 160 161
  return HAS_SMI_TAG(this);
}


162
bool Object::IsHeapObject() const {
163
  return Internals::HasHeapObjectTag(this);
164 165 166
}


167
TYPE_CHECKER(HeapNumber, HEAP_NUMBER_TYPE)
168
TYPE_CHECKER(MutableHeapNumber, MUTABLE_HEAP_NUMBER_TYPE)
169 170 171
TYPE_CHECKER(Symbol, SYMBOL_TYPE)


172
bool Object::IsString() const {
173
  return Object::IsHeapObject()
174
    && HeapObject::cast(this)->map()->instance_type() < FIRST_NONSTRING_TYPE;
175
}
176 177


178
bool Object::IsName() const {
179 180 181 182
  return IsString() || IsSymbol();
}


183
bool Object::IsUniqueName() const {
184
  return IsInternalizedString() || IsSymbol();
185 186 187
}


188
bool Object::IsSpecObject() const {
189 190 191 192 193
  return Object::IsHeapObject()
    && HeapObject::cast(this)->map()->instance_type() >= FIRST_SPEC_OBJECT_TYPE;
}


194
bool Object::IsSpecFunction() const {
195 196 197 198 199 200
  if (!Object::IsHeapObject()) return false;
  InstanceType type = HeapObject::cast(this)->map()->instance_type();
  return type == JS_FUNCTION_TYPE || type == JS_FUNCTION_PROXY_TYPE;
}


201
bool Object::IsTemplateInfo() const {
202 203 204 205
  return IsObjectTemplateInfo() || IsFunctionTemplateInfo();
}


206
bool Object::IsInternalizedString() const {
207 208
  if (!this->IsHeapObject()) return false;
  uint32_t type = HeapObject::cast(this)->map()->instance_type();
209 210 211
  STATIC_ASSERT(kNotInternalizedTag != 0);
  return (type & (kIsNotStringMask | kIsNotInternalizedMask)) ==
      (kStringTag | kInternalizedTag);
212 213 214
}


215
bool Object::IsConsString() const {
216 217 218 219 220
  if (!IsString()) return false;
  return StringShape(String::cast(this)).IsCons();
}


221
bool Object::IsSlicedString() const {
222 223
  if (!IsString()) return false;
  return StringShape(String::cast(this)).IsSliced();
224 225 226
}


227
bool Object::IsSeqString() const {
228 229
  if (!IsString()) return false;
  return StringShape(String::cast(this)).IsSequential();
230 231 232
}


233
bool Object::IsSeqOneByteString() const {
234
  if (!IsString()) return false;
235
  return StringShape(String::cast(this)).IsSequential() &&
236
         String::cast(this)->IsOneByteRepresentation();
237 238 239
}


240
bool Object::IsSeqTwoByteString() const {
241
  if (!IsString()) return false;
242
  return StringShape(String::cast(this)).IsSequential() &&
243
         String::cast(this)->IsTwoByteRepresentation();
244 245 246
}


247
bool Object::IsExternalString() const {
248 249
  if (!IsString()) return false;
  return StringShape(String::cast(this)).IsExternal();
250 251 252
}


253
bool Object::IsExternalAsciiString() const {
254
  if (!IsString()) return false;
255
  return StringShape(String::cast(this)).IsExternal() &&
256
         String::cast(this)->IsOneByteRepresentation();
257 258 259
}


260
bool Object::IsExternalTwoByteString() const {
261
  if (!IsString()) return false;
262
  return StringShape(String::cast(this)).IsExternal() &&
263
         String::cast(this)->IsTwoByteRepresentation();
264 265
}

266

267 268
bool Object::HasValidElements() {
  // Dictionary is covered under FixedArray.
269 270
  return IsFixedArray() || IsFixedDoubleArray() || IsExternalArray() ||
         IsFixedTypedArrayBase();
271
}
272

273

274 275 276 277 278
Handle<Object> Object::NewStorageFor(Isolate* isolate,
                                     Handle<Object> object,
                                     Representation representation) {
  if (representation.IsSmi() && object->IsUninitialized()) {
    return handle(Smi::FromInt(0), isolate);
279
  }
280
  if (!representation.IsDouble()) return object;
281
  double value;
282
  if (object->IsUninitialized()) {
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    value = 0;
  } else if (object->IsMutableHeapNumber()) {
    value = HeapNumber::cast(*object)->value();
  } else {
    value = object->Number();
  }
  return isolate->factory()->NewHeapNumber(value, MUTABLE);
}


Handle<Object> Object::WrapForRead(Isolate* isolate,
                                   Handle<Object> object,
                                   Representation representation) {
  ASSERT(!object->IsUninitialized());
  if (!representation.IsDouble()) {
    ASSERT(object->FitsRepresentation(representation));
    return object;
300
  }
301
  return isolate->factory()->NewHeapNumber(HeapNumber::cast(*object)->value());
302 303 304
}


305
StringShape::StringShape(const String* str)
306 307
  : type_(str->map()->instance_type()) {
  set_valid();
308
  ASSERT((type_ & kIsNotStringMask) == kStringTag);
309 310 311
}


312
StringShape::StringShape(Map* map)
313 314
  : type_(map->instance_type()) {
  set_valid();
315
  ASSERT((type_ & kIsNotStringMask) == kStringTag);
316 317 318
}


319
StringShape::StringShape(InstanceType t)
320 321
  : type_(static_cast<uint32_t>(t)) {
  set_valid();
322
  ASSERT((type_ & kIsNotStringMask) == kStringTag);
323 324 325
}


326
bool StringShape::IsInternalized() {
327
  ASSERT(valid());
328 329 330
  STATIC_ASSERT(kNotInternalizedTag != 0);
  return (type_ & (kIsNotStringMask | kIsNotInternalizedMask)) ==
      (kStringTag | kInternalizedTag);
331 332 333
}


334
bool String::IsOneByteRepresentation() const {
335
  uint32_t type = map()->instance_type();
336
  return (type & kStringEncodingMask) == kOneByteStringTag;
337 338 339
}


340
bool String::IsTwoByteRepresentation() const {
341 342
  uint32_t type = map()->instance_type();
  return (type & kStringEncodingMask) == kTwoByteStringTag;
343 344 345
}


346
bool String::IsOneByteRepresentationUnderneath() {
347 348 349 350 351
  uint32_t type = map()->instance_type();
  STATIC_ASSERT(kIsIndirectStringTag != 0);
  STATIC_ASSERT((kIsIndirectStringMask & kStringEncodingMask) == 0);
  ASSERT(IsFlat());
  switch (type & (kIsIndirectStringMask | kStringEncodingMask)) {
352
    case kOneByteStringTag:
353 354 355 356
      return true;
    case kTwoByteStringTag:
      return false;
    default:  // Cons or sliced string.  Need to go deeper.
357
      return GetUnderlying()->IsOneByteRepresentation();
358 359 360 361 362 363 364 365 366 367
  }
}


bool String::IsTwoByteRepresentationUnderneath() {
  uint32_t type = map()->instance_type();
  STATIC_ASSERT(kIsIndirectStringTag != 0);
  STATIC_ASSERT((kIsIndirectStringMask & kStringEncodingMask) == 0);
  ASSERT(IsFlat());
  switch (type & (kIsIndirectStringMask | kStringEncodingMask)) {
368
    case kOneByteStringTag:
369 370 371 372 373 374 375 376 377
      return false;
    case kTwoByteStringTag:
      return true;
    default:  // Cons or sliced string.  Need to go deeper.
      return GetUnderlying()->IsTwoByteRepresentation();
  }
}


378
bool String::HasOnlyOneByteChars() {
379
  uint32_t type = map()->instance_type();
380 381
  return (type & kOneByteDataHintMask) == kOneByteDataHintTag ||
         IsOneByteRepresentation();
382 383 384
}


385 386 387 388 389
bool StringShape::IsCons() {
  return (type_ & kStringRepresentationMask) == kConsStringTag;
}


390 391 392 393 394 395 396 397 398 399
bool StringShape::IsSliced() {
  return (type_ & kStringRepresentationMask) == kSlicedStringTag;
}


bool StringShape::IsIndirect() {
  return (type_ & kIsIndirectStringMask) == kIsIndirectStringTag;
}


400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
bool StringShape::IsExternal() {
  return (type_ & kStringRepresentationMask) == kExternalStringTag;
}


bool StringShape::IsSequential() {
  return (type_ & kStringRepresentationMask) == kSeqStringTag;
}


StringRepresentationTag StringShape::representation_tag() {
  uint32_t tag = (type_ & kStringRepresentationMask);
  return static_cast<StringRepresentationTag>(tag);
}


416 417 418 419 420
uint32_t StringShape::encoding_tag() {
  return type_ & kStringEncodingMask;
}


421 422 423 424 425
uint32_t StringShape::full_representation_tag() {
  return (type_ & (kStringRepresentationMask | kStringEncodingMask));
}


426
STATIC_ASSERT((kStringRepresentationMask | kStringEncodingMask) ==
427 428
             Internals::kFullStringRepresentationMask);

429
STATIC_ASSERT(static_cast<uint32_t>(kStringEncodingMask) ==
430 431
             Internals::kStringEncodingMask);

432

433
bool StringShape::IsSequentialAscii() {
434
  return full_representation_tag() == (kSeqStringTag | kOneByteStringTag);
435 436 437 438
}


bool StringShape::IsSequentialTwoByte() {
439
  return full_representation_tag() == (kSeqStringTag | kTwoByteStringTag);
440 441 442 443
}


bool StringShape::IsExternalAscii() {
444
  return full_representation_tag() == (kExternalStringTag | kOneByteStringTag);
445 446 447
}


448
STATIC_ASSERT((kExternalStringTag | kOneByteStringTag) ==
449 450
             Internals::kExternalAsciiRepresentationTag);

451
STATIC_ASSERT(v8::String::ASCII_ENCODING == kOneByteStringTag);
452 453


454
bool StringShape::IsExternalTwoByte() {
455
  return full_representation_tag() == (kExternalStringTag | kTwoByteStringTag);
456 457 458
}


459
STATIC_ASSERT((kExternalStringTag | kTwoByteStringTag) ==
460 461
             Internals::kExternalTwoByteRepresentationTag);

462
STATIC_ASSERT(v8::String::TWO_BYTE_ENCODING == kTwoByteStringTag);
463

464 465 466 467 468 469 470 471 472 473
uc32 FlatStringReader::Get(int index) {
  ASSERT(0 <= index && index <= length_);
  if (is_ascii_) {
    return static_cast<const byte*>(start_)[index];
  } else {
    return static_cast<const uc16*>(start_)[index];
  }
}


474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
Handle<Object> StringTableShape::AsHandle(Isolate* isolate, HashTableKey* key) {
  return key->AsHandle(isolate);
}


Handle<Object> MapCacheShape::AsHandle(Isolate* isolate, HashTableKey* key) {
  return key->AsHandle(isolate);
}


Handle<Object> CompilationCacheShape::AsHandle(Isolate* isolate,
                                               HashTableKey* key) {
  return key->AsHandle(isolate);
}


Handle<Object> CodeCacheHashTableShape::AsHandle(Isolate* isolate,
                                                 HashTableKey* key) {
  return key->AsHandle(isolate);
}

495 496 497 498 499 500
template <typename Char>
class SequentialStringKey : public HashTableKey {
 public:
  explicit SequentialStringKey(Vector<const Char> string, uint32_t seed)
      : string_(string), hash_field_(0), seed_(seed) { }

501
  virtual uint32_t Hash() V8_OVERRIDE {
502 503 504 505 506 507 508 509 510 511
    hash_field_ = StringHasher::HashSequentialString<Char>(string_.start(),
                                                           string_.length(),
                                                           seed_);

    uint32_t result = hash_field_ >> String::kHashShift;
    ASSERT(result != 0);  // Ensure that the hash value of 0 is never computed.
    return result;
  }


512
  virtual uint32_t HashForObject(Object* other) V8_OVERRIDE {
513 514 515 516 517 518 519 520 521 522 523 524 525 526
    return String::cast(other)->Hash();
  }

  Vector<const Char> string_;
  uint32_t hash_field_;
  uint32_t seed_;
};


class OneByteStringKey : public SequentialStringKey<uint8_t> {
 public:
  OneByteStringKey(Vector<const uint8_t> str, uint32_t seed)
      : SequentialStringKey<uint8_t>(str, seed) { }

527
  virtual bool IsMatch(Object* string) V8_OVERRIDE {
528 529 530
    return String::cast(string)->IsOneByteEqualTo(string_);
  }

531
  virtual Handle<Object> AsHandle(Isolate* isolate) V8_OVERRIDE;
532 533 534
};


535 536
template<class Char>
class SubStringKey : public HashTableKey {
537
 public:
538 539 540 541 542 543 544
  SubStringKey(Handle<String> string, int from, int length)
      : string_(string), from_(from), length_(length) {
    if (string_->IsSlicedString()) {
      string_ = Handle<String>(Unslice(*string_, &from_));
    }
    ASSERT(string_->IsSeqString() || string->IsExternalString());
  }
545

546
  virtual uint32_t Hash() V8_OVERRIDE {
547 548
    ASSERT(length_ >= 0);
    ASSERT(from_ + length_ <= string_->length());
549
    const Char* chars = GetChars() + from_;
550 551 552 553 554 555 556
    hash_field_ = StringHasher::HashSequentialString(
        chars, length_, string_->GetHeap()->HashSeed());
    uint32_t result = hash_field_ >> String::kHashShift;
    ASSERT(result != 0);  // Ensure that the hash value of 0 is never computed.
    return result;
  }

557
  virtual uint32_t HashForObject(Object* other) V8_OVERRIDE {
558 559 560
    return String::cast(other)->Hash();
  }

561
  virtual bool IsMatch(Object* string) V8_OVERRIDE;
562
  virtual Handle<Object> AsHandle(Isolate* isolate) V8_OVERRIDE;
563 564

 private:
565 566 567 568 569 570 571 572 573 574 575
  const Char* GetChars();
  String* Unslice(String* string, int* offset) {
    while (string->IsSlicedString()) {
      SlicedString* sliced = SlicedString::cast(string);
      *offset += sliced->offset();
      string = sliced->parent();
    }
    return string;
  }

  Handle<String> string_;
576 577 578 579 580 581 582 583 584 585 586
  int from_;
  int length_;
  uint32_t hash_field_;
};


class TwoByteStringKey : public SequentialStringKey<uc16> {
 public:
  explicit TwoByteStringKey(Vector<const uc16> str, uint32_t seed)
      : SequentialStringKey<uc16>(str, seed) { }

587
  virtual bool IsMatch(Object* string) V8_OVERRIDE {
588 589 590
    return String::cast(string)->IsTwoByteEqualTo(string_);
  }

591
  virtual Handle<Object> AsHandle(Isolate* isolate) V8_OVERRIDE;
592 593 594 595 596 597 598 599 600
};


// Utf8StringKey carries a vector of chars as key.
class Utf8StringKey : public HashTableKey {
 public:
  explicit Utf8StringKey(Vector<const char> string, uint32_t seed)
      : string_(string), hash_field_(0), seed_(seed) { }

601
  virtual bool IsMatch(Object* string) V8_OVERRIDE {
602 603 604
    return String::cast(string)->IsUtf8EqualTo(string_);
  }

605
  virtual uint32_t Hash() V8_OVERRIDE {
606 607 608 609 610 611 612
    if (hash_field_ != 0) return hash_field_ >> String::kHashShift;
    hash_field_ = StringHasher::ComputeUtf8Hash(string_, seed_, &chars_);
    uint32_t result = hash_field_ >> String::kHashShift;
    ASSERT(result != 0);  // Ensure that the hash value of 0 is never computed.
    return result;
  }

613
  virtual uint32_t HashForObject(Object* other) V8_OVERRIDE {
614 615 616
    return String::cast(other)->Hash();
  }

617
  virtual Handle<Object> AsHandle(Isolate* isolate) V8_OVERRIDE {
618
    if (hash_field_ == 0) Hash();
619 620
    return isolate->factory()->NewInternalizedStringFromUtf8(
        string_, chars_, hash_field_);
621 622 623 624 625 626 627 628 629
  }

  Vector<const char> string_;
  uint32_t hash_field_;
  int chars_;  // Caches the number of characters when computing the hash code.
  uint32_t seed_;
};


630
bool Object::IsNumber() const {
631 632 633 634
  return IsSmi() || IsHeapNumber();
}


635 636
TYPE_CHECKER(ByteArray, BYTE_ARRAY_TYPE)
TYPE_CHECKER(FreeSpace, FREE_SPACE_TYPE)
637 638


639
bool Object::IsFiller() const {
640 641 642 643 644 645
  if (!Object::IsHeapObject()) return false;
  InstanceType instance_type = HeapObject::cast(this)->map()->instance_type();
  return instance_type == FREE_SPACE_TYPE || instance_type == FILLER_TYPE;
}


646
bool Object::IsExternalArray() const {
647 648 649 650
  if (!Object::IsHeapObject())
    return false;
  InstanceType instance_type =
      HeapObject::cast(this)->map()->instance_type();
651 652
  return (instance_type >= FIRST_EXTERNAL_ARRAY_TYPE &&
          instance_type <= LAST_EXTERNAL_ARRAY_TYPE);
653 654 655
}


656 657 658 659 660 661
#define TYPED_ARRAY_TYPE_CHECKER(Type, type, TYPE, ctype, size)               \
  TYPE_CHECKER(External##Type##Array, EXTERNAL_##TYPE##_ARRAY_TYPE)           \
  TYPE_CHECKER(Fixed##Type##Array, FIXED_##TYPE##_ARRAY_TYPE)

TYPED_ARRAYS(TYPED_ARRAY_TYPE_CHECKER)
#undef TYPED_ARRAY_TYPE_CHECKER
662 663


664
bool Object::IsFixedTypedArrayBase() const {
665 666 667 668 669 670 671 672 673
  if (!Object::IsHeapObject()) return false;

  InstanceType instance_type =
      HeapObject::cast(this)->map()->instance_type();
  return (instance_type >= FIRST_FIXED_TYPED_ARRAY_TYPE &&
          instance_type <= LAST_FIXED_TYPED_ARRAY_TYPE);
}


674
bool Object::IsJSReceiver() const {
675
  STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
676 677 678 679 680
  return IsHeapObject() &&
      HeapObject::cast(this)->map()->instance_type() >= FIRST_JS_RECEIVER_TYPE;
}


681
bool Object::IsJSObject() const {
682 683 684
  STATIC_ASSERT(LAST_JS_OBJECT_TYPE == LAST_TYPE);
  return IsHeapObject() &&
      HeapObject::cast(this)->map()->instance_type() >= FIRST_JS_OBJECT_TYPE;
685 686 687
}


688
bool Object::IsJSProxy() const {
689
  if (!Object::IsHeapObject()) return false;
690
  return  HeapObject::cast(this)->map()->IsJSProxyMap();
691 692 693
}


694 695 696
TYPE_CHECKER(JSFunctionProxy, JS_FUNCTION_PROXY_TYPE)
TYPE_CHECKER(JSSet, JS_SET_TYPE)
TYPE_CHECKER(JSMap, JS_MAP_TYPE)
697 698
TYPE_CHECKER(JSSetIterator, JS_SET_ITERATOR_TYPE)
TYPE_CHECKER(JSMapIterator, JS_MAP_ITERATOR_TYPE)
699
TYPE_CHECKER(JSWeakMap, JS_WEAK_MAP_TYPE)
700
TYPE_CHECKER(JSWeakSet, JS_WEAK_SET_TYPE)
701 702 703 704
TYPE_CHECKER(JSContextExtensionObject, JS_CONTEXT_EXTENSION_OBJECT_TYPE)
TYPE_CHECKER(Map, MAP_TYPE)
TYPE_CHECKER(FixedArray, FIXED_ARRAY_TYPE)
TYPE_CHECKER(FixedDoubleArray, FIXED_DOUBLE_ARRAY_TYPE)
705
TYPE_CHECKER(ConstantPoolArray, CONSTANT_POOL_ARRAY_TYPE)
706 707


708
bool Object::IsJSWeakCollection() const {
709 710 711 712
  return IsJSWeakMap() || IsJSWeakSet();
}


713
bool Object::IsDescriptorArray() const {
714 715 716 717
  return IsFixedArray();
}


718
bool Object::IsTransitionArray() const {
719 720 721 722
  return IsFixedArray();
}


723
bool Object::IsDeoptimizationInputData() const {
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
  // Must be a fixed array.
  if (!IsFixedArray()) return false;

  // There's no sure way to detect the difference between a fixed array and
  // a deoptimization data array.  Since this is used for asserts we can
  // check that the length is zero or else the fixed size plus a multiple of
  // the entry size.
  int length = FixedArray::cast(this)->length();
  if (length == 0) return true;

  length -= DeoptimizationInputData::kFirstDeoptEntryIndex;
  return length >= 0 &&
      length % DeoptimizationInputData::kDeoptEntrySize == 0;
}


740
bool Object::IsDeoptimizationOutputData() const {
741 742 743 744 745 746 747 748 749
  if (!IsFixedArray()) return false;
  // There's actually no way to see the difference between a fixed array and
  // a deoptimization data array.  Since this is used for asserts we can check
  // that the length is plausible though.
  if (FixedArray::cast(this)->length() % 2 != 0) return false;
  return true;
}


750
bool Object::IsDependentCode() const {
751 752 753 754 755 756 757
  if (!IsFixedArray()) return false;
  // There's actually no way to see the difference between a fixed array and
  // a dependent codes array.
  return true;
}


758
bool Object::IsContext() const {
759 760 761 762 763 764 765 766 767 768
  if (!Object::IsHeapObject()) return false;
  Map* map = HeapObject::cast(this)->map();
  Heap* heap = map->GetHeap();
  return (map == heap->function_context_map() ||
      map == heap->catch_context_map() ||
      map == heap->with_context_map() ||
      map == heap->native_context_map() ||
      map == heap->block_context_map() ||
      map == heap->module_context_map() ||
      map == heap->global_context_map());
769 770 771
}


772
bool Object::IsNativeContext() const {
773 774
  return Object::IsHeapObject() &&
      HeapObject::cast(this)->map() ==
775
      HeapObject::cast(this)->GetHeap()->native_context_map();
776 777 778
}


779
bool Object::IsScopeInfo() const {
780 781
  return Object::IsHeapObject() &&
      HeapObject::cast(this)->map() ==
782
      HeapObject::cast(this)->GetHeap()->scope_info_map();
783 784 785
}


786
TYPE_CHECKER(JSFunction, JS_FUNCTION_TYPE)
787 788


789
template <> inline bool Is<JSFunction>(Object* obj) {
790 791 792 793
  return obj->IsJSFunction();
}


794 795
TYPE_CHECKER(Code, CODE_TYPE)
TYPE_CHECKER(Oddball, ODDBALL_TYPE)
796
TYPE_CHECKER(Cell, CELL_TYPE)
797
TYPE_CHECKER(PropertyCell, PROPERTY_CELL_TYPE)
798
TYPE_CHECKER(SharedFunctionInfo, SHARED_FUNCTION_INFO_TYPE)
799
TYPE_CHECKER(JSGeneratorObject, JS_GENERATOR_OBJECT_TYPE)
800
TYPE_CHECKER(JSModule, JS_MODULE_TYPE)
801
TYPE_CHECKER(JSValue, JS_VALUE_TYPE)
802
TYPE_CHECKER(JSDate, JS_DATE_TYPE)
803
TYPE_CHECKER(JSMessageObject, JS_MESSAGE_OBJECT_TYPE)
804 805


806
bool Object::IsStringWrapper() const {
807 808 809 810
  return IsJSValue() && JSValue::cast(this)->value()->IsString();
}


811
TYPE_CHECKER(Foreign, FOREIGN_TYPE)
812 813


814
bool Object::IsBoolean() const {
815 816
  return IsOddball() &&
      ((Oddball::cast(this)->kind() & Oddball::kNotBooleanMask) == 0);
817 818 819
}


820
TYPE_CHECKER(JSArray, JS_ARRAY_TYPE)
821
TYPE_CHECKER(JSArrayBuffer, JS_ARRAY_BUFFER_TYPE)
822
TYPE_CHECKER(JSTypedArray, JS_TYPED_ARRAY_TYPE)
823 824 825
TYPE_CHECKER(JSDataView, JS_DATA_VIEW_TYPE)


826
bool Object::IsJSArrayBufferView() const {
827 828 829 830
  return IsJSDataView() || IsJSTypedArray();
}


831
TYPE_CHECKER(JSRegExp, JS_REGEXP_TYPE)
832 833


834
template <> inline bool Is<JSArray>(Object* obj) {
835 836 837 838
  return obj->IsJSArray();
}


839
bool Object::IsHashTable() const {
840 841 842
  return Object::IsHeapObject() &&
      HeapObject::cast(this)->map() ==
      HeapObject::cast(this)->GetHeap()->hash_table_map();
843 844 845
}


846
bool Object::IsWeakHashTable() const {
847 848 849 850
  return IsHashTable();
}


851
bool Object::IsDictionary() const {
852
  return IsHashTable() &&
853
      this != HeapObject::cast(this)->GetHeap()->string_table();
854 855 856
}


857
bool Object::IsNameDictionary() const {
858 859 860 861
  return IsDictionary();
}


862
bool Object::IsSeededNumberDictionary() const {
863 864 865 866
  return IsDictionary();
}


867
bool Object::IsUnseededNumberDictionary() const {
868 869 870 871
  return IsDictionary();
}


872
bool Object::IsStringTable() const {
873
  return IsHashTable();
874 875 876
}


877
bool Object::IsJSFunctionResultCache() const {
878
  if (!IsFixedArray()) return false;
879
  const FixedArray* self = FixedArray::cast(this);
880 881 882 883 884 885
  int length = self->length();
  if (length < JSFunctionResultCache::kEntriesIndex) return false;
  if ((length - JSFunctionResultCache::kEntriesIndex)
      % JSFunctionResultCache::kEntrySize != 0) {
    return false;
  }
886
#ifdef VERIFY_HEAP
887
  if (FLAG_verify_heap) {
888 889 890 891
    // TODO(svenpanne) We use const_cast here and below to break our dependency
    // cycle between the predicates and the verifiers. This can be removed when
    // the verifiers are const-correct, too.
    reinterpret_cast<JSFunctionResultCache*>(const_cast<Object*>(this))->
892 893
        JSFunctionResultCacheVerify();
  }
894 895 896 897 898
#endif
  return true;
}


899
bool Object::IsNormalizedMapCache() const {
900 901 902 903 904 905 906 907 908
  return NormalizedMapCache::IsNormalizedMapCache(this);
}


int NormalizedMapCache::GetIndex(Handle<Map> map) {
  return map->Hash() % NormalizedMapCache::kEntries;
}


909
bool NormalizedMapCache::IsNormalizedMapCache(const Object* obj) {
910 911
  if (!obj->IsFixedArray()) return false;
  if (FixedArray::cast(obj)->length() != NormalizedMapCache::kEntries) {
912 913
    return false;
  }
914
#ifdef VERIFY_HEAP
915
  if (FLAG_verify_heap) {
916 917
    reinterpret_cast<NormalizedMapCache*>(const_cast<Object*>(obj))->
        NormalizedMapCacheVerify();
918
  }
919 920 921 922 923
#endif
  return true;
}


924
bool Object::IsCompilationCacheTable() const {
925
  return IsHashTable();
926 927 928
}


929
bool Object::IsCodeCacheHashTable() const {
930 931 932 933
  return IsHashTable();
}


934
bool Object::IsPolymorphicCodeCacheHashTable() const {
935 936 937 938
  return IsHashTable();
}


939
bool Object::IsMapCache() const {
940 941 942 943
  return IsHashTable();
}


944
bool Object::IsObjectHashTable() const {
945 946 947 948
  return IsHashTable();
}


949
bool Object::IsOrderedHashTable() const {
950 951 952 953 954 955
  return IsHeapObject() &&
      HeapObject::cast(this)->map() ==
      HeapObject::cast(this)->GetHeap()->ordered_hash_table_map();
}


956
bool Object::IsOrderedHashSet() const {
957 958 959 960
  return IsOrderedHashTable();
}


961
bool Object::IsOrderedHashMap() const {
962 963 964 965
  return IsOrderedHashTable();
}


966
bool Object::IsPrimitive() const {
967 968 969 970
  return IsOddball() || IsNumber() || IsString();
}


971
bool Object::IsJSGlobalProxy() const {
972 973 974
  bool result = IsHeapObject() &&
                (HeapObject::cast(this)->map()->instance_type() ==
                 JS_GLOBAL_PROXY_TYPE);
975 976
  ASSERT(!result ||
         HeapObject::cast(this)->map()->is_access_check_needed());
977 978 979 980
  return result;
}


981
bool Object::IsGlobalObject() const {
982 983
  if (!IsHeapObject()) return false;

984
  InstanceType type = HeapObject::cast(this)->map()->instance_type();
985 986
  return type == JS_GLOBAL_OBJECT_TYPE ||
         type == JS_BUILTINS_OBJECT_TYPE;
987 988 989
}


990 991
TYPE_CHECKER(JSGlobalObject, JS_GLOBAL_OBJECT_TYPE)
TYPE_CHECKER(JSBuiltinsObject, JS_BUILTINS_OBJECT_TYPE)
992 993


994
bool Object::IsUndetectableObject() const {
995 996 997 998 999
  return IsHeapObject()
    && HeapObject::cast(this)->map()->is_undetectable();
}


1000
bool Object::IsAccessCheckNeeded() const {
1001 1002
  if (!IsHeapObject()) return false;
  if (IsJSGlobalProxy()) {
1003 1004
    const JSGlobalProxy* proxy = JSGlobalProxy::cast(this);
    GlobalObject* global = proxy->GetIsolate()->context()->global_object();
1005 1006 1007
    return proxy->IsDetachedFrom(global);
  }
  return HeapObject::cast(this)->map()->is_access_check_needed();
1008 1009 1010
}


1011
bool Object::IsStruct() const {
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
  if (!IsHeapObject()) return false;
  switch (HeapObject::cast(this)->map()->instance_type()) {
#define MAKE_STRUCT_CASE(NAME, Name, name) case NAME##_TYPE: return true;
  STRUCT_LIST(MAKE_STRUCT_CASE)
#undef MAKE_STRUCT_CASE
    default: return false;
  }
}


1022 1023 1024
#define MAKE_STRUCT_PREDICATE(NAME, Name, name)                         \
  bool Object::Is##Name() const {                                       \
    return Object::IsHeapObject()                                       \
1025 1026 1027 1028 1029 1030
      && HeapObject::cast(this)->map()->instance_type() == NAME##_TYPE; \
  }
  STRUCT_LIST(MAKE_STRUCT_PREDICATE)
#undef MAKE_STRUCT_PREDICATE


1031
bool Object::IsUndefined() const {
1032
  return IsOddball() && Oddball::cast(this)->kind() == Oddball::kUndefined;
1033 1034 1035
}


1036
bool Object::IsNull() const {
1037 1038 1039 1040
  return IsOddball() && Oddball::cast(this)->kind() == Oddball::kNull;
}


1041
bool Object::IsTheHole() const {
1042
  return IsOddball() && Oddball::cast(this)->kind() == Oddball::kTheHole;
1043 1044 1045
}


1046
bool Object::IsException() const {
1047 1048 1049 1050
  return IsOddball() && Oddball::cast(this)->kind() == Oddball::kException;
}


1051
bool Object::IsUninitialized() const {
1052 1053 1054 1055
  return IsOddball() && Oddball::cast(this)->kind() == Oddball::kUninitialized;
}


1056
bool Object::IsTrue() const {
1057
  return IsOddball() && Oddball::cast(this)->kind() == Oddball::kTrue;
1058 1059 1060
}


1061
bool Object::IsFalse() const {
1062
  return IsOddball() && Oddball::cast(this)->kind() == Oddball::kFalse;
1063 1064 1065
}


1066
bool Object::IsArgumentsMarker() const {
1067
  return IsOddball() && Oddball::cast(this)->kind() == Oddball::kArgumentMarker;
1068 1069 1070
}


1071 1072 1073 1074 1075 1076 1077 1078
double Object::Number() {
  ASSERT(IsNumber());
  return IsSmi()
    ? static_cast<double>(reinterpret_cast<Smi*>(this)->value())
    : reinterpret_cast<HeapNumber*>(this)->value();
}


1079
bool Object::IsNaN() const {
1080
  return this->IsHeapNumber() && std::isnan(HeapNumber::cast(this)->value());
1081 1082 1083
}


1084 1085
MaybeHandle<Smi> Object::ToSmi(Isolate* isolate, Handle<Object> object) {
  if (object->IsSmi()) return Handle<Smi>::cast(object);
1086 1087 1088 1089 1090 1091 1092
  if (object->IsHeapNumber()) {
    double value = Handle<HeapNumber>::cast(object)->value();
    int int_value = FastD2I(value);
    if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
      return handle(Smi::FromInt(int_value), isolate);
    }
  }
1093
  return Handle<Smi>();
1094 1095 1096
}


1097 1098 1099 1100 1101 1102 1103
MaybeHandle<JSReceiver> Object::ToObject(Isolate* isolate,
                                         Handle<Object> object) {
  return ToObject(
      isolate, object, handle(isolate->context()->native_context(), isolate));
}


1104 1105 1106 1107 1108
bool Object::HasSpecificClassOf(String* name) {
  return this->IsJSObject() && (JSObject::cast(this)->class_name() == name);
}


1109 1110
MaybeHandle<Object> Object::GetProperty(Handle<Object> object,
                                        Handle<Name> name) {
1111 1112
  LookupIterator it(object, name);
  return GetProperty(&it);
1113 1114 1115
}


1116 1117 1118
MaybeHandle<Object> Object::GetElement(Isolate* isolate,
                                       Handle<Object> object,
                                       uint32_t index) {
1119 1120 1121
  // GetElement can trigger a getter which can cause allocation.
  // This was not always the case. This ASSERT is here to catch
  // leftover incorrect uses.
1122
  ASSERT(AllowHeapAllocation::IsAllowed());
1123
  return Object::GetElementWithReceiver(isolate, object, object, index);
1124 1125 1126
}


1127 1128 1129 1130 1131 1132 1133 1134 1135
MaybeHandle<Object> Object::GetPropertyOrElement(Handle<Object> object,
                                                 Handle<Name> name) {
  uint32_t index;
  Isolate* isolate = name->GetIsolate();
  if (name->AsArrayIndex(&index)) return GetElement(isolate, object, index);
  return GetProperty(object, name);
}


1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
MaybeHandle<Object> Object::GetProperty(Isolate* isolate,
                                        Handle<Object> object,
                                        const char* name) {
  Handle<String> str = isolate->factory()->InternalizeUtf8String(name);
  ASSERT(!str.is_null());
#ifdef DEBUG
  uint32_t index;  // Assert that the name is not an array index.
  ASSERT(!str->AsArrayIndex(&index));
#endif  // DEBUG
  return GetProperty(object, str);
}


1149 1150
MaybeHandle<Object> JSProxy::GetElementWithHandler(Handle<JSProxy> proxy,
                                                   Handle<Object> receiver,
1151
                                                   uint32_t index) {
1152 1153
  return GetPropertyWithHandler(
      proxy, receiver, proxy->GetIsolate()->factory()->Uint32ToString(index));
1154 1155 1156
}


1157 1158 1159 1160 1161 1162 1163
MaybeHandle<Object> JSProxy::SetElementWithHandler(Handle<JSProxy> proxy,
                                                   Handle<JSReceiver> receiver,
                                                   uint32_t index,
                                                   Handle<Object> value,
                                                   StrictMode strict_mode) {
  Isolate* isolate = proxy->GetIsolate();
  Handle<String> name = isolate->factory()->Uint32ToString(index);
1164
  return SetPropertyWithHandler(proxy, receiver, name, value, strict_mode);
1165 1166 1167 1168 1169 1170 1171
}


bool JSProxy::HasElementWithHandler(Handle<JSProxy> proxy, uint32_t index) {
  Isolate* isolate = proxy->GetIsolate();
  Handle<String> name = isolate->factory()->Uint32ToString(index);
  return HasPropertyWithHandler(proxy, name);
1172 1173 1174 1175 1176 1177
}


#define FIELD_ADDR(p, offset) \
  (reinterpret_cast<byte*>(p) + offset - kHeapObjectTag)

1178 1179 1180
#define FIELD_ADDR_CONST(p, offset) \
  (reinterpret_cast<const byte*>(p) + offset - kHeapObjectTag)

1181
#define READ_FIELD(p, offset) \
1182
  (*reinterpret_cast<Object* const*>(FIELD_ADDR_CONST(p, offset)))
1183

1184 1185
#define ACQUIRE_READ_FIELD(p, offset)           \
  reinterpret_cast<Object*>(base::Acquire_Load( \
1186
      reinterpret_cast<const base::AtomicWord*>(FIELD_ADDR_CONST(p, offset))))
1187

1188 1189
#define NOBARRIER_READ_FIELD(p, offset)           \
  reinterpret_cast<Object*>(base::NoBarrier_Load( \
1190
      reinterpret_cast<const base::AtomicWord*>(FIELD_ADDR_CONST(p, offset))))
1191

1192 1193 1194
#define WRITE_FIELD(p, offset, value) \
  (*reinterpret_cast<Object**>(FIELD_ADDR(p, offset)) = value)

1195 1196 1197 1198
#define RELEASE_WRITE_FIELD(p, offset, value)                     \
  base::Release_Store(                                            \
      reinterpret_cast<base::AtomicWord*>(FIELD_ADDR(p, offset)), \
      reinterpret_cast<base::AtomicWord>(value));
1199

1200 1201 1202 1203
#define NOBARRIER_WRITE_FIELD(p, offset, value)                   \
  base::NoBarrier_Store(                                          \
      reinterpret_cast<base::AtomicWord*>(FIELD_ADDR(p, offset)), \
      reinterpret_cast<base::AtomicWord>(value));
1204

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
#define WRITE_BARRIER(heap, object, offset, value)                      \
  heap->incremental_marking()->RecordWrite(                             \
      object, HeapObject::RawField(object, offset), value);             \
  if (heap->InNewSpace(value)) {                                        \
    heap->RecordWrite(object->address(), offset);                       \
  }

#define CONDITIONAL_WRITE_BARRIER(heap, object, offset, value, mode)    \
  if (mode == UPDATE_WRITE_BARRIER) {                                   \
    heap->incremental_marking()->RecordWrite(                           \
      object, HeapObject::RawField(object, offset), value);             \
    if (heap->InNewSpace(value)) {                                      \
      heap->RecordWrite(object->address(), offset);                     \
    }                                                                   \
1219 1220
  }

1221 1222
#ifndef V8_TARGET_ARCH_MIPS
  #define READ_DOUBLE_FIELD(p, offset) \
1223
    (*reinterpret_cast<const double*>(FIELD_ADDR_CONST(p, offset)))
1224 1225 1226
#else  // V8_TARGET_ARCH_MIPS
  // Prevent gcc from using load-double (mips ldc1) on (possibly)
  // non-64-bit aligned HeapNumber::value.
1227
  static inline double read_double_field(const void* p, int offset) {
1228 1229 1230 1231
    union conversion {
      double d;
      uint32_t u[2];
    } c;
1232 1233 1234 1235
    c.u[0] = (*reinterpret_cast<const uint32_t*>(
        FIELD_ADDR_CONST(p, offset)));
    c.u[1] = (*reinterpret_cast<const uint32_t*>(
        FIELD_ADDR_CONST(p, offset + 4)));
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    return c.d;
  }
  #define READ_DOUBLE_FIELD(p, offset) read_double_field(p, offset)
#endif  // V8_TARGET_ARCH_MIPS

#ifndef V8_TARGET_ARCH_MIPS
  #define WRITE_DOUBLE_FIELD(p, offset, value) \
    (*reinterpret_cast<double*>(FIELD_ADDR(p, offset)) = value)
#else  // V8_TARGET_ARCH_MIPS
  // Prevent gcc from using store-double (mips sdc1) on (possibly)
  // non-64-bit aligned HeapNumber::value.
1247
  static inline void write_double_field(void* p, int offset,
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
                                        double value) {
    union conversion {
      double d;
      uint32_t u[2];
    } c;
    c.d = value;
    (*reinterpret_cast<uint32_t*>(FIELD_ADDR(p, offset))) = c.u[0];
    (*reinterpret_cast<uint32_t*>(FIELD_ADDR(p, offset + 4))) = c.u[1];
  }
  #define WRITE_DOUBLE_FIELD(p, offset, value) \
    write_double_field(p, offset, value)
#endif  // V8_TARGET_ARCH_MIPS
1260 1261 1262


#define READ_INT_FIELD(p, offset) \
1263
  (*reinterpret_cast<const int*>(FIELD_ADDR_CONST(p, offset)))
1264 1265 1266 1267

#define WRITE_INT_FIELD(p, offset, value) \
  (*reinterpret_cast<int*>(FIELD_ADDR(p, offset)) = value)

1268
#define READ_INTPTR_FIELD(p, offset) \
1269
  (*reinterpret_cast<const intptr_t*>(FIELD_ADDR_CONST(p, offset)))
1270 1271 1272 1273

#define WRITE_INTPTR_FIELD(p, offset, value) \
  (*reinterpret_cast<intptr_t*>(FIELD_ADDR(p, offset)) = value)

1274
#define READ_UINT32_FIELD(p, offset) \
1275
  (*reinterpret_cast<const uint32_t*>(FIELD_ADDR_CONST(p, offset)))
1276 1277 1278 1279

#define WRITE_UINT32_FIELD(p, offset, value) \
  (*reinterpret_cast<uint32_t*>(FIELD_ADDR(p, offset)) = value)

1280
#define READ_INT32_FIELD(p, offset) \
1281
  (*reinterpret_cast<const int32_t*>(FIELD_ADDR_CONST(p, offset)))
1282 1283 1284 1285

#define WRITE_INT32_FIELD(p, offset, value) \
  (*reinterpret_cast<int32_t*>(FIELD_ADDR(p, offset)) = value)

1286
#define READ_INT64_FIELD(p, offset) \
1287
  (*reinterpret_cast<const int64_t*>(FIELD_ADDR_CONST(p, offset)))
1288 1289 1290 1291

#define WRITE_INT64_FIELD(p, offset, value) \
  (*reinterpret_cast<int64_t*>(FIELD_ADDR(p, offset)) = value)

1292
#define READ_SHORT_FIELD(p, offset) \
1293
  (*reinterpret_cast<const uint16_t*>(FIELD_ADDR_CONST(p, offset)))
1294 1295 1296 1297 1298

#define WRITE_SHORT_FIELD(p, offset, value) \
  (*reinterpret_cast<uint16_t*>(FIELD_ADDR(p, offset)) = value)

#define READ_BYTE_FIELD(p, offset) \
1299
  (*reinterpret_cast<const byte*>(FIELD_ADDR_CONST(p, offset)))
1300

1301 1302 1303
#define NOBARRIER_READ_BYTE_FIELD(p, offset) \
  static_cast<byte>(base::NoBarrier_Load(    \
      reinterpret_cast<base::Atomic8*>(FIELD_ADDR(p, offset))))
1304

1305 1306 1307
#define WRITE_BYTE_FIELD(p, offset, value) \
  (*reinterpret_cast<byte*>(FIELD_ADDR(p, offset)) = value)

1308 1309 1310 1311
#define NOBARRIER_WRITE_BYTE_FIELD(p, offset, value)           \
  base::NoBarrier_Store(                                       \
      reinterpret_cast<base::Atomic8*>(FIELD_ADDR(p, offset)), \
      static_cast<base::Atomic8>(value));
1312

1313
Object** HeapObject::RawField(HeapObject* obj, int byte_offset) {
1314
  return reinterpret_cast<Object**>(FIELD_ADDR(obj, byte_offset));
1315 1316 1317
}


1318
int Smi::value() const {
1319
  return Internals::SmiValue(this);
1320 1321 1322 1323
}


Smi* Smi::FromInt(int value) {
1324
  ASSERT(Smi::IsValid(value));
1325
  return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1326 1327 1328 1329
}


Smi* Smi::FromIntptr(intptr_t value) {
1330
  ASSERT(Smi::IsValid(value));
1331 1332
  int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
  return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1333 1334 1335
}


1336
bool Smi::IsValid(intptr_t value) {
1337 1338
  bool result = Internals::IsValidSmi(value);
  ASSERT_EQ(result, value >= kMinValue && value <= kMaxValue);
1339
  return result;
1340 1341 1342
}


1343
MapWord MapWord::FromMap(const Map* map) {
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
  return MapWord(reinterpret_cast<uintptr_t>(map));
}


Map* MapWord::ToMap() {
  return reinterpret_cast<Map*>(value_);
}


bool MapWord::IsForwardingAddress() {
1354
  return HAS_SMI_TAG(reinterpret_cast<Object*>(value_));
1355 1356 1357 1358
}


MapWord MapWord::FromForwardingAddress(HeapObject* object) {
1359 1360
  Address raw = reinterpret_cast<Address>(object) - kHeapObjectTag;
  return MapWord(reinterpret_cast<uintptr_t>(raw));
1361 1362 1363 1364 1365
}


HeapObject* MapWord::ToForwardingAddress() {
  ASSERT(IsForwardingAddress());
1366
  return HeapObject::FromAddress(reinterpret_cast<Address>(value_));
1367 1368 1369
}


1370
#ifdef VERIFY_HEAP
1371 1372 1373
void HeapObject::VerifyObjectField(int offset) {
  VerifyPointer(READ_FIELD(this, offset));
}
1374 1375

void HeapObject::VerifySmiField(int offset) {
1376
  CHECK(READ_FIELD(this, offset)->IsSmi());
1377
}
1378 1379 1380
#endif


1381
Heap* HeapObject::GetHeap() const {
1382
  Heap* heap =
1383
      MemoryChunk::FromAddress(reinterpret_cast<const byte*>(this))->heap();
1384
  SLOW_ASSERT(heap != NULL);
1385
  return heap;
1386 1387 1388
}


1389
Isolate* HeapObject::GetIsolate() const {
1390
  return GetHeap()->isolate();
1391 1392 1393
}


1394
Map* HeapObject::map() const {
ishell@chromium.org's avatar
ishell@chromium.org committed
1395 1396 1397 1398 1399 1400
#ifdef DEBUG
  // Clear mark potentially added by PathTracer.
  uintptr_t raw_value =
      map_word().ToRawValue() & ~static_cast<uintptr_t>(PathTracer::kMarkTag);
  return MapWord::FromRawValue(raw_value).ToMap();
#else
1401
  return map_word().ToMap();
ishell@chromium.org's avatar
ishell@chromium.org committed
1402
#endif
1403 1404 1405 1406
}


void HeapObject::set_map(Map* value) {
1407
  set_map_word(MapWord::FromMap(value));
1408 1409 1410 1411 1412
  if (value != NULL) {
    // TODO(1600) We are passing NULL as a slot because maps can never be on
    // evacuation candidate.
    value->GetHeap()->incremental_marking()->RecordWrite(this, NULL, value);
  }
1413 1414 1415
}


1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
Map* HeapObject::synchronized_map() {
  return synchronized_map_word().ToMap();
}


void HeapObject::synchronized_set_map(Map* value) {
  synchronized_set_map_word(MapWord::FromMap(value));
  if (value != NULL) {
    // TODO(1600) We are passing NULL as a slot because maps can never be on
    // evacuation candidate.
    value->GetHeap()->incremental_marking()->RecordWrite(this, NULL, value);
  }
}


1431 1432 1433 1434 1435
void HeapObject::synchronized_set_map_no_write_barrier(Map* value) {
  synchronized_set_map_word(MapWord::FromMap(value));
}


1436
// Unsafe accessor omitting write barrier.
1437
void HeapObject::set_map_no_write_barrier(Map* value) {
1438 1439 1440 1441
  set_map_word(MapWord::FromMap(value));
}


1442
MapWord HeapObject::map_word() const {
1443
  return MapWord(
1444
      reinterpret_cast<uintptr_t>(NOBARRIER_READ_FIELD(this, kMapOffset)));
1445 1446 1447
}


1448
void HeapObject::set_map_word(MapWord map_word) {
1449
  NOBARRIER_WRITE_FIELD(
1450 1451 1452 1453
      this, kMapOffset, reinterpret_cast<Object*>(map_word.value_));
}


1454
MapWord HeapObject::synchronized_map_word() const {
1455 1456 1457 1458 1459 1460 1461 1462
  return MapWord(
      reinterpret_cast<uintptr_t>(ACQUIRE_READ_FIELD(this, kMapOffset)));
}


void HeapObject::synchronized_set_map_word(MapWord map_word) {
  RELEASE_WRITE_FIELD(
      this, kMapOffset, reinterpret_cast<Object*>(map_word.value_));
1463
}
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492


HeapObject* HeapObject::FromAddress(Address address) {
  ASSERT_TAG_ALIGNED(address);
  return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
}


Address HeapObject::address() {
  return reinterpret_cast<Address>(this) - kHeapObjectTag;
}


int HeapObject::Size() {
  return SizeFromMap(map());
}


void HeapObject::IteratePointers(ObjectVisitor* v, int start, int end) {
  v->VisitPointers(reinterpret_cast<Object**>(FIELD_ADDR(this, start)),
                   reinterpret_cast<Object**>(FIELD_ADDR(this, end)));
}


void HeapObject::IteratePointer(ObjectVisitor* v, int offset) {
  v->VisitPointer(reinterpret_cast<Object**>(FIELD_ADDR(this, offset)));
}


1493 1494 1495 1496 1497
void HeapObject::IterateNextCodeLink(ObjectVisitor* v, int offset) {
  v->VisitNextCodeLink(reinterpret_cast<Object**>(FIELD_ADDR(this, offset)));
}


1498
double HeapNumber::value() const {
1499 1500 1501 1502 1503 1504 1505 1506 1507
  return READ_DOUBLE_FIELD(this, kValueOffset);
}


void HeapNumber::set_value(double value) {
  WRITE_DOUBLE_FIELD(this, kValueOffset, value);
}


1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
int HeapNumber::get_exponent() {
  return ((READ_INT_FIELD(this, kExponentOffset) & kExponentMask) >>
          kExponentShift) - kExponentBias;
}


int HeapNumber::get_sign() {
  return READ_INT_FIELD(this, kExponentOffset) & kSignMask;
}


1519
ACCESSORS(JSObject, properties, FixedArray, kPropertiesOffset)
1520 1521


1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
Object** FixedArray::GetFirstElementAddress() {
  return reinterpret_cast<Object**>(FIELD_ADDR(this, OffsetOfElementAt(0)));
}


bool FixedArray::ContainsOnlySmisOrHoles() {
  Object* the_hole = GetHeap()->the_hole_value();
  Object** current = GetFirstElementAddress();
  for (int i = 0; i < length(); ++i) {
    Object* candidate = *current++;
    if (!candidate->IsSmi() && candidate != the_hole) return false;
  }
  return true;
}


1538
FixedArrayBase* JSObject::elements() const {
1539
  Object* array = READ_FIELD(this, kElementsOffset);
1540
  return static_cast<FixedArrayBase*>(array);
1541 1542
}

1543

1544
void JSObject::ValidateElements(Handle<JSObject> object) {
1545
#ifdef ENABLE_SLOW_ASSERTS
1546
  if (FLAG_enable_slow_asserts) {
1547 1548
    ElementsAccessor* accessor = object->GetElementsAccessor();
    accessor->Validate(object);
1549 1550 1551 1552 1553
  }
#endif
}


1554
void AllocationSite::Initialize() {
1555
  set_transition_info(Smi::FromInt(0));
1556
  SetElementsKind(GetInitialFastElementsKind());
1557
  set_nested_site(Smi::FromInt(0));
1558 1559
  set_pretenure_data(Smi::FromInt(0));
  set_pretenure_create_count(Smi::FromInt(0));
1560 1561 1562 1563 1564
  set_dependent_code(DependentCode::cast(GetHeap()->empty_fixed_array()),
                     SKIP_WRITE_BARRIER);
}


1565 1566
void AllocationSite::MarkZombie() {
  ASSERT(!IsZombie());
1567
  Initialize();
1568
  set_pretenure_decision(kZombie);
1569 1570 1571
}


1572 1573
// Heuristic: We only need to create allocation site info if the boilerplate
// elements kind is the initial elements kind.
1574
AllocationSiteMode AllocationSite::GetMode(
1575
    ElementsKind boilerplate_elements_kind) {
1576 1577
  if (FLAG_pretenuring_call_new ||
      IsFastSmiElementsKind(boilerplate_elements_kind)) {
1578 1579 1580 1581 1582 1583 1584
    return TRACK_ALLOCATION_SITE;
  }

  return DONT_TRACK_ALLOCATION_SITE;
}


1585 1586
AllocationSiteMode AllocationSite::GetMode(ElementsKind from,
                                           ElementsKind to) {
1587 1588 1589
  if (FLAG_pretenuring_call_new ||
      (IsFastSmiElementsKind(from) &&
       IsMoreGeneralElementsKindTransition(from, to))) {
1590 1591 1592 1593 1594 1595 1596
    return TRACK_ALLOCATION_SITE;
  }

  return DONT_TRACK_ALLOCATION_SITE;
}


1597
inline bool AllocationSite::CanTrack(InstanceType type) {
1598
  if (FLAG_allocation_site_pretenuring) {
1599 1600 1601
    return type == JS_ARRAY_TYPE ||
        type == JS_OBJECT_TYPE ||
        type < FIRST_NONSTRING_TYPE;
1602
  }
1603 1604 1605 1606
  return type == JS_ARRAY_TYPE;
}


1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
inline DependentCode::DependencyGroup AllocationSite::ToDependencyGroup(
    Reason reason) {
  switch (reason) {
    case TENURING:
      return DependentCode::kAllocationSiteTenuringChangedGroup;
      break;
    case TRANSITIONS:
      return DependentCode::kAllocationSiteTransitionChangedGroup;
      break;
  }
  UNREACHABLE();
  return DependentCode::kAllocationSiteTransitionChangedGroup;
}


1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
inline void AllocationSite::set_memento_found_count(int count) {
  int value = pretenure_data()->value();
  // Verify that we can count more mementos than we can possibly find in one
  // new space collection.
  ASSERT((GetHeap()->MaxSemiSpaceSize() /
          (StaticVisitorBase::kMinObjectSizeInWords * kPointerSize +
           AllocationMemento::kSize)) < MementoFoundCountBits::kMax);
  ASSERT(count < MementoFoundCountBits::kMax);
  set_pretenure_data(
      Smi::FromInt(MementoFoundCountBits::update(value, count)),
      SKIP_WRITE_BARRIER);
}

1635 1636 1637
inline bool AllocationSite::IncrementMementoFoundCount() {
  if (IsZombie()) return false;

1638 1639
  int value = memento_found_count();
  set_memento_found_count(value + 1);
1640
  return memento_found_count() == kPretenureMinimumCreated;
1641 1642 1643 1644 1645
}


inline void AllocationSite::IncrementMementoCreateCount() {
  ASSERT(FLAG_allocation_site_pretenuring);
1646 1647
  int value = memento_create_count();
  set_memento_create_count(value + 1);
1648 1649 1650
}


1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
inline bool AllocationSite::MakePretenureDecision(
    PretenureDecision current_decision,
    double ratio,
    bool maximum_size_scavenge) {
  // Here we just allow state transitions from undecided or maybe tenure
  // to don't tenure, maybe tenure, or tenure.
  if ((current_decision == kUndecided || current_decision == kMaybeTenure)) {
    if (ratio >= kPretenureRatio) {
      // We just transition into tenure state when the semi-space was at
      // maximum capacity.
      if (maximum_size_scavenge) {
        set_deopt_dependent_code(true);
        set_pretenure_decision(kTenure);
        // Currently we just need to deopt when we make a state transition to
        // tenure.
        return true;
      }
      set_pretenure_decision(kMaybeTenure);
    } else {
      set_pretenure_decision(kDontTenure);
    }
  }
  return false;
}


inline bool AllocationSite::DigestPretenuringFeedback(
    bool maximum_size_scavenge) {
  bool deopt = false;
1680
  int create_count = memento_create_count();
1681
  int found_count = memento_found_count();
1682 1683 1684 1685
  bool minimum_mementos_created = create_count >= kPretenureMinimumCreated;
  double ratio =
      minimum_mementos_created || FLAG_trace_pretenuring_statistics ?
          static_cast<double>(found_count) / create_count : 0.0;
1686 1687 1688 1689 1690
  PretenureDecision current_decision = pretenure_decision();

  if (minimum_mementos_created) {
    deopt = MakePretenureDecision(
        current_decision, ratio, maximum_size_scavenge);
1691 1692
  }

1693 1694 1695 1696
  if (FLAG_trace_pretenuring_statistics) {
    PrintF(
        "AllocationSite(%p): (created, found, ratio) (%d, %d, %f) %s => %s\n",
         static_cast<void*>(this), create_count, found_count, ratio,
1697 1698
         PretenureDecisionName(current_decision),
         PretenureDecisionName(pretenure_decision()));
1699 1700
  }

1701
  // Clear feedback calculation fields until the next gc.
1702 1703
  set_memento_found_count(0);
  set_memento_create_count(0);
1704
  return deopt;
1705 1706 1707
}


1708
void JSObject::EnsureCanContainHeapObjectElements(Handle<JSObject> object) {
1709
  JSObject::ValidateElements(object);
1710
  ElementsKind elements_kind = object->map()->elements_kind();
1711 1712
  if (!IsFastObjectElementsKind(elements_kind)) {
    if (IsFastHoleyElementsKind(elements_kind)) {
1713
      TransitionElementsKind(object, FAST_HOLEY_ELEMENTS);
1714
    } else {
1715
      TransitionElementsKind(object, FAST_ELEMENTS);
1716
    }
1717 1718 1719 1720
  }
}


1721 1722 1723 1724 1725
void JSObject::EnsureCanContainElements(Handle<JSObject> object,
                                        Object** objects,
                                        uint32_t count,
                                        EnsureElementsMode mode) {
  ElementsKind current_kind = object->map()->elements_kind();
1726
  ElementsKind target_kind = current_kind;
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
  {
    DisallowHeapAllocation no_allocation;
    ASSERT(mode != ALLOW_COPIED_DOUBLE_ELEMENTS);
    bool is_holey = IsFastHoleyElementsKind(current_kind);
    if (current_kind == FAST_HOLEY_ELEMENTS) return;
    Heap* heap = object->GetHeap();
    Object* the_hole = heap->the_hole_value();
    for (uint32_t i = 0; i < count; ++i) {
      Object* current = *objects++;
      if (current == the_hole) {
        is_holey = true;
        target_kind = GetHoleyElementsKind(target_kind);
      } else if (!current->IsSmi()) {
        if (mode == ALLOW_CONVERTED_DOUBLE_ELEMENTS && current->IsNumber()) {
          if (IsFastSmiElementsKind(target_kind)) {
            if (is_holey) {
              target_kind = FAST_HOLEY_DOUBLE_ELEMENTS;
            } else {
              target_kind = FAST_DOUBLE_ELEMENTS;
            }
1747
          }
1748 1749 1750 1751 1752
        } else if (is_holey) {
          target_kind = FAST_HOLEY_ELEMENTS;
          break;
        } else {
          target_kind = FAST_ELEMENTS;
1753
        }
1754 1755 1756
      }
    }
  }
1757
  if (target_kind != current_kind) {
1758
    TransitionElementsKind(object, target_kind);
1759
  }
1760 1761 1762
}


1763 1764 1765 1766
void JSObject::EnsureCanContainElements(Handle<JSObject> object,
                                        Handle<FixedArrayBase> elements,
                                        uint32_t length,
                                        EnsureElementsMode mode) {
1767 1768 1769 1770
  Heap* heap = object->GetHeap();
  if (elements->map() != heap->fixed_double_array_map()) {
    ASSERT(elements->map() == heap->fixed_array_map() ||
           elements->map() == heap->fixed_cow_array_map());
1771 1772 1773
    if (mode == ALLOW_COPIED_DOUBLE_ELEMENTS) {
      mode = DONT_ALLOW_DOUBLE_ELEMENTS;
    }
1774 1775 1776 1777
    Object** objects =
        Handle<FixedArray>::cast(elements)->GetFirstElementAddress();
    EnsureCanContainElements(object, objects, length, mode);
    return;
1778 1779 1780
  }

  ASSERT(mode == ALLOW_COPIED_DOUBLE_ELEMENTS);
1781 1782 1783 1784 1785
  if (object->GetElementsKind() == FAST_HOLEY_SMI_ELEMENTS) {
    TransitionElementsKind(object, FAST_HOLEY_DOUBLE_ELEMENTS);
  } else if (object->GetElementsKind() == FAST_SMI_ELEMENTS) {
    Handle<FixedDoubleArray> double_array =
        Handle<FixedDoubleArray>::cast(elements);
1786 1787
    for (uint32_t i = 0; i < length; ++i) {
      if (double_array->is_the_hole(i)) {
1788 1789
        TransitionElementsKind(object, FAST_HOLEY_DOUBLE_ELEMENTS);
        return;
1790 1791
      }
    }
1792
    TransitionElementsKind(object, FAST_DOUBLE_ELEMENTS);
1793
  }
1794 1795
}

1796

1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
void JSObject::SetMapAndElements(Handle<JSObject> object,
                                 Handle<Map> new_map,
                                 Handle<FixedArrayBase> value) {
  JSObject::MigrateToMap(object, new_map);
  ASSERT((object->map()->has_fast_smi_or_object_elements() ||
          (*value == object->GetHeap()->empty_fixed_array())) ==
         (value->map() == object->GetHeap()->fixed_array_map() ||
          value->map() == object->GetHeap()->fixed_cow_array_map()));
  ASSERT((*value == object->GetHeap()->empty_fixed_array()) ||
         (object->map()->has_fast_double_elements() ==
          value->IsFixedDoubleArray()));
  object->set_elements(*value);
1809
}
1810 1811


1812
void JSObject::set_elements(FixedArrayBase* value, WriteBarrierMode mode) {
1813 1814
  WRITE_FIELD(this, kElementsOffset, value);
  CONDITIONAL_WRITE_BARRIER(GetHeap(), this, kElementsOffset, value, mode);
1815 1816 1817
}


1818
void JSObject::initialize_properties() {
1819 1820
  ASSERT(!GetHeap()->InNewSpace(GetHeap()->empty_fixed_array()));
  WRITE_FIELD(this, kPropertiesOffset, GetHeap()->empty_fixed_array());
1821 1822 1823 1824
}


void JSObject::initialize_elements() {
1825 1826
  FixedArrayBase* elements = map()->GetInitialElements();
  WRITE_FIELD(this, kElementsOffset, elements);
1827 1828 1829
}


1830
Handle<String> Map::ExpectedTransitionKey(Handle<Map> map) {
1831
  DisallowHeapAllocation no_gc;
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
  if (!map->HasTransitionArray()) return Handle<String>::null();
  TransitionArray* transitions = map->transitions();
  if (!transitions->IsSimpleTransition()) return Handle<String>::null();
  int transition = TransitionArray::kSimpleTransitionIndex;
  PropertyDetails details = transitions->GetTargetDetails(transition);
  Name* name = transitions->GetKey(transition);
  if (details.type() != FIELD) return Handle<String>::null();
  if (details.attributes() != NONE) return Handle<String>::null();
  if (!name->IsString()) return Handle<String>::null();
  return Handle<String>(String::cast(name));
}


1845
Handle<Map> Map::ExpectedTransitionTarget(Handle<Map> map) {
1846 1847 1848 1849 1850 1851
  ASSERT(!ExpectedTransitionKey(map).is_null());
  return Handle<Map>(map->transitions()->GetTarget(
      TransitionArray::kSimpleTransitionIndex));
}


1852
Handle<Map> Map::FindTransitionToField(Handle<Map> map, Handle<Name> key) {
1853
  DisallowHeapAllocation no_allocation;
1854 1855 1856 1857 1858 1859 1860 1861
  if (!map->HasTransitionArray()) return Handle<Map>::null();
  TransitionArray* transitions = map->transitions();
  int transition = transitions->Search(*key);
  if (transition == TransitionArray::kNotFound) return Handle<Map>::null();
  PropertyDetails target_details = transitions->GetTargetDetails(transition);
  if (target_details.type() != FIELD) return Handle<Map>::null();
  if (target_details.attributes() != NONE) return Handle<Map>::null();
  return Handle<Map>(transitions->GetTarget(transition));
1862 1863 1864
}


1865 1866 1867 1868
ACCESSORS(Oddball, to_string, String, kToStringOffset)
ACCESSORS(Oddball, to_number, Object, kToNumberOffset)


1869
byte Oddball::kind() const {
1870
  return Smi::cast(READ_FIELD(this, kKindOffset))->value();
1871 1872 1873 1874
}


void Oddball::set_kind(byte value) {
1875
  WRITE_FIELD(this, kKindOffset, Smi::FromInt(value));
1876 1877 1878
}


1879
Object* Cell::value() const {
1880 1881 1882 1883
  return READ_FIELD(this, kValueOffset);
}


1884
void Cell::set_value(Object* val, WriteBarrierMode ignored) {
1885
  // The write barrier is not used for global property cells.
1886
  ASSERT(!val->IsPropertyCell() && !val->IsCell());
1887 1888 1889
  WRITE_FIELD(this, kValueOffset, val);
}

1890
ACCESSORS(PropertyCell, dependent_code, DependentCode, kDependentCodeOffset)
1891

1892
Object* PropertyCell::type_raw() const {
1893 1894 1895 1896
  return READ_FIELD(this, kTypeOffset);
}


1897
void PropertyCell::set_type_raw(Object* val, WriteBarrierMode ignored) {
1898 1899 1900 1901
  WRITE_FIELD(this, kTypeOffset, val);
}


1902
int JSObject::GetHeaderSize() {
1903 1904 1905 1906 1907 1908
  InstanceType type = map()->instance_type();
  // Check for the most common kind of JavaScript object before
  // falling into the generic switch. This speeds up the internal
  // field operations considerably on average.
  if (type == JS_OBJECT_TYPE) return JSObject::kHeaderSize;
  switch (type) {
1909 1910
    case JS_GENERATOR_OBJECT_TYPE:
      return JSGeneratorObject::kSize;
1911 1912
    case JS_MODULE_TYPE:
      return JSModule::kSize;
1913 1914
    case JS_GLOBAL_PROXY_TYPE:
      return JSGlobalProxy::kSize;
1915 1916 1917 1918 1919 1920 1921 1922
    case JS_GLOBAL_OBJECT_TYPE:
      return JSGlobalObject::kSize;
    case JS_BUILTINS_OBJECT_TYPE:
      return JSBuiltinsObject::kSize;
    case JS_FUNCTION_TYPE:
      return JSFunction::kSize;
    case JS_VALUE_TYPE:
      return JSValue::kSize;
1923 1924
    case JS_DATE_TYPE:
      return JSDate::kSize;
1925
    case JS_ARRAY_TYPE:
1926
      return JSArray::kSize;
1927 1928
    case JS_ARRAY_BUFFER_TYPE:
      return JSArrayBuffer::kSize;
1929 1930
    case JS_TYPED_ARRAY_TYPE:
      return JSTypedArray::kSize;
1931 1932
    case JS_DATA_VIEW_TYPE:
      return JSDataView::kSize;
1933 1934 1935 1936
    case JS_SET_TYPE:
      return JSSet::kSize;
    case JS_MAP_TYPE:
      return JSMap::kSize;
1937 1938 1939 1940
    case JS_SET_ITERATOR_TYPE:
      return JSSetIterator::kSize;
    case JS_MAP_ITERATOR_TYPE:
      return JSMapIterator::kSize;
1941 1942
    case JS_WEAK_MAP_TYPE:
      return JSWeakMap::kSize;
1943 1944
    case JS_WEAK_SET_TYPE:
      return JSWeakSet::kSize;
1945
    case JS_REGEXP_TYPE:
1946
      return JSRegExp::kSize;
ager@chromium.org's avatar
ager@chromium.org committed
1947
    case JS_CONTEXT_EXTENSION_OBJECT_TYPE:
1948
      return JSObject::kHeaderSize;
1949 1950
    case JS_MESSAGE_OBJECT_TYPE:
      return JSMessageObject::kSize;
1951
    default:
1952 1953 1954
      // TODO(jkummerow): Re-enable this. Blink currently hits this
      // from its CustomElementConstructorBuilder.
      // UNREACHABLE();
1955 1956 1957 1958 1959 1960 1961
      return 0;
  }
}


int JSObject::GetInternalFieldCount() {
  ASSERT(1 << kPointerSizeLog2 == kPointerSize);
1962 1963 1964 1965
  // Make sure to adjust for the number of in-object properties. These
  // properties do contribute to the size, but are not internal fields.
  return ((Size() - GetHeaderSize()) >> kPointerSizeLog2) -
         map()->inobject_properties();
1966 1967 1968
}


1969 1970 1971 1972 1973 1974
int JSObject::GetInternalFieldOffset(int index) {
  ASSERT(index < GetInternalFieldCount() && index >= 0);
  return GetHeaderSize() + (kPointerSize * index);
}


1975 1976
Object* JSObject::GetInternalField(int index) {
  ASSERT(index < GetInternalFieldCount() && index >= 0);
1977 1978 1979
  // Internal objects do follow immediately after the header, whereas in-object
  // properties are at the end of the object. Therefore there is no need
  // to adjust the index here.
1980 1981 1982 1983 1984 1985
  return READ_FIELD(this, GetHeaderSize() + (kPointerSize * index));
}


void JSObject::SetInternalField(int index, Object* value) {
  ASSERT(index < GetInternalFieldCount() && index >= 0);
1986 1987 1988
  // Internal objects do follow immediately after the header, whereas in-object
  // properties are at the end of the object. Therefore there is no need
  // to adjust the index here.
1989 1990
  int offset = GetHeaderSize() + (kPointerSize * index);
  WRITE_FIELD(this, offset, value);
1991
  WRITE_BARRIER(GetHeap(), this, offset, value);
1992 1993 1994
}


1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
void JSObject::SetInternalField(int index, Smi* value) {
  ASSERT(index < GetInternalFieldCount() && index >= 0);
  // Internal objects do follow immediately after the header, whereas in-object
  // properties are at the end of the object. Therefore there is no need
  // to adjust the index here.
  int offset = GetHeaderSize() + (kPointerSize * index);
  WRITE_FIELD(this, offset, value);
}


2005 2006 2007
// Access fast-case object properties at index. The use of these routines
// is needed to correctly distinguish between properties stored in-object and
// properties stored in the properties array.
2008 2009 2010
Object* JSObject::RawFastPropertyAt(FieldIndex index) {
  if (index.is_inobject()) {
    return READ_FIELD(this, index.offset());
2011
  } else {
2012
    return properties()->get(index.outobject_array_index());
2013 2014 2015 2016
  }
}


2017 2018 2019
void JSObject::FastPropertyAtPut(FieldIndex index, Object* value) {
  if (index.is_inobject()) {
    int offset = index.offset();
2020
    WRITE_FIELD(this, offset, value);
2021
    WRITE_BARRIER(GetHeap(), this, offset, value);
2022
  } else {
2023
    properties()->set(index.outobject_array_index(), value);
2024 2025 2026 2027
  }
}


2028
int JSObject::GetInObjectPropertyOffset(int index) {
2029
  return map()->GetInObjectPropertyOffset(index);
2030 2031 2032
}


2033
Object* JSObject::InObjectPropertyAt(int index) {
2034
  int offset = GetInObjectPropertyOffset(index);
2035 2036 2037 2038
  return READ_FIELD(this, offset);
}


2039 2040 2041 2042
Object* JSObject::InObjectPropertyAtPut(int index,
                                        Object* value,
                                        WriteBarrierMode mode) {
  // Adjust for the number of properties stored in the object.
2043
  int offset = GetInObjectPropertyOffset(index);
2044
  WRITE_FIELD(this, offset, value);
2045
  CONDITIONAL_WRITE_BARRIER(GetHeap(), this, offset, value, mode);
2046 2047 2048 2049 2050
  return value;
}



2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
void JSObject::InitializeBody(Map* map,
                              Object* pre_allocated_value,
                              Object* filler_value) {
  ASSERT(!filler_value->IsHeapObject() ||
         !GetHeap()->InNewSpace(filler_value));
  ASSERT(!pre_allocated_value->IsHeapObject() ||
         !GetHeap()->InNewSpace(pre_allocated_value));
  int size = map->instance_size();
  int offset = kHeaderSize;
  if (filler_value != pre_allocated_value) {
    int pre_allocated = map->pre_allocated_property_fields();
    ASSERT(pre_allocated * kPointerSize + kHeaderSize <= size);
    for (int i = 0; i < pre_allocated; i++) {
      WRITE_FIELD(this, offset, pre_allocated_value);
      offset += kPointerSize;
    }
  }
  while (offset < size) {
    WRITE_FIELD(this, offset, filler_value);
    offset += kPointerSize;
2071 2072 2073 2074
  }
}


2075
bool JSObject::HasFastProperties() {
2076
  ASSERT(properties()->IsDictionary() == map()->is_dictionary_map());
2077 2078 2079 2080
  return !properties()->IsDictionary();
}


2081
bool JSObject::TooManyFastProperties(StoreFromKeyed store_mode) {
2082
  // Allow extra fast properties if the object has more than
2083 2084 2085 2086 2087 2088 2089
  // kFastPropertiesSoftLimit in-object properties. When this is the case, it is
  // very unlikely that the object is being used as a dictionary and there is a
  // good chance that allowing more map transitions will be worth it.
  Map* map = this->map();
  if (map->unused_property_fields() != 0) return false;

  int inobject = map->inobject_properties();
2090 2091

  int limit;
2092
  if (store_mode == CERTAINLY_NOT_STORE_FROM_KEYED) {
2093 2094 2095 2096
    limit = Max(inobject, kMaxFastProperties);
  } else {
    limit = Max(inobject, kFastPropertiesSoftLimit);
  }
2097
  return properties()->length() > limit;
2098 2099 2100
}


2101
void Struct::InitializeBody(int object_size) {
2102
  Object* value = GetHeap()->undefined_value();
2103
  for (int offset = kHeaderSize; offset < object_size; offset += kPointerSize) {
2104
    WRITE_FIELD(this, offset, value);
2105 2106 2107 2108
  }
}


2109 2110 2111
bool Object::ToArrayIndex(uint32_t* index) {
  if (IsSmi()) {
    int value = Smi::cast(this)->value();
2112 2113 2114 2115
    if (value < 0) return false;
    *index = value;
    return true;
  }
2116 2117
  if (IsHeapNumber()) {
    double value = HeapNumber::cast(this)->value();
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
    uint32_t uint_value = static_cast<uint32_t>(value);
    if (value == static_cast<double>(uint_value)) {
      *index = uint_value;
      return true;
    }
  }
  return false;
}


bool Object::IsStringObjectWithCharacterAt(uint32_t index) {
  if (!this->IsJSValue()) return false;

  JSValue* js_value = JSValue::cast(this);
  if (!js_value->value()->IsString()) return false;

  String* str = String::cast(js_value->value());
2135
  if (index >= static_cast<uint32_t>(str->length())) return false;
2136 2137 2138 2139 2140

  return true;
}


2141 2142 2143 2144
void Object::VerifyApiCallResultType() {
#if ENABLE_EXTRA_CHECKS
  if (!(IsSmi() ||
        IsString() ||
2145
        IsSymbol() ||
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
        IsSpecObject() ||
        IsHeapNumber() ||
        IsUndefined() ||
        IsTrue() ||
        IsFalse() ||
        IsNull())) {
    FATAL("API call returned invalid object");
  }
#endif  // ENABLE_EXTRA_CHECKS
}


2158
Object* FixedArray::get(int index) {
2159
  SLOW_ASSERT(index >= 0 && index < this->length());
2160 2161 2162 2163
  return READ_FIELD(this, kHeaderSize + index * kPointerSize);
}


2164 2165 2166 2167 2168
Handle<Object> FixedArray::get(Handle<FixedArray> array, int index) {
  return handle(array->get(index), array->GetIsolate());
}


2169 2170 2171 2172 2173
bool FixedArray::is_the_hole(int index) {
  return get(index) == GetHeap()->the_hole_value();
}


2174
void FixedArray::set(int index, Smi* value) {
2175
  ASSERT(map() != GetHeap()->fixed_cow_array_map());
2176
  ASSERT(index >= 0 && index < this->length());
2177 2178 2179 2180 2181 2182
  ASSERT(reinterpret_cast<Object*>(value)->IsSmi());
  int offset = kHeaderSize + index * kPointerSize;
  WRITE_FIELD(this, offset, value);
}


2183
void FixedArray::set(int index, Object* value) {
2184
  ASSERT(map() != GetHeap()->fixed_cow_array_map());
2185 2186 2187
  ASSERT(index >= 0 && index < this->length());
  int offset = kHeaderSize + index * kPointerSize;
  WRITE_FIELD(this, offset, value);
2188
  WRITE_BARRIER(GetHeap(), this, offset, value);
2189 2190 2191
}


2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
inline bool FixedDoubleArray::is_the_hole_nan(double value) {
  return BitCast<uint64_t, double>(value) == kHoleNanInt64;
}


inline double FixedDoubleArray::hole_nan_as_double() {
  return BitCast<double, uint64_t>(kHoleNanInt64);
}


inline double FixedDoubleArray::canonical_not_the_hole_nan_as_double() {
2203 2204 2205
  ASSERT(BitCast<uint64_t>(base::OS::nan_value()) != kHoleNanInt64);
  ASSERT((BitCast<uint64_t>(base::OS::nan_value()) >> 32) != kHoleNanUpper32);
  return base::OS::nan_value();
2206 2207 2208
}


2209
double FixedDoubleArray::get_scalar(int index) {
2210 2211
  ASSERT(map() != GetHeap()->fixed_cow_array_map() &&
         map() != GetHeap()->fixed_array_map());
2212 2213 2214 2215 2216 2217
  ASSERT(index >= 0 && index < this->length());
  double result = READ_DOUBLE_FIELD(this, kHeaderSize + index * kDoubleSize);
  ASSERT(!is_the_hole_nan(result));
  return result;
}

2218
int64_t FixedDoubleArray::get_representation(int index) {
2219 2220
  ASSERT(map() != GetHeap()->fixed_cow_array_map() &&
         map() != GetHeap()->fixed_array_map());
2221 2222 2223
  ASSERT(index >= 0 && index < this->length());
  return READ_INT64_FIELD(this, kHeaderSize + index * kDoubleSize);
}
2224

2225

2226 2227 2228 2229
Handle<Object> FixedDoubleArray::get(Handle<FixedDoubleArray> array,
                                     int index) {
  if (array->is_the_hole(index)) {
    return array->GetIsolate()->factory()->the_hole_value();
2230
  } else {
2231
    return array->GetIsolate()->factory()->NewNumber(array->get_scalar(index));
2232 2233 2234 2235
  }
}


2236
void FixedDoubleArray::set(int index, double value) {
2237 2238
  ASSERT(map() != GetHeap()->fixed_cow_array_map() &&
         map() != GetHeap()->fixed_array_map());
2239
  int offset = kHeaderSize + index * kDoubleSize;
2240
  if (std::isnan(value)) value = canonical_not_the_hole_nan_as_double();
2241 2242 2243 2244 2245
  WRITE_DOUBLE_FIELD(this, offset, value);
}


void FixedDoubleArray::set_the_hole(int index) {
2246 2247
  ASSERT(map() != GetHeap()->fixed_cow_array_map() &&
         map() != GetHeap()->fixed_array_map());
2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
  int offset = kHeaderSize + index * kDoubleSize;
  WRITE_DOUBLE_FIELD(this, offset, hole_nan_as_double());
}


bool FixedDoubleArray::is_the_hole(int index) {
  int offset = kHeaderSize + index * kDoubleSize;
  return is_the_hole_nan(READ_DOUBLE_FIELD(this, offset));
}


2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
double* FixedDoubleArray::data_start() {
  return reinterpret_cast<double*>(FIELD_ADDR(this, kHeaderSize));
}


void FixedDoubleArray::FillWithHoles(int from, int to) {
  for (int i = from; i < to; i++) {
    set_the_hole(i);
  }
}


2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
void ConstantPoolArray::NumberOfEntries::increment(Type type) {
  ASSERT(type < NUMBER_OF_TYPES);
  element_counts_[type]++;
}


int ConstantPoolArray::NumberOfEntries::equals(
    const ConstantPoolArray::NumberOfEntries& other) const {
  for (int i = 0; i < NUMBER_OF_TYPES; i++) {
    if (element_counts_[i] != other.element_counts_[i]) return false;
  }
  return true;
}


bool ConstantPoolArray::NumberOfEntries::is_empty() const {
  return total_count() == 0;
}


int ConstantPoolArray::NumberOfEntries::count_of(Type type) const {
  ASSERT(type < NUMBER_OF_TYPES);
  return element_counts_[type];
}


int ConstantPoolArray::NumberOfEntries::base_of(Type type) const {
  int base = 0;
  ASSERT(type < NUMBER_OF_TYPES);
  for (int i = 0; i < type; i++) {
    base += element_counts_[i];
  }
  return base;
}


int ConstantPoolArray::NumberOfEntries::total_count() const {
  int count = 0;
  for (int i = 0; i < NUMBER_OF_TYPES; i++) {
    count += element_counts_[i];
  }
  return count;
}


int ConstantPoolArray::NumberOfEntries::are_in_range(int min, int max) const {
  for (int i = FIRST_TYPE; i < NUMBER_OF_TYPES; i++) {
    if (element_counts_[i] < min || element_counts_[i] > max) {
      return false;
    }
  }
  return true;
}


int ConstantPoolArray::Iterator::next_index() {
  ASSERT(!is_finished());
  int ret = next_index_++;
  update_section();
  return ret;
}


bool ConstantPoolArray::Iterator::is_finished() {
  return next_index_ > array_->last_index(type_, final_section_);
}


void ConstantPoolArray::Iterator::update_section() {
  if (next_index_ > array_->last_index(type_, current_section_) &&
      current_section_ != final_section_) {
    ASSERT(final_section_ == EXTENDED_SECTION);
    current_section_ = EXTENDED_SECTION;
    next_index_ = array_->first_index(type_, EXTENDED_SECTION);
  }
}


2349 2350 2351
bool ConstantPoolArray::is_extended_layout() {
  uint32_t small_layout_1 = READ_UINT32_FIELD(this, kSmallLayout1Offset);
  return IsExtendedField::decode(small_layout_1);
2352 2353 2354
}


2355 2356
ConstantPoolArray::LayoutSection ConstantPoolArray::final_section() {
  return is_extended_layout() ? EXTENDED_SECTION : SMALL_SECTION;
2357
}
2358 2359


2360 2361 2362 2363
int ConstantPoolArray::first_extended_section_index() {
  ASSERT(is_extended_layout());
  uint32_t small_layout_2 = READ_UINT32_FIELD(this, kSmallLayout2Offset);
  return TotalCountField::decode(small_layout_2);
2364 2365 2366
}


2367 2368
int ConstantPoolArray::get_extended_section_header_offset() {
  return RoundUp(SizeFor(NumberOfEntries(this, SMALL_SECTION)), kInt64Size);
2369 2370 2371
}


2372 2373 2374
ConstantPoolArray::WeakObjectState ConstantPoolArray::get_weak_object_state() {
  uint32_t small_layout_2 = READ_UINT32_FIELD(this, kSmallLayout2Offset);
  return WeakObjectStateField::decode(small_layout_2);
2375 2376 2377
}


2378 2379 2380 2381 2382
void ConstantPoolArray::set_weak_object_state(
      ConstantPoolArray::WeakObjectState state) {
  uint32_t small_layout_2 = READ_UINT32_FIELD(this, kSmallLayout2Offset);
  small_layout_2 = WeakObjectStateField::update(small_layout_2, state);
  WRITE_INT32_FIELD(this, kSmallLayout2Offset, small_layout_2);
2383 2384 2385
}


2386 2387 2388 2389 2390 2391
int ConstantPoolArray::first_index(Type type, LayoutSection section) {
  int index = 0;
  if (section == EXTENDED_SECTION) {
    ASSERT(is_extended_layout());
    index += first_extended_section_index();
  }
2392

2393 2394 2395 2396
  for (Type type_iter = FIRST_TYPE; type_iter < type;
       type_iter = next_type(type_iter)) {
    index += number_of_entries(type_iter, section);
  }
2397

2398
  return index;
2399 2400 2401
}


2402 2403
int ConstantPoolArray::last_index(Type type, LayoutSection section) {
  return first_index(type, section) + number_of_entries(type, section) - 1;
2404 2405 2406
}


2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444
int ConstantPoolArray::number_of_entries(Type type, LayoutSection section) {
  if (section == SMALL_SECTION) {
    uint32_t small_layout_1 = READ_UINT32_FIELD(this, kSmallLayout1Offset);
    uint32_t small_layout_2 = READ_UINT32_FIELD(this, kSmallLayout2Offset);
    switch (type) {
      case INT64:
        return Int64CountField::decode(small_layout_1);
      case CODE_PTR:
        return CodePtrCountField::decode(small_layout_1);
      case HEAP_PTR:
        return HeapPtrCountField::decode(small_layout_1);
      case INT32:
        return Int32CountField::decode(small_layout_2);
      default:
        UNREACHABLE();
        return 0;
    }
  } else {
    ASSERT(section == EXTENDED_SECTION && is_extended_layout());
    int offset = get_extended_section_header_offset();
    switch (type) {
      case INT64:
        offset += kExtendedInt64CountOffset;
        break;
      case CODE_PTR:
        offset += kExtendedCodePtrCountOffset;
        break;
      case HEAP_PTR:
        offset += kExtendedHeapPtrCountOffset;
        break;
      case INT32:
        offset += kExtendedInt32CountOffset;
        break;
      default:
        UNREACHABLE();
    }
    return READ_INT_FIELD(this, offset);
  }
2445 2446 2447
}


2448 2449 2450 2451 2452 2453 2454 2455 2456
bool ConstantPoolArray::offset_is_type(int offset, Type type) {
  return (offset >= OffsetOfElementAt(first_index(type, SMALL_SECTION)) &&
          offset <= OffsetOfElementAt(last_index(type, SMALL_SECTION))) ||
         (is_extended_layout() &&
          offset >= OffsetOfElementAt(first_index(type, EXTENDED_SECTION)) &&
          offset <= OffsetOfElementAt(last_index(type, EXTENDED_SECTION)));
}


2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
ConstantPoolArray::Type ConstantPoolArray::get_type(int index) {
  LayoutSection section;
  if (is_extended_layout() && index >= first_extended_section_index()) {
    section = EXTENDED_SECTION;
  } else {
    section = SMALL_SECTION;
  }

  Type type = FIRST_TYPE;
  while (index > last_index(type, section)) {
    type = next_type(type);
  }
  ASSERT(type <= LAST_TYPE);
  return type;
2471 2472 2473 2474 2475
}


int64_t ConstantPoolArray::get_int64_entry(int index) {
  ASSERT(map() == GetHeap()->constant_pool_array_map());
2476
  ASSERT(get_type(index) == INT64);
2477 2478 2479
  return READ_INT64_FIELD(this, OffsetOfElementAt(index));
}

2480

2481 2482 2483
double ConstantPoolArray::get_int64_entry_as_double(int index) {
  STATIC_ASSERT(kDoubleSize == kInt64Size);
  ASSERT(map() == GetHeap()->constant_pool_array_map());
2484
  ASSERT(get_type(index) == INT64);
2485 2486 2487 2488
  return READ_DOUBLE_FIELD(this, OffsetOfElementAt(index));
}


2489
Address ConstantPoolArray::get_code_ptr_entry(int index) {
2490
  ASSERT(map() == GetHeap()->constant_pool_array_map());
2491
  ASSERT(get_type(index) == CODE_PTR);
2492 2493 2494 2495 2496 2497
  return reinterpret_cast<Address>(READ_FIELD(this, OffsetOfElementAt(index)));
}


Object* ConstantPoolArray::get_heap_ptr_entry(int index) {
  ASSERT(map() == GetHeap()->constant_pool_array_map());
2498
  ASSERT(get_type(index) == HEAP_PTR);
2499 2500 2501 2502 2503 2504
  return READ_FIELD(this, OffsetOfElementAt(index));
}


int32_t ConstantPoolArray::get_int32_entry(int index) {
  ASSERT(map() == GetHeap()->constant_pool_array_map());
2505
  ASSERT(get_type(index) == INT32);
2506 2507 2508 2509
  return READ_INT32_FIELD(this, OffsetOfElementAt(index));
}


2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
void ConstantPoolArray::set(int index, int64_t value) {
  ASSERT(map() == GetHeap()->constant_pool_array_map());
  ASSERT(get_type(index) == INT64);
  WRITE_INT64_FIELD(this, OffsetOfElementAt(index), value);
}


void ConstantPoolArray::set(int index, double value) {
  STATIC_ASSERT(kDoubleSize == kInt64Size);
  ASSERT(map() == GetHeap()->constant_pool_array_map());
  ASSERT(get_type(index) == INT64);
  WRITE_DOUBLE_FIELD(this, OffsetOfElementAt(index), value);
}


2525 2526
void ConstantPoolArray::set(int index, Address value) {
  ASSERT(map() == GetHeap()->constant_pool_array_map());
2527
  ASSERT(get_type(index) == CODE_PTR);
2528 2529 2530 2531
  WRITE_FIELD(this, OffsetOfElementAt(index), reinterpret_cast<Object*>(value));
}


2532 2533
void ConstantPoolArray::set(int index, Object* value) {
  ASSERT(map() == GetHeap()->constant_pool_array_map());
2534
  ASSERT(get_type(index) == HEAP_PTR);
2535 2536 2537 2538 2539
  WRITE_FIELD(this, OffsetOfElementAt(index), value);
  WRITE_BARRIER(GetHeap(), this, OffsetOfElementAt(index), value);
}


2540
void ConstantPoolArray::set(int index, int32_t value) {
2541
  ASSERT(map() == GetHeap()->constant_pool_array_map());
2542 2543
  ASSERT(get_type(index) == INT32);
  WRITE_INT32_FIELD(this, OffsetOfElementAt(index), value);
2544 2545 2546
}


2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583
void ConstantPoolArray::set_at_offset(int offset, int32_t value) {
  ASSERT(map() == GetHeap()->constant_pool_array_map());
  ASSERT(offset_is_type(offset, INT32));
  WRITE_INT32_FIELD(this, offset, value);
}


void ConstantPoolArray::set_at_offset(int offset, int64_t value) {
  ASSERT(map() == GetHeap()->constant_pool_array_map());
  ASSERT(offset_is_type(offset, INT64));
  WRITE_INT64_FIELD(this, offset, value);
}


void ConstantPoolArray::set_at_offset(int offset, double value) {
  ASSERT(map() == GetHeap()->constant_pool_array_map());
  ASSERT(offset_is_type(offset, INT64));
  WRITE_DOUBLE_FIELD(this, offset, value);
}


void ConstantPoolArray::set_at_offset(int offset, Address value) {
  ASSERT(map() == GetHeap()->constant_pool_array_map());
  ASSERT(offset_is_type(offset, CODE_PTR));
  WRITE_FIELD(this, offset, reinterpret_cast<Object*>(value));
  WRITE_BARRIER(GetHeap(), this, offset, reinterpret_cast<Object*>(value));
}


void ConstantPoolArray::set_at_offset(int offset, Object* value) {
  ASSERT(map() == GetHeap()->constant_pool_array_map());
  ASSERT(offset_is_type(offset, HEAP_PTR));
  WRITE_FIELD(this, offset, value);
  WRITE_BARRIER(GetHeap(), this, offset, value);
}


2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
void ConstantPoolArray::Init(const NumberOfEntries& small) {
  uint32_t small_layout_1 =
      Int64CountField::encode(small.count_of(INT64)) |
      CodePtrCountField::encode(small.count_of(CODE_PTR)) |
      HeapPtrCountField::encode(small.count_of(HEAP_PTR)) |
      IsExtendedField::encode(false);
  uint32_t small_layout_2 =
      Int32CountField::encode(small.count_of(INT32)) |
      TotalCountField::encode(small.total_count()) |
      WeakObjectStateField::encode(NO_WEAK_OBJECTS);
  WRITE_UINT32_FIELD(this, kSmallLayout1Offset, small_layout_1);
  WRITE_UINT32_FIELD(this, kSmallLayout2Offset, small_layout_2);
  if (kHeaderSize != kFirstEntryOffset) {
    ASSERT(kFirstEntryOffset - kHeaderSize == kInt32Size);
    WRITE_UINT32_FIELD(this, kHeaderSize, 0);  // Zero out header padding.
  }
2600 2601 2602
}


2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
void ConstantPoolArray::InitExtended(const NumberOfEntries& small,
                                     const NumberOfEntries& extended) {
  // Initialize small layout fields first.
  Init(small);

  // Set is_extended_layout field.
  uint32_t small_layout_1 = READ_UINT32_FIELD(this, kSmallLayout1Offset);
  small_layout_1 = IsExtendedField::update(small_layout_1, true);
  WRITE_INT32_FIELD(this, kSmallLayout1Offset, small_layout_1);

  // Initialize the extended layout fields.
  int extended_header_offset = get_extended_section_header_offset();
  WRITE_INT_FIELD(this, extended_header_offset + kExtendedInt64CountOffset,
      extended.count_of(INT64));
  WRITE_INT_FIELD(this, extended_header_offset + kExtendedCodePtrCountOffset,
      extended.count_of(CODE_PTR));
  WRITE_INT_FIELD(this, extended_header_offset + kExtendedHeapPtrCountOffset,
      extended.count_of(HEAP_PTR));
  WRITE_INT_FIELD(this, extended_header_offset + kExtendedInt32CountOffset,
      extended.count_of(INT32));
}


int ConstantPoolArray::size() {
  NumberOfEntries small(this, SMALL_SECTION);
  if (!is_extended_layout()) {
    return SizeFor(small);
  } else {
    NumberOfEntries extended(this, EXTENDED_SECTION);
    return SizeForExtended(small, extended);
  }
}


int ConstantPoolArray::length() {
  uint32_t small_layout_2 = READ_UINT32_FIELD(this, kSmallLayout2Offset);
  int length = TotalCountField::decode(small_layout_2);
  if (is_extended_layout()) {
    length += number_of_entries(INT64, EXTENDED_SECTION) +
              number_of_entries(CODE_PTR, EXTENDED_SECTION) +
              number_of_entries(HEAP_PTR, EXTENDED_SECTION) +
              number_of_entries(INT32, EXTENDED_SECTION);
  }
  return length;
}


2650 2651
WriteBarrierMode HeapObject::GetWriteBarrierMode(
    const DisallowHeapAllocation& promise) {
2652 2653 2654
  Heap* heap = GetHeap();
  if (heap->incremental_marking()->IsMarking()) return UPDATE_WRITE_BARRIER;
  if (heap->InNewSpace(this)) return SKIP_WRITE_BARRIER;
2655 2656 2657 2658 2659 2660
  return UPDATE_WRITE_BARRIER;
}


void FixedArray::set(int index,
                     Object* value,
2661
                     WriteBarrierMode mode) {
2662
  ASSERT(map() != GetHeap()->fixed_cow_array_map());
2663 2664 2665
  ASSERT(index >= 0 && index < this->length());
  int offset = kHeaderSize + index * kPointerSize;
  WRITE_FIELD(this, offset, value);
2666
  CONDITIONAL_WRITE_BARRIER(GetHeap(), this, offset, value, mode);
2667 2668 2669
}


2670 2671 2672
void FixedArray::NoIncrementalWriteBarrierSet(FixedArray* array,
                                              int index,
                                              Object* value) {
2673
  ASSERT(array->map() != array->GetHeap()->fixed_cow_array_map());
2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
  ASSERT(index >= 0 && index < array->length());
  int offset = kHeaderSize + index * kPointerSize;
  WRITE_FIELD(array, offset, value);
  Heap* heap = array->GetHeap();
  if (heap->InNewSpace(value)) {
    heap->RecordWrite(array->address(), offset);
  }
}


2684 2685 2686
void FixedArray::NoWriteBarrierSet(FixedArray* array,
                                   int index,
                                   Object* value) {
2687
  ASSERT(array->map() != array->GetHeap()->fixed_cow_array_map());
2688
  ASSERT(index >= 0 && index < array->length());
2689
  ASSERT(!array->GetHeap()->InNewSpace(value));
2690 2691 2692 2693 2694
  WRITE_FIELD(array, kHeaderSize + index * kPointerSize, value);
}


void FixedArray::set_undefined(int index) {
2695
  ASSERT(map() != GetHeap()->fixed_cow_array_map());
2696
  ASSERT(index >= 0 && index < this->length());
2697 2698 2699 2700
  ASSERT(!GetHeap()->InNewSpace(GetHeap()->undefined_value()));
  WRITE_FIELD(this,
              kHeaderSize + index * kPointerSize,
              GetHeap()->undefined_value());
2701 2702 2703
}


2704 2705
void FixedArray::set_null(int index) {
  ASSERT(index >= 0 && index < this->length());
2706 2707 2708 2709
  ASSERT(!GetHeap()->InNewSpace(GetHeap()->null_value()));
  WRITE_FIELD(this,
              kHeaderSize + index * kPointerSize,
              GetHeap()->null_value());
2710 2711 2712
}


2713
void FixedArray::set_the_hole(int index) {
2714
  ASSERT(map() != GetHeap()->fixed_cow_array_map());
2715
  ASSERT(index >= 0 && index < this->length());
2716
  ASSERT(!GetHeap()->InNewSpace(GetHeap()->the_hole_value()));
2717 2718 2719
  WRITE_FIELD(this,
              kHeaderSize + index * kPointerSize,
              GetHeap()->the_hole_value());
2720 2721 2722
}


2723 2724 2725 2726
void FixedArray::FillWithHoles(int from, int to) {
  for (int i = from; i < to; i++) {
    set_the_hole(i);
  }
2727 2728 2729
}


2730 2731 2732 2733 2734
Object** FixedArray::data_start() {
  return HeapObject::RawField(this, kHeaderSize);
}


2735
bool DescriptorArray::IsEmpty() {
2736
  ASSERT(length() >= kFirstIndex ||
2737
         this == GetHeap()->empty_descriptor_array());
2738
  return length() < kFirstIndex;
2739 2740 2741
}


2742 2743 2744 2745 2746 2747
void DescriptorArray::SetNumberOfDescriptors(int number_of_descriptors) {
  WRITE_FIELD(
      this, kDescriptorLengthOffset, Smi::FromInt(number_of_descriptors));
}


2748 2749 2750
// Perform a binary search in a fixed array. Low and high are entry indices. If
// there are three entries in this array it should be called with low=0 and
// high=2.
2751
template<SearchMode search_mode, typename T>
2752
int BinarySearch(T* array, Name* name, int low, int high, int valid_entries) {
2753 2754 2755 2756 2757 2758 2759
  uint32_t hash = name->Hash();
  int limit = high;

  ASSERT(low <= high);

  while (low != high) {
    int mid = (low + high) / 2;
2760
    Name* mid_name = array->GetSortedKey(mid);
2761 2762 2763 2764 2765 2766 2767 2768 2769
    uint32_t mid_hash = mid_name->Hash();

    if (mid_hash >= hash) {
      high = mid;
    } else {
      low = mid + 1;
    }
  }

2770 2771
  for (; low <= limit; ++low) {
    int sort_index = array->GetSortedKeyIndex(low);
2772
    Name* entry = array->GetKey(sort_index);
2773
    if (entry->Hash() != hash) break;
2774 2775 2776 2777 2778 2779
    if (entry->Equals(name)) {
      if (search_mode == ALL_ENTRIES || sort_index < valid_entries) {
        return sort_index;
      }
      return T::kNotFound;
    }
2780 2781 2782 2783 2784
  }

  return T::kNotFound;
}

2785

2786 2787
// Perform a linear search in this fixed array. len is the number of entry
// indices that are valid.
2788
template<SearchMode search_mode, typename T>
2789
int LinearSearch(T* array, Name* name, int len, int valid_entries) {
2790
  uint32_t hash = name->Hash();
2791 2792 2793
  if (search_mode == ALL_ENTRIES) {
    for (int number = 0; number < len; number++) {
      int sorted_index = array->GetSortedKeyIndex(number);
2794
      Name* entry = array->GetKey(sorted_index);
2795 2796 2797 2798 2799 2800 2801
      uint32_t current_hash = entry->Hash();
      if (current_hash > hash) break;
      if (current_hash == hash && entry->Equals(name)) return sorted_index;
    }
  } else {
    ASSERT(len >= valid_entries);
    for (int number = 0; number < valid_entries; number++) {
2802
      Name* entry = array->GetKey(number);
2803 2804 2805
      uint32_t current_hash = entry->Hash();
      if (current_hash == hash && entry->Equals(name)) return number;
    }
2806 2807 2808 2809 2810
  }
  return T::kNotFound;
}


2811
template<SearchMode search_mode, typename T>
2812
int Search(T* array, Name* name, int valid_entries) {
2813 2814 2815 2816 2817
  if (search_mode == VALID_ENTRIES) {
    SLOW_ASSERT(array->IsSortedNoDuplicates(valid_entries));
  } else {
    SLOW_ASSERT(array->IsSortedNoDuplicates());
  }
2818

2819 2820
  int nof = array->number_of_entries();
  if (nof == 0) return T::kNotFound;
2821 2822 2823

  // Fast case: do linear search for small arrays.
  const int kMaxElementsForLinearSearch = 8;
2824 2825 2826 2827
  if ((search_mode == ALL_ENTRIES &&
       nof <= kMaxElementsForLinearSearch) ||
      (search_mode == VALID_ENTRIES &&
       valid_entries <= (kMaxElementsForLinearSearch * 3))) {
2828
    return LinearSearch<search_mode>(array, name, nof, valid_entries);
2829 2830 2831
  }

  // Slow case: perform binary search.
2832
  return BinarySearch<search_mode>(array, name, 0, nof - 1, valid_entries);
2833 2834 2835
}


2836
int DescriptorArray::Search(Name* name, int valid_descriptors) {
2837
  return internal::Search<VALID_ENTRIES>(this, name, valid_descriptors);
2838 2839 2840
}


2841
int DescriptorArray::SearchWithCache(Name* name, Map* map) {
2842 2843
  int number_of_own_descriptors = map->NumberOfOwnDescriptors();
  if (number_of_own_descriptors == 0) return kNotFound;
2844

2845
  DescriptorLookupCache* cache = GetIsolate()->descriptor_lookup_cache();
2846
  int number = cache->Lookup(map, name);
2847

2848
  if (number == DescriptorLookupCache::kAbsent) {
2849 2850
    number = Search(name, number_of_own_descriptors);
    cache->Update(map, name, number);
2851
  }
2852

2853 2854 2855 2856
  return number;
}


2857 2858 2859 2860 2861
PropertyDetails Map::GetLastDescriptorDetails() {
  return instance_descriptors()->GetDetails(LastAdded());
}


2862
void Map::LookupDescriptor(JSObject* holder,
2863
                           Name* name,
2864 2865
                           LookupResult* result) {
  DescriptorArray* descriptors = this->instance_descriptors();
2866
  int number = descriptors->SearchWithCache(name, this);
2867 2868 2869 2870 2871 2872
  if (number == DescriptorArray::kNotFound) return result->NotFound();
  result->DescriptorResult(holder, descriptors->GetDetails(number), number);
}


void Map::LookupTransition(JSObject* holder,
2873
                           Name* name,
2874
                           LookupResult* result) {
2875 2876 2877
  int transition_index = this->SearchTransition(name);
  if (transition_index == TransitionArray::kNotFound) return result->NotFound();
  result->TransitionResult(holder, this->GetTransition(transition_index));
2878 2879 2880
}


2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894
FixedArrayBase* Map::GetInitialElements() {
  if (has_fast_smi_or_object_elements() ||
      has_fast_double_elements()) {
    ASSERT(!GetHeap()->InNewSpace(GetHeap()->empty_fixed_array()));
    return GetHeap()->empty_fixed_array();
  } else if (has_external_array_elements()) {
    ExternalArray* empty_array = GetHeap()->EmptyExternalArrayForMap(this);
    ASSERT(!GetHeap()->InNewSpace(empty_array));
    return empty_array;
  } else if (has_fixed_typed_array_elements()) {
    FixedTypedArrayBase* empty_array =
      GetHeap()->EmptyFixedTypedArrayForMap(this);
    ASSERT(!GetHeap()->InNewSpace(empty_array));
    return empty_array;
2895 2896 2897
  } else if (has_dictionary_elements()) {
    ASSERT(!GetHeap()->InNewSpace(GetHeap()->empty_slow_element_dictionary()));
    return GetHeap()->empty_slow_element_dictionary();
2898 2899 2900 2901 2902 2903 2904
  } else {
    UNREACHABLE();
  }
  return NULL;
}


2905 2906
Object** DescriptorArray::GetKeySlot(int descriptor_number) {
  ASSERT(descriptor_number < number_of_descriptors());
2907
  return RawFieldOfElementAt(ToKeyIndex(descriptor_number));
2908 2909 2910
}


2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
Object** DescriptorArray::GetDescriptorStartSlot(int descriptor_number) {
  return GetKeySlot(descriptor_number);
}


Object** DescriptorArray::GetDescriptorEndSlot(int descriptor_number) {
  return GetValueSlot(descriptor_number - 1) + 1;
}


2921
Name* DescriptorArray::GetKey(int descriptor_number) {
2922
  ASSERT(descriptor_number < number_of_descriptors());
2923
  return Name::cast(get(ToKeyIndex(descriptor_number)));
2924 2925 2926
}


2927 2928 2929 2930 2931
int DescriptorArray::GetSortedKeyIndex(int descriptor_number) {
  return GetDetails(descriptor_number).pointer();
}


2932
Name* DescriptorArray::GetSortedKey(int descriptor_number) {
2933 2934 2935 2936
  return GetKey(GetSortedKeyIndex(descriptor_number));
}


2937 2938 2939
void DescriptorArray::SetSortedKey(int descriptor_index, int pointer) {
  PropertyDetails details = GetDetails(descriptor_index);
  set(ToDetailsIndex(descriptor_index), details.set_pointer(pointer).AsSmi());
2940 2941 2942
}


2943 2944 2945 2946 2947 2948 2949 2950 2951
void DescriptorArray::SetRepresentation(int descriptor_index,
                                        Representation representation) {
  ASSERT(!representation.IsNone());
  PropertyDetails details = GetDetails(descriptor_index);
  set(ToDetailsIndex(descriptor_index),
      details.CopyWithRepresentation(representation).AsSmi());
}


2952 2953
Object** DescriptorArray::GetValueSlot(int descriptor_number) {
  ASSERT(descriptor_number < number_of_descriptors());
2954
  return RawFieldOfElementAt(ToValueIndex(descriptor_number));
2955 2956 2957
}


2958 2959
Object* DescriptorArray::GetValue(int descriptor_number) {
  ASSERT(descriptor_number < number_of_descriptors());
2960
  return get(ToValueIndex(descriptor_number));
2961 2962 2963
}


2964 2965 2966 2967 2968
void DescriptorArray::SetValue(int descriptor_index, Object* value) {
  set(ToValueIndex(descriptor_index), value);
}


2969
PropertyDetails DescriptorArray::GetDetails(int descriptor_number) {
2970
  ASSERT(descriptor_number < number_of_descriptors());
2971
  Object* details = get(ToDetailsIndex(descriptor_number));
2972
  return PropertyDetails(Smi::cast(details));
2973 2974 2975
}


2976
PropertyType DescriptorArray::GetType(int descriptor_number) {
2977
  return GetDetails(descriptor_number).type();
2978 2979 2980 2981
}


int DescriptorArray::GetFieldIndex(int descriptor_number) {
2982
  ASSERT(GetDetails(descriptor_number).type() == FIELD);
2983
  return GetDetails(descriptor_number).field_index();
2984 2985 2986
}


2987 2988 2989 2990 2991 2992
HeapType* DescriptorArray::GetFieldType(int descriptor_number) {
  ASSERT(GetDetails(descriptor_number).type() == FIELD);
  return HeapType::cast(GetValue(descriptor_number));
}


2993 2994
Object* DescriptorArray::GetConstant(int descriptor_number) {
  return GetValue(descriptor_number);
2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
}


Object* DescriptorArray::GetCallbacksObject(int descriptor_number) {
  ASSERT(GetType(descriptor_number) == CALLBACKS);
  return GetValue(descriptor_number);
}


AccessorDescriptor* DescriptorArray::GetCallbacks(int descriptor_number) {
  ASSERT(GetType(descriptor_number) == CALLBACKS);
3006
  Foreign* p = Foreign::cast(GetCallbacksObject(descriptor_number));
3007
  return reinterpret_cast<AccessorDescriptor*>(p->foreign_address());
3008 3009 3010
}


3011
void DescriptorArray::Get(int descriptor_number, Descriptor* desc) {
3012 3013
  desc->Init(handle(GetKey(descriptor_number), GetIsolate()),
             handle(GetValue(descriptor_number), GetIsolate()),
3014
             GetDetails(descriptor_number));
3015 3016 3017
}


3018 3019 3020
void DescriptorArray::Set(int descriptor_number,
                          Descriptor* desc,
                          const WhitenessWitness&) {
3021 3022 3023
  // Range check.
  ASSERT(descriptor_number < number_of_descriptors());

3024 3025
  NoIncrementalWriteBarrierSet(this,
                               ToKeyIndex(descriptor_number),
3026
                               *desc->GetKey());
3027
  NoIncrementalWriteBarrierSet(this,
3028
                               ToValueIndex(descriptor_number),
3029
                               *desc->GetValue());
3030
  NoIncrementalWriteBarrierSet(this,
3031 3032
                               ToDetailsIndex(descriptor_number),
                               desc->GetDetails().AsSmi());
3033 3034 3035
}


3036 3037 3038 3039
void DescriptorArray::Set(int descriptor_number, Descriptor* desc) {
  // Range check.
  ASSERT(descriptor_number < number_of_descriptors());

3040 3041
  set(ToKeyIndex(descriptor_number), *desc->GetKey());
  set(ToValueIndex(descriptor_number), *desc->GetValue());
3042 3043 3044 3045
  set(ToDetailsIndex(descriptor_number), desc->GetDetails().AsSmi());
}


3046
void DescriptorArray::Append(Descriptor* desc,
3047
                             const WhitenessWitness& witness) {
3048
  DisallowHeapAllocation no_gc;
3049 3050
  int descriptor_number = number_of_descriptors();
  SetNumberOfDescriptors(descriptor_number + 1);
3051
  Set(descriptor_number, desc, witness);
3052 3053 3054

  uint32_t hash = desc->GetKey()->Hash();

3055 3056
  int insertion;

3057
  for (insertion = descriptor_number; insertion > 0; --insertion) {
3058
    Name* key = GetSortedKey(insertion - 1);
3059
    if (key->Hash() <= hash) break;
3060
    SetSortedKey(insertion, GetSortedKeyIndex(insertion - 1));
3061 3062
  }

3063
  SetSortedKey(insertion, descriptor_number);
3064 3065 3066
}


3067
void DescriptorArray::Append(Descriptor* desc) {
3068
  DisallowHeapAllocation no_gc;
3069 3070 3071 3072 3073 3074 3075 3076 3077
  int descriptor_number = number_of_descriptors();
  SetNumberOfDescriptors(descriptor_number + 1);
  Set(descriptor_number, desc);

  uint32_t hash = desc->GetKey()->Hash();

  int insertion;

  for (insertion = descriptor_number; insertion > 0; --insertion) {
3078
    Name* key = GetSortedKey(insertion - 1);
3079 3080 3081 3082 3083 3084 3085 3086
    if (key->Hash() <= hash) break;
    SetSortedKey(insertion, GetSortedKeyIndex(insertion - 1));
  }

  SetSortedKey(insertion, descriptor_number);
}


3087 3088 3089 3090
void DescriptorArray::SwapSortedKeys(int first, int second) {
  int first_key = GetSortedKeyIndex(first);
  SetSortedKey(first, GetSortedKeyIndex(second));
  SetSortedKey(second, first_key);
3091 3092 3093
}


3094
DescriptorArray::WhitenessWitness::WhitenessWitness(DescriptorArray* array)
3095 3096
    : marking_(array->GetHeap()->incremental_marking()) {
  marking_->EnterNoMarkingScope();
3097 3098
  ASSERT(!marking_->IsMarking() ||
         Marking::Color(array) == Marking::WHITE_OBJECT);
3099 3100 3101
}


3102
DescriptorArray::WhitenessWitness::~WhitenessWitness() {
3103
  marking_->LeaveNoMarkingScope();
3104 3105 3106
}


3107 3108
template<typename Derived, typename Shape, typename Key>
int HashTable<Derived, Shape, Key>::ComputeCapacity(int at_least_space_for) {
3109 3110 3111 3112 3113 3114 3115 3116 3117
  const int kMinCapacity = 32;
  int capacity = RoundUpToPowerOf2(at_least_space_for * 2);
  if (capacity < kMinCapacity) {
    capacity = kMinCapacity;  // Guarantee min capacity.
  }
  return capacity;
}


3118 3119
template<typename Derived, typename Shape, typename Key>
int HashTable<Derived, Shape, Key>::FindEntry(Key key) {
3120 3121 3122 3123 3124
  return FindEntry(GetIsolate(), key);
}


// Find entry for key otherwise return kNotFound.
3125 3126
template<typename Derived, typename Shape, typename Key>
int HashTable<Derived, Shape, Key>::FindEntry(Isolate* isolate, Key key) {
3127
  uint32_t capacity = Capacity();
3128
  uint32_t entry = FirstProbe(HashTable::Hash(key), capacity);
3129 3130 3131 3132
  uint32_t count = 1;
  // EnsureCapacity will guarantee the hash table is never full.
  while (true) {
    Object* element = KeyAt(entry);
3133
    // Empty entry. Uses raw unchecked accessors because it is called by the
3134
    // string table during bootstrapping.
3135 3136
    if (element == isolate->heap()->raw_unchecked_undefined_value()) break;
    if (element != isolate->heap()->raw_unchecked_the_hole_value() &&
3137 3138 3139 3140 3141 3142 3143
        Shape::IsMatch(key, element)) return entry;
    entry = NextProbe(entry, count++, capacity);
  }
  return kNotFound;
}


3144
bool SeededNumberDictionary::requires_slow_elements() {
3145
  Object* max_index_object = get(kMaxNumberKeyIndex);
3146 3147 3148 3149 3150
  if (!max_index_object->IsSmi()) return false;
  return 0 !=
      (Smi::cast(max_index_object)->value() & kRequiresSlowElementsMask);
}

3151
uint32_t SeededNumberDictionary::max_number_key() {
3152
  ASSERT(!requires_slow_elements());
3153
  Object* max_index_object = get(kMaxNumberKeyIndex);
3154 3155 3156 3157 3158
  if (!max_index_object->IsSmi()) return 0;
  uint32_t value = static_cast<uint32_t>(Smi::cast(max_index_object)->value());
  return value >> kRequiresSlowElementsTagSize;
}

3159
void SeededNumberDictionary::set_requires_slow_elements() {
3160
  set(kMaxNumberKeyIndex, Smi::FromInt(kRequiresSlowElementsMask));
3161 3162 3163
}


3164 3165 3166 3167
// ------------------------------------
// Cast operations


3168 3169 3170 3171 3172 3173 3174
CAST_ACCESSOR(AccessorInfo)
CAST_ACCESSOR(ByteArray)
CAST_ACCESSOR(Cell)
CAST_ACCESSOR(Code)
CAST_ACCESSOR(CodeCacheHashTable)
CAST_ACCESSOR(CompilationCacheTable)
CAST_ACCESSOR(ConsString)
3175
CAST_ACCESSOR(ConstantPoolArray)
3176 3177
CAST_ACCESSOR(DeoptimizationInputData)
CAST_ACCESSOR(DeoptimizationOutputData)
3178
CAST_ACCESSOR(DependentCode)
3179 3180
CAST_ACCESSOR(DescriptorArray)
CAST_ACCESSOR(ExternalArray)
3181
CAST_ACCESSOR(ExternalAsciiString)
3182 3183 3184 3185 3186 3187
CAST_ACCESSOR(ExternalFloat32Array)
CAST_ACCESSOR(ExternalFloat64Array)
CAST_ACCESSOR(ExternalInt16Array)
CAST_ACCESSOR(ExternalInt32Array)
CAST_ACCESSOR(ExternalInt8Array)
CAST_ACCESSOR(ExternalString)
3188
CAST_ACCESSOR(ExternalTwoByteString)
3189 3190 3191 3192 3193 3194 3195 3196 3197 3198
CAST_ACCESSOR(ExternalUint16Array)
CAST_ACCESSOR(ExternalUint32Array)
CAST_ACCESSOR(ExternalUint8Array)
CAST_ACCESSOR(ExternalUint8ClampedArray)
CAST_ACCESSOR(FixedArray)
CAST_ACCESSOR(FixedArrayBase)
CAST_ACCESSOR(FixedDoubleArray)
CAST_ACCESSOR(FixedTypedArrayBase)
CAST_ACCESSOR(Foreign)
CAST_ACCESSOR(FreeSpace)
3199
CAST_ACCESSOR(GlobalObject)
3200
CAST_ACCESSOR(HeapObject)
3201
CAST_ACCESSOR(JSArray)
3202
CAST_ACCESSOR(JSArrayBuffer)
3203
CAST_ACCESSOR(JSArrayBufferView)
3204
CAST_ACCESSOR(JSBuiltinsObject)
3205
CAST_ACCESSOR(JSDataView)
3206 3207
CAST_ACCESSOR(JSDate)
CAST_ACCESSOR(JSFunction)
3208
CAST_ACCESSOR(JSFunctionProxy)
3209 3210 3211 3212
CAST_ACCESSOR(JSFunctionResultCache)
CAST_ACCESSOR(JSGeneratorObject)
CAST_ACCESSOR(JSGlobalObject)
CAST_ACCESSOR(JSGlobalProxy)
3213
CAST_ACCESSOR(JSMap)
3214
CAST_ACCESSOR(JSMapIterator)
3215 3216 3217 3218 3219 3220 3221 3222 3223 3224
CAST_ACCESSOR(JSMessageObject)
CAST_ACCESSOR(JSModule)
CAST_ACCESSOR(JSObject)
CAST_ACCESSOR(JSProxy)
CAST_ACCESSOR(JSReceiver)
CAST_ACCESSOR(JSRegExp)
CAST_ACCESSOR(JSSet)
CAST_ACCESSOR(JSSetIterator)
CAST_ACCESSOR(JSTypedArray)
CAST_ACCESSOR(JSValue)
3225
CAST_ACCESSOR(JSWeakMap)
3226
CAST_ACCESSOR(JSWeakSet)
3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248
CAST_ACCESSOR(Map)
CAST_ACCESSOR(MapCache)
CAST_ACCESSOR(Name)
CAST_ACCESSOR(NameDictionary)
CAST_ACCESSOR(NormalizedMapCache)
CAST_ACCESSOR(Object)
CAST_ACCESSOR(ObjectHashTable)
CAST_ACCESSOR(Oddball)
CAST_ACCESSOR(OrderedHashMap)
CAST_ACCESSOR(OrderedHashSet)
CAST_ACCESSOR(PolymorphicCodeCacheHashTable)
CAST_ACCESSOR(PropertyCell)
CAST_ACCESSOR(ScopeInfo)
CAST_ACCESSOR(SeededNumberDictionary)
CAST_ACCESSOR(SeqOneByteString)
CAST_ACCESSOR(SeqString)
CAST_ACCESSOR(SeqTwoByteString)
CAST_ACCESSOR(SharedFunctionInfo)
CAST_ACCESSOR(SlicedString)
CAST_ACCESSOR(Smi)
CAST_ACCESSOR(String)
CAST_ACCESSOR(StringTable)
3249
CAST_ACCESSOR(Struct)
3250 3251 3252 3253
CAST_ACCESSOR(Symbol)
CAST_ACCESSOR(UnseededNumberDictionary)
CAST_ACCESSOR(WeakHashTable)

3254

3255 3256 3257
template <class Traits>
FixedTypedArray<Traits>* FixedTypedArray<Traits>::cast(Object* object) {
  SLOW_ASSERT(object->IsHeapObject() &&
3258 3259 3260 3261 3262 3263 3264 3265 3266
              HeapObject::cast(object)->map()->instance_type() ==
              Traits::kInstanceType);
  return reinterpret_cast<FixedTypedArray<Traits>*>(object);
}


template <class Traits>
const FixedTypedArray<Traits>*
FixedTypedArray<Traits>::cast(const Object* object) {
3267
  SLOW_ASSERT(object->IsHeapObject() &&
3268 3269
              HeapObject::cast(object)->map()->instance_type() ==
              Traits::kInstanceType);
3270 3271 3272
  return reinterpret_cast<FixedTypedArray<Traits>*>(object);
}

3273 3274 3275 3276 3277

#define MAKE_STRUCT_CAST(NAME, Name, name) CAST_ACCESSOR(Name)
  STRUCT_LIST(MAKE_STRUCT_CAST)
#undef MAKE_STRUCT_CAST

3278

3279 3280 3281
template <typename Derived, typename Shape, typename Key>
HashTable<Derived, Shape, Key>*
HashTable<Derived, Shape, Key>::cast(Object* obj) {
3282
  SLOW_ASSERT(obj->IsHashTable());
3283 3284 3285 3286
  return reinterpret_cast<HashTable*>(obj);
}


3287 3288 3289
template <typename Derived, typename Shape, typename Key>
const HashTable<Derived, Shape, Key>*
HashTable<Derived, Shape, Key>::cast(const Object* obj) {
3290
  SLOW_ASSERT(obj->IsHashTable());
3291 3292 3293 3294
  return reinterpret_cast<const HashTable*>(obj);
}


3295
SMI_ACCESSORS(FixedArrayBase, length, kLengthOffset)
3296 3297
SYNCHRONIZED_SMI_ACCESSORS(FixedArrayBase, length, kLengthOffset)

3298
SMI_ACCESSORS(FreeSpace, size, kSizeOffset)
3299
NOBARRIER_SMI_ACCESSORS(FreeSpace, size, kSizeOffset)
3300

3301
SMI_ACCESSORS(String, length, kLengthOffset)
3302
SYNCHRONIZED_SMI_ACCESSORS(String, length, kLengthOffset)
3303

3304

3305
uint32_t Name::hash_field() {
3306
  return READ_UINT32_FIELD(this, kHashFieldOffset);
3307 3308 3309
}


3310
void Name::set_hash_field(uint32_t value) {
3311
  WRITE_UINT32_FIELD(this, kHashFieldOffset, value);
3312 3313 3314
#if V8_HOST_ARCH_64_BIT
  WRITE_UINT32_FIELD(this, kHashFieldOffset + kIntSize, 0);
#endif
3315 3316 3317
}


3318 3319
bool Name::Equals(Name* other) {
  if (other == this) return true;
3320 3321
  if ((this->IsInternalizedString() && other->IsInternalizedString()) ||
      this->IsSymbol() || other->IsSymbol()) {
3322 3323
    return false;
  }
3324 3325 3326 3327
  return String::cast(this)->SlowEquals(String::cast(other));
}


3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338
bool Name::Equals(Handle<Name> one, Handle<Name> two) {
  if (one.is_identical_to(two)) return true;
  if ((one->IsInternalizedString() && two->IsInternalizedString()) ||
      one->IsSymbol() || two->IsSymbol()) {
    return false;
  }
  return String::SlowEquals(Handle<String>::cast(one),
                            Handle<String>::cast(two));
}


3339
ACCESSORS(Symbol, name, Object, kNameOffset)
3340 3341
ACCESSORS(Symbol, flags, Smi, kFlagsOffset)
BOOL_ACCESSORS(Symbol, flags, is_private, kPrivateBit)
3342 3343


3344 3345
bool String::Equals(String* other) {
  if (other == this) return true;
3346
  if (this->IsInternalizedString() && other->IsInternalizedString()) {
3347 3348 3349
    return false;
  }
  return SlowEquals(other);
3350 3351 3352
}


3353 3354 3355 3356 3357 3358 3359 3360 3361
bool String::Equals(Handle<String> one, Handle<String> two) {
  if (one.is_identical_to(two)) return true;
  if (one->IsInternalizedString() && two->IsInternalizedString()) {
    return false;
  }
  return SlowEquals(one, two);
}


3362 3363 3364 3365 3366 3367 3368 3369
Handle<String> String::Flatten(Handle<String> string, PretenureFlag pretenure) {
  if (!string->IsConsString()) return string;
  Handle<ConsString> cons = Handle<ConsString>::cast(string);
  if (cons->IsFlat()) return handle(cons->first());
  return SlowFlatten(cons, pretenure);
}


3370 3371 3372
uint16_t String::Get(int index) {
  ASSERT(index >= 0 && index < length());
  switch (StringShape(this).full_representation_tag()) {
3373
    case kSeqStringTag | kOneByteStringTag:
3374
      return SeqOneByteString::cast(this)->SeqOneByteStringGet(index);
3375 3376
    case kSeqStringTag | kTwoByteStringTag:
      return SeqTwoByteString::cast(this)->SeqTwoByteStringGet(index);
3377
    case kConsStringTag | kOneByteStringTag:
3378
    case kConsStringTag | kTwoByteStringTag:
3379
      return ConsString::cast(this)->ConsStringGet(index);
3380
    case kExternalStringTag | kOneByteStringTag:
3381 3382 3383
      return ExternalAsciiString::cast(this)->ExternalAsciiStringGet(index);
    case kExternalStringTag | kTwoByteStringTag:
      return ExternalTwoByteString::cast(this)->ExternalTwoByteStringGet(index);
3384
    case kSlicedStringTag | kOneByteStringTag:
3385 3386
    case kSlicedStringTag | kTwoByteStringTag:
      return SlicedString::cast(this)->SlicedStringGet(index);
3387 3388 3389 3390 3391 3392 3393 3394 3395
    default:
      break;
  }

  UNREACHABLE();
  return 0;
}


3396 3397 3398
void String::Set(int index, uint16_t value) {
  ASSERT(index >= 0 && index < length());
  ASSERT(StringShape(this).IsSequential());
3399

3400
  return this->IsOneByteRepresentation()
3401
      ? SeqOneByteString::cast(this)->SeqOneByteStringSet(index, value)
3402
      : SeqTwoByteString::cast(this)->SeqTwoByteStringSet(index, value);
3403 3404 3405
}


3406
bool String::IsFlat() {
3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419
  if (!StringShape(this).IsCons()) return true;
  return ConsString::cast(this)->second()->length() == 0;
}


String* String::GetUnderlying() {
  // Giving direct access to underlying string only makes sense if the
  // wrapping string is already flattened.
  ASSERT(this->IsFlat());
  ASSERT(StringShape(this).IsIndirect());
  STATIC_ASSERT(ConsString::kFirstOffset == SlicedString::kParentOffset);
  const int kUnderlyingOffset = SlicedString::kParentOffset;
  return String::cast(READ_FIELD(this, kUnderlyingOffset));
3420 3421 3422
}


3423 3424 3425 3426 3427 3428
template<class Visitor>
ConsString* String::VisitFlat(Visitor* visitor,
                              String* string,
                              const int offset) {
  int slice_offset = offset;
  const int length = string->length();
3429 3430
  ASSERT(offset <= length);
  while (true) {
3431
    int32_t type = string->map()->instance_type();
3432 3433
    switch (type & (kStringRepresentationMask | kStringEncodingMask)) {
      case kSeqStringTag | kOneByteStringTag:
3434
        visitor->VisitOneByteString(
3435 3436
            SeqOneByteString::cast(string)->GetChars() + slice_offset,
            length - offset);
3437
        return NULL;
3438 3439

      case kSeqStringTag | kTwoByteStringTag:
3440
        visitor->VisitTwoByteString(
3441 3442
            SeqTwoByteString::cast(string)->GetChars() + slice_offset,
            length - offset);
3443
        return NULL;
3444 3445

      case kExternalStringTag | kOneByteStringTag:
3446
        visitor->VisitOneByteString(
3447 3448
            ExternalAsciiString::cast(string)->GetChars() + slice_offset,
            length - offset);
3449
        return NULL;
3450 3451

      case kExternalStringTag | kTwoByteStringTag:
3452
        visitor->VisitTwoByteString(
3453 3454
            ExternalTwoByteString::cast(string)->GetChars() + slice_offset,
            length - offset);
3455
        return NULL;
3456 3457 3458 3459

      case kSlicedStringTag | kOneByteStringTag:
      case kSlicedStringTag | kTwoByteStringTag: {
        SlicedString* slicedString = SlicedString::cast(string);
3460
        slice_offset += slicedString->offset();
3461 3462 3463 3464 3465 3466
        string = slicedString->parent();
        continue;
      }

      case kConsStringTag | kOneByteStringTag:
      case kConsStringTag | kTwoByteStringTag:
3467
        return ConsString::cast(string);
3468 3469 3470

      default:
        UNREACHABLE();
3471
        return NULL;
3472 3473 3474 3475 3476
    }
  }
}


3477
uint16_t SeqOneByteString::SeqOneByteStringGet(int index) {
3478 3479 3480 3481 3482
  ASSERT(index >= 0 && index < length());
  return READ_BYTE_FIELD(this, kHeaderSize + index * kCharSize);
}


3483
void SeqOneByteString::SeqOneByteStringSet(int index, uint16_t value) {
3484
  ASSERT(index >= 0 && index < length() && value <= kMaxOneByteCharCode);
3485 3486 3487 3488 3489
  WRITE_BYTE_FIELD(this, kHeaderSize + index * kCharSize,
                   static_cast<byte>(value));
}


3490
Address SeqOneByteString::GetCharsAddress() {
3491 3492 3493 3494
  return FIELD_ADDR(this, kHeaderSize);
}


3495
uint8_t* SeqOneByteString::GetChars() {
3496 3497 3498 3499
  return reinterpret_cast<uint8_t*>(GetCharsAddress());
}


3500
Address SeqTwoByteString::GetCharsAddress() {
3501 3502 3503 3504
  return FIELD_ADDR(this, kHeaderSize);
}


3505 3506 3507 3508 3509
uc16* SeqTwoByteString::GetChars() {
  return reinterpret_cast<uc16*>(FIELD_ADDR(this, kHeaderSize));
}


3510
uint16_t SeqTwoByteString::SeqTwoByteStringGet(int index) {
3511 3512 3513 3514 3515
  ASSERT(index >= 0 && index < length());
  return READ_SHORT_FIELD(this, kHeaderSize + index * kShortSize);
}


3516
void SeqTwoByteString::SeqTwoByteStringSet(int index, uint16_t value) {
3517 3518 3519 3520 3521
  ASSERT(index >= 0 && index < length());
  WRITE_SHORT_FIELD(this, kHeaderSize + index * kShortSize, value);
}


3522
int SeqTwoByteString::SeqTwoByteStringSize(InstanceType instance_type) {
3523
  return SizeFor(length());
3524 3525 3526
}


3527
int SeqOneByteString::SeqOneByteStringSize(InstanceType instance_type) {
3528
  return SizeFor(length());
3529 3530 3531
}


3532 3533 3534 3535 3536
String* SlicedString::parent() {
  return String::cast(READ_FIELD(this, kParentOffset));
}


3537
void SlicedString::set_parent(String* parent, WriteBarrierMode mode) {
3538
  ASSERT(parent->IsSeqString() || parent->IsExternalString());
3539
  WRITE_FIELD(this, kParentOffset, parent);
3540
  CONDITIONAL_WRITE_BARRIER(GetHeap(), this, kParentOffset, parent, mode);
3541 3542 3543 3544 3545 3546
}


SMI_ACCESSORS(SlicedString, offset, kOffsetOffset)


3547 3548 3549 3550 3551 3552
String* ConsString::first() {
  return String::cast(READ_FIELD(this, kFirstOffset));
}


Object* ConsString::unchecked_first() {
3553 3554 3555 3556
  return READ_FIELD(this, kFirstOffset);
}


3557
void ConsString::set_first(String* value, WriteBarrierMode mode) {
3558
  WRITE_FIELD(this, kFirstOffset, value);
3559
  CONDITIONAL_WRITE_BARRIER(GetHeap(), this, kFirstOffset, value, mode);
3560 3561 3562
}


3563 3564 3565 3566 3567 3568
String* ConsString::second() {
  return String::cast(READ_FIELD(this, kSecondOffset));
}


Object* ConsString::unchecked_second() {
3569 3570 3571 3572
  return READ_FIELD(this, kSecondOffset);
}


3573
void ConsString::set_second(String* value, WriteBarrierMode mode) {
3574
  WRITE_FIELD(this, kSecondOffset, value);
3575
  CONDITIONAL_WRITE_BARRIER(GetHeap(), this, kSecondOffset, value, mode);
3576 3577 3578
}


3579 3580 3581
bool ExternalString::is_short() {
  InstanceType type = map()->instance_type();
  return (type & kShortExternalStringMask) == kShortExternalStringTag;
3582 3583 3584
}


3585
const ExternalAsciiString::Resource* ExternalAsciiString::resource() {
3586 3587 3588 3589
  return *reinterpret_cast<Resource**>(FIELD_ADDR(this, kResourceOffset));
}


3590 3591 3592 3593 3594 3595 3596 3597
void ExternalAsciiString::update_data_cache() {
  if (is_short()) return;
  const char** data_field =
      reinterpret_cast<const char**>(FIELD_ADDR(this, kResourceDataOffset));
  *data_field = resource()->data();
}


3598
void ExternalAsciiString::set_resource(
3599
    const ExternalAsciiString::Resource* resource) {
3600
  ASSERT(IsAligned(reinterpret_cast<intptr_t>(resource), kPointerSize));
3601 3602
  *reinterpret_cast<const Resource**>(
      FIELD_ADDR(this, kResourceOffset)) = resource;
3603
  if (resource != NULL) update_data_cache();
3604 3605 3606
}


3607 3608
const uint8_t* ExternalAsciiString::GetChars() {
  return reinterpret_cast<const uint8_t*>(resource()->data());
3609 3610 3611 3612 3613 3614
}


uint16_t ExternalAsciiString::ExternalAsciiStringGet(int index) {
  ASSERT(index >= 0 && index < length());
  return GetChars()[index];
3615 3616 3617
}


3618
const ExternalTwoByteString::Resource* ExternalTwoByteString::resource() {
3619 3620 3621 3622
  return *reinterpret_cast<Resource**>(FIELD_ADDR(this, kResourceOffset));
}


3623 3624 3625 3626 3627 3628 3629 3630
void ExternalTwoByteString::update_data_cache() {
  if (is_short()) return;
  const uint16_t** data_field =
      reinterpret_cast<const uint16_t**>(FIELD_ADDR(this, kResourceDataOffset));
  *data_field = resource()->data();
}


3631
void ExternalTwoByteString::set_resource(
3632 3633 3634
    const ExternalTwoByteString::Resource* resource) {
  *reinterpret_cast<const Resource**>(
      FIELD_ADDR(this, kResourceOffset)) = resource;
3635
  if (resource != NULL) update_data_cache();
3636 3637 3638 3639
}


const uint16_t* ExternalTwoByteString::GetChars() {
3640
  return resource()->data();
3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652
}


uint16_t ExternalTwoByteString::ExternalTwoByteStringGet(int index) {
  ASSERT(index >= 0 && index < length());
  return GetChars()[index];
}


const uint16_t* ExternalTwoByteString::ExternalTwoByteStringGetData(
      unsigned start) {
  return GetChars() + start;
3653 3654 3655
}


3656
int ConsStringIteratorOp::OffsetForDepth(int depth) {
3657 3658 3659 3660 3661 3662 3663 3664 3665
  return depth & kDepthMask;
}


void ConsStringIteratorOp::PushLeft(ConsString* string) {
  frames_[depth_++ & kDepthMask] = string;
}


3666 3667
void ConsStringIteratorOp::PushRight(ConsString* string) {
  // Inplace update.
3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684
  frames_[(depth_-1) & kDepthMask] = string;
}


void ConsStringIteratorOp::AdjustMaximumDepth() {
  if (depth_ > maximum_depth_) maximum_depth_ = depth_;
}


void ConsStringIteratorOp::Pop() {
  ASSERT(depth_ > 0);
  ASSERT(depth_ <= maximum_depth_);
  depth_--;
}


uint16_t StringCharacterStream::GetNext() {
3685 3686 3687 3688
  ASSERT(buffer8_ != NULL && end_ != NULL);
  // Advance cursor if needed.
  if (buffer8_ == end_) HasMore();
  ASSERT(buffer8_ < end_);
3689 3690 3691 3692
  return is_one_byte_ ? *buffer8_++ : *buffer16_++;
}


3693 3694
StringCharacterStream::StringCharacterStream(String* string,
                                             ConsStringIteratorOp* op,
3695
                                             int offset)
3696
  : is_one_byte_(false),
3697
    op_(op) {
3698 3699 3700 3701
  Reset(string, offset);
}


3702
void StringCharacterStream::Reset(String* string, int offset) {
3703 3704
  buffer8_ = NULL;
  end_ = NULL;
3705 3706 3707 3708 3709 3710
  ConsString* cons_string = String::VisitFlat(this, string, offset);
  op_->Reset(cons_string, offset);
  if (cons_string != NULL) {
    string = op_->Next(&offset);
    if (string != NULL) String::VisitFlat(this, string, offset);
  }
3711 3712 3713 3714 3715
}


bool StringCharacterStream::HasMore() {
  if (buffer8_ != end_) return true;
3716 3717 3718
  int offset;
  String* string = op_->Next(&offset);
  ASSERT_EQ(offset, 0);
3719
  if (string == NULL) return false;
3720
  String::VisitFlat(this, string);
3721
  ASSERT(buffer8_ != end_);
3722 3723 3724 3725 3726
  return true;
}


void StringCharacterStream::VisitOneByteString(
3727
    const uint8_t* chars, int length) {
3728 3729 3730 3731 3732 3733 3734
  is_one_byte_ = true;
  buffer8_ = chars;
  end_ = chars + length;
}


void StringCharacterStream::VisitTwoByteString(
3735
    const uint16_t* chars, int length) {
3736 3737 3738 3739 3740 3741
  is_one_byte_ = false;
  buffer16_ = chars;
  end_ = reinterpret_cast<const uint8_t*>(chars + length);
}


3742
void JSFunctionResultCache::MakeZeroSize() {
3743 3744
  set_finger_index(kEntriesIndex);
  set_size(kEntriesIndex);
3745 3746 3747 3748
}


void JSFunctionResultCache::Clear() {
3749
  int cache_size = size();
3750
  Object** entries_start = RawFieldOfElementAt(kEntriesIndex);
3751
  MemsetPointer(entries_start,
3752
                GetHeap()->the_hole_value(),
3753
                cache_size - kEntriesIndex);
3754 3755 3756 3757
  MakeZeroSize();
}


3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777
int JSFunctionResultCache::size() {
  return Smi::cast(get(kCacheSizeIndex))->value();
}


void JSFunctionResultCache::set_size(int size) {
  set(kCacheSizeIndex, Smi::FromInt(size));
}


int JSFunctionResultCache::finger_index() {
  return Smi::cast(get(kFingerIndex))->value();
}


void JSFunctionResultCache::set_finger_index(int finger_index) {
  set(kFingerIndex, Smi::FromInt(finger_index));
}


3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806
byte ByteArray::get(int index) {
  ASSERT(index >= 0 && index < this->length());
  return READ_BYTE_FIELD(this, kHeaderSize + index * kCharSize);
}


void ByteArray::set(int index, byte value) {
  ASSERT(index >= 0 && index < this->length());
  WRITE_BYTE_FIELD(this, kHeaderSize + index * kCharSize, value);
}


int ByteArray::get_int(int index) {
  ASSERT(index >= 0 && (index * kIntSize) < this->length());
  return READ_INT_FIELD(this, kHeaderSize + index * kIntSize);
}


ByteArray* ByteArray::FromDataStartAddress(Address address) {
  ASSERT_TAG_ALIGNED(address);
  return reinterpret_cast<ByteArray*>(address - kHeaderSize + kHeapObjectTag);
}


Address ByteArray::GetDataStartAddress() {
  return reinterpret_cast<Address>(this) - kHeapObjectTag + kHeaderSize;
}


3807
uint8_t* ExternalUint8ClampedArray::external_uint8_clamped_pointer() {
3808
  return reinterpret_cast<uint8_t*>(external_pointer());
3809 3810 3811
}


3812
uint8_t ExternalUint8ClampedArray::get_scalar(int index) {
3813
  ASSERT((index >= 0) && (index < this->length()));
3814
  uint8_t* ptr = external_uint8_clamped_pointer();
3815 3816 3817 3818
  return ptr[index];
}


3819 3820 3821
Handle<Object> ExternalUint8ClampedArray::get(
    Handle<ExternalUint8ClampedArray> array,
    int index) {
3822 3823
  return Handle<Smi>(Smi::FromInt(array->get_scalar(index)),
                     array->GetIsolate());
3824 3825 3826
}


3827
void ExternalUint8ClampedArray::set(int index, uint8_t value) {
3828
  ASSERT((index >= 0) && (index < this->length()));
3829
  uint8_t* ptr = external_uint8_clamped_pointer();
3830 3831 3832 3833
  ptr[index] = value;
}


3834
void* ExternalArray::external_pointer() const {
3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845
  intptr_t ptr = READ_INTPTR_FIELD(this, kExternalPointerOffset);
  return reinterpret_cast<void*>(ptr);
}


void ExternalArray::set_external_pointer(void* value, WriteBarrierMode mode) {
  intptr_t ptr = reinterpret_cast<intptr_t>(value);
  WRITE_INTPTR_FIELD(this, kExternalPointerOffset, ptr);
}


3846
int8_t ExternalInt8Array::get_scalar(int index) {
3847 3848 3849 3850 3851 3852
  ASSERT((index >= 0) && (index < this->length()));
  int8_t* ptr = static_cast<int8_t*>(external_pointer());
  return ptr[index];
}


3853 3854
Handle<Object> ExternalInt8Array::get(Handle<ExternalInt8Array> array,
                                      int index) {
3855 3856
  return Handle<Smi>(Smi::FromInt(array->get_scalar(index)),
                     array->GetIsolate());
3857 3858 3859
}


3860
void ExternalInt8Array::set(int index, int8_t value) {
3861 3862 3863 3864 3865 3866
  ASSERT((index >= 0) && (index < this->length()));
  int8_t* ptr = static_cast<int8_t*>(external_pointer());
  ptr[index] = value;
}


3867
uint8_t ExternalUint8Array::get_scalar(int index) {
3868 3869 3870 3871 3872 3873
  ASSERT((index >= 0) && (index < this->length()));
  uint8_t* ptr = static_cast<uint8_t*>(external_pointer());
  return ptr[index];
}


3874 3875
Handle<Object> ExternalUint8Array::get(Handle<ExternalUint8Array> array,
                                       int index) {
3876 3877
  return Handle<Smi>(Smi::FromInt(array->get_scalar(index)),
                     array->GetIsolate());
3878 3879 3880
}


3881
void ExternalUint8Array::set(int index, uint8_t value) {
3882 3883 3884 3885 3886 3887
  ASSERT((index >= 0) && (index < this->length()));
  uint8_t* ptr = static_cast<uint8_t*>(external_pointer());
  ptr[index] = value;
}


3888
int16_t ExternalInt16Array::get_scalar(int index) {
3889 3890 3891 3892 3893 3894
  ASSERT((index >= 0) && (index < this->length()));
  int16_t* ptr = static_cast<int16_t*>(external_pointer());
  return ptr[index];
}


3895 3896
Handle<Object> ExternalInt16Array::get(Handle<ExternalInt16Array> array,
                                       int index) {
3897 3898
  return Handle<Smi>(Smi::FromInt(array->get_scalar(index)),
                     array->GetIsolate());
3899 3900 3901
}


3902
void ExternalInt16Array::set(int index, int16_t value) {
3903 3904 3905 3906 3907 3908
  ASSERT((index >= 0) && (index < this->length()));
  int16_t* ptr = static_cast<int16_t*>(external_pointer());
  ptr[index] = value;
}


3909
uint16_t ExternalUint16Array::get_scalar(int index) {
3910 3911 3912 3913 3914 3915
  ASSERT((index >= 0) && (index < this->length()));
  uint16_t* ptr = static_cast<uint16_t*>(external_pointer());
  return ptr[index];
}


3916 3917
Handle<Object> ExternalUint16Array::get(Handle<ExternalUint16Array> array,
                                        int index) {
3918 3919
  return Handle<Smi>(Smi::FromInt(array->get_scalar(index)),
                     array->GetIsolate());
3920 3921 3922
}


3923
void ExternalUint16Array::set(int index, uint16_t value) {
3924 3925 3926 3927 3928 3929
  ASSERT((index >= 0) && (index < this->length()));
  uint16_t* ptr = static_cast<uint16_t*>(external_pointer());
  ptr[index] = value;
}


3930
int32_t ExternalInt32Array::get_scalar(int index) {
3931 3932 3933 3934 3935 3936
  ASSERT((index >= 0) && (index < this->length()));
  int32_t* ptr = static_cast<int32_t*>(external_pointer());
  return ptr[index];
}


3937 3938 3939 3940
Handle<Object> ExternalInt32Array::get(Handle<ExternalInt32Array> array,
                                       int index) {
  return array->GetIsolate()->factory()->
      NewNumberFromInt(array->get_scalar(index));
3941 3942 3943
}


3944
void ExternalInt32Array::set(int index, int32_t value) {
3945 3946 3947 3948 3949 3950
  ASSERT((index >= 0) && (index < this->length()));
  int32_t* ptr = static_cast<int32_t*>(external_pointer());
  ptr[index] = value;
}


3951
uint32_t ExternalUint32Array::get_scalar(int index) {
3952 3953 3954 3955 3956 3957
  ASSERT((index >= 0) && (index < this->length()));
  uint32_t* ptr = static_cast<uint32_t*>(external_pointer());
  return ptr[index];
}


3958 3959 3960 3961
Handle<Object> ExternalUint32Array::get(Handle<ExternalUint32Array> array,
                                        int index) {
  return array->GetIsolate()->factory()->
      NewNumberFromUint(array->get_scalar(index));
3962 3963 3964
}


3965
void ExternalUint32Array::set(int index, uint32_t value) {
3966 3967 3968 3969 3970 3971
  ASSERT((index >= 0) && (index < this->length()));
  uint32_t* ptr = static_cast<uint32_t*>(external_pointer());
  ptr[index] = value;
}


3972
float ExternalFloat32Array::get_scalar(int index) {
3973 3974 3975 3976 3977 3978
  ASSERT((index >= 0) && (index < this->length()));
  float* ptr = static_cast<float*>(external_pointer());
  return ptr[index];
}


3979 3980 3981
Handle<Object> ExternalFloat32Array::get(Handle<ExternalFloat32Array> array,
                                         int index) {
  return array->GetIsolate()->factory()->NewNumber(array->get_scalar(index));
3982 3983 3984
}


3985
void ExternalFloat32Array::set(int index, float value) {
3986 3987 3988 3989 3990
  ASSERT((index >= 0) && (index < this->length()));
  float* ptr = static_cast<float*>(external_pointer());
  ptr[index] = value;
}

3991

3992
double ExternalFloat64Array::get_scalar(int index) {
3993 3994 3995 3996 3997 3998
  ASSERT((index >= 0) && (index < this->length()));
  double* ptr = static_cast<double*>(external_pointer());
  return ptr[index];
}


3999 4000 4001 4002 4003 4004
Handle<Object> ExternalFloat64Array::get(Handle<ExternalFloat64Array> array,
                                         int index) {
  return array->GetIsolate()->factory()->NewNumber(array->get_scalar(index));
}


4005
void ExternalFloat64Array::set(int index, double value) {
4006 4007 4008 4009 4010 4011
  ASSERT((index >= 0) && (index < this->length()));
  double* ptr = static_cast<double*>(external_pointer());
  ptr[index] = value;
}


4012 4013 4014 4015 4016
void* FixedTypedArrayBase::DataPtr() {
  return FIELD_ADDR(this, kDataOffset);
}


yangguo@chromium.org's avatar
yangguo@chromium.org committed
4017
int FixedTypedArrayBase::DataSize(InstanceType type) {
4018
  int element_size;
yangguo@chromium.org's avatar
yangguo@chromium.org committed
4019
  switch (type) {
4020 4021 4022
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size)                       \
    case FIXED_##TYPE##_ARRAY_TYPE:                                           \
      element_size = size;                                                    \
4023
      break;
4024 4025 4026

    TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
4027 4028 4029 4030
    default:
      UNREACHABLE();
      return 0;
  }
4031 4032 4033 4034
  return length() * element_size;
}


yangguo@chromium.org's avatar
yangguo@chromium.org committed
4035 4036 4037 4038 4039
int FixedTypedArrayBase::DataSize() {
  return DataSize(map()->instance_type());
}


4040 4041 4042 4043 4044
int FixedTypedArrayBase::size() {
  return OBJECT_POINTER_ALIGN(kDataOffset + DataSize());
}


yangguo@chromium.org's avatar
yangguo@chromium.org committed
4045 4046 4047 4048 4049
int FixedTypedArrayBase::TypedArraySize(InstanceType type) {
  return OBJECT_POINTER_ALIGN(kDataOffset + DataSize(type));
}


4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071
uint8_t Uint8ArrayTraits::defaultValue() { return 0; }


uint8_t Uint8ClampedArrayTraits::defaultValue() { return 0; }


int8_t Int8ArrayTraits::defaultValue() { return 0; }


uint16_t Uint16ArrayTraits::defaultValue() { return 0; }


int16_t Int16ArrayTraits::defaultValue() { return 0; }


uint32_t Uint32ArrayTraits::defaultValue() { return 0; }


int32_t Int32ArrayTraits::defaultValue() { return 0; }


float Float32ArrayTraits::defaultValue() {
4072
  return static_cast<float>(base::OS::nan_value());
4073 4074 4075
}


4076
double Float64ArrayTraits::defaultValue() { return base::OS::nan_value(); }
4077 4078


4079 4080 4081 4082 4083 4084 4085 4086
template <class Traits>
typename Traits::ElementType FixedTypedArray<Traits>::get_scalar(int index) {
  ASSERT((index >= 0) && (index < this->length()));
  ElementType* ptr = reinterpret_cast<ElementType*>(
      FIELD_ADDR(this, kDataOffset));
  return ptr[index];
}

4087 4088 4089 4090 4091 4092 4093 4094 4095

template<> inline
FixedTypedArray<Float64ArrayTraits>::ElementType
    FixedTypedArray<Float64ArrayTraits>::get_scalar(int index) {
  ASSERT((index >= 0) && (index < this->length()));
  return READ_DOUBLE_FIELD(this, ElementOffset(index));
}


4096 4097 4098 4099 4100 4101 4102 4103 4104
template <class Traits>
void FixedTypedArray<Traits>::set(int index, ElementType value) {
  ASSERT((index >= 0) && (index < this->length()));
  ElementType* ptr = reinterpret_cast<ElementType*>(
      FIELD_ADDR(this, kDataOffset));
  ptr[index] = value;
}


4105 4106 4107 4108 4109 4110 4111 4112
template<> inline
void FixedTypedArray<Float64ArrayTraits>::set(
    int index, Float64ArrayTraits::ElementType value) {
  ASSERT((index >= 0) && (index < this->length()));
  WRITE_DOUBLE_FIELD(this, ElementOffset(index), value);
}


4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153
template <class Traits>
typename Traits::ElementType FixedTypedArray<Traits>::from_int(int value) {
  return static_cast<ElementType>(value);
}


template <> inline
uint8_t FixedTypedArray<Uint8ClampedArrayTraits>::from_int(int value) {
  if (value < 0) return 0;
  if (value > 0xFF) return 0xFF;
  return static_cast<uint8_t>(value);
}


template <class Traits>
typename Traits::ElementType FixedTypedArray<Traits>::from_double(
    double value) {
  return static_cast<ElementType>(DoubleToInt32(value));
}


template<> inline
uint8_t FixedTypedArray<Uint8ClampedArrayTraits>::from_double(double value) {
  if (value < 0) return 0;
  if (value > 0xFF) return 0xFF;
  return static_cast<uint8_t>(lrint(value));
}


template<> inline
float FixedTypedArray<Float32ArrayTraits>::from_double(double value) {
  return static_cast<float>(value);
}


template<> inline
double FixedTypedArray<Float64ArrayTraits>::from_double(double value) {
  return value;
}


4154 4155 4156 4157 4158 4159 4160
template <class Traits>
Handle<Object> FixedTypedArray<Traits>::get(
    Handle<FixedTypedArray<Traits> > array,
    int index) {
  return Traits::ToHandle(array->GetIsolate(), array->get_scalar(index));
}

4161

4162
template <class Traits>
4163 4164 4165 4166
Handle<Object> FixedTypedArray<Traits>::SetValue(
    Handle<FixedTypedArray<Traits> > array,
    uint32_t index,
    Handle<Object> value) {
4167
  ElementType cast_value = Traits::defaultValue();
4168
  if (index < static_cast<uint32_t>(array->length())) {
4169
    if (value->IsSmi()) {
4170
      int int_value = Handle<Smi>::cast(value)->value();
4171
      cast_value = from_int(int_value);
4172
    } else if (value->IsHeapNumber()) {
4173
      double double_value = Handle<HeapNumber>::cast(value)->value();
4174
      cast_value = from_double(double_value);
4175 4176 4177 4178 4179
    } else {
      // Clamp undefined to the default value. All other types have been
      // converted to a number type further up in the call chain.
      ASSERT(value->IsUndefined());
    }
4180
    array->set(index, cast_value);
4181
  }
4182
  return Traits::ToHandle(array->GetIsolate(), cast_value);
4183 4184 4185
}


4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231
Handle<Object> Uint8ArrayTraits::ToHandle(Isolate* isolate, uint8_t scalar) {
  return handle(Smi::FromInt(scalar), isolate);
}


Handle<Object> Uint8ClampedArrayTraits::ToHandle(Isolate* isolate,
                                                 uint8_t scalar) {
  return handle(Smi::FromInt(scalar), isolate);
}


Handle<Object> Int8ArrayTraits::ToHandle(Isolate* isolate, int8_t scalar) {
  return handle(Smi::FromInt(scalar), isolate);
}


Handle<Object> Uint16ArrayTraits::ToHandle(Isolate* isolate, uint16_t scalar) {
  return handle(Smi::FromInt(scalar), isolate);
}


Handle<Object> Int16ArrayTraits::ToHandle(Isolate* isolate, int16_t scalar) {
  return handle(Smi::FromInt(scalar), isolate);
}


Handle<Object> Uint32ArrayTraits::ToHandle(Isolate* isolate, uint32_t scalar) {
  return isolate->factory()->NewNumberFromUint(scalar);
}


Handle<Object> Int32ArrayTraits::ToHandle(Isolate* isolate, int32_t scalar) {
  return isolate->factory()->NewNumberFromInt(scalar);
}


Handle<Object> Float32ArrayTraits::ToHandle(Isolate* isolate, float scalar) {
  return isolate->factory()->NewNumber(scalar);
}


Handle<Object> Float64ArrayTraits::ToHandle(Isolate* isolate, double scalar) {
  return isolate->factory()->NewNumber(scalar);
}


4232 4233 4234 4235 4236 4237 4238 4239 4240 4241
int Map::visitor_id() {
  return READ_BYTE_FIELD(this, kVisitorIdOffset);
}


void Map::set_visitor_id(int id) {
  ASSERT(0 <= id && id < 256);
  WRITE_BYTE_FIELD(this, kVisitorIdOffset, static_cast<byte>(id));
}

4242

4243
int Map::instance_size() {
4244 4245
  return NOBARRIER_READ_BYTE_FIELD(
      this, kInstanceSizeOffset) << kPointerSizeLog2;
4246 4247 4248 4249 4250
}


int Map::inobject_properties() {
  return READ_BYTE_FIELD(this, kInObjectPropertiesOffset);
4251 4252 4253
}


4254 4255 4256 4257 4258
int Map::pre_allocated_property_fields() {
  return READ_BYTE_FIELD(this, kPreAllocatedPropertyFieldsOffset);
}


4259 4260 4261
int Map::GetInObjectPropertyOffset(int index) {
  // Adjust for the number of properties stored in the object.
  index -= inobject_properties();
4262
  ASSERT(index <= 0);
4263 4264 4265 4266
  return instance_size() + (index * kPointerSize);
}


4267
int HeapObject::SizeFromMap(Map* map) {
4268 4269
  int instance_size = map->instance_size();
  if (instance_size != kVariableSizeSentinel) return instance_size;
4270
  // Only inline the most frequent cases.
yangguo@chromium.org's avatar
yangguo@chromium.org committed
4271
  InstanceType instance_type = map->instance_type();
4272
  if (instance_type == FIXED_ARRAY_TYPE) {
4273
    return FixedArray::BodyDescriptor::SizeOf(map, this);
4274
  }
4275 4276
  if (instance_type == ASCII_STRING_TYPE ||
      instance_type == ASCII_INTERNALIZED_STRING_TYPE) {
4277 4278
    return SeqOneByteString::SizeFor(
        reinterpret_cast<SeqOneByteString*>(this)->length());
4279
  }
4280 4281 4282
  if (instance_type == BYTE_ARRAY_TYPE) {
    return reinterpret_cast<ByteArray*>(this)->ByteArraySize();
  }
4283
  if (instance_type == FREE_SPACE_TYPE) {
4284
    return reinterpret_cast<FreeSpace*>(this)->nobarrier_size();
4285
  }
4286 4287
  if (instance_type == STRING_TYPE ||
      instance_type == INTERNALIZED_STRING_TYPE) {
4288 4289 4290
    return SeqTwoByteString::SizeFor(
        reinterpret_cast<SeqTwoByteString*>(this)->length());
  }
4291 4292 4293 4294
  if (instance_type == FIXED_DOUBLE_ARRAY_TYPE) {
    return FixedDoubleArray::SizeFor(
        reinterpret_cast<FixedDoubleArray*>(this)->length());
  }
4295
  if (instance_type == CONSTANT_POOL_ARRAY_TYPE) {
4296
    return reinterpret_cast<ConstantPoolArray*>(this)->size();
4297
  }
4298 4299
  if (instance_type >= FIRST_FIXED_TYPED_ARRAY_TYPE &&
      instance_type <= LAST_FIXED_TYPED_ARRAY_TYPE) {
yangguo@chromium.org's avatar
yangguo@chromium.org committed
4300 4301
    return reinterpret_cast<FixedTypedArrayBase*>(
        this)->TypedArraySize(instance_type);
4302
  }
4303 4304
  ASSERT(instance_type == CODE_TYPE);
  return reinterpret_cast<Code*>(this)->CodeSize();
4305 4306 4307 4308
}


void Map::set_instance_size(int value) {
4309
  ASSERT_EQ(0, value & (kPointerSize - 1));
4310
  value >>= kPointerSizeLog2;
4311
  ASSERT(0 <= value && value < 256);
4312 4313
  NOBARRIER_WRITE_BYTE_FIELD(
      this, kInstanceSizeOffset, static_cast<byte>(value));
4314 4315 4316
}


4317 4318 4319 4320 4321 4322
void Map::set_inobject_properties(int value) {
  ASSERT(0 <= value && value < 256);
  WRITE_BYTE_FIELD(this, kInObjectPropertiesOffset, static_cast<byte>(value));
}


4323 4324 4325 4326 4327 4328 4329 4330
void Map::set_pre_allocated_property_fields(int value) {
  ASSERT(0 <= value && value < 256);
  WRITE_BYTE_FIELD(this,
                   kPreAllocatedPropertyFieldsOffset,
                   static_cast<byte>(value));
}


4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360
InstanceType Map::instance_type() {
  return static_cast<InstanceType>(READ_BYTE_FIELD(this, kInstanceTypeOffset));
}


void Map::set_instance_type(InstanceType value) {
  WRITE_BYTE_FIELD(this, kInstanceTypeOffset, value);
}


int Map::unused_property_fields() {
  return READ_BYTE_FIELD(this, kUnusedPropertyFieldsOffset);
}


void Map::set_unused_property_fields(int value) {
  WRITE_BYTE_FIELD(this, kUnusedPropertyFieldsOffset, Min(value, 255));
}


byte Map::bit_field() {
  return READ_BYTE_FIELD(this, kBitFieldOffset);
}


void Map::set_bit_field(byte value) {
  WRITE_BYTE_FIELD(this, kBitFieldOffset, value);
}


4361 4362 4363 4364 4365 4366 4367 4368 4369 4370
byte Map::bit_field2() {
  return READ_BYTE_FIELD(this, kBitField2Offset);
}


void Map::set_bit_field2(byte value) {
  WRITE_BYTE_FIELD(this, kBitField2Offset, value);
}


4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384
void Map::set_non_instance_prototype(bool value) {
  if (value) {
    set_bit_field(bit_field() | (1 << kHasNonInstancePrototype));
  } else {
    set_bit_field(bit_field() & ~(1 << kHasNonInstancePrototype));
  }
}


bool Map::has_non_instance_prototype() {
  return ((1 << kHasNonInstancePrototype) & bit_field()) != 0;
}


4385
void Map::set_function_with_prototype(bool value) {
4386
  set_bit_field(FunctionWithPrototype::update(bit_field(), value));
4387 4388 4389 4390
}


bool Map::function_with_prototype() {
4391
  return FunctionWithPrototype::decode(bit_field());
4392 4393 4394
}


4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408
void Map::set_is_access_check_needed(bool access_check_needed) {
  if (access_check_needed) {
    set_bit_field(bit_field() | (1 << kIsAccessCheckNeeded));
  } else {
    set_bit_field(bit_field() & ~(1 << kIsAccessCheckNeeded));
  }
}


bool Map::is_access_check_needed() {
  return ((1 << kIsAccessCheckNeeded) & bit_field()) != 0;
}


4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421
void Map::set_is_extensible(bool value) {
  if (value) {
    set_bit_field2(bit_field2() | (1 << kIsExtensible));
  } else {
    set_bit_field2(bit_field2() & ~(1 << kIsExtensible));
  }
}

bool Map::is_extensible() {
  return ((1 << kIsExtensible) & bit_field2()) != 0;
}


4422
void Map::set_is_shared(bool value) {
4423
  set_bit_field3(IsShared::update(bit_field3(), value));
4424 4425
}

4426

4427
bool Map::is_shared() {
4428
  return IsShared::decode(bit_field3()); }
4429 4430


4431
void Map::set_dictionary_map(bool value) {
4432 4433 4434
  uint32_t new_bit_field3 = DictionaryMap::update(bit_field3(), value);
  new_bit_field3 = IsUnstable::update(new_bit_field3, value);
  set_bit_field3(new_bit_field3);
4435 4436 4437 4438 4439 4440 4441 4442
}


bool Map::is_dictionary_map() {
  return DictionaryMap::decode(bit_field3());
}


4443 4444 4445 4446 4447
Code::Flags Code::flags() {
  return static_cast<Flags>(READ_INT_FIELD(this, kFlagsOffset));
}


4448 4449 4450 4451 4452 4453 4454 4455 4456 4457
void Map::set_owns_descriptors(bool is_shared) {
  set_bit_field3(OwnsDescriptors::update(bit_field3(), is_shared));
}


bool Map::owns_descriptors() {
  return OwnsDescriptors::decode(bit_field3());
}


4458 4459
void Map::set_has_instance_call_handler() {
  set_bit_field3(HasInstanceCallHandler::update(bit_field3(), true));
4460 4461 4462
}


4463 4464
bool Map::has_instance_call_handler() {
  return HasInstanceCallHandler::decode(bit_field3());
4465 4466 4467
}


4468 4469 4470 4471 4472 4473 4474 4475 4476 4477
void Map::deprecate() {
  set_bit_field3(Deprecated::update(bit_field3(), true));
}


bool Map::is_deprecated() {
  return Deprecated::decode(bit_field3());
}


4478 4479 4480 4481 4482 4483 4484 4485 4486 4487
void Map::set_migration_target(bool value) {
  set_bit_field3(IsMigrationTarget::update(bit_field3(), value));
}


bool Map::is_migration_target() {
  return IsMigrationTarget::decode(bit_field3());
}


4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507
void Map::set_done_inobject_slack_tracking(bool value) {
  set_bit_field3(DoneInobjectSlackTracking::update(bit_field3(), value));
}


bool Map::done_inobject_slack_tracking() {
  return DoneInobjectSlackTracking::decode(bit_field3());
}


void Map::set_construction_count(int value) {
  set_bit_field3(ConstructionCount::update(bit_field3(), value));
}


int Map::construction_count() {
  return ConstructionCount::decode(bit_field3());
}


4508 4509 4510 4511 4512 4513 4514 4515 4516 4517
void Map::freeze() {
  set_bit_field3(IsFrozen::update(bit_field3(), true));
}


bool Map::is_frozen() {
  return IsFrozen::decode(bit_field3());
}


4518 4519 4520 4521 4522 4523 4524 4525 4526 4527
void Map::mark_unstable() {
  set_bit_field3(IsUnstable::update(bit_field3(), true));
}


bool Map::is_stable() {
  return !IsUnstable::decode(bit_field3());
}


4528 4529 4530 4531 4532
bool Map::has_code_cache() {
  return code_cache() != GetIsolate()->heap()->empty_fixed_array();
}


4533 4534 4535 4536
bool Map::CanBeDeprecated() {
  int descriptor = LastAdded();
  for (int i = 0; i <= descriptor; i++) {
    PropertyDetails details = instance_descriptors()->GetDetails(i);
4537 4538 4539 4540 4541
    if (details.representation().IsNone()) return true;
    if (details.representation().IsSmi()) return true;
    if (details.representation().IsDouble()) return true;
    if (details.representation().IsHeapObject()) return true;
    if (details.type() == CONSTANT) return true;
4542 4543 4544 4545 4546
  }
  return false;
}


4547
void Map::NotifyLeafMapLayoutChange() {
4548 4549 4550 4551 4552 4553
  if (is_stable()) {
    mark_unstable();
    dependent_code()->DeoptimizeDependentCodeGroup(
        GetIsolate(),
        DependentCode::kPrototypeCheckGroup);
  }
4554 4555 4556
}


4557
bool Map::CanOmitMapChecks() {
4558
  return is_stable() && FLAG_omit_map_checks_for_leaf_maps;
4559 4560 4561
}


4562
int DependentCode::number_of_entries(DependencyGroup group) {
4563
  if (length() == 0) return 0;
4564
  return Smi::cast(get(group))->value();
4565 4566 4567
}


4568 4569
void DependentCode::set_number_of_entries(DependencyGroup group, int value) {
  set(group, Smi::FromInt(value));
4570 4571 4572
}


4573 4574 4575 4576
bool DependentCode::is_code_at(int i) {
  return get(kCodesStartIndex + i)->IsCode();
}

4577 4578
Code* DependentCode::code_at(int i) {
  return Code::cast(get(kCodesStartIndex + i));
4579 4580 4581
}


4582 4583 4584
CompilationInfo* DependentCode::compilation_info_at(int i) {
  return reinterpret_cast<CompilationInfo*>(
      Foreign::cast(get(kCodesStartIndex + i))->foreign_address());
4585 4586 4587
}


4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598
void DependentCode::set_object_at(int i, Object* object) {
  set(kCodesStartIndex + i, object);
}


Object* DependentCode::object_at(int i) {
  return get(kCodesStartIndex + i);
}


Object** DependentCode::slot_at(int i) {
4599
  return RawFieldOfElementAt(kCodesStartIndex + i);
4600 4601 4602
}


4603
void DependentCode::clear_at(int i) {
4604 4605 4606 4607
  set_undefined(kCodesStartIndex + i);
}


4608 4609 4610 4611 4612
void DependentCode::copy(int from, int to) {
  set(kCodesStartIndex + to, get(kCodesStartIndex + from));
}


4613 4614 4615 4616
void DependentCode::ExtendGroup(DependencyGroup group) {
  GroupStartIndexes starts(this);
  for (int g = kGroupCount - 1; g > group; g--) {
    if (starts.at(g) < starts.at(g + 1)) {
4617
      copy(starts.at(g), starts.at(g + 1));
4618 4619
    }
  }
4620 4621 4622
}


4623
void Code::set_flags(Code::Flags flags) {
4624
  STATIC_ASSERT(Code::NUMBER_OF_KINDS <= KindField::kMax + 1);
4625 4626 4627 4628 4629 4630 4631 4632 4633
  WRITE_INT_FIELD(this, kFlagsOffset, flags);
}


Code::Kind Code::kind() {
  return ExtractKindFromFlags(flags());
}


4634 4635
InlineCacheState Code::ic_state() {
  InlineCacheState result = ExtractICStateFromFlags(flags());
4636 4637 4638 4639 4640
  // Only allow uninitialized or debugger states for non-IC code
  // objects. This is used in the debugger to determine whether or not
  // a call to code object has been replaced with a debug break call.
  ASSERT(is_inline_cache_stub() ||
         result == UNINITIALIZED ||
4641
         result == DEBUG_STUB);
4642 4643 4644 4645
  return result;
}


4646
ExtraICState Code::extra_ic_state() {
4647
  ASSERT(is_inline_cache_stub() || ic_state() == DEBUG_STUB);
4648
  return ExtractExtraICStateFromFlags(flags());
4649 4650 4651
}


4652
Code::StubType Code::type() {
4653 4654 4655 4656
  return ExtractTypeFromFlags(flags());
}


4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667
// For initialization.
void Code::set_raw_kind_specific_flags1(int value) {
  WRITE_INT_FIELD(this, kKindSpecificFlags1Offset, value);
}


void Code::set_raw_kind_specific_flags2(int value) {
  WRITE_INT_FIELD(this, kKindSpecificFlags2Offset, value);
}


4668 4669 4670 4671 4672 4673
inline bool Code::is_crankshafted() {
  return IsCrankshaftedField::decode(
      READ_UINT32_FIELD(this, kKindSpecificFlags2Offset));
}


4674 4675 4676 4677 4678
inline bool Code::is_hydrogen_stub() {
  return is_crankshafted() && kind() != OPTIMIZED_FUNCTION;
}


4679 4680 4681 4682 4683 4684 4685
inline void Code::set_is_crankshafted(bool value) {
  int previous = READ_UINT32_FIELD(this, kKindSpecificFlags2Offset);
  int updated = IsCrankshaftedField::update(previous, value);
  WRITE_UINT32_FIELD(this, kKindSpecificFlags2Offset, updated);
}


4686
int Code::major_key() {
4687
  ASSERT(has_major_key());
4688 4689
  return StubMajorKeyField::decode(
      READ_UINT32_FIELD(this, kKindSpecificFlags2Offset));
4690 4691 4692
}


4693
void Code::set_major_key(int major) {
4694
  ASSERT(has_major_key());
4695
  ASSERT(0 <= major && major < 256);
4696 4697 4698
  int previous = READ_UINT32_FIELD(this, kKindSpecificFlags2Offset);
  int updated = StubMajorKeyField::update(previous, major);
  WRITE_UINT32_FIELD(this, kKindSpecificFlags2Offset, updated);
4699 4700 4701
}


4702 4703 4704 4705 4706 4707 4708 4709 4710
bool Code::has_major_key() {
  return kind() == STUB ||
      kind() == HANDLER ||
      kind() == BINARY_OP_IC ||
      kind() == COMPARE_IC ||
      kind() == COMPARE_NIL_IC ||
      kind() == LOAD_IC ||
      kind() == KEYED_LOAD_IC ||
      kind() == STORE_IC ||
4711
      kind() == CALL_IC ||
4712 4713 4714 4715 4716
      kind() == KEYED_STORE_IC ||
      kind() == TO_BOOLEAN_IC;
}


4717
bool Code::optimizable() {
4718
  ASSERT_EQ(FUNCTION, kind());
4719 4720 4721 4722 4723
  return READ_BYTE_FIELD(this, kOptimizableOffset) == 1;
}


void Code::set_optimizable(bool value) {
4724
  ASSERT_EQ(FUNCTION, kind());
4725 4726 4727 4728 4729
  WRITE_BYTE_FIELD(this, kOptimizableOffset, value ? 1 : 0);
}


bool Code::has_deoptimization_support() {
4730
  ASSERT_EQ(FUNCTION, kind());
4731 4732
  byte flags = READ_BYTE_FIELD(this, kFullCodeFlags);
  return FullCodeFlagsHasDeoptimizationSupportField::decode(flags);
4733 4734 4735 4736
}


void Code::set_has_deoptimization_support(bool value) {
4737
  ASSERT_EQ(FUNCTION, kind());
4738 4739 4740 4741 4742 4743 4744
  byte flags = READ_BYTE_FIELD(this, kFullCodeFlags);
  flags = FullCodeFlagsHasDeoptimizationSupportField::update(flags, value);
  WRITE_BYTE_FIELD(this, kFullCodeFlags, flags);
}


bool Code::has_debug_break_slots() {
4745
  ASSERT_EQ(FUNCTION, kind());
4746 4747 4748 4749 4750 4751
  byte flags = READ_BYTE_FIELD(this, kFullCodeFlags);
  return FullCodeFlagsHasDebugBreakSlotsField::decode(flags);
}


void Code::set_has_debug_break_slots(bool value) {
4752
  ASSERT_EQ(FUNCTION, kind());
4753 4754 4755
  byte flags = READ_BYTE_FIELD(this, kFullCodeFlags);
  flags = FullCodeFlagsHasDebugBreakSlotsField::update(flags, value);
  WRITE_BYTE_FIELD(this, kFullCodeFlags, flags);
4756 4757 4758
}


4759
bool Code::is_compiled_optimizable() {
4760
  ASSERT_EQ(FUNCTION, kind());
4761 4762 4763 4764 4765 4766
  byte flags = READ_BYTE_FIELD(this, kFullCodeFlags);
  return FullCodeFlagsIsCompiledOptimizable::decode(flags);
}


void Code::set_compiled_optimizable(bool value) {
4767
  ASSERT_EQ(FUNCTION, kind());
4768 4769 4770 4771 4772 4773
  byte flags = READ_BYTE_FIELD(this, kFullCodeFlags);
  flags = FullCodeFlagsIsCompiledOptimizable::update(flags, value);
  WRITE_BYTE_FIELD(this, kFullCodeFlags, flags);
}


4774
int Code::allow_osr_at_loop_nesting_level() {
4775
  ASSERT_EQ(FUNCTION, kind());
4776 4777
  int fields = READ_UINT32_FIELD(this, kKindSpecificFlags2Offset);
  return AllowOSRAtLoopNestingLevelField::decode(fields);
4778 4779 4780 4781
}


void Code::set_allow_osr_at_loop_nesting_level(int level) {
4782
  ASSERT_EQ(FUNCTION, kind());
4783
  ASSERT(level >= 0 && level <= kMaxLoopNestingMarker);
4784 4785 4786
  int previous = READ_UINT32_FIELD(this, kKindSpecificFlags2Offset);
  int updated = AllowOSRAtLoopNestingLevelField::update(previous, level);
  WRITE_UINT32_FIELD(this, kKindSpecificFlags2Offset, updated);
4787 4788 4789
}


4790
int Code::profiler_ticks() {
4791
  ASSERT_EQ(FUNCTION, kind());
4792 4793 4794 4795 4796
  return READ_BYTE_FIELD(this, kProfilerTicksOffset);
}


void Code::set_profiler_ticks(int ticks) {
4797
  ASSERT_EQ(FUNCTION, kind());
4798 4799 4800 4801 4802
  ASSERT(ticks < 256);
  WRITE_BYTE_FIELD(this, kProfilerTicksOffset, ticks);
}


4803
unsigned Code::stack_slots() {
4804
  ASSERT(is_crankshafted());
4805 4806
  return StackSlotsField::decode(
      READ_UINT32_FIELD(this, kKindSpecificFlags1Offset));
4807 4808 4809 4810
}


void Code::set_stack_slots(unsigned slots) {
4811
  CHECK(slots <= (1 << kStackSlotsBitCount));
4812
  ASSERT(is_crankshafted());
4813 4814 4815
  int previous = READ_UINT32_FIELD(this, kKindSpecificFlags1Offset);
  int updated = StackSlotsField::update(previous, slots);
  WRITE_UINT32_FIELD(this, kKindSpecificFlags1Offset, updated);
4816 4817 4818
}


4819
unsigned Code::safepoint_table_offset() {
4820
  ASSERT(is_crankshafted());
4821 4822
  return SafepointTableOffsetField::decode(
      READ_UINT32_FIELD(this, kKindSpecificFlags2Offset));
4823 4824 4825
}


4826
void Code::set_safepoint_table_offset(unsigned offset) {
4827
  CHECK(offset <= (1 << kSafepointTableOffsetBitCount));
4828
  ASSERT(is_crankshafted());
4829
  ASSERT(IsAligned(offset, static_cast<unsigned>(kIntSize)));
4830 4831 4832
  int previous = READ_UINT32_FIELD(this, kKindSpecificFlags2Offset);
  int updated = SafepointTableOffsetField::update(previous, offset);
  WRITE_UINT32_FIELD(this, kKindSpecificFlags2Offset, updated);
4833 4834 4835
}


4836
unsigned Code::back_edge_table_offset() {
4837
  ASSERT_EQ(FUNCTION, kind());
4838
  return BackEdgeTableOffsetField::decode(
4839
      READ_UINT32_FIELD(this, kKindSpecificFlags2Offset)) << kPointerSizeLog2;
4840 4841 4842
}


4843
void Code::set_back_edge_table_offset(unsigned offset) {
4844
  ASSERT_EQ(FUNCTION, kind());
4845 4846
  ASSERT(IsAligned(offset, static_cast<unsigned>(kPointerSize)));
  offset = offset >> kPointerSizeLog2;
4847
  int previous = READ_UINT32_FIELD(this, kKindSpecificFlags2Offset);
4848
  int updated = BackEdgeTableOffsetField::update(previous, offset);
4849
  WRITE_UINT32_FIELD(this, kKindSpecificFlags2Offset, updated);
4850 4851 4852
}


4853
bool Code::back_edges_patched_for_osr() {
4854
  ASSERT_EQ(FUNCTION, kind());
4855
  return allow_osr_at_loop_nesting_level() > 0;
4856 4857 4858
}


4859
byte Code::to_boolean_state() {
4860
  return extra_ic_state();
4861 4862
}

4863

4864 4865
bool Code::has_function_cache() {
  ASSERT(kind() == STUB);
4866 4867
  return HasFunctionCacheField::decode(
      READ_UINT32_FIELD(this, kKindSpecificFlags1Offset));
4868 4869 4870 4871 4872
}


void Code::set_has_function_cache(bool flag) {
  ASSERT(kind() == STUB);
4873 4874 4875
  int previous = READ_UINT32_FIELD(this, kKindSpecificFlags1Offset);
  int updated = HasFunctionCacheField::update(previous, flag);
  WRITE_UINT32_FIELD(this, kKindSpecificFlags1Offset, updated);
4876 4877 4878
}


4879 4880 4881 4882 4883 4884 4885 4886 4887
bool Code::marked_for_deoptimization() {
  ASSERT(kind() == OPTIMIZED_FUNCTION);
  return MarkedForDeoptimizationField::decode(
      READ_UINT32_FIELD(this, kKindSpecificFlags1Offset));
}


void Code::set_marked_for_deoptimization(bool flag) {
  ASSERT(kind() == OPTIMIZED_FUNCTION);
4888
  ASSERT(!flag || AllowDeoptimization::IsAllowed(GetIsolate()));
4889 4890 4891 4892 4893 4894
  int previous = READ_UINT32_FIELD(this, kKindSpecificFlags1Offset);
  int updated = MarkedForDeoptimizationField::update(previous, flag);
  WRITE_UINT32_FIELD(this, kKindSpecificFlags1Offset, updated);
}


4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922
bool Code::is_weak_stub() {
  return CanBeWeakStub() && WeakStubField::decode(
      READ_UINT32_FIELD(this, kKindSpecificFlags1Offset));
}


void Code::mark_as_weak_stub() {
  ASSERT(CanBeWeakStub());
  int previous = READ_UINT32_FIELD(this, kKindSpecificFlags1Offset);
  int updated = WeakStubField::update(previous, true);
  WRITE_UINT32_FIELD(this, kKindSpecificFlags1Offset, updated);
}


bool Code::is_invalidated_weak_stub() {
  return is_weak_stub() && InvalidatedWeakStubField::decode(
      READ_UINT32_FIELD(this, kKindSpecificFlags1Offset));
}


void Code::mark_as_invalidated_weak_stub() {
  ASSERT(is_inline_cache_stub());
  int previous = READ_UINT32_FIELD(this, kKindSpecificFlags1Offset);
  int updated = InvalidatedWeakStubField::update(previous, true);
  WRITE_UINT32_FIELD(this, kKindSpecificFlags1Offset, updated);
}


4923 4924
bool Code::is_inline_cache_stub() {
  Kind kind = this->kind();
4925 4926 4927 4928 4929 4930
  switch (kind) {
#define CASE(name) case name: return true;
    IC_KIND_LIST(CASE)
#undef CASE
    default: return false;
  }
4931 4932 4933
}


4934
bool Code::is_keyed_stub() {
verwaest@chromium.org's avatar
verwaest@chromium.org committed
4935
  return is_keyed_load_stub() || is_keyed_store_stub();
4936 4937 4938
}


4939 4940
bool Code::is_debug_stub() {
  return ic_state() == DEBUG_STUB;
4941 4942 4943
}


4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955
ConstantPoolArray* Code::constant_pool() {
  return ConstantPoolArray::cast(READ_FIELD(this, kConstantPoolOffset));
}


void Code::set_constant_pool(Object* value) {
  ASSERT(value->IsConstantPoolArray());
  WRITE_FIELD(this, kConstantPoolOffset, value);
  WRITE_BARRIER(GetHeap(), this, kConstantPoolOffset, value);
}


4956
Code::Flags Code::ComputeFlags(Kind kind,
4957
                               InlineCacheState ic_state,
4958
                               ExtraICState extra_ic_state,
4959
                               StubType type,
4960
                               InlineCacheHolderFlag holder) {
4961
  // Compute the bit mask.
4962
  unsigned int bits = KindField::encode(kind)
4963 4964
      | ICStateField::encode(ic_state)
      | TypeField::encode(type)
4965
      | ExtraICStateField::encode(extra_ic_state)
4966 4967
      | CacheHolderField::encode(holder);
  return static_cast<Flags>(bits);
4968 4969 4970 4971
}


Code::Flags Code::ComputeMonomorphicFlags(Kind kind,
4972
                                          ExtraICState extra_ic_state,
4973
                                          InlineCacheHolderFlag holder,
4974 4975 4976 4977 4978 4979 4980 4981
                                          StubType type) {
  return ComputeFlags(kind, MONOMORPHIC, extra_ic_state, type, holder);
}


Code::Flags Code::ComputeHandlerFlags(Kind handler_kind,
                                      StubType type,
                                      InlineCacheHolderFlag holder) {
4982
  return ComputeFlags(Code::HANDLER, MONOMORPHIC, handler_kind, type, holder);
4983 4984 4985 4986
}


Code::Kind Code::ExtractKindFromFlags(Flags flags) {
4987
  return KindField::decode(flags);
4988 4989 4990
}


4991
InlineCacheState Code::ExtractICStateFromFlags(Flags flags) {
4992
  return ICStateField::decode(flags);
4993 4994 4995
}


4996
ExtraICState Code::ExtractExtraICStateFromFlags(Flags flags) {
4997
  return ExtraICStateField::decode(flags);
4998 4999 5000
}


5001
Code::StubType Code::ExtractTypeFromFlags(Flags flags) {
5002
  return TypeField::decode(flags);
5003 5004 5005
}


5006
InlineCacheHolderFlag Code::ExtractCacheHolderFromFlags(Flags flags) {
5007
  return CacheHolderField::decode(flags);
5008 5009 5010
}


5011
Code::Flags Code::RemoveTypeFromFlags(Flags flags) {
5012
  int bits = flags & ~TypeField::kMask;
5013 5014 5015 5016
  return static_cast<Flags>(bits);
}


5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027
Code* Code::GetCodeFromTargetAddress(Address address) {
  HeapObject* code = HeapObject::FromAddress(address - Code::kHeaderSize);
  // GetCodeFromTargetAddress might be called when marking objects during mark
  // sweep. reinterpret_cast is therefore used instead of the more appropriate
  // Code::cast. Code::cast does not work when the object's map is
  // marked.
  Code* result = reinterpret_cast<Code*>(code);
  return result;
}


5028 5029 5030 5031 5032 5033
Object* Code::GetObjectFromEntryAddress(Address location_of_address) {
  return HeapObject::
      FromAddress(Memory::Address_at(location_of_address) - Code::kHeaderSize);
}


5034
bool Code::IsWeakObjectInOptimizedCode(Object* object) {
5035
  if (!FLAG_collect_maps) return false;
5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047
  if (object->IsMap()) {
    return Map::cast(object)->CanTransition() &&
           FLAG_weak_embedded_maps_in_optimized_code;
  }
  if (object->IsJSObject() ||
      (object->IsCell() && Cell::cast(object)->value()->IsJSObject())) {
    return FLAG_weak_embedded_objects_in_optimized_code;
  }
  return false;
}


5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065
class Code::FindAndReplacePattern {
 public:
  FindAndReplacePattern() : count_(0) { }
  void Add(Handle<Map> map_to_find, Handle<Object> obj_to_replace) {
    ASSERT(count_ < kMaxCount);
    find_[count_] = map_to_find;
    replace_[count_] = obj_to_replace;
    ++count_;
  }
 private:
  static const int kMaxCount = 4;
  int count_;
  Handle<Map> find_[kMaxCount];
  Handle<Object> replace_[kMaxCount];
  friend class Code;
};


5066 5067 5068 5069 5070 5071 5072
bool Code::IsWeakObjectInIC(Object* object) {
  return object->IsMap() && Map::cast(object)->CanTransition() &&
         FLAG_collect_maps &&
         FLAG_weak_embedded_maps_in_ic;
}


5073
Object* Map::prototype() const {
5074 5075 5076 5077
  return READ_FIELD(this, kPrototypeOffset);
}


5078
void Map::set_prototype(Object* value, WriteBarrierMode mode) {
5079
  ASSERT(value->IsNull() || value->IsJSReceiver());
5080
  WRITE_FIELD(this, kPrototypeOffset, value);
5081
  CONDITIONAL_WRITE_BARRIER(GetHeap(), this, kPrototypeOffset, value, mode);
5082 5083 5084
}


5085 5086
// If the descriptor is using the empty transition array, install a new empty
// transition array that will have place for an element transition.
5087 5088
static void EnsureHasTransitionArray(Handle<Map> map) {
  Handle<TransitionArray> transitions;
5089
  if (!map->HasTransitionArray()) {
5090
    transitions = TransitionArray::Allocate(map->GetIsolate(), 0);
5091
    transitions->set_back_pointer_storage(map->GetBackPointer());
5092
  } else if (!map->transitions()->IsFullTransitionArray()) {
5093
    transitions = TransitionArray::ExtendToFullTransitionArray(map);
5094
  } else {
5095
    return;
5096
  }
5097
  map->set_transitions(*transitions);
5098
}
5099 5100


5101
void Map::InitializeDescriptors(DescriptorArray* descriptors) {
5102
  int len = descriptors->number_of_descriptors();
5103
  set_instance_descriptors(descriptors);
5104
  SetNumberOfOwnDescriptors(len);
5105 5106 5107
}


5108
ACCESSORS(Map, instance_descriptors, DescriptorArray, kDescriptorsOffset)
5109 5110 5111


void Map::set_bit_field3(uint32_t bits) {
5112 5113 5114 5115
  if (kInt32Size != kPointerSize) {
    WRITE_UINT32_FIELD(this, kBitField3Offset + kInt32Size, 0);
  }
  WRITE_UINT32_FIELD(this, kBitField3Offset, bits);
5116 5117 5118 5119
}


uint32_t Map::bit_field3() {
5120
  return READ_UINT32_FIELD(this, kBitField3Offset);
5121
}
5122 5123


5124
void Map::AppendDescriptor(Descriptor* desc) {
5125
  DescriptorArray* descriptors = instance_descriptors();
5126
  int number_of_own_descriptors = NumberOfOwnDescriptors();
5127
  ASSERT(descriptors->number_of_descriptors() == number_of_own_descriptors);
5128
  descriptors->Append(desc);
5129
  SetNumberOfOwnDescriptors(number_of_own_descriptors + 1);
5130 5131
}

5132

5133
Object* Map::GetBackPointer() {
5134
  Object* object = READ_FIELD(this, kTransitionsOrBackPointerOffset);
5135
  if (object->IsDescriptorArray()) {
5136
    return TransitionArray::cast(object)->back_pointer_storage();
5137 5138 5139 5140
  } else {
    ASSERT(object->IsMap() || object->IsUndefined());
    return object;
  }
5141 5142 5143
}


5144 5145 5146 5147 5148
bool Map::HasElementsTransition() {
  return HasTransitionArray() && transitions()->HasElementsTransition();
}


5149
bool Map::HasTransitionArray() const {
5150 5151
  Object* object = READ_FIELD(this, kTransitionsOrBackPointerOffset);
  return object->IsTransitionArray();
5152 5153 5154
}


5155
Map* Map::elements_transition_map() {
5156 5157
  int index = transitions()->Search(GetHeap()->elements_transition_symbol());
  return transitions()->GetTarget(index);
5158 5159 5160
}


5161 5162 5163 5164
bool Map::CanHaveMoreTransitions() {
  if (!HasTransitionArray()) return true;
  return FixedArray::SizeFor(transitions()->length() +
                             TransitionArray::kTransitionSize)
5165
      <= Page::kMaxRegularHeapObjectSize;
5166 5167 5168
}


5169 5170 5171 5172 5173
Map* Map::GetTransition(int transition_index) {
  return transitions()->GetTarget(transition_index);
}


5174 5175 5176 5177 5178 5179
int Map::SearchTransition(Name* name) {
  if (HasTransitionArray()) return transitions()->Search(name);
  return TransitionArray::kNotFound;
}


5180 5181 5182 5183 5184 5185 5186 5187 5188
FixedArray* Map::GetPrototypeTransitions() {
  if (!HasTransitionArray()) return GetHeap()->empty_fixed_array();
  if (!transitions()->HasPrototypeTransitions()) {
    return GetHeap()->empty_fixed_array();
  }
  return transitions()->GetPrototypeTransitions();
}


5189 5190 5191 5192
void Map::SetPrototypeTransitions(
    Handle<Map> map, Handle<FixedArray> proto_transitions) {
  EnsureHasTransitionArray(map);
  int old_number_of_transitions = map->NumberOfProtoTransitions();
5193
#ifdef DEBUG
5194 5195 5196
  if (map->HasPrototypeTransitions()) {
    ASSERT(map->GetPrototypeTransitions() != *proto_transitions);
    map->ZapPrototypeTransitions();
5197 5198
  }
#endif
5199 5200
  map->transitions()->SetPrototypeTransitions(*proto_transitions);
  map->SetNumberOfProtoTransitions(old_number_of_transitions);
5201 5202 5203 5204 5205 5206 5207 5208
}


bool Map::HasPrototypeTransitions() {
  return HasTransitionArray() && transitions()->HasPrototypeTransitions();
}


5209
TransitionArray* Map::transitions() const {
5210 5211 5212
  ASSERT(HasTransitionArray());
  Object* object = READ_FIELD(this, kTransitionsOrBackPointerOffset);
  return TransitionArray::cast(object);
5213 5214 5215
}


5216 5217
void Map::set_transitions(TransitionArray* transition_array,
                          WriteBarrierMode mode) {
5218 5219 5220 5221 5222
  // Transition arrays are not shared. When one is replaced, it should not
  // keep referenced objects alive, so we zap it.
  // When there is another reference to the array somewhere (e.g. a handle),
  // not zapping turns from a waste of memory into a source of crashes.
  if (HasTransitionArray()) {
5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233
#ifdef DEBUG
    for (int i = 0; i < transitions()->number_of_transitions(); i++) {
      Map* target = transitions()->GetTarget(i);
      if (target->instance_descriptors() == instance_descriptors()) {
        Name* key = transitions()->GetKey(i);
        int new_target_index = transition_array->Search(key);
        ASSERT(new_target_index != TransitionArray::kNotFound);
        ASSERT(transition_array->GetTarget(new_target_index) == target);
      }
    }
#endif
5234
    ASSERT(transitions() != transition_array);
5235 5236
    ZapTransitions();
  }
5237 5238 5239 5240

  WRITE_FIELD(this, kTransitionsOrBackPointerOffset, transition_array);
  CONDITIONAL_WRITE_BARRIER(
      GetHeap(), this, kTransitionsOrBackPointerOffset, transition_array, mode);
5241 5242 5243
}


5244 5245
void Map::init_back_pointer(Object* undefined) {
  ASSERT(undefined->IsUndefined());
5246
  WRITE_FIELD(this, kTransitionsOrBackPointerOffset, undefined);
5247 5248 5249
}


5250 5251 5252 5253
void Map::SetBackPointer(Object* value, WriteBarrierMode mode) {
  ASSERT(instance_type() >= FIRST_JS_RECEIVER_TYPE);
  ASSERT((value->IsUndefined() && GetBackPointer()->IsMap()) ||
         (value->IsMap() && GetBackPointer()->IsUndefined()));
5254 5255 5256
  Object* object = READ_FIELD(this, kTransitionsOrBackPointerOffset);
  if (object->IsTransitionArray()) {
    TransitionArray::cast(object)->set_back_pointer_storage(value);
5257
  } else {
5258
    WRITE_FIELD(this, kTransitionsOrBackPointerOffset, value);
5259
    CONDITIONAL_WRITE_BARRIER(
5260
        GetHeap(), this, kTransitionsOrBackPointerOffset, value, mode);
5261
  }
5262 5263 5264
}


5265
ACCESSORS(Map, code_cache, Object, kCodeCacheOffset)
5266
ACCESSORS(Map, dependent_code, DependentCode, kDependentCodeOffset)
5267 5268 5269
ACCESSORS(Map, constructor, Object, kConstructorOffset)

ACCESSORS(JSFunction, shared, SharedFunctionInfo, kSharedFunctionInfoOffset)
5270
ACCESSORS(JSFunction, literals_or_bindings, FixedArray, kLiteralsOffset)
5271
ACCESSORS(JSFunction, next_function_link, Object, kNextFunctionLinkOffset)
5272 5273

ACCESSORS(GlobalObject, builtins, JSBuiltinsObject, kBuiltinsOffset)
5274
ACCESSORS(GlobalObject, native_context, Context, kNativeContextOffset)
5275
ACCESSORS(GlobalObject, global_context, Context, kGlobalContextOffset)
5276
ACCESSORS(GlobalObject, global_proxy, JSObject, kGlobalProxyOffset)
5277

5278
ACCESSORS(JSGlobalProxy, native_context, Object, kNativeContextOffset)
5279
ACCESSORS(JSGlobalProxy, hash, Object, kHashOffset)
5280 5281

ACCESSORS(AccessorInfo, name, Object, kNameOffset)
5282
ACCESSORS_TO_SMI(AccessorInfo, flag, kFlagOffset)
5283 5284
ACCESSORS(AccessorInfo, expected_receiver_type, Object,
          kExpectedReceiverTypeOffset)
5285

5286 5287
ACCESSORS(DeclaredAccessorDescriptor, serialized_data, ByteArray,
          kSerializedDataOffset)
5288 5289 5290 5291 5292 5293 5294 5295

ACCESSORS(DeclaredAccessorInfo, descriptor, DeclaredAccessorDescriptor,
          kDescriptorOffset)

ACCESSORS(ExecutableAccessorInfo, getter, Object, kGetterOffset)
ACCESSORS(ExecutableAccessorInfo, setter, Object, kSetterOffset)
ACCESSORS(ExecutableAccessorInfo, data, Object, kDataOffset)

5296 5297
ACCESSORS(Box, value, Object, kValueOffset)

5298 5299 5300
ACCESSORS(AccessorPair, getter, Object, kGetterOffset)
ACCESSORS(AccessorPair, setter, Object, kSetterOffset)

5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316
ACCESSORS(AccessCheckInfo, named_callback, Object, kNamedCallbackOffset)
ACCESSORS(AccessCheckInfo, indexed_callback, Object, kIndexedCallbackOffset)
ACCESSORS(AccessCheckInfo, data, Object, kDataOffset)

ACCESSORS(InterceptorInfo, getter, Object, kGetterOffset)
ACCESSORS(InterceptorInfo, setter, Object, kSetterOffset)
ACCESSORS(InterceptorInfo, query, Object, kQueryOffset)
ACCESSORS(InterceptorInfo, deleter, Object, kDeleterOffset)
ACCESSORS(InterceptorInfo, enumerator, Object, kEnumeratorOffset)
ACCESSORS(InterceptorInfo, data, Object, kDataOffset)

ACCESSORS(CallHandlerInfo, callback, Object, kCallbackOffset)
ACCESSORS(CallHandlerInfo, data, Object, kDataOffset)

ACCESSORS(TemplateInfo, tag, Object, kTagOffset)
ACCESSORS(TemplateInfo, property_list, Object, kPropertyListOffset)
5317
ACCESSORS(TemplateInfo, property_accessors, Object, kPropertyAccessorsOffset)
5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335

ACCESSORS(FunctionTemplateInfo, serial_number, Object, kSerialNumberOffset)
ACCESSORS(FunctionTemplateInfo, call_code, Object, kCallCodeOffset)
ACCESSORS(FunctionTemplateInfo, prototype_template, Object,
          kPrototypeTemplateOffset)
ACCESSORS(FunctionTemplateInfo, parent_template, Object, kParentTemplateOffset)
ACCESSORS(FunctionTemplateInfo, named_property_handler, Object,
          kNamedPropertyHandlerOffset)
ACCESSORS(FunctionTemplateInfo, indexed_property_handler, Object,
          kIndexedPropertyHandlerOffset)
ACCESSORS(FunctionTemplateInfo, instance_template, Object,
          kInstanceTemplateOffset)
ACCESSORS(FunctionTemplateInfo, class_name, Object, kClassNameOffset)
ACCESSORS(FunctionTemplateInfo, signature, Object, kSignatureOffset)
ACCESSORS(FunctionTemplateInfo, instance_call_handler, Object,
          kInstanceCallHandlerOffset)
ACCESSORS(FunctionTemplateInfo, access_check_info, Object,
          kAccessCheckInfoOffset)
5336
ACCESSORS_TO_SMI(FunctionTemplateInfo, flag, kFlagOffset)
5337 5338

ACCESSORS(ObjectTemplateInfo, constructor, Object, kConstructorOffset)
5339 5340
ACCESSORS(ObjectTemplateInfo, internal_field_count, Object,
          kInternalFieldCountOffset)
5341 5342 5343 5344 5345 5346

ACCESSORS(SignatureInfo, receiver, Object, kReceiverOffset)
ACCESSORS(SignatureInfo, args, Object, kArgsOffset)

ACCESSORS(TypeSwitchInfo, types, Object, kTypesOffset)

5347
ACCESSORS(AllocationSite, transition_info, Object, kTransitionInfoOffset)
5348
ACCESSORS(AllocationSite, nested_site, Object, kNestedSiteOffset)
5349 5350 5351
ACCESSORS_TO_SMI(AllocationSite, pretenure_data, kPretenureDataOffset)
ACCESSORS_TO_SMI(AllocationSite, pretenure_create_count,
                 kPretenureCreateCountOffset)
5352 5353
ACCESSORS(AllocationSite, dependent_code, DependentCode,
          kDependentCodeOffset)
5354
ACCESSORS(AllocationSite, weak_next, Object, kWeakNextOffset)
5355
ACCESSORS(AllocationMemento, allocation_site, Object, kAllocationSiteOffset)
5356

5357 5358
ACCESSORS(Script, source, Object, kSourceOffset)
ACCESSORS(Script, name, Object, kNameOffset)
5359
ACCESSORS(Script, id, Smi, kIdOffset)
5360 5361
ACCESSORS_TO_SMI(Script, line_offset, kLineOffsetOffset)
ACCESSORS_TO_SMI(Script, column_offset, kColumnOffsetOffset)
5362
ACCESSORS(Script, context_data, Object, kContextOffset)
5363
ACCESSORS(Script, wrapper, Foreign, kWrapperOffset)
5364
ACCESSORS_TO_SMI(Script, type, kTypeOffset)
5365
ACCESSORS(Script, line_ends, Object, kLineEndsOffset)
5366
ACCESSORS(Script, eval_from_shared, Object, kEvalFromSharedOffset)
5367 5368
ACCESSORS_TO_SMI(Script, eval_from_instructions_offset,
                 kEvalFrominstructionsOffsetOffset)
5369
ACCESSORS_TO_SMI(Script, flags, kFlagsOffset)
5370
BOOL_ACCESSORS(Script, flags, is_shared_cross_origin, kIsSharedCrossOriginBit)
5371 5372
ACCESSORS(Script, source_url, Object, kSourceUrlOffset)
ACCESSORS(Script, source_mapping_url, Object, kSourceMappingUrlOffset)
5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390

Script::CompilationType Script::compilation_type() {
  return BooleanBit::get(flags(), kCompilationTypeBit) ?
      COMPILATION_TYPE_EVAL : COMPILATION_TYPE_HOST;
}
void Script::set_compilation_type(CompilationType type) {
  set_flags(BooleanBit::set(flags(), kCompilationTypeBit,
      type == COMPILATION_TYPE_EVAL));
}
Script::CompilationState Script::compilation_state() {
  return BooleanBit::get(flags(), kCompilationStateBit) ?
      COMPILATION_STATE_COMPILED : COMPILATION_STATE_INITIAL;
}
void Script::set_compilation_state(CompilationState state) {
  set_flags(BooleanBit::set(flags(), kCompilationStateBit,
      state == COMPILATION_STATE_COMPILED));
}

5391 5392 5393 5394 5395 5396

ACCESSORS(DebugInfo, shared, SharedFunctionInfo, kSharedFunctionInfoIndex)
ACCESSORS(DebugInfo, original_code, Code, kOriginalCodeIndex)
ACCESSORS(DebugInfo, code, Code, kPatchedCodeIndex)
ACCESSORS(DebugInfo, break_points, FixedArray, kBreakPointsStateIndex)

5397 5398 5399
ACCESSORS_TO_SMI(BreakPointInfo, code_position, kCodePositionIndex)
ACCESSORS_TO_SMI(BreakPointInfo, source_position, kSourcePositionIndex)
ACCESSORS_TO_SMI(BreakPointInfo, statement_position, kStatementPositionIndex)
5400 5401 5402
ACCESSORS(BreakPointInfo, break_point_objects, Object, kBreakPointObjectsIndex)

ACCESSORS(SharedFunctionInfo, name, Object, kNameOffset)
5403 5404
ACCESSORS(SharedFunctionInfo, optimized_code_map, Object,
                 kOptimizedCodeMapOffset)
5405
ACCESSORS(SharedFunctionInfo, construct_stub, Code, kConstructStubOffset)
5406 5407
ACCESSORS(SharedFunctionInfo, feedback_vector, FixedArray,
          kFeedbackVectorOffset)
5408 5409
ACCESSORS(SharedFunctionInfo, instance_class_name, Object,
          kInstanceClassNameOffset)
5410
ACCESSORS(SharedFunctionInfo, function_data, Object, kFunctionDataOffset)
5411 5412
ACCESSORS(SharedFunctionInfo, script, Object, kScriptOffset)
ACCESSORS(SharedFunctionInfo, debug_info, Object, kDebugInfoOffset)
5413
ACCESSORS(SharedFunctionInfo, inferred_name, String, kInferredNameOffset)
5414

5415

5416
SMI_ACCESSORS(FunctionTemplateInfo, length, kLengthOffset)
5417 5418 5419 5420 5421
BOOL_ACCESSORS(FunctionTemplateInfo, flag, hidden_prototype,
               kHiddenPrototypeBit)
BOOL_ACCESSORS(FunctionTemplateInfo, flag, undetectable, kUndetectableBit)
BOOL_ACCESSORS(FunctionTemplateInfo, flag, needs_access_check,
               kNeedsAccessCheckBit)
5422 5423
BOOL_ACCESSORS(FunctionTemplateInfo, flag, read_only_prototype,
               kReadOnlyPrototypeBit)
5424 5425
BOOL_ACCESSORS(FunctionTemplateInfo, flag, remove_prototype,
               kRemovePrototypeBit)
5426 5427
BOOL_ACCESSORS(FunctionTemplateInfo, flag, do_not_cache,
               kDoNotCacheBit)
5428 5429 5430 5431
BOOL_ACCESSORS(SharedFunctionInfo, start_position_and_type, is_expression,
               kIsExpressionBit)
BOOL_ACCESSORS(SharedFunctionInfo, start_position_and_type, is_toplevel,
               kIsTopLevelBit)
5432

5433 5434 5435 5436
BOOL_ACCESSORS(SharedFunctionInfo,
               compiler_hints,
               allows_lazy_compilation,
               kAllowLazyCompilation)
5437 5438 5439 5440
BOOL_ACCESSORS(SharedFunctionInfo,
               compiler_hints,
               allows_lazy_compilation_without_context,
               kAllowLazyCompilationWithoutContext)
5441 5442 5443 5444 5445 5446 5447 5448
BOOL_ACCESSORS(SharedFunctionInfo,
               compiler_hints,
               uses_arguments,
               kUsesArguments)
BOOL_ACCESSORS(SharedFunctionInfo,
               compiler_hints,
               has_duplicate_parameters,
               kHasDuplicateParameters)
5449

5450

5451 5452 5453
#if V8_HOST_ARCH_32_BIT
SMI_ACCESSORS(SharedFunctionInfo, length, kLengthOffset)
SMI_ACCESSORS(SharedFunctionInfo, formal_parameter_count,
5454
              kFormalParameterCountOffset)
5455
SMI_ACCESSORS(SharedFunctionInfo, expected_nof_properties,
5456
              kExpectedNofPropertiesOffset)
5457 5458
SMI_ACCESSORS(SharedFunctionInfo, num_literals, kNumLiteralsOffset)
SMI_ACCESSORS(SharedFunctionInfo, start_position_and_type,
5459
              kStartPositionAndTypeOffset)
5460 5461
SMI_ACCESSORS(SharedFunctionInfo, end_position, kEndPositionOffset)
SMI_ACCESSORS(SharedFunctionInfo, function_token_position,
5462
              kFunctionTokenPositionOffset)
5463
SMI_ACCESSORS(SharedFunctionInfo, compiler_hints,
5464
              kCompilerHintsOffset)
5465 5466
SMI_ACCESSORS(SharedFunctionInfo, opt_count_and_bailout_reason,
              kOptCountAndBailoutReasonOffset)
5467
SMI_ACCESSORS(SharedFunctionInfo, counters, kCountersOffset)
5468 5469
SMI_ACCESSORS(SharedFunctionInfo, ast_node_count, kAstNodeCountOffset)
SMI_ACCESSORS(SharedFunctionInfo, profiler_ticks, kProfilerTicksOffset)
5470

5471 5472 5473
#else

#define PSEUDO_SMI_ACCESSORS_LO(holder, name, offset)             \
5474
  STATIC_ASSERT(holder::offset % kPointerSize == 0);              \
5475
  int holder::name() const {                                      \
5476 5477 5478 5479 5480 5481 5482 5483
    int value = READ_INT_FIELD(this, offset);                     \
    ASSERT(kHeapObjectTag == 1);                                  \
    ASSERT((value & kHeapObjectTag) == 0);                        \
    return value >> 1;                                            \
  }                                                               \
  void holder::set_##name(int value) {                            \
    ASSERT(kHeapObjectTag == 1);                                  \
    ASSERT((value & 0xC0000000) == 0xC0000000 ||                  \
5484
           (value & 0xC0000000) == 0x0);                          \
5485 5486 5487 5488 5489
    WRITE_INT_FIELD(this,                                         \
                    offset,                                       \
                    (value << 1) & ~kHeapObjectTag);              \
  }

5490 5491
#define PSEUDO_SMI_ACCESSORS_HI(holder, name, offset)             \
  STATIC_ASSERT(holder::offset % kPointerSize == kIntSize);       \
5492 5493 5494 5495
  INT_ACCESSORS(holder, name, offset)


PSEUDO_SMI_ACCESSORS_LO(SharedFunctionInfo, length, kLengthOffset)
5496 5497 5498
PSEUDO_SMI_ACCESSORS_HI(SharedFunctionInfo,
                        formal_parameter_count,
                        kFormalParameterCountOffset)
5499

5500 5501 5502
PSEUDO_SMI_ACCESSORS_LO(SharedFunctionInfo,
                        expected_nof_properties,
                        kExpectedNofPropertiesOffset)
5503
PSEUDO_SMI_ACCESSORS_HI(SharedFunctionInfo, num_literals, kNumLiteralsOffset)
5504

5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516
PSEUDO_SMI_ACCESSORS_LO(SharedFunctionInfo, end_position, kEndPositionOffset)
PSEUDO_SMI_ACCESSORS_HI(SharedFunctionInfo,
                        start_position_and_type,
                        kStartPositionAndTypeOffset)

PSEUDO_SMI_ACCESSORS_LO(SharedFunctionInfo,
                        function_token_position,
                        kFunctionTokenPositionOffset)
PSEUDO_SMI_ACCESSORS_HI(SharedFunctionInfo,
                        compiler_hints,
                        kCompilerHintsOffset)

5517 5518 5519
PSEUDO_SMI_ACCESSORS_LO(SharedFunctionInfo,
                        opt_count_and_bailout_reason,
                        kOptCountAndBailoutReasonOffset)
5520
PSEUDO_SMI_ACCESSORS_HI(SharedFunctionInfo, counters, kCountersOffset)
5521

5522 5523 5524 5525 5526 5527 5528
PSEUDO_SMI_ACCESSORS_LO(SharedFunctionInfo,
                        ast_node_count,
                        kAstNodeCountOffset)
PSEUDO_SMI_ACCESSORS_HI(SharedFunctionInfo,
                        profiler_ticks,
                        kProfilerTicksOffset)

5529
#endif
5530

5531

5532 5533 5534 5535
BOOL_GETTER(SharedFunctionInfo,
            compiler_hints,
            optimization_disabled,
            kOptimizationDisabled)
5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549


void SharedFunctionInfo::set_optimization_disabled(bool disable) {
  set_compiler_hints(BooleanBit::set(compiler_hints(),
                                     kOptimizationDisabled,
                                     disable));
  // If disabling optimizations we reflect that in the code object so
  // it will not be counted as optimizable code.
  if ((code()->kind() == Code::FUNCTION) && disable) {
    code()->set_optimizable(false);
  }
}


5550 5551 5552
StrictMode SharedFunctionInfo::strict_mode() {
  return BooleanBit::get(compiler_hints(), kStrictModeFunction)
      ? STRICT : SLOPPY;
5553 5554 5555
}


5556 5557 5558
void SharedFunctionInfo::set_strict_mode(StrictMode strict_mode) {
  // We only allow mode transitions from sloppy to strict.
  ASSERT(this->strict_mode() == SLOPPY || this->strict_mode() == strict_mode);
5559
  int hints = compiler_hints();
5560
  hints = BooleanBit::set(hints, kStrictModeFunction, strict_mode == STRICT);
5561
  set_compiler_hints(hints);
5562 5563 5564
}


5565
BOOL_ACCESSORS(SharedFunctionInfo, compiler_hints, native, kNative)
5566 5567
BOOL_ACCESSORS(SharedFunctionInfo, compiler_hints, inline_builtin,
               kInlineBuiltin)
5568 5569 5570 5571 5572
BOOL_ACCESSORS(SharedFunctionInfo, compiler_hints,
               name_should_print_as_anonymous,
               kNameShouldPrintAsAnonymous)
BOOL_ACCESSORS(SharedFunctionInfo, compiler_hints, bound, kBoundFunction)
BOOL_ACCESSORS(SharedFunctionInfo, compiler_hints, is_anonymous, kIsAnonymous)
5573
BOOL_ACCESSORS(SharedFunctionInfo, compiler_hints, is_function, kIsFunction)
5574
BOOL_ACCESSORS(SharedFunctionInfo, compiler_hints, dont_cache, kDontCache)
5575
BOOL_ACCESSORS(SharedFunctionInfo, compiler_hints, dont_flush, kDontFlush)
5576
BOOL_ACCESSORS(SharedFunctionInfo, compiler_hints, is_generator, kIsGenerator)
5577

5578 5579 5580
ACCESSORS(CodeCache, default_cache, FixedArray, kDefaultCacheOffset)
ACCESSORS(CodeCache, normal_type_cache, Object, kNormalTypeCacheOffset)

5581 5582
ACCESSORS(PolymorphicCodeCache, cache, Object, kCacheOffset)

5583 5584 5585 5586 5587
bool Script::HasValidSource() {
  Object* src = this->source();
  if (!src->IsString()) return true;
  String* src_str = String::cast(src);
  if (!StringShape(src_str).IsExternal()) return true;
5588
  if (src_str->IsOneByteRepresentation()) {
5589 5590 5591 5592 5593 5594 5595 5596
    return ExternalAsciiString::cast(src)->resource() != NULL;
  } else if (src_str->IsTwoByteRepresentation()) {
    return ExternalTwoByteString::cast(src)->resource() != NULL;
  }
  return true;
}


5597
void SharedFunctionInfo::DontAdaptArguments() {
5598
  ASSERT(code()->kind() == Code::BUILTIN);
5599 5600 5601 5602
  set_formal_parameter_count(kDontAdaptArgumentsSentinel);
}


5603
int SharedFunctionInfo::start_position() const {
5604 5605 5606 5607 5608 5609 5610 5611 5612 5613
  return start_position_and_type() >> kStartPositionShift;
}


void SharedFunctionInfo::set_start_position(int start_position) {
  set_start_position_and_type((start_position << kStartPositionShift)
    | (start_position_and_type() & ~kStartPositionMask));
}


5614
Code* SharedFunctionInfo::code() const {
5615 5616 5617 5618
  return Code::cast(READ_FIELD(this, kCodeOffset));
}


5619
void SharedFunctionInfo::set_code(Code* value, WriteBarrierMode mode) {
5620
  ASSERT(value->kind() != Code::OPTIMIZED_FUNCTION);
5621
  WRITE_FIELD(this, kCodeOffset, value);
5622
  CONDITIONAL_WRITE_BARRIER(value->GetHeap(), this, kCodeOffset, value, mode);
5623 5624 5625
}


5626 5627 5628 5629 5630 5631 5632 5633 5634
void SharedFunctionInfo::ReplaceCode(Code* value) {
  // If the GC metadata field is already used then the function was
  // enqueued as a code flushing candidate and we remove it now.
  if (code()->gc_metadata() != NULL) {
    CodeFlusher* flusher = GetHeap()->mark_compact_collector()->code_flusher();
    flusher->EvictCandidate(this);
  }

  ASSERT(code()->gc_metadata() == NULL && value->gc_metadata() == NULL);
5635

5636 5637 5638 5639
  set_code(value);
}


5640
ScopeInfo* SharedFunctionInfo::scope_info() const {
5641
  return reinterpret_cast<ScopeInfo*>(READ_FIELD(this, kScopeInfoOffset));
5642 5643 5644
}


5645
void SharedFunctionInfo::set_scope_info(ScopeInfo* value,
5646 5647
                                        WriteBarrierMode mode) {
  WRITE_FIELD(this, kScopeInfoOffset, reinterpret_cast<Object*>(value));
5648 5649 5650 5651 5652
  CONDITIONAL_WRITE_BARRIER(GetHeap(),
                            this,
                            kScopeInfoOffset,
                            reinterpret_cast<Object*>(value),
                            mode);
5653 5654 5655
}


5656
bool SharedFunctionInfo::is_compiled() {
5657
  return code() !=
5658
      GetIsolate()->builtins()->builtin(Builtins::kCompileUnoptimized);
5659 5660 5661
}


5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672
bool SharedFunctionInfo::IsApiFunction() {
  return function_data()->IsFunctionTemplateInfo();
}


FunctionTemplateInfo* SharedFunctionInfo::get_api_func_data() {
  ASSERT(IsApiFunction());
  return FunctionTemplateInfo::cast(function_data());
}


5673
bool SharedFunctionInfo::HasBuiltinFunctionId() {
5674 5675 5676 5677
  return function_data()->IsSmi();
}


5678 5679 5680
BuiltinFunctionId SharedFunctionInfo::builtin_function_id() {
  ASSERT(HasBuiltinFunctionId());
  return static_cast<BuiltinFunctionId>(Smi::cast(function_data())->value());
5681 5682 5683
}


5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721
int SharedFunctionInfo::ic_age() {
  return ICAgeBits::decode(counters());
}


void SharedFunctionInfo::set_ic_age(int ic_age) {
  set_counters(ICAgeBits::update(counters(), ic_age));
}


int SharedFunctionInfo::deopt_count() {
  return DeoptCountBits::decode(counters());
}


void SharedFunctionInfo::set_deopt_count(int deopt_count) {
  set_counters(DeoptCountBits::update(counters(), deopt_count));
}


void SharedFunctionInfo::increment_deopt_count() {
  int value = counters();
  int deopt_count = DeoptCountBits::decode(value);
  deopt_count = (deopt_count + 1) & DeoptCountBits::kMax;
  set_counters(DeoptCountBits::update(value, deopt_count));
}


int SharedFunctionInfo::opt_reenable_tries() {
  return OptReenableTriesBits::decode(counters());
}


void SharedFunctionInfo::set_opt_reenable_tries(int tries) {
  set_counters(OptReenableTriesBits::update(counters(), tries));
}


5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739
int SharedFunctionInfo::opt_count() {
  return OptCountBits::decode(opt_count_and_bailout_reason());
}


void SharedFunctionInfo::set_opt_count(int opt_count) {
  set_opt_count_and_bailout_reason(
      OptCountBits::update(opt_count_and_bailout_reason(), opt_count));
}


BailoutReason SharedFunctionInfo::DisableOptimizationReason() {
  BailoutReason reason = static_cast<BailoutReason>(
      DisabledOptimizationReasonBits::decode(opt_count_and_bailout_reason()));
  return reason;
}


5740 5741 5742 5743 5744 5745
bool SharedFunctionInfo::has_deoptimization_support() {
  Code* code = this->code();
  return code->kind() == Code::FUNCTION && code->has_deoptimization_support();
}


5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759
void SharedFunctionInfo::TryReenableOptimization() {
  int tries = opt_reenable_tries();
  set_opt_reenable_tries((tries + 1) & OptReenableTriesBits::kMax);
  // We reenable optimization whenever the number of tries is a large
  // enough power of 2.
  if (tries >= 16 && (((tries - 1) & tries) == 0)) {
    set_optimization_disabled(false);
    set_opt_count(0);
    set_deopt_count(0);
    code()->set_optimizable(true);
  }
}


5760
bool JSFunction::IsBuiltin() {
5761
  return context()->global_object()->IsJSBuiltinsObject();
5762 5763 5764
}


5765
bool JSFunction::IsFromNativeScript() {
5766 5767 5768 5769 5770 5771 5772 5773
  Object* script = shared()->script();
  bool native = script->IsScript() &&
                Script::cast(script)->type()->value() == Script::TYPE_NATIVE;
  ASSERT(!IsBuiltin() || native);  // All builtins are also native.
  return native;
}


5774 5775 5776 5777 5778 5779 5780
bool JSFunction::IsFromExtensionScript() {
  Object* script = shared()->script();
  return script->IsScript() &&
         Script::cast(script)->type()->value() == Script::TYPE_EXTENSION;
}


5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791
bool JSFunction::NeedsArgumentsAdaption() {
  return shared()->formal_parameter_count() !=
      SharedFunctionInfo::kDontAdaptArgumentsSentinel;
}


bool JSFunction::IsOptimized() {
  return code()->kind() == Code::OPTIMIZED_FUNCTION;
}


5792 5793 5794 5795 5796
bool JSFunction::IsOptimizable() {
  return code()->kind() == Code::FUNCTION && code()->optimizable();
}


5797 5798 5799
bool JSFunction::IsMarkedForOptimization() {
  return code() == GetIsolate()->builtins()->builtin(
      Builtins::kCompileOptimized);
5800 5801 5802
}


5803
bool JSFunction::IsMarkedForConcurrentOptimization() {
5804
  return code() == GetIsolate()->builtins()->builtin(
5805
      Builtins::kCompileOptimizedConcurrent);
5806 5807 5808
}


5809
bool JSFunction::IsInOptimizationQueue() {
5810
  return code() == GetIsolate()->builtins()->builtin(
5811
      Builtins::kInOptimizationQueue);
5812 5813 5814
}


5815 5816 5817 5818 5819 5820
bool JSFunction::IsInobjectSlackTrackingInProgress() {
  return has_initial_map() &&
      initial_map()->construction_count() != JSFunction::kNoSlackTracking;
}


5821
Code* JSFunction::code() {
5822
  return Code::cast(
5823
      Code::GetObjectFromEntryAddress(FIELD_ADDR(this, kCodeEntryOffset)));
5824 5825 5826
}


5827
void JSFunction::set_code(Code* value) {
5828
  ASSERT(!GetHeap()->InNewSpace(value));
5829 5830
  Address entry = value->entry();
  WRITE_INTPTR_FIELD(this, kCodeEntryOffset, reinterpret_cast<intptr_t>(entry));
5831 5832 5833 5834
  GetHeap()->incremental_marking()->RecordWriteOfCodeEntry(
      this,
      HeapObject::RawField(this, kCodeEntryOffset),
      value);
5835 5836 5837
}


5838
void JSFunction::set_code_no_write_barrier(Code* value) {
5839
  ASSERT(!GetHeap()->InNewSpace(value));
5840 5841 5842 5843 5844
  Address entry = value->entry();
  WRITE_INTPTR_FIELD(this, kCodeEntryOffset, reinterpret_cast<intptr_t>(entry));
}


5845 5846 5847 5848
void JSFunction::ReplaceCode(Code* code) {
  bool was_optimized = IsOptimized();
  bool is_optimized = code->kind() == Code::OPTIMIZED_FUNCTION;

5849 5850 5851 5852 5853
  if (was_optimized && is_optimized) {
    shared()->EvictFromOptimizedCodeMap(this->code(),
        "Replacing with another optimized code");
  }

5854 5855 5856 5857 5858
  set_code(code);

  // Add/remove the function from the list of optimized functions for this
  // context based on the state change.
  if (!was_optimized && is_optimized) {
5859
    context()->native_context()->AddOptimizedFunction(this);
5860 5861
  }
  if (was_optimized && !is_optimized) {
5862
    // TODO(titzer): linear in the number of optimized functions; fix!
5863
    context()->native_context()->RemoveOptimizedFunction(this);
5864 5865 5866 5867
  }
}


5868 5869 5870 5871 5872
Context* JSFunction::context() {
  return Context::cast(READ_FIELD(this, kContextOffset));
}


5873 5874 5875 5876 5877
JSObject* JSFunction::global_proxy() {
  return context()->global_proxy();
}


5878
void JSFunction::set_context(Object* value) {
5879
  ASSERT(value->IsUndefined() || value->IsContext());
5880
  WRITE_FIELD(this, kContextOffset, value);
5881
  WRITE_BARRIER(GetHeap(), this, kContextOffset, value);
5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894
}

ACCESSORS(JSFunction, prototype_or_initial_map, Object,
          kPrototypeOrInitialMapOffset)


Map* JSFunction::initial_map() {
  return Map::cast(prototype_or_initial_map());
}


void JSFunction::set_initial_map(Map* value) {
  set_prototype_or_initial_map(value);
5895 5896 5897
}


5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929
bool JSFunction::has_initial_map() {
  return prototype_or_initial_map()->IsMap();
}


bool JSFunction::has_instance_prototype() {
  return has_initial_map() || !prototype_or_initial_map()->IsTheHole();
}


bool JSFunction::has_prototype() {
  return map()->has_non_instance_prototype() || has_instance_prototype();
}


Object* JSFunction::instance_prototype() {
  ASSERT(has_instance_prototype());
  if (has_initial_map()) return initial_map()->prototype();
  // When there is no initial map and the prototype is a JSObject, the
  // initial map field is used for the prototype field.
  return prototype_or_initial_map();
}


Object* JSFunction::prototype() {
  ASSERT(has_prototype());
  // If the function's prototype property has been set to a non-JSObject
  // value, that value is stored in the constructor field of the map.
  if (map()->has_non_instance_prototype()) return map()->constructor();
  return instance_prototype();
}

5930

5931 5932 5933 5934
bool JSFunction::should_have_prototype() {
  return map()->function_with_prototype();
}

5935 5936

bool JSFunction::is_compiled() {
5937 5938
  return code() !=
      GetIsolate()->builtins()->builtin(Builtins::kCompileUnoptimized);
5939 5940 5941
}


5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969
FixedArray* JSFunction::literals() {
  ASSERT(!shared()->bound());
  return literals_or_bindings();
}


void JSFunction::set_literals(FixedArray* literals) {
  ASSERT(!shared()->bound());
  set_literals_or_bindings(literals);
}


FixedArray* JSFunction::function_bindings() {
  ASSERT(shared()->bound());
  return literals_or_bindings();
}


void JSFunction::set_function_bindings(FixedArray* bindings) {
  ASSERT(shared()->bound());
  // Bound function literal may be initialized to the empty fixed array
  // before the bindings are set.
  ASSERT(bindings == GetHeap()->empty_fixed_array() ||
         bindings->map() == GetHeap()->fixed_cow_array_map());
  set_literals_or_bindings(bindings);
}


5970
int JSFunction::NumberOfLiterals() {
5971
  ASSERT(!shared()->bound());
5972 5973 5974 5975
  return literals()->length();
}


5976
Object* JSBuiltinsObject::javascript_builtin(Builtins::JavaScript id) {
5977
  ASSERT(id < kJSBuiltinsCount);  // id is unsigned.
5978
  return READ_FIELD(this, OffsetOfFunctionWithId(id));
5979 5980 5981 5982 5983
}


void JSBuiltinsObject::set_javascript_builtin(Builtins::JavaScript id,
                                              Object* value) {
5984
  ASSERT(id < kJSBuiltinsCount);  // id is unsigned.
5985
  WRITE_FIELD(this, OffsetOfFunctionWithId(id), value);
5986
  WRITE_BARRIER(GetHeap(), this, OffsetOfFunctionWithId(id), value);
5987 5988 5989 5990
}


Code* JSBuiltinsObject::javascript_builtin_code(Builtins::JavaScript id) {
5991
  ASSERT(id < kJSBuiltinsCount);  // id is unsigned.
5992 5993 5994 5995 5996 5997
  return Code::cast(READ_FIELD(this, OffsetOfCodeWithId(id)));
}


void JSBuiltinsObject::set_javascript_builtin_code(Builtins::JavaScript id,
                                                   Code* value) {
5998
  ASSERT(id < kJSBuiltinsCount);  // id is unsigned.
5999
  WRITE_FIELD(this, OffsetOfCodeWithId(id), value);
6000
  ASSERT(!GetHeap()->InNewSpace(value));
6001 6002 6003
}


6004
ACCESSORS(JSProxy, handler, Object, kHandlerOffset)
6005
ACCESSORS(JSProxy, hash, Object, kHashOffset)
6006 6007 6008 6009 6010 6011 6012 6013 6014 6015
ACCESSORS(JSFunctionProxy, call_trap, Object, kCallTrapOffset)
ACCESSORS(JSFunctionProxy, construct_trap, Object, kConstructTrapOffset)


void JSProxy::InitializeBody(int object_size, Object* value) {
  ASSERT(!value->IsHeapObject() || !GetHeap()->InNewSpace(value));
  for (int offset = kHeaderSize; offset < object_size; offset += kPointerSize) {
    WRITE_FIELD(this, offset, value);
  }
}
6016 6017


6018
ACCESSORS(JSCollection, table, Object, kTableOffset)
6019 6020 6021 6022


#define ORDERED_HASH_TABLE_ITERATOR_ACCESSORS(name, type, offset)    \
  template<class Derived, class TableType>                           \
6023
  type* OrderedHashTableIterator<Derived, TableType>::name() const { \
6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039
    return type::cast(READ_FIELD(this, offset));                     \
  }                                                                  \
  template<class Derived, class TableType>                           \
  void OrderedHashTableIterator<Derived, TableType>::set_##name(     \
      type* value, WriteBarrierMode mode) {                          \
    WRITE_FIELD(this, offset, value);                                \
    CONDITIONAL_WRITE_BARRIER(GetHeap(), this, offset, value, mode); \
  }

ORDERED_HASH_TABLE_ITERATOR_ACCESSORS(table, Object, kTableOffset)
ORDERED_HASH_TABLE_ITERATOR_ACCESSORS(index, Smi, kIndexOffset)
ORDERED_HASH_TABLE_ITERATOR_ACCESSORS(kind, Smi, kKindOffset)

#undef ORDERED_HASH_TABLE_ITERATOR_ACCESSORS


6040 6041
ACCESSORS(JSWeakCollection, table, Object, kTableOffset)
ACCESSORS(JSWeakCollection, next, Object, kNextOffset)
6042 6043


6044 6045
Address Foreign::foreign_address() {
  return AddressFrom<Address>(READ_INTPTR_FIELD(this, kForeignAddressOffset));
6046 6047 6048
}


6049 6050
void Foreign::set_foreign_address(Address value) {
  WRITE_INTPTR_FIELD(this, kForeignAddressOffset, OffsetFrom(value));
6051 6052 6053
}


6054
ACCESSORS(JSGeneratorObject, function, JSFunction, kFunctionOffset)
6055
ACCESSORS(JSGeneratorObject, context, Context, kContextOffset)
6056
ACCESSORS(JSGeneratorObject, receiver, Object, kReceiverOffset)
6057 6058
SMI_ACCESSORS(JSGeneratorObject, continuation, kContinuationOffset)
ACCESSORS(JSGeneratorObject, operand_stack, FixedArray, kOperandStackOffset)
6059
SMI_ACCESSORS(JSGeneratorObject, stack_handler_index, kStackHandlerIndexOffset)
6060

6061 6062 6063 6064 6065
bool JSGeneratorObject::is_suspended() {
  ASSERT_LT(kGeneratorExecuting, kGeneratorClosed);
  ASSERT_EQ(kGeneratorClosed, 0);
  return continuation() > 0;
}
6066

6067 6068 6069 6070 6071 6072 6073 6074
bool JSGeneratorObject::is_closed() {
  return continuation() == kGeneratorClosed;
}

bool JSGeneratorObject::is_executing() {
  return continuation() == kGeneratorExecuting;
}

6075
ACCESSORS(JSModule, context, Object, kContextOffset)
6076
ACCESSORS(JSModule, scope_info, ScopeInfo, kScopeInfoOffset)
6077 6078


6079 6080 6081
ACCESSORS(JSValue, value, Object, kValueOffset)


6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093
HeapNumber* HeapNumber::cast(Object* object) {
  SLOW_ASSERT(object->IsHeapNumber() || object->IsMutableHeapNumber());
  return reinterpret_cast<HeapNumber*>(object);
}


const HeapNumber* HeapNumber::cast(const Object* object) {
  SLOW_ASSERT(object->IsHeapNumber() || object->IsMutableHeapNumber());
  return reinterpret_cast<const HeapNumber*>(object);
}


6094
ACCESSORS(JSDate, value, Object, kValueOffset)
6095
ACCESSORS(JSDate, cache_stamp, Object, kCacheStampOffset)
6096 6097 6098
ACCESSORS(JSDate, year, Object, kYearOffset)
ACCESSORS(JSDate, month, Object, kMonthOffset)
ACCESSORS(JSDate, day, Object, kDayOffset)
6099
ACCESSORS(JSDate, weekday, Object, kWeekdayOffset)
6100 6101 6102 6103 6104
ACCESSORS(JSDate, hour, Object, kHourOffset)
ACCESSORS(JSDate, min, Object, kMinOffset)
ACCESSORS(JSDate, sec, Object, kSecOffset)


6105 6106 6107 6108 6109 6110 6111 6112
ACCESSORS(JSMessageObject, type, String, kTypeOffset)
ACCESSORS(JSMessageObject, arguments, JSArray, kArgumentsOffset)
ACCESSORS(JSMessageObject, script, Object, kScriptOffset)
ACCESSORS(JSMessageObject, stack_frames, Object, kStackFramesOffset)
SMI_ACCESSORS(JSMessageObject, start_position, kStartPositionOffset)
SMI_ACCESSORS(JSMessageObject, end_position, kEndPositionOffset)


6113
INT_ACCESSORS(Code, instruction_size, kInstructionSizeOffset)
6114
INT_ACCESSORS(Code, prologue_offset, kPrologueOffset)
6115
ACCESSORS(Code, relocation_info, ByteArray, kRelocationInfoOffset)
6116
ACCESSORS(Code, handler_table, FixedArray, kHandlerTableOffset)
6117
ACCESSORS(Code, deoptimization_data, FixedArray, kDeoptimizationDataOffset)
6118
ACCESSORS(Code, raw_type_feedback_info, Object, kTypeFeedbackInfoOffset)
6119
ACCESSORS(Code, next_code_link, Object, kNextCodeLinkOffset)
6120 6121


6122 6123 6124 6125
void Code::WipeOutHeader() {
  WRITE_FIELD(this, kRelocationInfoOffset, NULL);
  WRITE_FIELD(this, kHandlerTableOffset, NULL);
  WRITE_FIELD(this, kDeoptimizationDataOffset, NULL);
6126
  WRITE_FIELD(this, kConstantPoolOffset, NULL);
6127 6128 6129 6130 6131 6132 6133
  // Do not wipe out e.g. a minor key.
  if (!READ_FIELD(this, kTypeFeedbackInfoOffset)->IsSmi()) {
    WRITE_FIELD(this, kTypeFeedbackInfoOffset, NULL);
  }
}


6134 6135
Object* Code::type_feedback_info() {
  ASSERT(kind() == FUNCTION);
6136
  return raw_type_feedback_info();
6137 6138 6139 6140 6141
}


void Code::set_type_feedback_info(Object* value, WriteBarrierMode mode) {
  ASSERT(kind() == FUNCTION);
6142
  set_raw_type_feedback_info(value, mode);
6143 6144
  CONDITIONAL_WRITE_BARRIER(GetHeap(), this, kTypeFeedbackInfoOffset,
                            value, mode);
6145 6146 6147
}


6148
int Code::stub_info() {
6149
  ASSERT(kind() == COMPARE_IC || kind() == COMPARE_NIL_IC ||
6150
         kind() == BINARY_OP_IC || kind() == LOAD_IC || kind() == CALL_IC);
6151
  return Smi::cast(raw_type_feedback_info())->value();
6152 6153 6154 6155
}


void Code::set_stub_info(int value) {
6156
  ASSERT(kind() == COMPARE_IC ||
6157
         kind() == COMPARE_NIL_IC ||
6158
         kind() == BINARY_OP_IC ||
6159
         kind() == STUB ||
6160
         kind() == LOAD_IC ||
6161
         kind() == CALL_IC ||
6162 6163 6164
         kind() == KEYED_LOAD_IC ||
         kind() == STORE_IC ||
         kind() == KEYED_STORE_IC);
6165
  set_raw_type_feedback_info(Smi::FromInt(value));
6166 6167 6168
}


6169
ACCESSORS(Code, gc_metadata, Object, kGCMetadataOffset)
6170
INT_ACCESSORS(Code, ic_age, kICAgeOffset)
6171

6172

6173 6174 6175 6176 6177
byte* Code::instruction_start()  {
  return FIELD_ADDR(this, kHeaderSize);
}


6178 6179 6180 6181 6182
byte* Code::instruction_end()  {
  return instruction_start() + instruction_size();
}


6183
int Code::body_size() {
6184 6185 6186 6187 6188 6189
  return RoundUp(instruction_size(), kObjectAlignment);
}


ByteArray* Code::unchecked_relocation_info() {
  return reinterpret_cast<ByteArray*>(READ_FIELD(this, kRelocationInfoOffset));
6190 6191 6192 6193
}


byte* Code::relocation_start() {
6194 6195 6196 6197 6198 6199
  return unchecked_relocation_info()->GetDataStartAddress();
}


int Code::relocation_size() {
  return unchecked_relocation_info()->length();
6200 6201 6202 6203 6204 6205 6206 6207
}


byte* Code::entry() {
  return instruction_start();
}


6208 6209
bool Code::contains(byte* inner_pointer) {
  return (address() <= inner_pointer) && (inner_pointer <= address() + Size());
6210 6211 6212 6213 6214 6215
}


ACCESSORS(JSArray, length, Object, kLengthOffset)


6216
void* JSArrayBuffer::backing_store() const {
6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228
  intptr_t ptr = READ_INTPTR_FIELD(this, kBackingStoreOffset);
  return reinterpret_cast<void*>(ptr);
}


void JSArrayBuffer::set_backing_store(void* value, WriteBarrierMode mode) {
  intptr_t ptr = reinterpret_cast<intptr_t>(value);
  WRITE_INTPTR_FIELD(this, kBackingStoreOffset, ptr);
}


ACCESSORS(JSArrayBuffer, byte_length, Object, kByteLengthOffset)
6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239
ACCESSORS_TO_SMI(JSArrayBuffer, flag, kFlagOffset)


bool JSArrayBuffer::is_external() {
  return BooleanBit::get(flag(), kIsExternalBit);
}


void JSArrayBuffer::set_is_external(bool value) {
  set_flag(BooleanBit::set(flag(), kIsExternalBit, value));
}
6240 6241


6242 6243 6244 6245 6246 6247 6248 6249 6250 6251
bool JSArrayBuffer::should_be_freed() {
  return BooleanBit::get(flag(), kShouldBeFreed);
}


void JSArrayBuffer::set_should_be_freed(bool value) {
  set_flag(BooleanBit::set(flag(), kShouldBeFreed, value));
}


6252
ACCESSORS(JSArrayBuffer, weak_next, Object, kWeakNextOffset)
6253
ACCESSORS(JSArrayBuffer, weak_first_view, Object, kWeakFirstViewOffset)
6254 6255


6256 6257 6258 6259
ACCESSORS(JSArrayBufferView, buffer, Object, kBufferOffset)
ACCESSORS(JSArrayBufferView, byte_offset, Object, kByteOffsetOffset)
ACCESSORS(JSArrayBufferView, byte_length, Object, kByteLengthOffset)
ACCESSORS(JSArrayBufferView, weak_next, Object, kWeakNextOffset)
6260 6261
ACCESSORS(JSTypedArray, length, Object, kLengthOffset)

6262 6263 6264
ACCESSORS(JSRegExp, data, Object, kDataOffset)


6265 6266 6267 6268 6269
JSRegExp::Type JSRegExp::TypeTag() {
  Object* data = this->data();
  if (data->IsUndefined()) return JSRegExp::NOT_COMPILED;
  Smi* smi = Smi::cast(FixedArray::cast(data)->get(kTagIndex));
  return static_cast<JSRegExp::Type>(smi->value());
6270 6271 6272
}


6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285
int JSRegExp::CaptureCount() {
  switch (TypeTag()) {
    case ATOM:
      return 0;
    case IRREGEXP:
      return Smi::cast(DataAt(kIrregexpCaptureCountIndex))->value();
    default:
      UNREACHABLE();
      return -1;
  }
}


6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301
JSRegExp::Flags JSRegExp::GetFlags() {
  ASSERT(this->data()->IsFixedArray());
  Object* data = this->data();
  Smi* smi = Smi::cast(FixedArray::cast(data)->get(kFlagsIndex));
  return Flags(smi->value());
}


String* JSRegExp::Pattern() {
  ASSERT(this->data()->IsFixedArray());
  Object* data = this->data();
  String* pattern= String::cast(FixedArray::cast(data)->get(kSourceIndex));
  return pattern;
}


6302 6303 6304
Object* JSRegExp::DataAt(int index) {
  ASSERT(TypeTag() != NOT_COMPILED);
  return FixedArray::cast(data())->get(index);
6305 6306 6307
}


6308 6309 6310 6311 6312 6313 6314
void JSRegExp::SetDataAt(int index, Object* value) {
  ASSERT(TypeTag() != NOT_COMPILED);
  ASSERT(index >= kDataIndex);  // Only implementation data can be set this way.
  FixedArray::cast(data())->set(index, value);
}


6315
ElementsKind JSObject::GetElementsKind() {
6316
  ElementsKind kind = map()->elements_kind();
6317 6318 6319
#if DEBUG
  FixedArrayBase* fixed_array =
      reinterpret_cast<FixedArrayBase*>(READ_FIELD(this, kElementsOffset));
6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331

  // If a GC was caused while constructing this object, the elements
  // pointer may point to a one pointer filler map.
  if (ElementsAreSafeToExamine()) {
    Map* map = fixed_array->map();
    ASSERT((IsFastSmiOrObjectElementsKind(kind) &&
            (map == GetHeap()->fixed_array_map() ||
             map == GetHeap()->fixed_cow_array_map())) ||
           (IsFastDoubleElementsKind(kind) &&
            (fixed_array->IsFixedDoubleArray() ||
             fixed_array == GetHeap()->empty_fixed_array())) ||
           (kind == DICTIONARY_ELEMENTS &&
6332
            fixed_array->IsFixedArray() &&
6333 6334
            fixed_array->IsDictionary()) ||
           (kind > DICTIONARY_ELEMENTS));
6335
    ASSERT((kind != SLOPPY_ARGUMENTS_ELEMENTS) ||
6336 6337
           (elements()->IsFixedArray() && elements()->length() >= 2));
  }
6338
#endif
6339
  return kind;
6340 6341 6342
}


6343 6344 6345 6346 6347
ElementsAccessor* JSObject::GetElementsAccessor() {
  return ElementsAccessor::ForKind(GetElementsKind());
}


6348 6349
bool JSObject::HasFastObjectElements() {
  return IsFastObjectElementsKind(GetElementsKind());
6350 6351 6352
}


6353 6354
bool JSObject::HasFastSmiElements() {
  return IsFastSmiElementsKind(GetElementsKind());
6355 6356 6357
}


6358 6359
bool JSObject::HasFastSmiOrObjectElements() {
  return IsFastSmiOrObjectElementsKind(GetElementsKind());
6360 6361 6362
}


6363
bool JSObject::HasFastDoubleElements() {
6364 6365 6366 6367 6368 6369
  return IsFastDoubleElementsKind(GetElementsKind());
}


bool JSObject::HasFastHoleyElements() {
  return IsFastHoleyElementsKind(GetElementsKind());
6370 6371 6372
}


6373 6374 6375 6376 6377
bool JSObject::HasFastElements() {
  return IsFastElementsKind(GetElementsKind());
}


6378 6379 6380 6381 6382
bool JSObject::HasDictionaryElements() {
  return GetElementsKind() == DICTIONARY_ELEMENTS;
}


6383 6384
bool JSObject::HasSloppyArgumentsElements() {
  return GetElementsKind() == SLOPPY_ARGUMENTS_ELEMENTS;
6385 6386 6387
}


6388
bool JSObject::HasExternalArrayElements() {
6389 6390 6391
  HeapObject* array = elements();
  ASSERT(array != NULL);
  return array->IsExternalArray();
6392 6393 6394
}


6395 6396 6397 6398 6399 6400 6401
#define EXTERNAL_ELEMENTS_CHECK(Type, type, TYPE, ctype, size)          \
bool JSObject::HasExternal##Type##Elements() {                          \
  HeapObject* array = elements();                                       \
  ASSERT(array != NULL);                                                \
  if (!array->IsHeapObject())                                           \
    return false;                                                       \
  return array->map()->instance_type() == EXTERNAL_##TYPE##_ARRAY_TYPE; \
6402 6403
}

6404
TYPED_ARRAYS(EXTERNAL_ELEMENTS_CHECK)
6405

6406
#undef EXTERNAL_ELEMENTS_CHECK
6407 6408


6409 6410 6411 6412 6413 6414 6415
bool JSObject::HasFixedTypedArrayElements() {
  HeapObject* array = elements();
  ASSERT(array != NULL);
  return array->IsFixedTypedArrayBase();
}


6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429
#define FIXED_TYPED_ELEMENTS_CHECK(Type, type, TYPE, ctype, size)         \
bool JSObject::HasFixed##Type##Elements() {                               \
  HeapObject* array = elements();                                         \
  ASSERT(array != NULL);                                                  \
  if (!array->IsHeapObject())                                             \
    return false;                                                         \
  return array->map()->instance_type() == FIXED_##TYPE##_ARRAY_TYPE;      \
}

TYPED_ARRAYS(FIXED_TYPED_ELEMENTS_CHECK)

#undef FIXED_TYPED_ELEMENTS_CHECK


6430 6431 6432 6433 6434 6435 6436 6437 6438 6439
bool JSObject::HasNamedInterceptor() {
  return map()->has_named_interceptor();
}


bool JSObject::HasIndexedInterceptor() {
  return map()->has_indexed_interceptor();
}


6440
NameDictionary* JSObject::property_dictionary() {
6441
  ASSERT(!HasFastProperties());
6442
  return NameDictionary::cast(properties());
6443 6444 6445
}


6446
SeededNumberDictionary* JSObject::element_dictionary() {
6447
  ASSERT(HasDictionaryElements());
6448
  return SeededNumberDictionary::cast(elements());
6449 6450 6451
}


6452
bool Name::IsHashFieldComputed(uint32_t field) {
6453 6454 6455 6456
  return (field & kHashNotComputedMask) == 0;
}


6457
bool Name::HasHashCode() {
6458
  return IsHashFieldComputed(hash_field());
6459 6460 6461
}


6462
uint32_t Name::Hash() {
6463
  // Fast case: has hash code already been computed?
6464
  uint32_t field = hash_field();
6465
  if (IsHashFieldComputed(field)) return field >> kHashShift;
6466 6467
  // Slow case: compute hash code and set it. Has to be a string.
  return String::cast(this)->ComputeAndSetHash();
6468 6469 6470
}


6471
StringHasher::StringHasher(int length, uint32_t seed)
6472
  : length_(length),
6473
    raw_running_hash_(seed),
6474
    array_index_(0),
6475
    is_array_index_(0 < length_ && length_ <= String::kMaxArrayIndexSize),
6476
    is_first_char_(true) {
6477
  ASSERT(FLAG_randomize_hashes || raw_running_hash_ == 0);
6478
}
6479 6480 6481


bool StringHasher::has_trivial_hash() {
6482
  return length_ > String::kMaxHashCalcLength;
6483 6484 6485
}


6486
uint32_t StringHasher::AddCharacterCore(uint32_t running_hash, uint16_t c) {
6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498
  running_hash += c;
  running_hash += (running_hash << 10);
  running_hash ^= (running_hash >> 6);
  return running_hash;
}


uint32_t StringHasher::GetHashCore(uint32_t running_hash) {
  running_hash += (running_hash << 3);
  running_hash ^= (running_hash >> 11);
  running_hash += (running_hash << 15);
  if ((running_hash & String::kHashBitMask) == 0) {
6499
    return kZeroHash;
6500 6501 6502 6503 6504
  }
  return running_hash;
}


6505
void StringHasher::AddCharacter(uint16_t c) {
6506 6507
  // Use the Jenkins one-at-a-time hash function to update the hash
  // for the given character.
6508
  raw_running_hash_ = AddCharacterCore(raw_running_hash_, c);
6509 6510 6511
}


6512 6513 6514 6515 6516
bool StringHasher::UpdateIndex(uint16_t c) {
  ASSERT(is_array_index_);
  if (c < '0' || c > '9') {
    is_array_index_ = false;
    return false;
6517
  }
6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531
  int d = c - '0';
  if (is_first_char_) {
    is_first_char_ = false;
    if (c == '0' && length_ > 1) {
      is_array_index_ = false;
      return false;
    }
  }
  if (array_index_ > 429496729U - ((d + 2) >> 3)) {
    is_array_index_ = false;
    return false;
  }
  array_index_ = array_index_ * 10 + d;
  return true;
6532 6533 6534
}


6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551
template<typename Char>
inline void StringHasher::AddCharacters(const Char* chars, int length) {
  ASSERT(sizeof(Char) == 1 || sizeof(Char) == 2);
  int i = 0;
  if (is_array_index_) {
    for (; i < length; i++) {
      AddCharacter(chars[i]);
      if (!UpdateIndex(chars[i])) {
        i++;
        break;
      }
    }
  }
  for (; i < length; i++) {
    ASSERT(!is_array_index_);
    AddCharacter(chars[i]);
  }
6552 6553 6554
}


6555
template <typename schar>
6556 6557 6558
uint32_t StringHasher::HashSequentialString(const schar* chars,
                                            int length,
                                            uint32_t seed) {
6559
  StringHasher hasher(length, seed);
6560
  if (!hasher.has_trivial_hash()) hasher.AddCharacters(chars, length);
6561 6562 6563 6564
  return hasher.GetHashField();
}


6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593
uint32_t IteratingStringHasher::Hash(String* string, uint32_t seed) {
  IteratingStringHasher hasher(string->length(), seed);
  // Nothing to do.
  if (hasher.has_trivial_hash()) return hasher.GetHashField();
  ConsString* cons_string = String::VisitFlat(&hasher, string);
  // The string was flat.
  if (cons_string == NULL) return hasher.GetHashField();
  // This is a ConsString, iterate across it.
  ConsStringIteratorOp op(cons_string);
  int offset;
  while (NULL != (string = op.Next(&offset))) {
    String::VisitFlat(&hasher, string, offset);
  }
  return hasher.GetHashField();
}


void IteratingStringHasher::VisitOneByteString(const uint8_t* chars,
                                               int length) {
  AddCharacters(chars, length);
}


void IteratingStringHasher::VisitTwoByteString(const uint16_t* chars,
                                               int length) {
  AddCharacters(chars, length);
}


6594 6595 6596 6597 6598
bool Name::AsArrayIndex(uint32_t* index) {
  return IsString() && String::cast(this)->AsArrayIndex(index);
}


6599
bool String::AsArrayIndex(uint32_t* index) {
6600
  uint32_t field = hash_field();
6601 6602 6603
  if (IsHashFieldComputed(field) && (field & kIsNotArrayIndexMask)) {
    return false;
  }
6604 6605 6606 6607
  return SlowAsArrayIndex(index);
}


6608
Object* JSReceiver::GetPrototype() const {
6609
  return map()->prototype();
6610 6611 6612
}


6613 6614 6615 6616 6617
Object* JSReceiver::GetConstructor() {
  return map()->constructor();
}


6618 6619 6620 6621 6622
bool JSReceiver::HasProperty(Handle<JSReceiver> object,
                             Handle<Name> name) {
  if (object->IsJSProxy()) {
    Handle<JSProxy> proxy = Handle<JSProxy>::cast(object);
    return JSProxy::HasPropertyWithHandler(proxy, name);
6623
  }
6624
  return GetPropertyAttributes(object, name) != ABSENT;
6625 6626 6627
}


6628
bool JSReceiver::HasOwnProperty(Handle<JSReceiver> object, Handle<Name> name) {
6629 6630 6631
  if (object->IsJSProxy()) {
    Handle<JSProxy> proxy = Handle<JSProxy>::cast(object);
    return JSProxy::HasPropertyWithHandler(proxy, name);
6632
  }
6633
  return GetOwnPropertyAttributes(object, name) != ABSENT;
6634 6635 6636
}


6637 6638
PropertyAttributes JSReceiver::GetPropertyAttributes(Handle<JSReceiver> object,
                                                     Handle<Name> key) {
6639
  uint32_t index;
6640 6641
  if (object->IsJSObject() && key->AsArrayIndex(&index)) {
    return GetElementAttribute(object, index);
6642
  }
6643 6644
  LookupIterator it(object, key);
  return GetPropertyAttributes(&it);
6645 6646
}

6647

6648 6649 6650 6651 6652
PropertyAttributes JSReceiver::GetElementAttribute(Handle<JSReceiver> object,
                                                   uint32_t index) {
  if (object->IsJSProxy()) {
    return JSProxy::GetElementAttributeWithHandler(
        Handle<JSProxy>::cast(object), object, index);
6653
  }
6654 6655
  return JSObject::GetElementAttributeWithReceiver(
      Handle<JSObject>::cast(object), object, index, true);
6656 6657 6658
}


6659
bool JSGlobalObject::IsDetached() {
6660
  return JSGlobalProxy::cast(global_proxy())->IsDetachedFrom(this);
6661 6662 6663
}


6664
bool JSGlobalProxy::IsDetachedFrom(GlobalObject* global) const {
6665
  return GetPrototype() != global;
6666 6667 6668
}


6669
Handle<Smi> JSReceiver::GetOrCreateIdentityHash(Handle<JSReceiver> object) {
6670 6671 6672 6673 6674 6675 6676
  return object->IsJSProxy()
      ? JSProxy::GetOrCreateIdentityHash(Handle<JSProxy>::cast(object))
      : JSObject::GetOrCreateIdentityHash(Handle<JSObject>::cast(object));
}


Object* JSReceiver::GetIdentityHash() {
6677
  return IsJSProxy()
6678 6679
      ? JSProxy::cast(this)->GetIdentityHash()
      : JSObject::cast(this)->GetIdentityHash();
6680 6681 6682
}


6683 6684 6685 6686
bool JSReceiver::HasElement(Handle<JSReceiver> object, uint32_t index) {
  if (object->IsJSProxy()) {
    Handle<JSProxy> proxy = Handle<JSProxy>::cast(object);
    return JSProxy::HasElementWithHandler(proxy, index);
6687
  }
6688 6689
  return JSObject::GetElementAttributeWithReceiver(
      Handle<JSObject>::cast(object), object, index, true) != ABSENT;
6690 6691 6692
}


6693
bool JSReceiver::HasOwnElement(Handle<JSReceiver> object, uint32_t index) {
6694 6695 6696
  if (object->IsJSProxy()) {
    Handle<JSProxy> proxy = Handle<JSProxy>::cast(object);
    return JSProxy::HasElementWithHandler(proxy, index);
6697
  }
6698 6699
  return JSObject::GetElementAttributeWithReceiver(
      Handle<JSObject>::cast(object), object, index, false) != ABSENT;
6700 6701 6702
}


6703
PropertyAttributes JSReceiver::GetOwnElementAttribute(
6704 6705 6706 6707
    Handle<JSReceiver> object, uint32_t index) {
  if (object->IsJSProxy()) {
    return JSProxy::GetElementAttributeWithHandler(
        Handle<JSProxy>::cast(object), object, index);
6708
  }
6709 6710
  return JSObject::GetElementAttributeWithReceiver(
      Handle<JSObject>::cast(object), object, index, false);
6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739
}


bool AccessorInfo::all_can_read() {
  return BooleanBit::get(flag(), kAllCanReadBit);
}


void AccessorInfo::set_all_can_read(bool value) {
  set_flag(BooleanBit::set(flag(), kAllCanReadBit, value));
}


bool AccessorInfo::all_can_write() {
  return BooleanBit::get(flag(), kAllCanWriteBit);
}


void AccessorInfo::set_all_can_write(bool value) {
  set_flag(BooleanBit::set(flag(), kAllCanWriteBit, value));
}


PropertyAttributes AccessorInfo::property_attributes() {
  return AttributesField::decode(static_cast<uint32_t>(flag()->value()));
}


void AccessorInfo::set_property_attributes(PropertyAttributes attributes) {
6740
  set_flag(Smi::FromInt(AttributesField::update(flag()->value(), attributes)));
6741 6742
}

6743

6744 6745 6746
bool AccessorInfo::IsCompatibleReceiver(Object* receiver) {
  Object* function_template = expected_receiver_type();
  if (!function_template->IsFunctionTemplateInfo()) return true;
6747
  return FunctionTemplateInfo::cast(function_template)->IsTemplateFor(receiver);
6748 6749 6750
}


6751 6752 6753 6754 6755
void ExecutableAccessorInfo::clear_setter() {
  set_setter(GetIsolate()->heap()->undefined_value(), SKIP_WRITE_BARRIER);
}


6756 6757
template<typename Derived, typename Shape, typename Key>
void Dictionary<Derived, Shape, Key>::SetEntry(int entry,
6758 6759
                                               Handle<Object> key,
                                               Handle<Object> value) {
6760 6761 6762 6763
  SetEntry(entry, key, value, PropertyDetails(Smi::FromInt(0)));
}


6764 6765
template<typename Derived, typename Shape, typename Key>
void Dictionary<Derived, Shape, Key>::SetEntry(int entry,
6766 6767
                                               Handle<Object> key,
                                               Handle<Object> value,
6768
                                               PropertyDetails details) {
6769
  ASSERT(!key->IsName() ||
6770 6771
         details.IsDeleted() ||
         details.dictionary_index() > 0);
6772
  int index = DerivedHashTable::EntryToIndex(entry);
6773
  DisallowHeapAllocation no_gc;
6774
  WriteBarrierMode mode = FixedArray::GetWriteBarrierMode(no_gc);
6775 6776
  FixedArray::set(index, *key, mode);
  FixedArray::set(index+1, *value, mode);
6777
  FixedArray::set(index+2, details.AsSmi());
6778 6779 6780
}


6781 6782 6783 6784 6785 6786
bool NumberDictionaryShape::IsMatch(uint32_t key, Object* other) {
  ASSERT(other->IsNumber());
  return key == static_cast<uint32_t>(other->Number());
}


6787 6788
uint32_t UnseededNumberDictionaryShape::Hash(uint32_t key) {
  return ComputeIntegerHash(key, 0);
6789 6790 6791
}


6792 6793 6794 6795
uint32_t UnseededNumberDictionaryShape::HashForObject(uint32_t key,
                                                      Object* other) {
  ASSERT(other->IsNumber());
  return ComputeIntegerHash(static_cast<uint32_t>(other->Number()), 0);
6796 6797
}

6798

6799
uint32_t SeededNumberDictionaryShape::SeededHash(uint32_t key, uint32_t seed) {
6800 6801 6802
  return ComputeIntegerHash(key, seed);
}

6803

6804 6805 6806
uint32_t SeededNumberDictionaryShape::SeededHashForObject(uint32_t key,
                                                          uint32_t seed,
                                                          Object* other) {
6807 6808 6809
  ASSERT(other->IsNumber());
  return ComputeIntegerHash(static_cast<uint32_t>(other->Number()), seed);
}
6810 6811


6812 6813 6814 6815
Handle<Object> NumberDictionaryShape::AsHandle(Isolate* isolate, uint32_t key) {
  return isolate->factory()->NewNumberFromUint(key);
}

6816

6817
bool NameDictionaryShape::IsMatch(Handle<Name> key, Object* other) {
6818 6819
  // We know that all entries in a hash table had their hash keys created.
  // Use that knowledge to have fast failure.
6820 6821
  if (key->Hash() != Name::cast(other)->Hash()) return false;
  return key->Equals(Name::cast(other));
6822 6823 6824
}


6825
uint32_t NameDictionaryShape::Hash(Handle<Name> key) {
6826 6827 6828 6829
  return key->Hash();
}


6830
uint32_t NameDictionaryShape::HashForObject(Handle<Name> key, Object* other) {
6831
  return Name::cast(other)->Hash();
6832 6833 6834
}


6835 6836
Handle<Object> NameDictionaryShape::AsHandle(Isolate* isolate,
                                             Handle<Name> key) {
6837
  ASSERT(key->IsUniqueName());
6838
  return key;
6839 6840 6841
}


6842 6843 6844 6845 6846 6847
void NameDictionary::DoGenerateNewEnumerationIndices(
    Handle<NameDictionary> dictionary) {
  DerivedDictionary::GenerateNewEnumerationIndices(dictionary);
}


6848
bool ObjectHashTableShape::IsMatch(Handle<Object> key, Object* other) {
6849
  return key->SameValue(other);
6850 6851 6852
}


6853
uint32_t ObjectHashTableShape::Hash(Handle<Object> key) {
6854
  return Smi::cast(key->GetHash())->value();
6855 6856 6857
}


6858 6859
uint32_t ObjectHashTableShape::HashForObject(Handle<Object> key,
                                             Object* other) {
6860
  return Smi::cast(other->GetHash())->value();
6861 6862 6863
}


6864 6865
Handle<Object> ObjectHashTableShape::AsHandle(Isolate* isolate,
                                              Handle<Object> key) {
6866 6867 6868 6869
  return key;
}


6870 6871
Handle<ObjectHashTable> ObjectHashTable::Shrink(
    Handle<ObjectHashTable> table, Handle<Object> key) {
6872
  return DerivedHashTable::Shrink(table, key);
6873 6874 6875
}


6876
template <int entrysize>
6877
bool WeakHashTableShape<entrysize>::IsMatch(Handle<Object> key, Object* other) {
6878 6879 6880 6881 6882
  return key->SameValue(other);
}


template <int entrysize>
6883 6884
uint32_t WeakHashTableShape<entrysize>::Hash(Handle<Object> key) {
  intptr_t hash = reinterpret_cast<intptr_t>(*key);
6885 6886 6887 6888 6889
  return (uint32_t)(hash & 0xFFFFFFFF);
}


template <int entrysize>
6890
uint32_t WeakHashTableShape<entrysize>::HashForObject(Handle<Object> key,
6891 6892 6893 6894 6895 6896 6897
                                                      Object* other) {
  intptr_t hash = reinterpret_cast<intptr_t>(other);
  return (uint32_t)(hash & 0xFFFFFFFF);
}


template <int entrysize>
6898 6899
Handle<Object> WeakHashTableShape<entrysize>::AsHandle(Isolate* isolate,
                                                       Handle<Object> key) {
6900 6901 6902 6903
  return key;
}


6904
void Map::ClearCodeCache(Heap* heap) {
6905 6906 6907
  // No write barrier is needed since empty_fixed_array is not in new space.
  // Please note this function is used during marking:
  //  - MarkCompactCollector::MarkUnmarkedObject
6908
  //  - IncrementalMarking::Step
6909 6910
  ASSERT(!heap->InNewSpace(heap->empty_fixed_array()));
  WRITE_FIELD(this, kCodeCacheOffset, heap->empty_fixed_array());
6911 6912 6913
}


6914 6915 6916
void JSArray::EnsureSize(Handle<JSArray> array, int required_size) {
  ASSERT(array->HasFastSmiOrObjectElements());
  Handle<FixedArray> elts = handle(FixedArray::cast(array->elements()));
6917 6918 6919 6920
  const int kArraySizeThatFitsComfortablyInNewSpace = 128;
  if (elts->length() < required_size) {
    // Doubling in size would be overkill, but leave some slack to avoid
    // constantly growing.
6921
    Expand(array, required_size + (required_size >> 3));
6922
    // It's a performance benefit to keep a frequently used array in new-space.
6923
  } else if (!array->GetHeap()->new_space()->Contains(*elts) &&
6924 6925 6926
             required_size < kArraySizeThatFitsComfortablyInNewSpace) {
    // Expand will allocate a new backing store in new space even if the size
    // we asked for isn't larger than what we had before.
6927
    Expand(array, required_size);
6928
  }
6929 6930 6931
}


6932
void JSArray::set_length(Smi* length) {
6933
  // Don't need a write barrier for a Smi.
6934 6935 6936 6937
  set_length(static_cast<Object*>(length), SKIP_WRITE_BARRIER);
}


6938 6939 6940 6941 6942 6943 6944
bool JSArray::AllowsSetElementsLength() {
  bool result = elements()->IsFixedArray() || elements()->IsFixedDoubleArray();
  ASSERT(result == !HasExternalArrayElements());
  return result;
}


6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957
void JSArray::SetContent(Handle<JSArray> array,
                         Handle<FixedArrayBase> storage) {
  EnsureCanContainElements(array, storage, storage->length(),
                           ALLOW_COPIED_DOUBLE_ELEMENTS);

  ASSERT((storage->map() == array->GetHeap()->fixed_double_array_map() &&
          IsFastDoubleElementsKind(array->GetElementsKind())) ||
         ((storage->map() != array->GetHeap()->fixed_double_array_map()) &&
          (IsFastObjectElementsKind(array->GetElementsKind()) ||
           (IsFastSmiElementsKind(array->GetElementsKind()) &&
            Handle<FixedArray>::cast(storage)->ContainsOnlySmisOrHoles()))));
  array->set_elements(*storage);
  array->set_length(Smi::FromInt(storage->length()));
6958 6959 6960
}


6961
Handle<Object> TypeFeedbackInfo::UninitializedSentinel(Isolate* isolate) {
6962
  return isolate->factory()->uninitialized_symbol();
6963 6964 6965
}


6966
Handle<Object> TypeFeedbackInfo::MegamorphicSentinel(Isolate* isolate) {
6967
  return isolate->factory()->megamorphic_symbol();
6968 6969 6970
}


6971
Handle<Object> TypeFeedbackInfo::MonomorphicArraySentinel(Isolate* isolate,
6972 6973 6974 6975 6976
    ElementsKind elements_kind) {
  return Handle<Object>(Smi::FromInt(static_cast<int>(elements_kind)), isolate);
}


6977
Object* TypeFeedbackInfo::RawUninitializedSentinel(Heap* heap) {
6978
  return heap->uninitialized_symbol();
6979 6980 6981
}


6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003
int TypeFeedbackInfo::ic_total_count() {
  int current = Smi::cast(READ_FIELD(this, kStorage1Offset))->value();
  return ICTotalCountField::decode(current);
}


void TypeFeedbackInfo::set_ic_total_count(int count) {
  int value = Smi::cast(READ_FIELD(this, kStorage1Offset))->value();
  value = ICTotalCountField::update(value,
                                    ICTotalCountField::decode(count));
  WRITE_FIELD(this, kStorage1Offset, Smi::FromInt(value));
}


int TypeFeedbackInfo::ic_with_type_info_count() {
  int current = Smi::cast(READ_FIELD(this, kStorage2Offset))->value();
  return ICsWithTypeInfoCountField::decode(current);
}


void TypeFeedbackInfo::change_ic_with_type_info_count(int delta) {
  int value = Smi::cast(READ_FIELD(this, kStorage2Offset))->value();
7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014
  int new_count = ICsWithTypeInfoCountField::decode(value) + delta;
  // We can get negative count here when the type-feedback info is
  // shared between two code objects. The can only happen when
  // the debugger made a shallow copy of code object (see Heap::CopyCode).
  // Since we do not optimize when the debugger is active, we can skip
  // this counter update.
  if (new_count >= 0) {
    new_count &= ICsWithTypeInfoCountField::kMask;
    value = ICsWithTypeInfoCountField::update(value, new_count);
    WRITE_FIELD(this, kStorage2Offset, Smi::FromInt(value));
  }
7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059
}


void TypeFeedbackInfo::initialize_storage() {
  WRITE_FIELD(this, kStorage1Offset, Smi::FromInt(0));
  WRITE_FIELD(this, kStorage2Offset, Smi::FromInt(0));
}


void TypeFeedbackInfo::change_own_type_change_checksum() {
  int value = Smi::cast(READ_FIELD(this, kStorage1Offset))->value();
  int checksum = OwnTypeChangeChecksum::decode(value);
  checksum = (checksum + 1) % (1 << kTypeChangeChecksumBits);
  value = OwnTypeChangeChecksum::update(value, checksum);
  // Ensure packed bit field is in Smi range.
  if (value > Smi::kMaxValue) value |= Smi::kMinValue;
  if (value < Smi::kMinValue) value &= ~Smi::kMinValue;
  WRITE_FIELD(this, kStorage1Offset, Smi::FromInt(value));
}


void TypeFeedbackInfo::set_inlined_type_change_checksum(int checksum) {
  int value = Smi::cast(READ_FIELD(this, kStorage2Offset))->value();
  int mask = (1 << kTypeChangeChecksumBits) - 1;
  value = InlinedTypeChangeChecksum::update(value, checksum & mask);
  // Ensure packed bit field is in Smi range.
  if (value > Smi::kMaxValue) value |= Smi::kMinValue;
  if (value < Smi::kMinValue) value &= ~Smi::kMinValue;
  WRITE_FIELD(this, kStorage2Offset, Smi::FromInt(value));
}


int TypeFeedbackInfo::own_type_change_checksum() {
  int value = Smi::cast(READ_FIELD(this, kStorage1Offset))->value();
  return OwnTypeChangeChecksum::decode(value);
}


bool TypeFeedbackInfo::matches_inlined_type_change_checksum(int checksum) {
  int value = Smi::cast(READ_FIELD(this, kStorage2Offset))->value();
  int mask = (1 << kTypeChangeChecksumBits) - 1;
  return InlinedTypeChangeChecksum::decode(value) == (checksum & mask);
}


7060 7061 7062
SMI_ACCESSORS(AliasedArgumentsEntry, aliased_context_slot, kAliasedContextSlot)


7063 7064 7065 7066 7067 7068 7069 7070 7071 7072
Relocatable::Relocatable(Isolate* isolate) {
  isolate_ = isolate;
  prev_ = isolate->relocatable_top();
  isolate->set_relocatable_top(this);
}


Relocatable::~Relocatable() {
  ASSERT_EQ(isolate_->relocatable_top(), this);
  isolate_->set_relocatable_top(prev_);
7073 7074 7075
}


7076 7077 7078 7079 7080
int JSObject::BodyDescriptor::SizeOf(Map* map, HeapObject* object) {
  return map->instance_size();
}


7081
void Foreign::ForeignIterateBody(ObjectVisitor* v) {
7082
  v->VisitExternalReference(
7083
      reinterpret_cast<Address*>(FIELD_ADDR(this, kForeignAddressOffset)));
7084 7085 7086 7087
}


template<typename StaticVisitor>
7088
void Foreign::ForeignIterateBody() {
7089
  StaticVisitor::VisitExternalReference(
7090
      reinterpret_cast<Address*>(FIELD_ADDR(this, kForeignAddressOffset)));
7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127
}


void ExternalAsciiString::ExternalAsciiStringIterateBody(ObjectVisitor* v) {
  typedef v8::String::ExternalAsciiStringResource Resource;
  v->VisitExternalAsciiString(
      reinterpret_cast<Resource**>(FIELD_ADDR(this, kResourceOffset)));
}


template<typename StaticVisitor>
void ExternalAsciiString::ExternalAsciiStringIterateBody() {
  typedef v8::String::ExternalAsciiStringResource Resource;
  StaticVisitor::VisitExternalAsciiString(
      reinterpret_cast<Resource**>(FIELD_ADDR(this, kResourceOffset)));
}


void ExternalTwoByteString::ExternalTwoByteStringIterateBody(ObjectVisitor* v) {
  typedef v8::String::ExternalStringResource Resource;
  v->VisitExternalTwoByteString(
      reinterpret_cast<Resource**>(FIELD_ADDR(this, kResourceOffset)));
}


template<typename StaticVisitor>
void ExternalTwoByteString::ExternalTwoByteStringIterateBody() {
  typedef v8::String::ExternalStringResource Resource;
  StaticVisitor::VisitExternalTwoByteString(
      reinterpret_cast<Resource**>(FIELD_ADDR(this, kResourceOffset)));
}


template<int start_offset, int end_offset, int size>
void FixedBodyDescriptor<start_offset, end_offset, size>::IterateBody(
    HeapObject* obj,
    ObjectVisitor* v) {
7128 7129
    v->VisitPointers(HeapObject::RawField(obj, start_offset),
                     HeapObject::RawField(obj, end_offset));
7130 7131 7132 7133 7134 7135 7136
}


template<int start_offset>
void FlexibleBodyDescriptor<start_offset>::IterateBody(HeapObject* obj,
                                                       int object_size,
                                                       ObjectVisitor* v) {
7137 7138
  v->VisitPointers(HeapObject::RawField(obj, start_offset),
                   HeapObject::RawField(obj, object_size));
7139 7140 7141
}


7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171
template<class Derived, class TableType>
Object* OrderedHashTableIterator<Derived, TableType>::CurrentKey() {
  TableType* table(TableType::cast(this->table()));
  int index = Smi::cast(this->index())->value();
  Object* key = table->KeyAt(index);
  ASSERT(!key->IsTheHole());
  return key;
}


void JSSetIterator::PopulateValueArray(FixedArray* array) {
  array->set(0, CurrentKey());
}


void JSMapIterator::PopulateValueArray(FixedArray* array) {
  array->set(0, CurrentKey());
  array->set(1, CurrentValue());
}


Object* JSMapIterator::CurrentValue() {
  OrderedHashMap* table(OrderedHashMap::cast(this->table()));
  int index = Smi::cast(this->index())->value();
  Object* value = table->ValueAt(index);
  ASSERT(!value->IsTheHole());
  return value;
}


7172
#undef TYPE_CHECKER
7173 7174 7175
#undef CAST_ACCESSOR
#undef INT_ACCESSORS
#undef ACCESSORS
7176 7177
#undef ACCESSORS_TO_SMI
#undef SMI_ACCESSORS
7178 7179
#undef SYNCHRONIZED_SMI_ACCESSORS
#undef NOBARRIER_SMI_ACCESSORS
7180 7181
#undef BOOL_GETTER
#undef BOOL_ACCESSORS
7182
#undef FIELD_ADDR
7183
#undef FIELD_ADDR_CONST
7184
#undef READ_FIELD
7185
#undef NOBARRIER_READ_FIELD
7186
#undef WRITE_FIELD
7187
#undef NOBARRIER_WRITE_FIELD
7188
#undef WRITE_BARRIER
7189
#undef CONDITIONAL_WRITE_BARRIER
7190 7191 7192 7193
#undef READ_DOUBLE_FIELD
#undef WRITE_DOUBLE_FIELD
#undef READ_INT_FIELD
#undef WRITE_INT_FIELD
7194 7195 7196 7197
#undef READ_INTPTR_FIELD
#undef WRITE_INTPTR_FIELD
#undef READ_UINT32_FIELD
#undef WRITE_UINT32_FIELD
7198 7199 7200 7201
#undef READ_SHORT_FIELD
#undef WRITE_SHORT_FIELD
#undef READ_BYTE_FIELD
#undef WRITE_BYTE_FIELD
7202 7203
#undef NOBARRIER_READ_BYTE_FIELD
#undef NOBARRIER_WRITE_BYTE_FIELD
7204 7205 7206 7207

} }  // namespace v8::internal

#endif  // V8_OBJECTS_INL_H_