elements.cc 71.6 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
#include "src/v8.h"
6

7 8 9 10 11
#include "src/arguments.h"
#include "src/conversions.h"
#include "src/elements.h"
#include "src/objects.h"
#include "src/utils.h"
12 13 14 15 16 17 18 19

// Each concrete ElementsAccessor can handle exactly one ElementsKind,
// several abstract ElementsAccessor classes are used to allow sharing
// common code.
//
// Inheritance hierarchy:
// - ElementsAccessorBase                        (abstract)
//   - FastElementsAccessor                      (abstract)
20 21 22 23 24
//     - FastSmiOrObjectElementsAccessor
//       - FastPackedSmiElementsAccessor
//       - FastHoleySmiElementsAccessor
//       - FastPackedObjectElementsAccessor
//       - FastHoleyObjectElementsAccessor
25
//     - FastDoubleElementsAccessor
26 27
//       - FastPackedDoubleElementsAccessor
//       - FastHoleyDoubleElementsAccessor
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
//   - TypedElementsAccessor: template, with instantiations:
//     - ExternalInt8ElementsAccessor
//     - ExternalUint8ElementsAccessor
//     - ExternalInt16ElementsAccessor
//     - ExternalUint16ElementsAccessor
//     - ExternalInt32ElementsAccessor
//     - ExternalUint32ElementsAccessor
//     - ExternalFloat32ElementsAccessor
//     - ExternalFloat64ElementsAccessor
//     - ExternalUint8ClampedElementsAccessor
//     - FixedUint8ElementsAccessor
//     - FixedInt8ElementsAccessor
//     - FixedUint16ElementsAccessor
//     - FixedInt16ElementsAccessor
//     - FixedUint32ElementsAccessor
//     - FixedInt32ElementsAccessor
//     - FixedFloat32ElementsAccessor
//     - FixedFloat64ElementsAccessor
//     - FixedUint8ClampedElementsAccessor
47
//   - DictionaryElementsAccessor
48
//   - SloppyArgumentsElementsAccessor
49 50


51 52 53 54
namespace v8 {
namespace internal {


55 56 57
static const int kPackedSizeNotKnown = -1;


58 59 60 61 62 63
// First argument in list is the accessor class, the second argument is the
// accessor ElementsKind, and the third is the backing store class.  Use the
// fast element handler for smi-only arrays.  The implementation is currently
// identical.  Note that the order must match that of the ElementsKind enum for
// the |accessor_array[]| below to work.
#define ELEMENTS_LIST(V)                                                \
64 65 66 67 68 69 70 71 72
  V(FastPackedSmiElementsAccessor, FAST_SMI_ELEMENTS, FixedArray)       \
  V(FastHoleySmiElementsAccessor, FAST_HOLEY_SMI_ELEMENTS,              \
    FixedArray)                                                         \
  V(FastPackedObjectElementsAccessor, FAST_ELEMENTS, FixedArray)        \
  V(FastHoleyObjectElementsAccessor, FAST_HOLEY_ELEMENTS, FixedArray)   \
  V(FastPackedDoubleElementsAccessor, FAST_DOUBLE_ELEMENTS,             \
    FixedDoubleArray)                                                   \
  V(FastHoleyDoubleElementsAccessor, FAST_HOLEY_DOUBLE_ELEMENTS,        \
    FixedDoubleArray)                                                   \
73 74
  V(DictionaryElementsAccessor, DICTIONARY_ELEMENTS,                    \
    SeededNumberDictionary)                                             \
75
  V(SloppyArgumentsElementsAccessor, SLOPPY_ARGUMENTS_ELEMENTS,         \
76
    FixedArray)                                                         \
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
  V(ExternalInt8ElementsAccessor, EXTERNAL_INT8_ELEMENTS,               \
    ExternalInt8Array)                                                  \
  V(ExternalUint8ElementsAccessor,                                      \
    EXTERNAL_UINT8_ELEMENTS, ExternalUint8Array)                        \
  V(ExternalInt16ElementsAccessor, EXTERNAL_INT16_ELEMENTS,             \
    ExternalInt16Array)                                                 \
  V(ExternalUint16ElementsAccessor,                                     \
    EXTERNAL_UINT16_ELEMENTS, ExternalUint16Array)                      \
  V(ExternalInt32ElementsAccessor, EXTERNAL_INT32_ELEMENTS,             \
    ExternalInt32Array)                                                 \
  V(ExternalUint32ElementsAccessor,                                     \
    EXTERNAL_UINT32_ELEMENTS, ExternalUint32Array)                      \
  V(ExternalFloat32ElementsAccessor,                                    \
    EXTERNAL_FLOAT32_ELEMENTS, ExternalFloat32Array)                    \
  V(ExternalFloat64ElementsAccessor,                                    \
    EXTERNAL_FLOAT64_ELEMENTS, ExternalFloat64Array)                    \
  V(ExternalUint8ClampedElementsAccessor,                               \
    EXTERNAL_UINT8_CLAMPED_ELEMENTS,                                    \
    ExternalUint8ClampedArray)                                          \
  V(FixedUint8ElementsAccessor, UINT8_ELEMENTS, FixedUint8Array)        \
  V(FixedInt8ElementsAccessor, INT8_ELEMENTS, FixedInt8Array)           \
  V(FixedUint16ElementsAccessor, UINT16_ELEMENTS, FixedUint16Array)     \
  V(FixedInt16ElementsAccessor, INT16_ELEMENTS, FixedInt16Array)        \
  V(FixedUint32ElementsAccessor, UINT32_ELEMENTS, FixedUint32Array)     \
  V(FixedInt32ElementsAccessor, INT32_ELEMENTS, FixedInt32Array)        \
  V(FixedFloat32ElementsAccessor, FLOAT32_ELEMENTS, FixedFloat32Array)  \
  V(FixedFloat64ElementsAccessor, FLOAT64_ELEMENTS, FixedFloat64Array)  \
  V(FixedUint8ClampedElementsAccessor, UINT8_CLAMPED_ELEMENTS,          \
105
    FixedUint8ClampedArray)
106 107 108 109 110 111 112 113 114


template<ElementsKind Kind> class ElementsKindTraits {
 public:
  typedef FixedArrayBase BackingStore;
};

#define ELEMENTS_TRAITS(Class, KindParam, Store)               \
template<> class ElementsKindTraits<KindParam> {               \
115
 public:   /* NOLINT */                                        \
116 117 118 119 120 121 122
  static const ElementsKind Kind = KindParam;                  \
  typedef Store BackingStore;                                  \
};
ELEMENTS_LIST(ELEMENTS_TRAITS)
#undef ELEMENTS_TRAITS


123
ElementsAccessor** ElementsAccessor::elements_accessors_ = NULL;
124 125


126 127 128
static bool HasKey(Handle<FixedArray> array, Handle<Object> key_handle) {
  DisallowHeapAllocation no_gc;
  Object* key = *key_handle;
129 130 131 132 133 134 135 136 137 138 139 140 141
  int len0 = array->length();
  for (int i = 0; i < len0; i++) {
    Object* element = array->get(i);
    if (element->IsSmi() && element == key) return true;
    if (element->IsString() &&
        key->IsString() && String::cast(element)->Equals(String::cast(key))) {
      return true;
    }
  }
  return false;
}


142 143
MUST_USE_RESULT
static MaybeHandle<Object> ThrowArrayLengthRangeError(Isolate* isolate) {
144 145 146
  THROW_NEW_ERROR(isolate, NewRangeError("invalid_array_length",
                                         HandleVector<Object>(NULL, 0)),
                  Object);
147 148 149
}


150
static void CopyObjectToObjectElements(FixedArrayBase* from_base,
151 152
                                       ElementsKind from_kind,
                                       uint32_t from_start,
153 154
                                       FixedArrayBase* to_base,
                                       ElementsKind to_kind, uint32_t to_start,
155
                                       int raw_copy_size) {
156
  DCHECK(to_base->map() !=
157
      from_base->GetIsolate()->heap()->fixed_cow_array_map());
158
  DisallowHeapAllocation no_allocation;
159 160
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
161
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
162
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
163 164
    copy_size = Min(from_base->length() - from_start,
                    to_base->length() - to_start);
165
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
166
      int start = to_start + copy_size;
167
      int length = to_base->length() - start;
168
      if (length > 0) {
169
        Heap* heap = from_base->GetHeap();
170
        MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
171
                      heap->the_hole_value(), length);
172 173
      }
    }
174
  }
175
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
176
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
177
  if (copy_size == 0) return;
178 179
  FixedArray* from = FixedArray::cast(from_base);
  FixedArray* to = FixedArray::cast(to_base);
180 181
  DCHECK(IsFastSmiOrObjectElementsKind(from_kind));
  DCHECK(IsFastSmiOrObjectElementsKind(to_kind));
182 183 184 185
  Address to_address = to->address() + FixedArray::kHeaderSize;
  Address from_address = from->address() + FixedArray::kHeaderSize;
  CopyWords(reinterpret_cast<Object**>(to_address) + to_start,
            reinterpret_cast<Object**>(from_address) + from_start,
186
            static_cast<size_t>(copy_size));
187 188
  if (IsFastObjectElementsKind(from_kind) &&
      IsFastObjectElementsKind(to_kind)) {
189
    Heap* heap = from->GetHeap();
190
    if (!heap->InNewSpace(to)) {
191 192
      heap->RecordWrites(to->address(),
                         to->OffsetOfElementAt(to_start),
193 194
                         copy_size);
    }
195
    heap->incremental_marking()->RecordWrites(to);
196 197 198 199
  }
}


200 201 202
static void CopyDictionaryToObjectElements(
    FixedArrayBase* from_base, uint32_t from_start, FixedArrayBase* to_base,
    ElementsKind to_kind, uint32_t to_start, int raw_copy_size) {
203
  DisallowHeapAllocation no_allocation;
204
  SeededNumberDictionary* from = SeededNumberDictionary::cast(from_base);
205 206 207
  int copy_size = raw_copy_size;
  Heap* heap = from->GetHeap();
  if (raw_copy_size < 0) {
208
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
209 210 211
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
    copy_size = from->max_number_key() + 1 - from_start;
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
212
      int start = to_start + copy_size;
213
      int length = to_base->length() - start;
214 215
      if (length > 0) {
        Heap* heap = from->GetHeap();
216
        MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
217
                      heap->the_hole_value(), length);
218 219 220
      }
    }
  }
221 222
  DCHECK(to_base != from_base);
  DCHECK(IsFastSmiOrObjectElementsKind(to_kind));
223
  if (copy_size == 0) return;
224
  FixedArray* to = FixedArray::cast(to_base);
225 226 227 228
  uint32_t to_length = to->length();
  if (to_start + copy_size > to_length) {
    copy_size = to_length - to_start;
  }
229 230 231 232
  for (int i = 0; i < copy_size; i++) {
    int entry = from->FindEntry(i + from_start);
    if (entry != SeededNumberDictionary::kNotFound) {
      Object* value = from->ValueAt(entry);
233
      DCHECK(!value->IsTheHole());
234 235 236 237 238
      to->set(i + to_start, value, SKIP_WRITE_BARRIER);
    } else {
      to->set_the_hole(i + to_start);
    }
  }
239
  if (IsFastObjectElementsKind(to_kind)) {
240
    if (!heap->InNewSpace(to)) {
241 242 243
      heap->RecordWrites(to->address(),
                         to->OffsetOfElementAt(to_start),
                         copy_size);
244
    }
245
    heap->incremental_marking()->RecordWrites(to);
246 247 248 249
  }
}


250 251 252 253
// NOTE: this method violates the handlified function signature convention:
// raw pointer parameters in the function that allocates.
// See ElementsAccessorBase::CopyElements() for details.
static void CopyDoubleToObjectElements(FixedArrayBase* from_base,
254
                                       uint32_t from_start,
255 256
                                       FixedArrayBase* to_base,
                                       ElementsKind to_kind, uint32_t to_start,
257
                                       int raw_copy_size) {
258
  DCHECK(IsFastSmiOrObjectElementsKind(to_kind));
259 260
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
261
    DisallowHeapAllocation no_allocation;
262
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
263
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
264 265
    copy_size = Min(from_base->length() - from_start,
                    to_base->length() - to_start);
266
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
267 268 269 270
      // Also initialize the area that will be copied over since HeapNumber
      // allocation below can cause an incremental marking step, requiring all
      // existing heap objects to be propertly initialized.
      int start = to_start;
271
      int length = to_base->length() - start;
272
      if (length > 0) {
273
        Heap* heap = from_base->GetHeap();
274
        MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
275
                      heap->the_hole_value(), length);
276 277
      }
    }
278
  }
279
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
280
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
281
  if (copy_size == 0) return;
282 283 284

  // From here on, the code below could actually allocate. Therefore the raw
  // values are wrapped into handles.
285
  Isolate* isolate = from_base->GetIsolate();
286 287
  Handle<FixedDoubleArray> from(FixedDoubleArray::cast(from_base), isolate);
  Handle<FixedArray> to(FixedArray::cast(to_base), isolate);
288
  for (int i = 0; i < copy_size; ++i) {
289
    HandleScope scope(isolate);
290
    if (IsFastSmiElementsKind(to_kind)) {
291 292
      UNIMPLEMENTED();
    } else {
293
      DCHECK(IsFastObjectElementsKind(to_kind));
294
      Handle<Object> value = FixedDoubleArray::get(from, i + from_start);
295
      to->set(i + to_start, *value, UPDATE_WRITE_BARRIER);
296 297 298 299 300
    }
  }
}


301
static void CopyDoubleToDoubleElements(FixedArrayBase* from_base,
302
                                       uint32_t from_start,
303 304
                                       FixedArrayBase* to_base,
                                       uint32_t to_start, int raw_copy_size) {
305
  DisallowHeapAllocation no_allocation;
306 307
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
308
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
309
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
310 311
    copy_size = Min(from_base->length() - from_start,
                    to_base->length() - to_start);
312
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
313
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
314
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
315 316
      }
    }
317
  }
318
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
319
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
320
  if (copy_size == 0) return;
321 322
  FixedDoubleArray* from = FixedDoubleArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
323 324 325 326
  Address to_address = to->address() + FixedDoubleArray::kHeaderSize;
  Address from_address = from->address() + FixedDoubleArray::kHeaderSize;
  to_address += kDoubleSize * to_start;
  from_address += kDoubleSize * from_start;
327
  int words_per_double = (kDoubleSize / kPointerSize);
328 329
  CopyWords(reinterpret_cast<Object**>(to_address),
            reinterpret_cast<Object**>(from_address),
330
            static_cast<size_t>(words_per_double * copy_size));
331 332 333
}


334
static void CopySmiToDoubleElements(FixedArrayBase* from_base,
335
                                    uint32_t from_start,
336
                                    FixedArrayBase* to_base, uint32_t to_start,
337
                                    int raw_copy_size) {
338
  DisallowHeapAllocation no_allocation;
339 340
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
341
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
342
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
343
    copy_size = from_base->length() - from_start;
344
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
345
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
346
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
347 348 349
      }
    }
  }
350
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
351
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
352
  if (copy_size == 0) return;
353 354 355
  FixedArray* from = FixedArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
  Object* the_hole = from->GetHeap()->the_hole_value();
356 357 358
  for (uint32_t from_end = from_start + static_cast<uint32_t>(copy_size);
       from_start < from_end; from_start++, to_start++) {
    Object* hole_or_smi = from->get(from_start);
359
    if (hole_or_smi == the_hole) {
360 361 362 363 364 365 366 367
      to->set_the_hole(to_start);
    } else {
      to->set(to_start, Smi::cast(hole_or_smi)->value());
    }
  }
}


368
static void CopyPackedSmiToDoubleElements(FixedArrayBase* from_base,
369
                                          uint32_t from_start,
370 371
                                          FixedArrayBase* to_base,
                                          uint32_t to_start, int packed_size,
372
                                          int raw_copy_size) {
373
  DisallowHeapAllocation no_allocation;
374 375 376
  int copy_size = raw_copy_size;
  uint32_t to_end;
  if (raw_copy_size < 0) {
377
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
378
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
379
    copy_size = packed_size - from_start;
380
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
381
      to_end = to_base->length();
382
      for (uint32_t i = to_start + copy_size; i < to_end; ++i) {
383
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
384
      }
385 386 387 388 389 390
    } else {
      to_end = to_start + static_cast<uint32_t>(copy_size);
    }
  } else {
    to_end = to_start + static_cast<uint32_t>(copy_size);
  }
391 392 393
  DCHECK(static_cast<int>(to_end) <= to_base->length());
  DCHECK(packed_size >= 0 && packed_size <= copy_size);
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
394
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
395
  if (copy_size == 0) return;
396 397
  FixedArray* from = FixedArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
398 399 400
  for (uint32_t from_end = from_start + static_cast<uint32_t>(packed_size);
       from_start < from_end; from_start++, to_start++) {
    Object* smi = from->get(from_start);
401
    DCHECK(!smi->IsTheHole());
402 403 404 405 406
    to->set(to_start, Smi::cast(smi)->value());
  }
}


407
static void CopyObjectToDoubleElements(FixedArrayBase* from_base,
408
                                       uint32_t from_start,
409 410
                                       FixedArrayBase* to_base,
                                       uint32_t to_start, int raw_copy_size) {
411
  DisallowHeapAllocation no_allocation;
412 413
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
414
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
415
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
416
    copy_size = from_base->length() - from_start;
417
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
418
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
419
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
420 421 422
      }
    }
  }
423
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
424
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
425
  if (copy_size == 0) return;
426 427 428
  FixedArray* from = FixedArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
  Object* the_hole = from->GetHeap()->the_hole_value();
429 430 431
  for (uint32_t from_end = from_start + copy_size;
       from_start < from_end; from_start++, to_start++) {
    Object* hole_or_object = from->get(from_start);
432
    if (hole_or_object == the_hole) {
433
      to->set_the_hole(to_start);
434
    } else {
435
      to->set(to_start, hole_or_object->Number());
436 437 438 439 440
    }
  }
}


441
static void CopyDictionaryToDoubleElements(FixedArrayBase* from_base,
442
                                           uint32_t from_start,
443
                                           FixedArrayBase* to_base,
444 445
                                           uint32_t to_start,
                                           int raw_copy_size) {
446
  DisallowHeapAllocation no_allocation;
447
  SeededNumberDictionary* from = SeededNumberDictionary::cast(from_base);
448 449
  int copy_size = raw_copy_size;
  if (copy_size < 0) {
450
    DCHECK(copy_size == ElementsAccessor::kCopyToEnd ||
451 452 453
           copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
    copy_size = from->max_number_key() + 1 - from_start;
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
454
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
455
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
456 457 458 459
      }
    }
  }
  if (copy_size == 0) return;
460
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
461 462 463 464
  uint32_t to_length = to->length();
  if (to_start + copy_size > to_length) {
    copy_size = to_length - to_start;
  }
465 466 467 468 469 470 471 472 473 474 475
  for (int i = 0; i < copy_size; i++) {
    int entry = from->FindEntry(i + from_start);
    if (entry != SeededNumberDictionary::kNotFound) {
      to->set(i + to_start, from->ValueAt(entry)->Number());
    } else {
      to->set_the_hole(i + to_start);
    }
  }
}


476 477
static void TraceTopFrame(Isolate* isolate) {
  StackFrameIterator it(isolate);
478 479 480 481 482 483 484 485 486 487 488 489 490 491
  if (it.done()) {
    PrintF("unknown location (no JavaScript frames present)");
    return;
  }
  StackFrame* raw_frame = it.frame();
  if (raw_frame->is_internal()) {
    Code* apply_builtin = isolate->builtins()->builtin(
        Builtins::kFunctionApply);
    if (raw_frame->unchecked_code() == apply_builtin) {
      PrintF("apply from ");
      it.Advance();
      raw_frame = it.frame();
    }
  }
492
  JavaScriptFrame::PrintTop(isolate, stdout, false, true);
493 494 495
}


496
void CheckArrayAbuse(Handle<JSObject> obj, const char* op, uint32_t key,
497
                     bool allow_appending) {
498
  DisallowHeapAllocation no_allocation;
499 500 501
  Object* raw_length = NULL;
  const char* elements_type = "array";
  if (obj->IsJSArray()) {
502
    JSArray* array = JSArray::cast(*obj);
503 504 505 506 507 508 509 510 511 512
    raw_length = array->length();
  } else {
    raw_length = Smi::FromInt(obj->elements()->length());
    elements_type = "object";
  }

  if (raw_length->IsNumber()) {
    double n = raw_length->Number();
    if (FastI2D(FastD2UI(n)) == n) {
      int32_t int32_length = DoubleToInt32(n);
513 514 515
      uint32_t compare_length = static_cast<uint32_t>(int32_length);
      if (allow_appending) compare_length++;
      if (key >= compare_length) {
516 517 518 519
        PrintF("[OOB %s %s (%s length = %d, element accessed = %d) in ",
               elements_type, op, elements_type,
               static_cast<int>(int32_length),
               static_cast<int>(key));
520
        TraceTopFrame(obj->GetIsolate());
521 522 523 524
        PrintF("]\n");
      }
    } else {
      PrintF("[%s elements length not integer value in ", elements_type);
525
      TraceTopFrame(obj->GetIsolate());
526 527 528 529
      PrintF("]\n");
    }
  } else {
    PrintF("[%s elements length not a number in ", elements_type);
530
    TraceTopFrame(obj->GetIsolate());
531 532 533 534 535
    PrintF("]\n");
  }
}


536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
// Base class for element handler implementations. Contains the
// the common logic for objects with different ElementsKinds.
// Subclasses must specialize method for which the element
// implementation differs from the base class implementation.
//
// This class is intended to be used in the following way:
//
//   class SomeElementsAccessor :
//       public ElementsAccessorBase<SomeElementsAccessor,
//                                   BackingStoreClass> {
//     ...
//   }
//
// This is an example of the Curiously Recurring Template Pattern (see
// http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern).  We use
// CRTP to guarantee aggressive compile time optimizations (i.e.  inlining and
// specialization of SomeElementsAccessor methods).
553 554
template <typename ElementsAccessorSubclass,
          typename ElementsTraitsParam>
555
class ElementsAccessorBase : public ElementsAccessor {
556
 protected:
557 558 559 560 561 562
  explicit ElementsAccessorBase(const char* name)
      : ElementsAccessor(name) { }

  typedef ElementsTraitsParam ElementsTraits;
  typedef typename ElementsTraitsParam::BackingStore BackingStore;

563
  virtual ElementsKind kind() const FINAL OVERRIDE {
564 565
    return ElementsTraits::Kind;
  }
566

567
  static void ValidateContents(Handle<JSObject> holder, int length) {
568 569
  }

570 571
  static void ValidateImpl(Handle<JSObject> holder) {
    Handle<FixedArrayBase> fixed_array_base(holder->elements());
572 573
    if (!fixed_array_base->IsHeapObject()) return;
    // Arrays that have been shifted in place can't be verified.
574
    if (fixed_array_base->IsFiller()) return;
575 576
    int length = 0;
    if (holder->IsJSArray()) {
577
      Object* length_obj = Handle<JSArray>::cast(holder)->length();
578 579 580 581 582 583 584 585 586
      if (length_obj->IsSmi()) {
        length = Smi::cast(length_obj)->value();
      }
    } else {
      length = fixed_array_base->length();
    }
    ElementsAccessorSubclass::ValidateContents(holder, length);
  }

587
  virtual void Validate(Handle<JSObject> holder) FINAL OVERRIDE {
588
    DisallowHeapAllocation no_gc;
589
    ElementsAccessorSubclass::ValidateImpl(holder);
590 591
  }

592 593
  static bool HasElementImpl(Handle<Object> receiver,
                             Handle<JSObject> holder,
594
                             uint32_t key,
595
                             Handle<FixedArrayBase> backing_store) {
596
    return ElementsAccessorSubclass::GetAttributesImpl(
597
        receiver, holder, key, backing_store) != ABSENT;
598 599
  }

600 601 602 603
  virtual bool HasElement(
      Handle<Object> receiver,
      Handle<JSObject> holder,
      uint32_t key,
604
      Handle<FixedArrayBase> backing_store) FINAL OVERRIDE {
605
    return ElementsAccessorSubclass::HasElementImpl(
606
        receiver, holder, key, backing_store);
607 608
  }

609
  MUST_USE_RESULT virtual MaybeHandle<Object> Get(
610 611 612
      Handle<Object> receiver,
      Handle<JSObject> holder,
      uint32_t key,
613
      Handle<FixedArrayBase> backing_store) FINAL OVERRIDE {
614 615 616 617 618 619 620 621
    if (!IsExternalArrayElementsKind(ElementsTraits::Kind) &&
        FLAG_trace_js_array_abuse) {
      CheckArrayAbuse(holder, "elements read", key);
    }

    if (IsExternalArrayElementsKind(ElementsTraits::Kind) &&
        FLAG_trace_external_array_abuse) {
      CheckArrayAbuse(holder, "external elements read", key);
622 623
    }

624
    return ElementsAccessorSubclass::GetImpl(
625
        receiver, holder, key, backing_store);
626 627
  }

628 629 630 631 632
  MUST_USE_RESULT static MaybeHandle<Object> GetImpl(
      Handle<Object> receiver,
      Handle<JSObject> obj,
      uint32_t key,
      Handle<FixedArrayBase> backing_store) {
633
    if (key < ElementsAccessorSubclass::GetCapacityImpl(backing_store)) {
634 635 636 637
      return BackingStore::get(Handle<BackingStore>::cast(backing_store), key);
    } else {
      return backing_store->GetIsolate()->factory()->the_hole_value();
    }
638 639
  }

640 641 642 643
  MUST_USE_RESULT virtual PropertyAttributes GetAttributes(
      Handle<Object> receiver,
      Handle<JSObject> holder,
      uint32_t key,
644
      Handle<FixedArrayBase> backing_store) FINAL OVERRIDE {
645
    return ElementsAccessorSubclass::GetAttributesImpl(
646
        receiver, holder, key, backing_store);
647 648 649
  }

  MUST_USE_RESULT static PropertyAttributes GetAttributesImpl(
650 651
        Handle<Object> receiver,
        Handle<JSObject> obj,
652
        uint32_t key,
653
        Handle<FixedArrayBase> backing_store) {
654 655 656
    if (key >= ElementsAccessorSubclass::GetCapacityImpl(backing_store)) {
      return ABSENT;
    }
657 658 659
    return
        Handle<BackingStore>::cast(backing_store)->is_the_hole(key)
          ? ABSENT : NONE;
660 661
  }

662 663 664
  MUST_USE_RESULT virtual MaybeHandle<AccessorPair> GetAccessorPair(
      Handle<Object> receiver,
      Handle<JSObject> holder,
665
      uint32_t key,
666
      Handle<FixedArrayBase> backing_store) FINAL OVERRIDE {
667
    return ElementsAccessorSubclass::GetAccessorPairImpl(
668
        receiver, holder, key, backing_store);
669 670
  }

671 672 673 674 675 676
  MUST_USE_RESULT static MaybeHandle<AccessorPair> GetAccessorPairImpl(
      Handle<Object> receiver,
      Handle<JSObject> obj,
      uint32_t key,
      Handle<FixedArrayBase> backing_store) {
    return MaybeHandle<AccessorPair>();
677 678
  }

679
  MUST_USE_RESULT virtual MaybeHandle<Object> SetLength(
680
      Handle<JSArray> array,
681
      Handle<Object> length) FINAL OVERRIDE {
682
    return ElementsAccessorSubclass::SetLengthImpl(
683
        array, length, handle(array->elements()));
684 685
  }

686
  MUST_USE_RESULT static MaybeHandle<Object> SetLengthImpl(
687 688 689
      Handle<JSObject> obj,
      Handle<Object> length,
      Handle<FixedArrayBase> backing_store);
690

691 692
  virtual void SetCapacityAndLength(
      Handle<JSArray> array,
693
      int capacity,
694
      int length) FINAL OVERRIDE {
695 696
    ElementsAccessorSubclass::
        SetFastElementsCapacityAndLength(array, capacity, length);
697 698
  }

699
  static void SetFastElementsCapacityAndLength(
700 701 702
      Handle<JSObject> obj,
      int capacity,
      int length) {
703
    UNIMPLEMENTED();
704 705
  }

706
  MUST_USE_RESULT virtual MaybeHandle<Object> Delete(
707 708
      Handle<JSObject> obj,
      uint32_t key,
709
      JSReceiver::DeleteMode mode) OVERRIDE = 0;
710

711 712 713
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
714
                               int copy_size) {
715
    UNREACHABLE();
716 717
  }

718
  virtual void CopyElements(
719
      Handle<FixedArrayBase> from,
720 721 722 723
      uint32_t from_start,
      ElementsKind from_kind,
      Handle<FixedArrayBase> to,
      uint32_t to_start,
724
      int copy_size) FINAL OVERRIDE {
725
    DCHECK(!from.is_null());
726 727 728 729 730 731 732 733 734
    // NOTE: the ElementsAccessorSubclass::CopyElementsImpl() methods
    // violate the handlified function signature convention:
    // raw pointer parameters in the function that allocates. This is done
    // intentionally to avoid ArrayConcat() builtin performance degradation.
    // See the comment in another ElementsAccessorBase::CopyElements() for
    // details.
    ElementsAccessorSubclass::CopyElementsImpl(*from, from_start, *to,
                                               from_kind, to_start,
                                               kPackedSizeNotKnown, copy_size);
735
  }
736

737 738 739 740 741 742
  virtual void CopyElements(
      JSObject* from_holder,
      uint32_t from_start,
      ElementsKind from_kind,
      Handle<FixedArrayBase> to,
      uint32_t to_start,
743
      int copy_size) FINAL OVERRIDE {
744 745 746 747 748 749 750 751
    int packed_size = kPackedSizeNotKnown;
    bool is_packed = IsFastPackedElementsKind(from_kind) &&
        from_holder->IsJSArray();
    if (is_packed) {
      packed_size =
          Smi::cast(JSArray::cast(from_holder)->length())->value();
      if (copy_size >= 0 && packed_size > copy_size) {
        packed_size = copy_size;
752 753
      }
    }
754 755 756 757 758 759 760 761 762 763
    FixedArrayBase* from = from_holder->elements();
    // NOTE: the ElementsAccessorSubclass::CopyElementsImpl() methods
    // violate the handlified function signature convention:
    // raw pointer parameters in the function that allocates. This is done
    // intentionally to avoid ArrayConcat() builtin performance degradation.
    //
    // Details: The idea is that allocations actually happen only in case of
    // copying from object with fast double elements to object with object
    // elements. In all the other cases there are no allocations performed and
    // handle creation causes noticeable performance degradation of the builtin.
764
    ElementsAccessorSubclass::CopyElementsImpl(
765
        from, from_start, *to, from_kind, to_start, packed_size, copy_size);
766 767
  }

768
  virtual MaybeHandle<FixedArray> AddElementsToFixedArray(
769 770 771
      Handle<Object> receiver,
      Handle<JSObject> holder,
      Handle<FixedArray> to,
772
      Handle<FixedArrayBase> from) FINAL OVERRIDE {
773
    int len0 = to->length();
774
#ifdef ENABLE_SLOW_DCHECKS
775 776
    if (FLAG_enable_slow_asserts) {
      for (int i = 0; i < len0; i++) {
777
        DCHECK(!to->get(i)->IsTheHole());
778 779 780 781 782
      }
    }
#endif

    // Optimize if 'other' is empty.
783
    // We cannot optimize if 'this' is empty, as other may have holes.
784
    uint32_t len1 = ElementsAccessorSubclass::GetCapacityImpl(from);
785
    if (len1 == 0) return to;
786

787 788
    Isolate* isolate = from->GetIsolate();

789
    // Compute how many elements are not in other.
790
    uint32_t extra = 0;
791
    for (uint32_t y = 0; y < len1; y++) {
792
      uint32_t key = ElementsAccessorSubclass::GetKeyForIndexImpl(from, y);
793
      if (ElementsAccessorSubclass::HasElementImpl(
794
              receiver, holder, key, from)) {
795 796 797 798 799
        Handle<Object> value;
        ASSIGN_RETURN_ON_EXCEPTION(
            isolate, value,
            ElementsAccessorSubclass::GetImpl(receiver, holder, key, from),
            FixedArray);
800

801
        DCHECK(!value->IsTheHole());
802
        if (!HasKey(to, value)) {
803 804 805
          extra++;
        }
      }
806 807
    }

808
    if (extra == 0) return to;
809 810

    // Allocate the result
811
    Handle<FixedArray> result = isolate->factory()->NewFixedArray(len0 + extra);
812 813 814

    // Fill in the content
    {
815
      DisallowHeapAllocation no_gc;
816 817
      WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
      for (int i = 0; i < len0; i++) {
818
        Object* e = to->get(i);
819
        DCHECK(e->IsString() || e->IsNumber());
820 821 822
        result->set(i, e, mode);
      }
    }
823
    // Fill in the extra values.
824
    uint32_t index = 0;
825
    for (uint32_t y = 0; y < len1; y++) {
826
      uint32_t key =
827
          ElementsAccessorSubclass::GetKeyForIndexImpl(from, y);
828
      if (ElementsAccessorSubclass::HasElementImpl(
829
              receiver, holder, key, from)) {
830 831 832 833 834
        Handle<Object> value;
        ASSIGN_RETURN_ON_EXCEPTION(
            isolate, value,
            ElementsAccessorSubclass::GetImpl(receiver, holder, key, from),
            FixedArray);
835
        if (!value->IsTheHole() && !HasKey(to, value)) {
836
          result->set(len0 + index, *value);
837 838
          index++;
        }
839 840
      }
    }
841
    DCHECK(extra == index);
842 843 844
    return result;
  }

845
 protected:
846
  static uint32_t GetCapacityImpl(Handle<FixedArrayBase> backing_store) {
847
    return backing_store->length();
848 849
  }

850
  virtual uint32_t GetCapacity(Handle<FixedArrayBase> backing_store)
851
      FINAL OVERRIDE {
852
    return ElementsAccessorSubclass::GetCapacityImpl(backing_store);
853 854
  }

855
  static uint32_t GetKeyForIndexImpl(Handle<FixedArrayBase> backing_store,
856
                                     uint32_t index) {
857 858 859
    return index;
  }

860
  virtual uint32_t GetKeyForIndex(Handle<FixedArrayBase> backing_store,
861
                                  uint32_t index) FINAL OVERRIDE {
862
    return ElementsAccessorSubclass::GetKeyForIndexImpl(backing_store, index);
863 864 865 866 867 868 869
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(ElementsAccessorBase);
};


870 871
// Super class for all fast element arrays.
template<typename FastElementsAccessorSubclass,
872
         typename KindTraits>
873
class FastElementsAccessor
874
    : public ElementsAccessorBase<FastElementsAccessorSubclass, KindTraits> {
875 876 877
 public:
  explicit FastElementsAccessor(const char* name)
      : ElementsAccessorBase<FastElementsAccessorSubclass,
878
                             KindTraits>(name) {}
879
 protected:
880
  friend class ElementsAccessorBase<FastElementsAccessorSubclass, KindTraits>;
881
  friend class SloppyArgumentsElementsAccessor;
882 883

  typedef typename KindTraits::BackingStore BackingStore;
884

885
  // Adjusts the length of the fast backing store.
886 887 888 889 890 891
  static Handle<Object> SetLengthWithoutNormalize(
      Handle<FixedArrayBase> backing_store,
      Handle<JSArray> array,
      Handle<Object> length_object,
      uint32_t length) {
    Isolate* isolate = array->GetIsolate();
892
    uint32_t old_capacity = backing_store->length();
893
    Handle<Object> old_length(array->length(), isolate);
894
    bool same_or_smaller_size = old_length->IsSmi() &&
895
        static_cast<uint32_t>(Handle<Smi>::cast(old_length)->value()) >= length;
896 897
    ElementsKind kind = array->GetElementsKind();

898
    if (!same_or_smaller_size && IsFastElementsKind(kind) &&
899 900
        !IsFastHoleyElementsKind(kind)) {
      kind = GetHoleyElementsKind(kind);
901
      JSObject::TransitionElementsKind(array, kind);
902
    }
903 904 905

    // Check whether the backing store should be shrunk.
    if (length <= old_capacity) {
906
      if (array->HasFastSmiOrObjectElements()) {
907
        backing_store = JSObject::EnsureWritableFastElements(array);
908 909 910 911 912 913
      }
      if (2 * length <= old_capacity) {
        // If more than half the elements won't be used, trim the array.
        if (length == 0) {
          array->initialize_elements();
        } else {
914 915
          isolate->heap()->RightTrimFixedArray<Heap::FROM_MUTATOR>(
              *backing_store, old_capacity - length);
916 917 918
        }
      } else {
        // Otherwise, fill the unused tail with holes.
919
        int old_length = FastD2IChecked(array->length()->Number());
920
        for (int i = length; i < old_length; i++) {
921
          Handle<BackingStore>::cast(backing_store)->set_the_hole(i);
922 923 924 925 926 927 928 929
        }
      }
      return length_object;
    }

    // Check whether the backing store should be expanded.
    uint32_t min = JSObject::NewElementsCapacity(old_capacity);
    uint32_t new_capacity = length > min ? length : min;
930 931 932 933
    FastElementsAccessorSubclass::SetFastElementsCapacityAndLength(
        array, new_capacity, length);
    JSObject::ValidateElements(array);
    return length_object;
934 935
  }

936 937 938
  static Handle<Object> DeleteCommon(Handle<JSObject> obj,
                                     uint32_t key,
                                     JSReceiver::DeleteMode mode) {
939
    DCHECK(obj->HasFastSmiOrObjectElements() ||
940
           obj->HasFastDoubleElements() ||
941
           obj->HasFastArgumentsElements());
942
    Isolate* isolate = obj->GetIsolate();
943
    Heap* heap = obj->GetHeap();
944
    Handle<FixedArrayBase> elements(obj->elements());
945 946
    if (*elements == heap->empty_fixed_array()) {
      return isolate->factory()->true_value();
947
    }
948
    Handle<BackingStore> backing_store = Handle<BackingStore>::cast(elements);
949 950 951
    bool is_sloppy_arguments_elements_map =
        backing_store->map() == heap->sloppy_arguments_elements_map();
    if (is_sloppy_arguments_elements_map) {
952
      backing_store = handle(
953 954
          BackingStore::cast(Handle<FixedArray>::cast(backing_store)->get(1)),
          isolate);
955 956 957
    }
    uint32_t length = static_cast<uint32_t>(
        obj->IsJSArray()
958
        ? Smi::cast(Handle<JSArray>::cast(obj)->length())->value()
959
        : backing_store->length());
960
    if (key < length) {
961
      if (!is_sloppy_arguments_elements_map) {
962 963
        ElementsKind kind = KindTraits::Kind;
        if (IsFastPackedElementsKind(kind)) {
964
          JSObject::TransitionElementsKind(obj, GetHoleyElementsKind(kind));
965 966
        }
        if (IsFastSmiOrObjectElementsKind(KindTraits::Kind)) {
967 968
          Handle<Object> writable = JSObject::EnsureWritableFastElements(obj);
          backing_store = Handle<BackingStore>::cast(writable);
969 970
        }
      }
971
      backing_store->set_the_hole(key);
972 973 974 975 976 977
      // If an old space backing store is larger than a certain size and
      // has too few used values, normalize it.
      // To avoid doing the check on every delete we require at least
      // one adjacent hole to the value being deleted.
      const int kMinLengthForSparsenessCheck = 64;
      if (backing_store->length() >= kMinLengthForSparsenessCheck &&
978
          !heap->InNewSpace(*backing_store) &&
979 980
          ((key > 0 && backing_store->is_the_hole(key - 1)) ||
           (key + 1 < length && backing_store->is_the_hole(key + 1)))) {
981 982
        int num_used = 0;
        for (int i = 0; i < backing_store->length(); ++i) {
983
          if (!backing_store->is_the_hole(i)) ++num_used;
984 985 986 987
          // Bail out early if more than 1/4 is used.
          if (4 * num_used > backing_store->length()) break;
        }
        if (4 * num_used <= backing_store->length()) {
988
          JSObject::NormalizeElements(obj);
989 990 991
        }
      }
    }
992
    return isolate->factory()->true_value();
993 994
  }

995
  virtual MaybeHandle<Object> Delete(
996 997
      Handle<JSObject> obj,
      uint32_t key,
998
      JSReceiver::DeleteMode mode) FINAL OVERRIDE {
999 1000 1001 1002
    return DeleteCommon(obj, key, mode);
  }

  static bool HasElementImpl(
1003 1004
      Handle<Object> receiver,
      Handle<JSObject> holder,
1005
      uint32_t key,
1006
      Handle<FixedArrayBase> backing_store) {
1007 1008 1009
    if (key >= static_cast<uint32_t>(backing_store->length())) {
      return false;
    }
1010
    return !Handle<BackingStore>::cast(backing_store)->is_the_hole(key);
1011 1012
  }

1013
  static void ValidateContents(Handle<JSObject> holder, int length) {
1014
#if DEBUG
1015 1016 1017
    Isolate* isolate = holder->GetIsolate();
    HandleScope scope(isolate);
    Handle<FixedArrayBase> elements(holder->elements(), isolate);
1018
    Map* map = elements->map();
1019
    DCHECK((IsFastSmiOrObjectElementsKind(KindTraits::Kind) &&
1020 1021
            (map == isolate->heap()->fixed_array_map() ||
             map == isolate->heap()->fixed_cow_array_map())) ||
1022
           (IsFastDoubleElementsKind(KindTraits::Kind) ==
1023 1024 1025
            ((map == isolate->heap()->fixed_array_map() && length == 0) ||
             map == isolate->heap()->fixed_double_array_map())));
    DisallowHeapAllocation no_gc;
1026
    for (int i = 0; i < length; i++) {
1027 1028
      HandleScope scope(isolate);
      Handle<BackingStore> backing_store = Handle<BackingStore>::cast(elements);
1029
      DCHECK((!IsFastSmiElementsKind(KindTraits::Kind) ||
1030
              BackingStore::get(backing_store, i)->IsSmi()) ||
1031 1032 1033 1034 1035 1036 1037 1038
             (IsFastHoleyElementsKind(KindTraits::Kind) ==
              backing_store->is_the_hole(i)));
    }
#endif
  }
};


1039
static inline ElementsKind ElementsKindForArray(FixedArrayBase* array) {
1040 1041 1042 1043 1044 1045 1046 1047 1048
  switch (array->map()->instance_type()) {
    case FIXED_ARRAY_TYPE:
      if (array->IsDictionary()) {
        return DICTIONARY_ELEMENTS;
      } else {
        return FAST_HOLEY_ELEMENTS;
      }
    case FIXED_DOUBLE_ARRAY_TYPE:
      return FAST_HOLEY_DOUBLE_ELEMENTS;
1049 1050 1051 1052 1053 1054 1055 1056 1057

#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size)                       \
    case EXTERNAL_##TYPE##_ARRAY_TYPE:                                        \
      return EXTERNAL_##TYPE##_ELEMENTS;                                      \
    case FIXED_##TYPE##_ARRAY_TYPE:                                           \
      return TYPE##_ELEMENTS;

    TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
1058

1059 1060 1061 1062 1063 1064 1065
    default:
      UNREACHABLE();
  }
  return FAST_HOLEY_ELEMENTS;
}


1066 1067 1068
template<typename FastElementsAccessorSubclass,
         typename KindTraits>
class FastSmiOrObjectElementsAccessor
1069
    : public FastElementsAccessor<FastElementsAccessorSubclass, KindTraits> {
1070 1071 1072
 public:
  explicit FastSmiOrObjectElementsAccessor(const char* name)
      : FastElementsAccessor<FastElementsAccessorSubclass,
1073
                             KindTraits>(name) {}
1074

1075 1076 1077 1078 1079 1080 1081 1082
  // NOTE: this method violates the handlified function signature convention:
  // raw pointer parameters in the function that allocates.
  // See ElementsAccessor::CopyElements() for details.
  // This method could actually allocate if copying from double elements to
  // object elements.
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
1083
                               int copy_size) {
1084
    DisallowHeapAllocation no_gc;
1085 1086 1087 1088 1089 1090
    ElementsKind to_kind = KindTraits::Kind;
    switch (from_kind) {
      case FAST_SMI_ELEMENTS:
      case FAST_HOLEY_SMI_ELEMENTS:
      case FAST_ELEMENTS:
      case FAST_HOLEY_ELEMENTS:
1091
        CopyObjectToObjectElements(from, from_kind, from_start, to, to_kind,
1092
                                   to_start, copy_size);
1093
        break;
1094
      case FAST_DOUBLE_ELEMENTS:
1095 1096
      case FAST_HOLEY_DOUBLE_ELEMENTS: {
        AllowHeapAllocation allow_allocation;
1097
        CopyDoubleToObjectElements(
1098
            from, from_start, to, to_kind, to_start, copy_size);
1099
        break;
1100
      }
1101
      case DICTIONARY_ELEMENTS:
1102 1103
        CopyDictionaryToObjectElements(from, from_start, to, to_kind, to_start,
                                       copy_size);
1104
        break;
1105
      case SLOPPY_ARGUMENTS_ELEMENTS: {
1106
        // TODO(verwaest): This is a temporary hack to support extending
1107
        // SLOPPY_ARGUMENTS_ELEMENTS in SetFastElementsCapacityAndLength.
1108
        // This case should be UNREACHABLE().
1109 1110
        FixedArray* parameter_map = FixedArray::cast(from);
        FixedArrayBase* arguments = FixedArrayBase::cast(parameter_map->get(1));
1111
        ElementsKind from_kind = ElementsKindForArray(arguments);
1112 1113 1114
        CopyElementsImpl(arguments, from_start, to, from_kind,
                         to_start, packed_size, copy_size);
        break;
1115
      }
1116 1117 1118
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size)                       \
      case EXTERNAL_##TYPE##_ELEMENTS:                                        \
      case TYPE##_ELEMENTS:                                                   \
1119
        UNREACHABLE();
1120 1121
      TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
1122 1123 1124 1125
    }
  }


1126 1127 1128 1129
  static void SetFastElementsCapacityAndLength(
      Handle<JSObject> obj,
      uint32_t capacity,
      uint32_t length) {
1130 1131 1132 1133
    JSObject::SetFastElementsCapacitySmiMode set_capacity_mode =
        obj->HasFastSmiElements()
            ? JSObject::kAllowSmiElements
            : JSObject::kDontAllowSmiElements;
1134 1135
    JSObject::SetFastElementsCapacityAndLength(
        obj, capacity, length, set_capacity_mode);
1136
  }
1137
};
1138

1139

1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
class FastPackedSmiElementsAccessor
    : public FastSmiOrObjectElementsAccessor<
        FastPackedSmiElementsAccessor,
        ElementsKindTraits<FAST_SMI_ELEMENTS> > {
 public:
  explicit FastPackedSmiElementsAccessor(const char* name)
      : FastSmiOrObjectElementsAccessor<
          FastPackedSmiElementsAccessor,
          ElementsKindTraits<FAST_SMI_ELEMENTS> >(name) {}
};


class FastHoleySmiElementsAccessor
    : public FastSmiOrObjectElementsAccessor<
        FastHoleySmiElementsAccessor,
        ElementsKindTraits<FAST_HOLEY_SMI_ELEMENTS> > {
 public:
  explicit FastHoleySmiElementsAccessor(const char* name)
      : FastSmiOrObjectElementsAccessor<
          FastHoleySmiElementsAccessor,
          ElementsKindTraits<FAST_HOLEY_SMI_ELEMENTS> >(name) {}
1161 1162 1163
};


1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
class FastPackedObjectElementsAccessor
    : public FastSmiOrObjectElementsAccessor<
        FastPackedObjectElementsAccessor,
        ElementsKindTraits<FAST_ELEMENTS> > {
 public:
  explicit FastPackedObjectElementsAccessor(const char* name)
      : FastSmiOrObjectElementsAccessor<
          FastPackedObjectElementsAccessor,
          ElementsKindTraits<FAST_ELEMENTS> >(name) {}
};


class FastHoleyObjectElementsAccessor
    : public FastSmiOrObjectElementsAccessor<
        FastHoleyObjectElementsAccessor,
        ElementsKindTraits<FAST_HOLEY_ELEMENTS> > {
 public:
  explicit FastHoleyObjectElementsAccessor(const char* name)
      : FastSmiOrObjectElementsAccessor<
          FastHoleyObjectElementsAccessor,
          ElementsKindTraits<FAST_HOLEY_ELEMENTS> >(name) {}
};


template<typename FastElementsAccessorSubclass,
         typename KindTraits>
1190
class FastDoubleElementsAccessor
1191
    : public FastElementsAccessor<FastElementsAccessorSubclass, KindTraits> {
1192 1193
 public:
  explicit FastDoubleElementsAccessor(const char* name)
1194
      : FastElementsAccessor<FastElementsAccessorSubclass,
1195
                             KindTraits>(name) {}
1196

1197 1198 1199 1200
  static void SetFastElementsCapacityAndLength(Handle<JSObject> obj,
                                               uint32_t capacity,
                                               uint32_t length) {
    JSObject::SetFastDoubleElementsCapacityAndLength(obj, capacity, length);
1201 1202
  }

1203
 protected:
1204 1205 1206
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
1207
                               int copy_size) {
1208
    DisallowHeapAllocation no_allocation;
1209
    switch (from_kind) {
1210
      case FAST_SMI_ELEMENTS:
1211
        CopyPackedSmiToDoubleElements(from, from_start, to, to_start,
1212
                                      packed_size, copy_size);
1213
        break;
1214
      case FAST_HOLEY_SMI_ELEMENTS:
1215
        CopySmiToDoubleElements(from, from_start, to, to_start, copy_size);
1216
        break;
1217
      case FAST_DOUBLE_ELEMENTS:
1218
      case FAST_HOLEY_DOUBLE_ELEMENTS:
1219
        CopyDoubleToDoubleElements(from, from_start, to, to_start, copy_size);
1220 1221 1222
        break;
      case FAST_ELEMENTS:
      case FAST_HOLEY_ELEMENTS:
1223
        CopyObjectToDoubleElements(from, from_start, to, to_start, copy_size);
1224 1225
        break;
      case DICTIONARY_ELEMENTS:
1226
        CopyDictionaryToDoubleElements(from, from_start, to, to_start,
1227
                                       copy_size);
1228
        break;
1229
      case SLOPPY_ARGUMENTS_ELEMENTS:
1230
        UNREACHABLE();
1231 1232 1233 1234 1235 1236 1237

#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size)                       \
      case EXTERNAL_##TYPE##_ELEMENTS:                                        \
      case TYPE##_ELEMENTS:                                                   \
        UNREACHABLE();
      TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
1238 1239
    }
  }
1240
};
1241

1242

1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
class FastPackedDoubleElementsAccessor
    : public FastDoubleElementsAccessor<
        FastPackedDoubleElementsAccessor,
        ElementsKindTraits<FAST_DOUBLE_ELEMENTS> > {
 public:
  friend class ElementsAccessorBase<FastPackedDoubleElementsAccessor,
                                    ElementsKindTraits<FAST_DOUBLE_ELEMENTS> >;
  explicit FastPackedDoubleElementsAccessor(const char* name)
      : FastDoubleElementsAccessor<
          FastPackedDoubleElementsAccessor,
          ElementsKindTraits<FAST_DOUBLE_ELEMENTS> >(name) {}
};


class FastHoleyDoubleElementsAccessor
    : public FastDoubleElementsAccessor<
        FastHoleyDoubleElementsAccessor,
        ElementsKindTraits<FAST_HOLEY_DOUBLE_ELEMENTS> > {
 public:
  friend class ElementsAccessorBase<
    FastHoleyDoubleElementsAccessor,
    ElementsKindTraits<FAST_HOLEY_DOUBLE_ELEMENTS> >;
  explicit FastHoleyDoubleElementsAccessor(const char* name)
      : FastDoubleElementsAccessor<
          FastHoleyDoubleElementsAccessor,
          ElementsKindTraits<FAST_HOLEY_DOUBLE_ELEMENTS> >(name) {}
1269 1270 1271 1272
};


// Super class for all external element arrays.
1273
template<ElementsKind Kind>
1274
class TypedElementsAccessor
1275
    : public ElementsAccessorBase<TypedElementsAccessor<Kind>,
1276
                                  ElementsKindTraits<Kind> > {
1277
 public:
1278
  explicit TypedElementsAccessor(const char* name)
1279
      : ElementsAccessorBase<AccessorClass,
1280
                             ElementsKindTraits<Kind> >(name) {}
1281

1282
 protected:
1283
  typedef typename ElementsKindTraits<Kind>::BackingStore BackingStore;
1284
  typedef TypedElementsAccessor<Kind> AccessorClass;
1285

1286
  friend class ElementsAccessorBase<AccessorClass,
1287
                                    ElementsKindTraits<Kind> >;
1288

1289 1290 1291 1292 1293
  MUST_USE_RESULT static MaybeHandle<Object> GetImpl(
      Handle<Object> receiver,
      Handle<JSObject> obj,
      uint32_t key,
      Handle<FixedArrayBase> backing_store) {
1294
    if (key < AccessorClass::GetCapacityImpl(backing_store)) {
1295 1296 1297 1298
      return BackingStore::get(Handle<BackingStore>::cast(backing_store), key);
    } else {
      return backing_store->GetIsolate()->factory()->undefined_value();
    }
1299
  }
1300

1301
  MUST_USE_RESULT static PropertyAttributes GetAttributesImpl(
1302 1303
      Handle<Object> receiver,
      Handle<JSObject> obj,
1304
      uint32_t key,
1305
      Handle<FixedArrayBase> backing_store) {
1306
    return
1307
        key < AccessorClass::GetCapacityImpl(backing_store)
1308 1309 1310
          ? NONE : ABSENT;
  }

1311
  MUST_USE_RESULT static MaybeHandle<Object> SetLengthImpl(
1312 1313 1314
      Handle<JSObject> obj,
      Handle<Object> length,
      Handle<FixedArrayBase> backing_store) {
1315 1316 1317 1318 1319
    // External arrays do not support changing their length.
    UNREACHABLE();
    return obj;
  }

1320
  MUST_USE_RESULT virtual MaybeHandle<Object> Delete(
1321 1322
      Handle<JSObject> obj,
      uint32_t key,
1323
      JSReceiver::DeleteMode mode) FINAL OVERRIDE {
1324
    // External arrays always ignore deletes.
1325
    return obj->GetIsolate()->factory()->true_value();
1326
  }
1327

1328 1329
  static bool HasElementImpl(Handle<Object> receiver,
                             Handle<JSObject> holder,
1330
                             uint32_t key,
1331
                             Handle<FixedArrayBase> backing_store) {
1332
    uint32_t capacity =
1333
        AccessorClass::GetCapacityImpl(backing_store);
1334 1335
    return key < capacity;
  }
1336 1337 1338 1339
};



1340 1341 1342
#define EXTERNAL_ELEMENTS_ACCESSOR(Type, type, TYPE, ctype, size)    \
  typedef TypedElementsAccessor<EXTERNAL_##TYPE##_ELEMENTS>          \
      External##Type##ElementsAccessor;
1343

1344 1345
TYPED_ARRAYS(EXTERNAL_ELEMENTS_ACCESSOR)
#undef EXTERNAL_ELEMENTS_ACCESSOR
1346

1347 1348 1349
#define FIXED_ELEMENTS_ACCESSOR(Type, type, TYPE, ctype, size)       \
  typedef TypedElementsAccessor<TYPE##_ELEMENTS >                    \
      Fixed##Type##ElementsAccessor;
1350

1351 1352
TYPED_ARRAYS(FIXED_ELEMENTS_ACCESSOR)
#undef FIXED_ELEMENTS_ACCESSOR
1353 1354 1355 1356 1357



class DictionaryElementsAccessor
    : public ElementsAccessorBase<DictionaryElementsAccessor,
1358
                                  ElementsKindTraits<DICTIONARY_ELEMENTS> > {
1359
 public:
1360 1361
  explicit DictionaryElementsAccessor(const char* name)
      : ElementsAccessorBase<DictionaryElementsAccessor,
1362
                             ElementsKindTraits<DICTIONARY_ELEMENTS> >(name) {}
1363

1364 1365
  // Adjusts the length of the dictionary backing store and returns the new
  // length according to ES5 section 15.4.5.2 behavior.
1366 1367 1368 1369
  static Handle<Object> SetLengthWithoutNormalize(
      Handle<FixedArrayBase> store,
      Handle<JSArray> array,
      Handle<Object> length_object,
1370
      uint32_t length) {
1371 1372 1373
    Handle<SeededNumberDictionary> dict =
        Handle<SeededNumberDictionary>::cast(store);
    Isolate* isolate = array->GetIsolate();
1374 1375 1376 1377 1378 1379 1380
    int capacity = dict->Capacity();
    uint32_t new_length = length;
    uint32_t old_length = static_cast<uint32_t>(array->length()->Number());
    if (new_length < old_length) {
      // Find last non-deletable element in range of elements to be
      // deleted and adjust range accordingly.
      for (int i = 0; i < capacity; i++) {
1381
        DisallowHeapAllocation no_gc;
1382 1383 1384 1385 1386
        Object* key = dict->KeyAt(i);
        if (key->IsNumber()) {
          uint32_t number = static_cast<uint32_t>(key->Number());
          if (new_length <= number && number < old_length) {
            PropertyDetails details = dict->DetailsAt(i);
1387
            if (!details.IsConfigurable()) new_length = number + 1;
1388 1389 1390 1391
          }
        }
      }
      if (new_length != length) {
1392
        length_object = isolate->factory()->NewNumberFromUint(new_length);
1393 1394 1395 1396
      }
    }

    if (new_length == 0) {
1397
      // Flush the backing store.
1398
      JSObject::ResetElements(array);
1399
    } else {
1400
      DisallowHeapAllocation no_gc;
1401 1402
      // Remove elements that should be deleted.
      int removed_entries = 0;
1403
      Handle<Object> the_hole_value = isolate->factory()->the_hole_value();
1404 1405 1406 1407 1408 1409 1410
      for (int i = 0; i < capacity; i++) {
        Object* key = dict->KeyAt(i);
        if (key->IsNumber()) {
          uint32_t number = static_cast<uint32_t>(key->Number());
          if (new_length <= number && number < old_length) {
            dict->SetEntry(i, the_hole_value, the_hole_value);
            removed_entries++;
1411 1412 1413
          }
        }
      }
1414 1415 1416

      // Update the number of elements.
      dict->ElementsRemoved(removed_entries);
1417 1418 1419 1420
    }
    return length_object;
  }

1421 1422
  MUST_USE_RESULT static MaybeHandle<Object> DeleteCommon(
      Handle<JSObject> obj,
1423 1424
      uint32_t key,
      JSReceiver::DeleteMode mode) {
1425
    Isolate* isolate = obj->GetIsolate();
1426 1427
    Handle<FixedArray> backing_store(FixedArray::cast(obj->elements()),
                                     isolate);
1428
    bool is_arguments =
1429
        (obj->GetElementsKind() == SLOPPY_ARGUMENTS_ELEMENTS);
1430
    if (is_arguments) {
1431
      backing_store = handle(FixedArray::cast(backing_store->get(1)), isolate);
1432
    }
1433 1434
    Handle<SeededNumberDictionary> dictionary =
        Handle<SeededNumberDictionary>::cast(backing_store);
1435
    int entry = dictionary->FindEntry(key);
1436
    if (entry != SeededNumberDictionary::kNotFound) {
1437 1438 1439
      Handle<Object> result =
          SeededNumberDictionary::DeleteProperty(dictionary, entry, mode);
      if (*result == *isolate->factory()->false_value()) {
1440 1441 1442
        if (mode == JSObject::STRICT_DELETION) {
          // Deleting a non-configurable property in strict mode.
          Handle<Object> name = isolate->factory()->NewNumberFromUint(key);
1443
          Handle<Object> args[2] = { name, obj };
1444 1445 1446
          THROW_NEW_ERROR(isolate, NewTypeError("strict_delete_property",
                                                HandleVector(args, 2)),
                          Object);
1447
        }
1448
        return isolate->factory()->false_value();
1449
      }
1450 1451 1452
      Handle<FixedArray> new_elements =
          SeededNumberDictionary::Shrink(dictionary, key);

1453
      if (is_arguments) {
1454
        FixedArray::cast(obj->elements())->set(1, *new_elements);
1455
      } else {
1456
        obj->set_elements(*new_elements);
1457 1458
      }
    }
1459
    return isolate->factory()->true_value();
1460 1461
  }

1462 1463 1464
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
1465
                               int copy_size) {
1466
    UNREACHABLE();
1467 1468 1469
  }


1470 1471
 protected:
  friend class ElementsAccessorBase<DictionaryElementsAccessor,
1472
                                    ElementsKindTraits<DICTIONARY_ELEMENTS> >;
1473

1474
  MUST_USE_RESULT virtual MaybeHandle<Object> Delete(
1475 1476
      Handle<JSObject> obj,
      uint32_t key,
1477
      JSReceiver::DeleteMode mode) FINAL OVERRIDE {
1478
    return DeleteCommon(obj, key, mode);
1479 1480
  }

1481
  MUST_USE_RESULT static MaybeHandle<Object> GetImpl(
1482 1483
      Handle<Object> receiver,
      Handle<JSObject> obj,
1484
      uint32_t key,
1485 1486 1487 1488
      Handle<FixedArrayBase> store) {
    Handle<SeededNumberDictionary> backing_store =
        Handle<SeededNumberDictionary>::cast(store);
    Isolate* isolate = backing_store->GetIsolate();
1489
    int entry = backing_store->FindEntry(key);
1490
    if (entry != SeededNumberDictionary::kNotFound) {
1491
      Handle<Object> element(backing_store->ValueAt(entry), isolate);
1492 1493
      PropertyDetails details = backing_store->DetailsAt(entry);
      if (details.type() == CALLBACKS) {
1494 1495
        return JSObject::GetElementWithCallback(
            obj, receiver, element, key, obj);
1496 1497 1498 1499
      } else {
        return element;
      }
    }
1500
    return isolate->factory()->the_hole_value();
1501
  }
1502

1503
  MUST_USE_RESULT static PropertyAttributes GetAttributesImpl(
1504 1505
      Handle<Object> receiver,
      Handle<JSObject> obj,
1506
      uint32_t key,
1507 1508 1509
      Handle<FixedArrayBase> backing_store) {
    Handle<SeededNumberDictionary> dictionary =
        Handle<SeededNumberDictionary>::cast(backing_store);
1510
    int entry = dictionary->FindEntry(key);
1511
    if (entry != SeededNumberDictionary::kNotFound) {
1512
      return dictionary->DetailsAt(entry).attributes();
1513 1514 1515 1516
    }
    return ABSENT;
  }

1517 1518 1519
  MUST_USE_RESULT static MaybeHandle<AccessorPair> GetAccessorPairImpl(
      Handle<Object> receiver,
      Handle<JSObject> obj,
1520
      uint32_t key,
1521 1522 1523
      Handle<FixedArrayBase> store) {
    Handle<SeededNumberDictionary> backing_store =
        Handle<SeededNumberDictionary>::cast(store);
1524 1525 1526 1527
    int entry = backing_store->FindEntry(key);
    if (entry != SeededNumberDictionary::kNotFound &&
        backing_store->DetailsAt(entry).type() == CALLBACKS &&
        backing_store->ValueAt(entry)->IsAccessorPair()) {
1528
      return handle(AccessorPair::cast(backing_store->ValueAt(entry)));
1529
    }
1530
    return MaybeHandle<AccessorPair>();
1531 1532
  }

1533 1534
  static bool HasElementImpl(Handle<Object> receiver,
                             Handle<JSObject> holder,
1535
                             uint32_t key,
1536 1537 1538 1539
                             Handle<FixedArrayBase> store) {
    Handle<SeededNumberDictionary> backing_store =
        Handle<SeededNumberDictionary>::cast(store);
    return backing_store->FindEntry(key) != SeededNumberDictionary::kNotFound;
1540 1541
  }

1542
  static uint32_t GetKeyForIndexImpl(Handle<FixedArrayBase> store,
1543
                                     uint32_t index) {
1544 1545 1546
    DisallowHeapAllocation no_gc;
    Handle<SeededNumberDictionary> dict =
        Handle<SeededNumberDictionary>::cast(store);
1547 1548
    Object* key = dict->KeyAt(index);
    return Smi::cast(key)->value();
1549
  }
1550 1551 1552
};


1553 1554 1555
class SloppyArgumentsElementsAccessor : public ElementsAccessorBase<
    SloppyArgumentsElementsAccessor,
    ElementsKindTraits<SLOPPY_ARGUMENTS_ELEMENTS> > {
1556
 public:
1557
  explicit SloppyArgumentsElementsAccessor(const char* name)
1558
      : ElementsAccessorBase<
1559 1560
          SloppyArgumentsElementsAccessor,
          ElementsKindTraits<SLOPPY_ARGUMENTS_ELEMENTS> >(name) {}
1561
 protected:
1562
  friend class ElementsAccessorBase<
1563 1564
      SloppyArgumentsElementsAccessor,
      ElementsKindTraits<SLOPPY_ARGUMENTS_ELEMENTS> >;
1565

1566
  MUST_USE_RESULT static MaybeHandle<Object> GetImpl(
1567 1568 1569 1570 1571 1572 1573
      Handle<Object> receiver,
      Handle<JSObject> obj,
      uint32_t key,
      Handle<FixedArrayBase> parameters) {
    Isolate* isolate = obj->GetIsolate();
    Handle<FixedArray> parameter_map = Handle<FixedArray>::cast(parameters);
    Handle<Object> probe = GetParameterMapArg(obj, parameter_map, key);
1574
    if (!probe->IsTheHole()) {
1575
      DisallowHeapAllocation no_gc;
1576
      Context* context = Context::cast(parameter_map->get(0));
1577
      int context_index = Handle<Smi>::cast(probe)->value();
1578
      DCHECK(!context->get(context_index)->IsTheHole());
1579
      return handle(context->get(context_index), isolate);
1580 1581
    } else {
      // Object is not mapped, defer to the arguments.
1582 1583
      Handle<FixedArray> arguments(FixedArray::cast(parameter_map->get(1)),
                                   isolate);
1584 1585 1586 1587 1588 1589
      Handle<Object> result;
      ASSIGN_RETURN_ON_EXCEPTION(
          isolate, result,
          ElementsAccessor::ForArray(arguments)->Get(
              receiver, obj, key, arguments),
          Object);
1590 1591
      // Elements of the arguments object in slow mode might be slow aliases.
      if (result->IsAliasedArgumentsEntry()) {
1592 1593
        DisallowHeapAllocation no_gc;
        AliasedArgumentsEntry* entry = AliasedArgumentsEntry::cast(*result);
1594 1595
        Context* context = Context::cast(parameter_map->get(0));
        int context_index = entry->aliased_context_slot();
1596
        DCHECK(!context->get(context_index)->IsTheHole());
1597
        return handle(context->get(context_index), isolate);
1598 1599 1600
      } else {
        return result;
      }
1601 1602
    }
  }
1603

1604
  MUST_USE_RESULT static PropertyAttributes GetAttributesImpl(
1605 1606
      Handle<Object> receiver,
      Handle<JSObject> obj,
1607
      uint32_t key,
1608 1609 1610
      Handle<FixedArrayBase> backing_store) {
    Handle<FixedArray> parameter_map = Handle<FixedArray>::cast(backing_store);
    Handle<Object> probe = GetParameterMapArg(obj, parameter_map, key);
1611 1612 1613 1614
    if (!probe->IsTheHole()) {
      return NONE;
    } else {
      // If not aliased, check the arguments.
1615
      Handle<FixedArray> arguments(FixedArray::cast(parameter_map->get(1)));
1616 1617 1618 1619 1620
      return ElementsAccessor::ForArray(arguments)->GetAttributes(
          receiver, obj, key, arguments);
    }
  }

1621 1622 1623
  MUST_USE_RESULT static MaybeHandle<AccessorPair> GetAccessorPairImpl(
      Handle<Object> receiver,
      Handle<JSObject> obj,
1624
      uint32_t key,
1625 1626 1627
      Handle<FixedArrayBase> parameters) {
    Handle<FixedArray> parameter_map = Handle<FixedArray>::cast(parameters);
    Handle<Object> probe = GetParameterMapArg(obj, parameter_map, key);
1628
    if (!probe->IsTheHole()) {
1629
      return MaybeHandle<AccessorPair>();
1630 1631
    } else {
      // If not aliased, check the arguments.
1632
      Handle<FixedArray> arguments(FixedArray::cast(parameter_map->get(1)));
1633 1634 1635 1636 1637
      return ElementsAccessor::ForArray(arguments)->GetAccessorPair(
          receiver, obj, key, arguments);
    }
  }

1638
  MUST_USE_RESULT static MaybeHandle<Object> SetLengthImpl(
1639 1640 1641
      Handle<JSObject> obj,
      Handle<Object> length,
      Handle<FixedArrayBase> parameter_map) {
1642 1643 1644 1645 1646 1647
    // TODO(mstarzinger): This was never implemented but will be used once we
    // correctly implement [[DefineOwnProperty]] on arrays.
    UNIMPLEMENTED();
    return obj;
  }

1648
  MUST_USE_RESULT virtual MaybeHandle<Object> Delete(
1649 1650
      Handle<JSObject> obj,
      uint32_t key,
1651
      JSReceiver::DeleteMode mode) FINAL OVERRIDE {
1652
    Isolate* isolate = obj->GetIsolate();
1653
    Handle<FixedArray> parameter_map(FixedArray::cast(obj->elements()));
1654
    Handle<Object> probe = GetParameterMapArg(obj, parameter_map, key);
1655
    if (!probe->IsTheHole()) {
1656 1657 1658
      // TODO(kmillikin): We could check if this was the last aliased
      // parameter, and revert to normal elements in that case.  That
      // would enable GC of the context.
1659
      parameter_map->set_the_hole(key + 2);
1660
    } else {
1661
      Handle<FixedArray> arguments(FixedArray::cast(parameter_map->get(1)));
1662
      if (arguments->IsDictionary()) {
1663
        return DictionaryElementsAccessor::DeleteCommon(obj, key, mode);
1664
      } else {
1665 1666 1667 1668
        // It's difficult to access the version of DeleteCommon that is declared
        // in the templatized super class, call the concrete implementation in
        // the class for the most generalized ElementsKind subclass.
        return FastHoleyObjectElementsAccessor::DeleteCommon(obj, key, mode);
1669 1670
      }
    }
1671
    return isolate->factory()->true_value();
1672
  }
1673

1674 1675 1676
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
1677
                               int copy_size) {
1678
    UNREACHABLE();
1679 1680
  }

1681 1682 1683 1684
  static uint32_t GetCapacityImpl(Handle<FixedArrayBase> backing_store) {
    Handle<FixedArray> parameter_map = Handle<FixedArray>::cast(backing_store);
    Handle<FixedArrayBase> arguments(
        FixedArrayBase::cast(parameter_map->get(1)));
1685 1686
    return Max(static_cast<uint32_t>(parameter_map->length() - 2),
               ForArray(arguments)->GetCapacity(arguments));
1687 1688
  }

1689
  static uint32_t GetKeyForIndexImpl(Handle<FixedArrayBase> dict,
1690
                                     uint32_t index) {
1691 1692 1693
    return index;
  }

1694 1695
  static bool HasElementImpl(Handle<Object> receiver,
                             Handle<JSObject> holder,
1696
                             uint32_t key,
1697 1698 1699
                             Handle<FixedArrayBase> parameters) {
    Handle<FixedArray> parameter_map = Handle<FixedArray>::cast(parameters);
    Handle<Object> probe = GetParameterMapArg(holder, parameter_map, key);
1700 1701 1702
    if (!probe->IsTheHole()) {
      return true;
    } else {
1703
      Isolate* isolate = holder->GetIsolate();
1704
      Handle<FixedArrayBase> arguments(FixedArrayBase::cast(
1705
          Handle<FixedArray>::cast(parameter_map)->get(1)), isolate);
1706
      ElementsAccessor* accessor = ElementsAccessor::ForArray(arguments);
1707 1708 1709 1710 1711 1712
      Handle<Object> value;
      ASSIGN_RETURN_ON_EXCEPTION_VALUE(
          isolate, value,
          accessor->Get(receiver, holder, key, arguments),
          false);
      return !value->IsTheHole();
1713 1714 1715 1716
    }
  }

 private:
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
  static Handle<Object> GetParameterMapArg(Handle<JSObject> holder,
                                           Handle<FixedArray> parameter_map,
                                           uint32_t key) {
    Isolate* isolate = holder->GetIsolate();
    uint32_t length = holder->IsJSArray()
        ? Smi::cast(Handle<JSArray>::cast(holder)->length())->value()
        : parameter_map->length();
    return key < (length - 2)
        ? handle(parameter_map->get(key + 2), isolate)
        : Handle<Object>::cast(isolate->factory()->the_hole_value());
  }
1728 1729 1730
};


1731
ElementsAccessor* ElementsAccessor::ForArray(Handle<FixedArrayBase> array) {
1732
  return elements_accessors_[ElementsKindForArray(*array)];
1733 1734 1735
}


1736 1737
void ElementsAccessor::InitializeOncePerProcess() {
  static ElementsAccessor* accessor_array[] = {
1738
#define ACCESSOR_ARRAY(Class, Kind, Store) new Class(#Kind),
1739 1740
    ELEMENTS_LIST(ACCESSOR_ARRAY)
#undef ACCESSOR_ARRAY
1741 1742
  };

1743 1744 1745
  STATIC_ASSERT((sizeof(accessor_array) / sizeof(*accessor_array)) ==
                kElementsKindCount);

1746 1747 1748 1749
  elements_accessors_ = accessor_array;
}


1750
void ElementsAccessor::TearDown() {
1751
  if (elements_accessors_ == NULL) return;
1752 1753 1754 1755 1756 1757 1758
#define ACCESSOR_DELETE(Class, Kind, Store) delete elements_accessors_[Kind];
  ELEMENTS_LIST(ACCESSOR_DELETE)
#undef ACCESSOR_DELETE
  elements_accessors_ = NULL;
}


1759
template <typename ElementsAccessorSubclass, typename ElementsKindTraits>
1760 1761 1762
MUST_USE_RESULT
MaybeHandle<Object> ElementsAccessorBase<ElementsAccessorSubclass,
                                         ElementsKindTraits>::
1763 1764 1765 1766 1767
    SetLengthImpl(Handle<JSObject> obj,
                  Handle<Object> length,
                  Handle<FixedArrayBase> backing_store) {
  Isolate* isolate = obj->GetIsolate();
  Handle<JSArray> array = Handle<JSArray>::cast(obj);
1768 1769

  // Fast case: The new length fits into a Smi.
1770
  Handle<Object> smi_length;
1771

1772 1773
  if (Object::ToSmi(isolate, length).ToHandle(&smi_length) &&
      smi_length->IsSmi()) {
1774
    const int value = Handle<Smi>::cast(smi_length)->value();
1775
    if (value >= 0) {
1776
      Handle<Object> new_length = ElementsAccessorSubclass::
1777
          SetLengthWithoutNormalize(backing_store, array, smi_length, value);
1778
      DCHECK(!new_length.is_null());
1779

1780 1781 1782 1783
      // even though the proposed length was a smi, new_length could
      // still be a heap number because SetLengthWithoutNormalize doesn't
      // allow the array length property to drop below the index of
      // non-deletable elements.
1784
      DCHECK(new_length->IsSmi() || new_length->IsHeapNumber() ||
1785
             new_length->IsUndefined());
1786
      if (new_length->IsSmi()) {
1787
        array->set_length(*Handle<Smi>::cast(new_length));
1788
        return array;
1789
      } else if (new_length->IsHeapNumber()) {
1790
        array->set_length(*new_length);
1791
        return array;
1792 1793
      }
    } else {
1794
      return ThrowArrayLengthRangeError(isolate);
1795 1796 1797 1798 1799 1800 1801 1802
    }
  }

  // Slow case: The new length does not fit into a Smi or conversion
  // to slow elements is needed for other reasons.
  if (length->IsNumber()) {
    uint32_t value;
    if (length->ToArrayIndex(&value)) {
1803 1804
      Handle<SeededNumberDictionary> dictionary =
          JSObject::NormalizeElements(array);
1805
      DCHECK(!dictionary.is_null());
1806 1807

      Handle<Object> new_length = DictionaryElementsAccessor::
1808
          SetLengthWithoutNormalize(dictionary, array, length, value);
1809
      DCHECK(!new_length.is_null());
1810

1811
      DCHECK(new_length->IsNumber());
1812
      array->set_length(*new_length);
1813 1814
      return array;
    } else {
1815
      return ThrowArrayLengthRangeError(isolate);
1816 1817 1818 1819 1820
    }
  }

  // Fall-back case: The new length is not a number so make the array
  // size one and set only element to length.
1821
  Handle<FixedArray> new_backing_store = isolate->factory()->NewFixedArray(1);
1822
  new_backing_store->set(0, *length);
1823
  JSArray::SetContent(array, new_backing_store);
1824 1825 1826 1827
  return array;
}


1828 1829
MaybeHandle<Object> ArrayConstructInitializeElements(Handle<JSArray> array,
                                                     Arguments* args) {
1830 1831 1832
  // Optimize the case where there is one argument and the argument is a
  // small smi.
  if (args->length() == 1) {
1833
    Handle<Object> obj = args->at<Object>(0);
1834
    if (obj->IsSmi()) {
1835
      int len = Handle<Smi>::cast(obj)->value();
1836 1837
      if (len > 0 && len < JSObject::kInitialMaxFastElementArray) {
        ElementsKind elements_kind = array->GetElementsKind();
1838
        JSArray::Initialize(array, len, len);
1839 1840 1841

        if (!IsFastHoleyElementsKind(elements_kind)) {
          elements_kind = GetHoleyElementsKind(elements_kind);
1842
          JSObject::TransitionElementsKind(array, elements_kind);
1843 1844 1845
        }
        return array;
      } else if (len == 0) {
1846 1847
        JSArray::Initialize(array, JSArray::kPreallocatedArrayElements);
        return array;
1848 1849 1850 1851
      }
    }

    // Take the argument as the length.
1852
    JSArray::Initialize(array, 0);
1853

1854
    return JSArray::SetElementsLength(array, obj);
1855 1856 1857 1858
  }

  // Optimize the case where there are no parameters passed.
  if (args->length() == 0) {
1859 1860
    JSArray::Initialize(array, JSArray::kPreallocatedArrayElements);
    return array;
1861 1862
  }

1863 1864
  Factory* factory = array->GetIsolate()->factory();

1865 1866
  // Set length and elements on the array.
  int number_of_elements = args->length();
1867 1868
  JSObject::EnsureCanContainElements(
      array, args, 0, number_of_elements, ALLOW_CONVERTED_DOUBLE_ELEMENTS);
1869 1870 1871

  // Allocate an appropriately typed elements array.
  ElementsKind elements_kind = array->GetElementsKind();
1872
  Handle<FixedArrayBase> elms;
1873
  if (IsFastDoubleElementsKind(elements_kind)) {
1874 1875
    elms = Handle<FixedArrayBase>::cast(
        factory->NewFixedDoubleArray(number_of_elements));
1876
  } else {
1877 1878
    elms = Handle<FixedArrayBase>::cast(
        factory->NewFixedArrayWithHoles(number_of_elements));
1879 1880 1881 1882 1883 1884
  }

  // Fill in the content
  switch (array->GetElementsKind()) {
    case FAST_HOLEY_SMI_ELEMENTS:
    case FAST_SMI_ELEMENTS: {
1885
      Handle<FixedArray> smi_elms = Handle<FixedArray>::cast(elms);
1886 1887 1888 1889 1890 1891 1892
      for (int index = 0; index < number_of_elements; index++) {
        smi_elms->set(index, (*args)[index], SKIP_WRITE_BARRIER);
      }
      break;
    }
    case FAST_HOLEY_ELEMENTS:
    case FAST_ELEMENTS: {
1893
      DisallowHeapAllocation no_gc;
1894
      WriteBarrierMode mode = elms->GetWriteBarrierMode(no_gc);
1895
      Handle<FixedArray> object_elms = Handle<FixedArray>::cast(elms);
1896 1897 1898 1899 1900 1901 1902
      for (int index = 0; index < number_of_elements; index++) {
        object_elms->set(index, (*args)[index], mode);
      }
      break;
    }
    case FAST_HOLEY_DOUBLE_ELEMENTS:
    case FAST_DOUBLE_ELEMENTS: {
1903 1904
      Handle<FixedDoubleArray> double_elms =
          Handle<FixedDoubleArray>::cast(elms);
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
      for (int index = 0; index < number_of_elements; index++) {
        double_elms->set(index, (*args)[index]->Number());
      }
      break;
    }
    default:
      UNREACHABLE();
      break;
  }

1915
  array->set_elements(*elms);
1916 1917 1918 1919
  array->set_length(Smi::FromInt(number_of_elements));
  return array;
}

1920
} }  // namespace v8::internal