elements.cc 155 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/elements.h"
6

7 8
#include "src/arguments.h"
#include "src/conversions.h"
9
#include "src/factory.h"
10
#include "src/isolate-inl.h"
11
#include "src/messages.h"
12
#include "src/objects-inl.h"
13
#include "src/utils.h"
14 15 16 17 18 19 20 21

// 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)
22 23 24 25 26
//     - FastSmiOrObjectElementsAccessor
//       - FastPackedSmiElementsAccessor
//       - FastHoleySmiElementsAccessor
//       - FastPackedObjectElementsAccessor
//       - FastHoleyObjectElementsAccessor
27
//     - FastDoubleElementsAccessor
28 29
//       - FastPackedDoubleElementsAccessor
//       - FastHoleyDoubleElementsAccessor
30 31 32 33 34 35 36 37 38 39
//   - TypedElementsAccessor: template, with instantiations:
//     - FixedUint8ElementsAccessor
//     - FixedInt8ElementsAccessor
//     - FixedUint16ElementsAccessor
//     - FixedInt16ElementsAccessor
//     - FixedUint32ElementsAccessor
//     - FixedInt32ElementsAccessor
//     - FixedFloat32ElementsAccessor
//     - FixedFloat64ElementsAccessor
//     - FixedUint8ClampedElementsAccessor
40
//   - DictionaryElementsAccessor
41
//   - SloppyArgumentsElementsAccessor
42 43
//     - FastSloppyArgumentsElementsAccessor
//     - SlowSloppyArgumentsElementsAccessor
44 45 46
//   - StringWrapperElementsAccessor
//     - FastStringWrapperElementsAccessor
//     - SlowStringWrapperElementsAccessor
47

48 49 50 51
namespace v8 {
namespace internal {


52 53 54
namespace {


55 56
static const int kPackedSizeNotKnown = -1;

cbruni's avatar
cbruni committed
57 58
enum Where { AT_START, AT_END };

59

60 61 62 63 64
// 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.
65 66 67 68 69 70 71 72 73 74 75 76 77
#define ELEMENTS_LIST(V)                                                      \
  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)                                                         \
  V(DictionaryElementsAccessor, DICTIONARY_ELEMENTS, SeededNumberDictionary)  \
  V(FastSloppyArgumentsElementsAccessor, FAST_SLOPPY_ARGUMENTS_ELEMENTS,      \
    FixedArray)                                                               \
  V(SlowSloppyArgumentsElementsAccessor, SLOW_SLOPPY_ARGUMENTS_ELEMENTS,      \
    FixedArray)                                                               \
78 79 80 81
  V(FastStringWrapperElementsAccessor, FAST_STRING_WRAPPER_ELEMENTS,          \
    FixedArray)                                                               \
  V(SlowStringWrapperElementsAccessor, SLOW_STRING_WRAPPER_ELEMENTS,          \
    FixedArray)                                                               \
82 83 84 85 86 87 88 89 90
  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,                \
91
    FixedUint8ClampedArray)
92 93 94 95 96 97 98 99

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

#define ELEMENTS_TRAITS(Class, KindParam, Store)               \
template<> class ElementsKindTraits<KindParam> {               \
100
 public:   /* NOLINT */                                        \
101 102 103 104 105 106 107
  static const ElementsKind Kind = KindParam;                  \
  typedef Store BackingStore;                                  \
};
ELEMENTS_LIST(ELEMENTS_TRAITS)
#undef ELEMENTS_TRAITS


108
MUST_USE_RESULT
109
MaybeHandle<Object> ThrowArrayLengthRangeError(Isolate* isolate) {
110
  THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kInvalidArrayLength),
111
                  Object);
112 113
}

114

115 116 117 118
void CopyObjectToObjectElements(FixedArrayBase* from_base,
                                ElementsKind from_kind, uint32_t from_start,
                                FixedArrayBase* to_base, ElementsKind to_kind,
                                uint32_t to_start, int raw_copy_size) {
119
  DCHECK(to_base->map() !=
120
      from_base->GetIsolate()->heap()->fixed_cow_array_map());
121
  DisallowHeapAllocation no_allocation;
122 123
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
124
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
125
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
126 127
    copy_size = Min(from_base->length() - from_start,
                    to_base->length() - to_start);
128
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
129
      int start = to_start + copy_size;
130
      int length = to_base->length() - start;
131
      if (length > 0) {
132
        Heap* heap = from_base->GetHeap();
133
        MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
134
                      heap->the_hole_value(), length);
135 136
      }
    }
137
  }
138
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
139
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
140
  if (copy_size == 0) return;
141 142
  FixedArray* from = FixedArray::cast(from_base);
  FixedArray* to = FixedArray::cast(to_base);
143
  DCHECK(IsFastSmiOrObjectElementsKind(from_kind));
144
  DCHECK(IsFastSmiOrObjectElementsKind(to_kind));
145 146

  WriteBarrierMode write_barrier_mode =
147
      (IsFastObjectElementsKind(from_kind) && IsFastObjectElementsKind(to_kind))
148 149 150 151 152
          ? UPDATE_WRITE_BARRIER
          : SKIP_WRITE_BARRIER;
  for (int i = 0; i < copy_size; i++) {
    Object* value = from->get(from_start + i);
    to->set(to_start + i, value, write_barrier_mode);
153 154 155 156
  }
}


157 158 159
static void CopyDictionaryToObjectElements(
    FixedArrayBase* from_base, uint32_t from_start, FixedArrayBase* to_base,
    ElementsKind to_kind, uint32_t to_start, int raw_copy_size) {
160
  DisallowHeapAllocation no_allocation;
161
  SeededNumberDictionary* from = SeededNumberDictionary::cast(from_base);
162 163
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
164
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
165 166 167
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
    copy_size = from->max_number_key() + 1 - from_start;
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
168
      int start = to_start + copy_size;
169
      int length = to_base->length() - start;
170 171
      if (length > 0) {
        Heap* heap = from->GetHeap();
172
        MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
173
                      heap->the_hole_value(), length);
174 175 176
      }
    }
  }
177 178
  DCHECK(to_base != from_base);
  DCHECK(IsFastSmiOrObjectElementsKind(to_kind));
179
  if (copy_size == 0) return;
180
  FixedArray* to = FixedArray::cast(to_base);
181 182 183 184
  uint32_t to_length = to->length();
  if (to_start + copy_size > to_length) {
    copy_size = to_length - to_start;
  }
185 186 187
  WriteBarrierMode write_barrier_mode = IsFastObjectElementsKind(to_kind)
                                            ? UPDATE_WRITE_BARRIER
                                            : SKIP_WRITE_BARRIER;
188
  Isolate* isolate = from->GetIsolate();
189 190 191 192
  for (int i = 0; i < copy_size; i++) {
    int entry = from->FindEntry(i + from_start);
    if (entry != SeededNumberDictionary::kNotFound) {
      Object* value = from->ValueAt(entry);
193
      DCHECK(!value->IsTheHole(isolate));
194
      to->set(i + to_start, value, write_barrier_mode);
195
    } else {
196
      to->set_the_hole(isolate, i + to_start);
197 198
    }
  }
199 200 201
}


202 203 204 205
// 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,
206
                                       uint32_t from_start,
207
                                       FixedArrayBase* to_base,
208
                                       uint32_t to_start, int raw_copy_size) {
209 210
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
211
    DisallowHeapAllocation no_allocation;
212
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
213
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
214 215
    copy_size = Min(from_base->length() - from_start,
                    to_base->length() - to_start);
216
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
217 218 219 220
      // 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;
221
      int length = to_base->length() - start;
222
      if (length > 0) {
223
        Heap* heap = from_base->GetHeap();
224
        MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
225
                      heap->the_hole_value(), length);
226 227
      }
    }
228
  }
229

230
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
231
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
232
  if (copy_size == 0) return;
233 234 235

  // From here on, the code below could actually allocate. Therefore the raw
  // values are wrapped into handles.
236
  Isolate* isolate = from_base->GetIsolate();
237 238
  Handle<FixedDoubleArray> from(FixedDoubleArray::cast(from_base), isolate);
  Handle<FixedArray> to(FixedArray::cast(to_base), isolate);
239

240 241 242
  // Use an outer loop to not waste too much time on creating HandleScopes.
  // On the other hand we might overflow a single handle scope depending on
  // the copy_size.
243 244
  int offset = 0;
  while (offset < copy_size) {
245
    HandleScope scope(isolate);
246 247
    offset += 100;
    for (int i = offset - 100; i < offset && i < copy_size; ++i) {
248 249
      Handle<Object> value =
          FixedDoubleArray::get(*from, i + from_start, isolate);
250
      to->set(i + to_start, *value, UPDATE_WRITE_BARRIER);
251 252 253 254 255
    }
  }
}


256
static void CopyDoubleToDoubleElements(FixedArrayBase* from_base,
257
                                       uint32_t from_start,
258 259
                                       FixedArrayBase* to_base,
                                       uint32_t to_start, int raw_copy_size) {
260
  DisallowHeapAllocation no_allocation;
261 262
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
263
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
264
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
265 266
    copy_size = Min(from_base->length() - from_start,
                    to_base->length() - to_start);
267
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
268
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
269
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
270 271
      }
    }
272
  }
273
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
274
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
275
  if (copy_size == 0) return;
276 277
  FixedDoubleArray* from = FixedDoubleArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
278 279 280 281
  Address to_address = to->address() + FixedDoubleArray::kHeaderSize;
  Address from_address = from->address() + FixedDoubleArray::kHeaderSize;
  to_address += kDoubleSize * to_start;
  from_address += kDoubleSize * from_start;
282
  int words_per_double = (kDoubleSize / kPointerSize);
283 284
  CopyWords(reinterpret_cast<Object**>(to_address),
            reinterpret_cast<Object**>(from_address),
285
            static_cast<size_t>(words_per_double * copy_size));
286 287 288
}


289
static void CopySmiToDoubleElements(FixedArrayBase* from_base,
290
                                    uint32_t from_start,
291
                                    FixedArrayBase* to_base, uint32_t to_start,
292
                                    int raw_copy_size) {
293
  DisallowHeapAllocation no_allocation;
294 295
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
296
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
297
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
298
    copy_size = from_base->length() - from_start;
299
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
300
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
301
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
302 303 304
      }
    }
  }
305
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
306
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
307
  if (copy_size == 0) return;
308 309 310
  FixedArray* from = FixedArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
  Object* the_hole = from->GetHeap()->the_hole_value();
311 312 313
  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);
314
    if (hole_or_smi == the_hole) {
315 316 317 318 319 320 321 322
      to->set_the_hole(to_start);
    } else {
      to->set(to_start, Smi::cast(hole_or_smi)->value());
    }
  }
}


323
static void CopyPackedSmiToDoubleElements(FixedArrayBase* from_base,
324
                                          uint32_t from_start,
325 326
                                          FixedArrayBase* to_base,
                                          uint32_t to_start, int packed_size,
327
                                          int raw_copy_size) {
328
  DisallowHeapAllocation no_allocation;
329 330 331
  int copy_size = raw_copy_size;
  uint32_t to_end;
  if (raw_copy_size < 0) {
332
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
333
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
334
    copy_size = packed_size - from_start;
335
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
336
      to_end = to_base->length();
337
      for (uint32_t i = to_start + copy_size; i < to_end; ++i) {
338
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
339
      }
340 341 342 343 344 345
    } else {
      to_end = to_start + static_cast<uint32_t>(copy_size);
    }
  } else {
    to_end = to_start + static_cast<uint32_t>(copy_size);
  }
346 347 348
  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() &&
349
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
350
  if (copy_size == 0) return;
351 352
  FixedArray* from = FixedArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
353 354 355
  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);
356
    DCHECK(!smi->IsTheHole(from->GetIsolate()));
357 358 359 360 361
    to->set(to_start, Smi::cast(smi)->value());
  }
}


362
static void CopyObjectToDoubleElements(FixedArrayBase* from_base,
363
                                       uint32_t from_start,
364 365
                                       FixedArrayBase* to_base,
                                       uint32_t to_start, int raw_copy_size) {
366
  DisallowHeapAllocation no_allocation;
367 368
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
369
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
370
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
371
    copy_size = from_base->length() - from_start;
372
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
373
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
374
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
375 376 377
      }
    }
  }
378
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
379
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
380
  if (copy_size == 0) return;
381 382 383
  FixedArray* from = FixedArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
  Object* the_hole = from->GetHeap()->the_hole_value();
384 385 386
  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);
387
    if (hole_or_object == the_hole) {
388
      to->set_the_hole(to_start);
389
    } else {
390
      to->set(to_start, hole_or_object->Number());
391 392 393 394 395
    }
  }
}


396
static void CopyDictionaryToDoubleElements(FixedArrayBase* from_base,
397
                                           uint32_t from_start,
398
                                           FixedArrayBase* to_base,
399 400
                                           uint32_t to_start,
                                           int raw_copy_size) {
401
  DisallowHeapAllocation no_allocation;
402
  SeededNumberDictionary* from = SeededNumberDictionary::cast(from_base);
403 404
  int copy_size = raw_copy_size;
  if (copy_size < 0) {
405
    DCHECK(copy_size == ElementsAccessor::kCopyToEnd ||
406 407 408
           copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
    copy_size = from->max_number_key() + 1 - from_start;
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
409
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
410
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
411 412 413 414
      }
    }
  }
  if (copy_size == 0) return;
415
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
416 417 418 419
  uint32_t to_length = to->length();
  if (to_start + copy_size > to_length) {
    copy_size = to_length - to_start;
  }
420 421 422 423 424 425 426 427 428 429
  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);
    }
  }
}

430 431
static void TraceTopFrame(Isolate* isolate) {
  StackFrameIterator it(isolate);
432 433 434 435 436 437
  if (it.done()) {
    PrintF("unknown location (no JavaScript frames present)");
    return;
  }
  StackFrame* raw_frame = it.frame();
  if (raw_frame->is_internal()) {
438 439
    Code* apply_builtin =
        isolate->builtins()->builtin(Builtins::kFunctionPrototypeApply);
440 441 442 443 444 445
    if (raw_frame->unchecked_code() == apply_builtin) {
      PrintF("apply from ");
      it.Advance();
      raw_frame = it.frame();
    }
  }
446
  JavaScriptFrame::PrintTop(isolate, stdout, false, true);
447 448
}

449 450 451 452 453
static void SortIndices(
    Handle<FixedArray> indices, uint32_t sort_size,
    WriteBarrierMode write_barrier_mode = UPDATE_WRITE_BARRIER) {
  struct {
    bool operator()(Object* a, Object* b) {
454 455 456 457
      if (a->IsSmi() || !a->IsUndefined(HeapObject::cast(a)->GetIsolate())) {
        if (!b->IsSmi() && b->IsUndefined(HeapObject::cast(b)->GetIsolate())) {
          return true;
        }
458 459
        return a->Number() < b->Number();
      }
460
      return !b->IsSmi() && b->IsUndefined(HeapObject::cast(b)->GetIsolate());
461 462 463 464 465 466 467 468 469 470
    }
  } cmp;
  Object** start =
      reinterpret_cast<Object**>(indices->GetFirstElementAddress());
  std::sort(start, start + sort_size, cmp);
  if (write_barrier_mode != SKIP_WRITE_BARRIER) {
    FIXED_ARRAY_ELEMENTS_WRITE_BARRIER(indices->GetIsolate()->heap(), *indices,
                                       0, sort_size);
  }
}
471

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
static Maybe<bool> IncludesValueSlowPath(Isolate* isolate,
                                         Handle<JSObject> receiver,
                                         Handle<Object> value,
                                         uint32_t start_from, uint32_t length) {
  bool search_for_hole = value->IsUndefined(isolate);
  for (uint32_t k = start_from; k < length; ++k) {
    LookupIterator it(isolate, receiver, k);
    if (!it.IsFound()) {
      if (search_for_hole) return Just(true);
      continue;
    }
    Handle<Object> element_k;
    ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k,
                                     Object::GetProperty(&it), Nothing<bool>());

    if (value->SameValueZero(*element_k)) return Just(true);
  }

  return Just(false);
}

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
static Maybe<int64_t> IndexOfValueSlowPath(Isolate* isolate,
                                           Handle<JSObject> receiver,
                                           Handle<Object> value,
                                           uint32_t start_from,
                                           uint32_t length) {
  for (uint32_t k = start_from; k < length; ++k) {
    LookupIterator it(isolate, receiver, k);
    if (!it.IsFound()) {
      continue;
    }
    Handle<Object> element_k;
    ASSIGN_RETURN_ON_EXCEPTION_VALUE(
        isolate, element_k, Object::GetProperty(&it), Nothing<int64_t>());

    if (value->StrictEquals(*element_k)) return Just<int64_t>(k);
  }

  return Just<int64_t>(-1);
}

513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
// 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).
530
template <typename Subclass, typename ElementsTraitsParam>
531
class ElementsAccessorBase : public ElementsAccessor {
532
 public:
533 534 535 536 537 538
  explicit ElementsAccessorBase(const char* name)
      : ElementsAccessor(name) { }

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

539
  static ElementsKind kind() { return ElementsTraits::Kind; }
540

541
  static void ValidateContents(Handle<JSObject> holder, int length) {
542 543
  }

544 545
  static void ValidateImpl(Handle<JSObject> holder) {
    Handle<FixedArrayBase> fixed_array_base(holder->elements());
546 547
    if (!fixed_array_base->IsHeapObject()) return;
    // Arrays that have been shifted in place can't be verified.
548
    if (fixed_array_base->IsFiller()) return;
549 550
    int length = 0;
    if (holder->IsJSArray()) {
551
      Object* length_obj = Handle<JSArray>::cast(holder)->length();
552 553 554 555 556 557
      if (length_obj->IsSmi()) {
        length = Smi::cast(length_obj)->value();
      }
    } else {
      length = fixed_array_base->length();
    }
558
    Subclass::ValidateContents(holder, length);
559 560
  }

561
  void Validate(Handle<JSObject> holder) final {
562
    DisallowHeapAllocation no_gc;
563
    Subclass::ValidateImpl(holder);
564 565
  }

566 567 568 569
  static bool IsPackedImpl(Handle<JSObject> holder,
                           Handle<FixedArrayBase> backing_store, uint32_t start,
                           uint32_t end) {
    if (IsFastPackedElementsKind(kind())) return true;
570
    Isolate* isolate = backing_store->GetIsolate();
571
    for (uint32_t i = start; i < end; i++) {
572 573
      if (!Subclass::HasElementImpl(isolate, holder, i, backing_store,
                                    ALL_PROPERTIES)) {
574 575 576 577 578 579
        return false;
      }
    }
    return true;
  }

580 581 582 583
  static void TryTransitionResultArrayToPacked(Handle<JSArray> array) {
    if (!IsHoleyElementsKind(kind())) return;
    int length = Smi::cast(array->length())->value();
    Handle<FixedArrayBase> backing_store(array->elements());
584
    if (!Subclass::IsPackedImpl(array, backing_store, 0, length)) {
585 586 587 588 589 590 591 592 593 594 595 596
      return;
    }
    ElementsKind packed_kind = GetPackedElementsKind(kind());
    Handle<Map> new_map =
        JSObject::GetElementsTransitionMap(array, packed_kind);
    JSObject::MigrateToMap(array, new_map);
    if (FLAG_trace_elements_transitions) {
      JSObject::PrintElementsTransition(stdout, array, kind(), backing_store,
                                        packed_kind, backing_store);
    }
  }

597 598
  bool HasElement(Handle<JSObject> holder, uint32_t index,
                  Handle<FixedArrayBase> backing_store,
599
                  PropertyFilter filter) final {
600 601
    return Subclass::HasElementImpl(holder->GetIsolate(), holder, index,
                                    backing_store, filter);
602 603
  }

604 605
  static bool HasElementImpl(Isolate* isolate, Handle<JSObject> holder,
                             uint32_t index,
606
                             Handle<FixedArrayBase> backing_store,
607
                             PropertyFilter filter = ALL_PROPERTIES) {
608 609
    return Subclass::GetEntryForIndexImpl(isolate, *holder, *backing_store,
                                          index, filter) != kMaxUInt32;
610 611
  }

612
  bool HasAccessors(JSObject* holder) final {
613
    return Subclass::HasAccessorsImpl(holder, holder->elements());
614 615 616 617 618 619 620
  }

  static bool HasAccessorsImpl(JSObject* holder,
                               FixedArrayBase* backing_store) {
    return false;
  }

621
  Handle<Object> Get(Handle<JSObject> holder, uint32_t entry) final {
622
    return Subclass::GetInternalImpl(holder, entry);
623 624
  }

625 626 627
  static Handle<Object> GetInternalImpl(Handle<JSObject> holder,
                                        uint32_t entry) {
    return Subclass::GetImpl(holder->GetIsolate(), holder->elements(), entry);
628 629
  }

630 631
  static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* backing_store,
                                uint32_t entry) {
632 633
    uint32_t index = GetIndexForEntryImpl(backing_store, entry);
    return handle(BackingStore::cast(backing_store)->get(index), isolate);
634 635
  }

636
  void Set(Handle<JSObject> holder, uint32_t entry, Object* value) final {
637
    Subclass::SetImpl(holder, entry, value);
638 639
  }

640 641 642
  void Reconfigure(Handle<JSObject> object, Handle<FixedArrayBase> store,
                   uint32_t entry, Handle<Object> value,
                   PropertyAttributes attributes) final {
643
    Subclass::ReconfigureImpl(object, store, entry, value, attributes);
644 645 646
  }

  static void ReconfigureImpl(Handle<JSObject> object,
647
                              Handle<FixedArrayBase> store, uint32_t entry,
648 649 650 651 652
                              Handle<Object> value,
                              PropertyAttributes attributes) {
    UNREACHABLE();
  }

653 654
  void Add(Handle<JSObject> object, uint32_t index, Handle<Object> value,
           PropertyAttributes attributes, uint32_t new_capacity) final {
655
    Subclass::AddImpl(object, index, value, attributes, new_capacity);
656 657
  }

658
  static void AddImpl(Handle<JSObject> object, uint32_t index,
659 660 661 662 663
                      Handle<Object> value, PropertyAttributes attributes,
                      uint32_t new_capacity) {
    UNREACHABLE();
  }

664 665
  uint32_t Push(Handle<JSArray> receiver, Arguments* args,
                uint32_t push_size) final {
666
    return Subclass::PushImpl(receiver, args, push_size);
667 668
  }

669
  static uint32_t PushImpl(Handle<JSArray> receiver, Arguments* args,
670
                           uint32_t push_sized) {
671 672 673 674
    UNREACHABLE();
    return 0;
  }

675
  uint32_t Unshift(Handle<JSArray> receiver, Arguments* args,
676
                   uint32_t unshift_size) final {
677
    return Subclass::UnshiftImpl(receiver, args, unshift_size);
678 679
  }

680
  static uint32_t UnshiftImpl(Handle<JSArray> receiver, Arguments* args,
681 682 683 684 685
                              uint32_t unshift_size) {
    UNREACHABLE();
    return 0;
  }

686
  Handle<JSArray> Slice(Handle<JSObject> receiver, uint32_t start,
687
                        uint32_t end) final {
688
    return Subclass::SliceImpl(receiver, start, end);
689 690 691 692 693 694 695 696
  }

  static Handle<JSArray> SliceImpl(Handle<JSObject> receiver,
                                   uint32_t start, uint32_t end) {
    UNREACHABLE();
    return Handle<JSArray>();
  }

697
  Handle<JSArray> Splice(Handle<JSArray> receiver, uint32_t start,
698 699
                         uint32_t delete_count, Arguments* args,
                         uint32_t add_count) final {
700
    return Subclass::SpliceImpl(receiver, start, delete_count, args, add_count);
701 702 703 704
  }

  static Handle<JSArray> SpliceImpl(Handle<JSArray> receiver,
                                    uint32_t start, uint32_t delete_count,
705
                                    Arguments* args, uint32_t add_count) {
706 707 708 709
    UNREACHABLE();
    return Handle<JSArray>();
  }

710
  Handle<Object> Pop(Handle<JSArray> receiver) final {
711
    return Subclass::PopImpl(receiver);
cbruni's avatar
cbruni committed
712 713
  }

714
  static Handle<Object> PopImpl(Handle<JSArray> receiver) {
cbruni's avatar
cbruni committed
715 716 717
    UNREACHABLE();
    return Handle<Object>();
  }
718

719
  Handle<Object> Shift(Handle<JSArray> receiver) final {
720
    return Subclass::ShiftImpl(receiver);
721 722
  }

723
  static Handle<Object> ShiftImpl(Handle<JSArray> receiver) {
724 725 726 727
    UNREACHABLE();
    return Handle<Object>();
  }

728
  void SetLength(Handle<JSArray> array, uint32_t length) final {
729 730
    Subclass::SetLengthImpl(array->GetIsolate(), array, length,
                            handle(array->elements()));
731 732
  }

733 734
  static void SetLengthImpl(Isolate* isolate, Handle<JSArray> array,
                            uint32_t length,
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
                            Handle<FixedArrayBase> backing_store) {
    DCHECK(!array->SetLengthWouldNormalize(length));
    DCHECK(IsFastElementsKind(array->GetElementsKind()));
    uint32_t old_length = 0;
    CHECK(array->length()->ToArrayIndex(&old_length));

    if (old_length < length) {
      ElementsKind kind = array->GetElementsKind();
      if (!IsFastHoleyElementsKind(kind)) {
        kind = GetHoleyElementsKind(kind);
        JSObject::TransitionElementsKind(array, kind);
      }
    }

    // Check whether the backing store should be shrunk.
    uint32_t capacity = backing_store->length();
751
    old_length = Min(old_length, capacity);
752 753 754
    if (length == 0) {
      array->initialize_elements();
    } else if (length <= capacity) {
755
      if (IsFastSmiOrObjectElementsKind(kind())) {
756 757 758 759
        JSObject::EnsureWritableFastElements(array);
        if (array->elements() != *backing_store) {
          backing_store = handle(array->elements(), isolate);
        }
760 761 762
      }
      if (2 * length <= capacity) {
        // If more than half the elements won't be used, trim the array.
763
        isolate->heap()->RightTrimFixedArray(*backing_store, capacity - length);
764 765
      } else {
        // Otherwise, fill the unused tail with holes.
766
        BackingStore::cast(*backing_store)->FillWithHoles(length, old_length);
767 768 769 770
      }
    } else {
      // Check whether the backing store should be expanded.
      capacity = Max(length, JSObject::NewElementsCapacity(capacity));
771
      Subclass::GrowCapacityAndConvertImpl(array, capacity);
772 773 774 775 776
    }

    array->set_length(Smi::FromInt(length));
    JSObject::ValidateElements(array);
  }
777

778 779 780 781 782 783 784 785 786
  uint32_t NumberOfElements(JSObject* receiver) final {
    return Subclass::NumberOfElementsImpl(receiver, receiver->elements());
  }

  static uint32_t NumberOfElementsImpl(JSObject* receiver,
                                       FixedArrayBase* backing_store) {
    UNREACHABLE();
  }

787
  static uint32_t GetMaxIndex(JSObject* receiver, FixedArrayBase* elements) {
788
    if (receiver->IsJSArray()) {
789
      DCHECK(JSArray::cast(receiver)->length()->IsSmi());
790 791 792
      return static_cast<uint32_t>(
          Smi::cast(JSArray::cast(receiver)->length())->value());
    }
793
    return Subclass::GetCapacityImpl(receiver, elements);
794 795
  }

796 797 798 799 800
  static uint32_t GetMaxNumberOfEntries(JSObject* receiver,
                                        FixedArrayBase* elements) {
    return Subclass::GetMaxIndex(receiver, elements);
  }

801 802 803
  static Handle<FixedArrayBase> ConvertElementsWithCapacity(
      Handle<JSObject> object, Handle<FixedArrayBase> old_elements,
      ElementsKind from_kind, uint32_t capacity) {
804
    return ConvertElementsWithCapacity(
805
        object, old_elements, from_kind, capacity, 0, 0,
806 807 808 809 810 811
        ElementsAccessor::kCopyToEndAndInitializeToHole);
  }

  static Handle<FixedArrayBase> ConvertElementsWithCapacity(
      Handle<JSObject> object, Handle<FixedArrayBase> old_elements,
      ElementsKind from_kind, uint32_t capacity, int copy_size) {
812 813 814 815 816 817 818 819
    return ConvertElementsWithCapacity(object, old_elements, from_kind,
                                       capacity, 0, 0, copy_size);
  }

  static Handle<FixedArrayBase> ConvertElementsWithCapacity(
      Handle<JSObject> object, Handle<FixedArrayBase> old_elements,
      ElementsKind from_kind, uint32_t capacity, uint32_t src_index,
      uint32_t dst_index, int copy_size) {
820
    Isolate* isolate = object->GetIsolate();
821
    Handle<FixedArrayBase> new_elements;
822
    if (IsFastDoubleElementsKind(kind())) {
823
      new_elements = isolate->factory()->NewFixedDoubleArray(capacity);
824
    } else {
825
      new_elements = isolate->factory()->NewUninitializedFixedArray(capacity);
826 827
    }

828
    int packed_size = kPackedSizeNotKnown;
829
    if (IsFastPackedElementsKind(from_kind) && object->IsJSArray()) {
830
      packed_size = Smi::cast(JSArray::cast(*object)->length())->value();
831 832
    }

833 834
    Subclass::CopyElementsImpl(*old_elements, src_index, *new_elements,
                               from_kind, dst_index, packed_size, copy_size);
835 836

    return new_elements;
837 838
  }

839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
  static void TransitionElementsKindImpl(Handle<JSObject> object,
                                         Handle<Map> to_map) {
    Handle<Map> from_map = handle(object->map());
    ElementsKind from_kind = from_map->elements_kind();
    ElementsKind to_kind = to_map->elements_kind();
    if (IsFastHoleyElementsKind(from_kind)) {
      to_kind = GetHoleyElementsKind(to_kind);
    }
    if (from_kind != to_kind) {
      // This method should never be called for any other case.
      DCHECK(IsFastElementsKind(from_kind));
      DCHECK(IsFastElementsKind(to_kind));
      DCHECK_NE(TERMINAL_FAST_ELEMENTS_KIND, from_kind);

      Handle<FixedArrayBase> from_elements(object->elements());
      if (object->elements() == object->GetHeap()->empty_fixed_array() ||
          IsFastDoubleElementsKind(from_kind) ==
              IsFastDoubleElementsKind(to_kind)) {
        // No change is needed to the elements() buffer, the transition
        // only requires a map change.
        JSObject::MigrateToMap(object, to_map);
      } else {
        DCHECK((IsFastSmiElementsKind(from_kind) &&
                IsFastDoubleElementsKind(to_kind)) ||
               (IsFastDoubleElementsKind(from_kind) &&
                IsFastObjectElementsKind(to_kind)));
        uint32_t capacity = static_cast<uint32_t>(object->elements()->length());
        Handle<FixedArrayBase> elements = ConvertElementsWithCapacity(
            object, from_elements, from_kind, capacity);
        JSObject::SetMapAndElements(object, to_map, elements);
      }
      if (FLAG_trace_elements_transitions) {
        JSObject::PrintElementsTransition(stdout, object, from_kind,
                                          from_elements, to_kind,
                                          handle(object->elements()));
      }
    }
  }

878
  static void GrowCapacityAndConvertImpl(Handle<JSObject> object,
879
                                         uint32_t capacity) {
880 881 882 883 884 885 886 887 888 889 890 891 892 893
    ElementsKind from_kind = object->GetElementsKind();
    if (IsFastSmiOrObjectElementsKind(from_kind)) {
      // Array optimizations rely on the prototype lookups of Array objects
      // always returning undefined. If there is a store to the initial
      // prototype object, make sure all of these optimizations are invalidated.
      object->GetIsolate()->UpdateArrayProtectorOnSetLength(object);
    }
    Handle<FixedArrayBase> old_elements(object->elements());
    // This method should only be called if there's a reason to update the
    // elements.
    DCHECK(IsFastDoubleElementsKind(from_kind) !=
               IsFastDoubleElementsKind(kind()) ||
           IsDictionaryElementsKind(from_kind) ||
           static_cast<uint32_t>(old_elements->length()) < capacity);
894 895 896 897 898 899 900
    Subclass::BasicGrowCapacityAndConvertImpl(object, old_elements, from_kind,
                                              kind(), capacity);
  }

  static void BasicGrowCapacityAndConvertImpl(
      Handle<JSObject> object, Handle<FixedArrayBase> old_elements,
      ElementsKind from_kind, ElementsKind to_kind, uint32_t capacity) {
901 902 903 904 905 906 907 908 909 910 911 912 913 914
    Handle<FixedArrayBase> elements =
        ConvertElementsWithCapacity(object, old_elements, from_kind, capacity);

    if (IsHoleyElementsKind(from_kind)) to_kind = GetHoleyElementsKind(to_kind);
    Handle<Map> new_map = JSObject::GetElementsTransitionMap(object, to_kind);
    JSObject::SetMapAndElements(object, new_map, elements);

    // Transition through the allocation site as well if present.
    JSObject::UpdateAllocationSite(object, to_kind);

    if (FLAG_trace_elements_transitions) {
      JSObject::PrintElementsTransition(stdout, object, from_kind, old_elements,
                                        to_kind, elements);
    }
915 916
  }

917 918 919 920
  void TransitionElementsKind(Handle<JSObject> object, Handle<Map> map) final {
    Subclass::TransitionElementsKindImpl(object, map);
  }

921 922
  void GrowCapacityAndConvert(Handle<JSObject> object,
                              uint32_t capacity) final {
923
    Subclass::GrowCapacityAndConvertImpl(object, capacity);
924 925
  }

926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
  bool GrowCapacity(Handle<JSObject> object, uint32_t index) final {
    // This function is intended to be called from optimized code. We don't
    // want to trigger lazy deopts there, so refuse to handle cases that would.
    if (object->map()->is_prototype_map() ||
        object->WouldConvertToSlowElements(index)) {
      return false;
    }
    Handle<FixedArrayBase> old_elements(object->elements());
    uint32_t new_capacity = JSObject::NewElementsCapacity(index + 1);
    DCHECK(static_cast<uint32_t>(old_elements->length()) < new_capacity);
    Handle<FixedArrayBase> elements =
        ConvertElementsWithCapacity(object, old_elements, kind(), new_capacity);

    DCHECK_EQ(object->GetElementsKind(), kind());
    // Transition through the allocation site as well if present.
    if (JSObject::UpdateAllocationSite<AllocationSiteUpdateMode::kCheckOnly>(
            object, kind())) {
      return false;
    }

    object->set_elements(*elements);
    return true;
  }

950
  void Delete(Handle<JSObject> obj, uint32_t entry) final {
951
    Subclass::DeleteImpl(obj, entry);
952
  }
953

954 955 956
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
957
                               int copy_size) {
958
    UNREACHABLE();
959 960
  }

961 962 963
  void CopyElements(JSObject* from_holder, uint32_t from_start,
                    ElementsKind from_kind, Handle<FixedArrayBase> to,
                    uint32_t to_start, int copy_size) final {
964 965 966 967 968 969 970 971
    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;
972 973
      }
    }
974
    FixedArrayBase* from = from_holder->elements();
975
    // NOTE: the Subclass::CopyElementsImpl() methods
976 977 978 979 980 981 982 983
    // 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.
984 985
    Subclass::CopyElementsImpl(from, from_start, *to, from_kind, to_start,
                               packed_size, copy_size);
986 987
  }

988 989 990 991 992 993
  void CopyElements(Handle<FixedArrayBase> source, ElementsKind source_kind,
                    Handle<FixedArrayBase> destination, int size) {
    Subclass::CopyElementsImpl(*source, 0, *destination, source_kind, 0,
                               kPackedSizeNotKnown, size);
  }

994
  Handle<SeededNumberDictionary> Normalize(Handle<JSObject> object) final {
995
    return Subclass::NormalizeImpl(object, handle(object->elements()));
996 997 998 999 1000 1001 1002 1003
  }

  static Handle<SeededNumberDictionary> NormalizeImpl(
      Handle<JSObject> object, Handle<FixedArrayBase> elements) {
    UNREACHABLE();
    return Handle<SeededNumberDictionary>();
  }

1004 1005 1006 1007
  Maybe<bool> CollectValuesOrEntries(Isolate* isolate, Handle<JSObject> object,
                                     Handle<FixedArray> values_or_entries,
                                     bool get_entries, int* nof_items,
                                     PropertyFilter filter) {
1008
    return Subclass::CollectValuesOrEntriesImpl(
1009 1010 1011 1012 1013 1014 1015 1016
        isolate, object, values_or_entries, get_entries, nof_items, filter);
  }

  static Maybe<bool> CollectValuesOrEntriesImpl(
      Isolate* isolate, Handle<JSObject> object,
      Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items,
      PropertyFilter filter) {
    int count = 0;
1017 1018
    KeyAccumulator accumulator(isolate, KeyCollectionMode::kOwnOnly,
                               ALL_PROPERTIES);
1019
    Subclass::CollectElementIndicesImpl(
1020
        object, handle(object->elements(), isolate), &accumulator);
1021 1022 1023 1024 1025 1026 1027 1028
    Handle<FixedArray> keys = accumulator.GetKeys();

    for (int i = 0; i < keys->length(); ++i) {
      Handle<Object> key(keys->get(i), isolate);
      Handle<Object> value;
      uint32_t index;
      if (!key->ToUint32(&index)) continue;

1029
      uint32_t entry = Subclass::GetEntryForIndexImpl(
1030
          isolate, *object, object->elements(), index, filter);
1031 1032
      if (entry == kMaxUInt32) continue;

1033
      PropertyDetails details = Subclass::GetDetailsImpl(*object, entry);
1034 1035

      if (details.kind() == kData) {
1036
        value = Subclass::GetImpl(isolate, object->elements(), entry);
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
      } else {
        LookupIterator it(isolate, object, index, LookupIterator::OWN);
        ASSIGN_RETURN_ON_EXCEPTION_VALUE(
            isolate, value, Object::GetProperty(&it), Nothing<bool>());
      }
      if (get_entries) {
        value = MakeEntryPair(isolate, index, value);
      }
      values_or_entries->set(count++, *value);
    }

    *nof_items = count;
    return Just(true);
  }

1052 1053
  void CollectElementIndices(Handle<JSObject> object,
                             Handle<FixedArrayBase> backing_store,
1054 1055 1056
                             KeyAccumulator* keys) final {
    if (keys->filter() & ONLY_ALL_CAN_READ) return;
    Subclass::CollectElementIndicesImpl(object, backing_store, keys);
1057 1058
  }

1059 1060
  static void CollectElementIndicesImpl(Handle<JSObject> object,
                                        Handle<FixedArrayBase> backing_store,
1061
                                        KeyAccumulator* keys) {
1062
    DCHECK_NE(DICTIONARY_ELEMENTS, kind());
1063
    // Non-dictionary elements can't have all-can-read accessors.
1064
    uint32_t length = Subclass::GetMaxIndex(*object, *backing_store);
1065
    PropertyFilter filter = keys->filter();
1066 1067
    Isolate* isolate = keys->isolate();
    Factory* factory = isolate->factory();
1068
    for (uint32_t i = 0; i < length; i++) {
1069
      if (Subclass::HasElementImpl(isolate, object, i, backing_store, filter)) {
1070
        keys->AddKey(factory->NewNumberFromUint(i));
1071 1072 1073 1074
      }
    }
  }

1075 1076 1077
  static Handle<FixedArray> DirectCollectElementIndicesImpl(
      Isolate* isolate, Handle<JSObject> object,
      Handle<FixedArrayBase> backing_store, GetKeysConversion convert,
1078 1079
      PropertyFilter filter, Handle<FixedArray> list, uint32_t* nof_indices,
      uint32_t insertion_index = 0) {
1080
    uint32_t length = Subclass::GetMaxIndex(*object, *backing_store);
1081
    for (uint32_t i = 0; i < length; i++) {
1082
      if (Subclass::HasElementImpl(isolate, object, i, backing_store, filter)) {
1083
        if (convert == GetKeysConversion::kConvertToString) {
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
          Handle<String> index_string = isolate->factory()->Uint32ToString(i);
          list->set(insertion_index, *index_string);
        } else {
          list->set(insertion_index, Smi::FromInt(i), SKIP_WRITE_BARRIER);
        }
        insertion_index++;
      }
    }
    *nof_indices = insertion_index;
    return list;
  }

1096 1097 1098 1099
  MaybeHandle<FixedArray> PrependElementIndices(
      Handle<JSObject> object, Handle<FixedArrayBase> backing_store,
      Handle<FixedArray> keys, GetKeysConversion convert,
      PropertyFilter filter) final {
1100 1101
    return Subclass::PrependElementIndicesImpl(object, backing_store, keys,
                                               convert, filter);
1102 1103
  }

1104
  static MaybeHandle<FixedArray> PrependElementIndicesImpl(
1105 1106 1107 1108 1109 1110
      Handle<JSObject> object, Handle<FixedArrayBase> backing_store,
      Handle<FixedArray> keys, GetKeysConversion convert,
      PropertyFilter filter) {
    Isolate* isolate = object->GetIsolate();
    uint32_t nof_property_keys = keys->length();
    uint32_t initial_list_length =
1111
        Subclass::GetMaxNumberOfEntries(*object, *backing_store);
1112

1113
    initial_list_length += nof_property_keys;
1114 1115 1116 1117 1118
    if (initial_list_length > FixedArray::kMaxLength ||
        initial_list_length < nof_property_keys) {
      return isolate->Throw<FixedArray>(isolate->factory()->NewRangeError(
          MessageTemplate::kInvalidArrayLength));
    }
1119 1120

    // Collect the element indices into a new list.
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    MaybeHandle<FixedArray> raw_array =
        isolate->factory()->TryNewFixedArray(initial_list_length);
    Handle<FixedArray> combined_keys;

    // If we have a holey backing store try to precisely estimate the backing
    // store size as a last emergency measure if we cannot allocate the big
    // array.
    if (!raw_array.ToHandle(&combined_keys)) {
      if (IsHoleyElementsKind(kind())) {
        // If we overestimate the result list size we might end up in the
        // large-object space which doesn't free memory on shrinking the list.
        // Hence we try to estimate the final size for holey backing stores more
        // precisely here.
        initial_list_length =
            Subclass::NumberOfElementsImpl(*object, *backing_store);
        initial_list_length += nof_property_keys;
      }
      combined_keys = isolate->factory()->NewFixedArray(initial_list_length);
    }

1141
    uint32_t nof_indices = 0;
1142 1143
    bool needs_sorting =
        IsDictionaryElementsKind(kind()) || IsSloppyArgumentsElements(kind());
1144
    combined_keys = Subclass::DirectCollectElementIndicesImpl(
1145 1146 1147
        isolate, object, backing_store,
        needs_sorting ? GetKeysConversion::kKeepNumbers : convert, filter,
        combined_keys, &nof_indices);
1148

1149
    if (needs_sorting) {
1150
      SortIndices(combined_keys, nof_indices);
1151 1152
      // Indices from dictionary elements should only be converted after
      // sorting.
1153
      if (convert == GetKeysConversion::kConvertToString) {
1154 1155
        for (uint32_t i = 0; i < nof_indices; i++) {
          Handle<Object> index_string = isolate->factory()->Uint32ToString(
1156
              combined_keys->get(i)->Number());
1157 1158 1159 1160 1161 1162 1163 1164 1165
          combined_keys->set(i, *index_string);
        }
      }
    }

    // Copy over the passed-in property keys.
    CopyObjectToObjectElements(*keys, FAST_ELEMENTS, 0, *combined_keys,
                               FAST_ELEMENTS, nof_indices, nof_property_keys);

1166 1167 1168
    // For holey elements and arguments we might have to shrink the collected
    // keys since the estimates might be off.
    if (IsHoleyElementsKind(kind()) || IsSloppyArgumentsElements(kind())) {
1169 1170 1171 1172 1173 1174 1175 1176
      // Shrink combined_keys to the final size.
      int final_size = nof_indices + nof_property_keys;
      DCHECK_LE(final_size, combined_keys->length());
      combined_keys->Shrink(final_size);
    }

    return combined_keys;
  }
1177

1178 1179 1180
  void AddElementsToKeyAccumulator(Handle<JSObject> receiver,
                                   KeyAccumulator* accumulator,
                                   AddKeyConversion convert) final {
1181
    Subclass::AddElementsToKeyAccumulatorImpl(receiver, accumulator, convert);
1182 1183
  }

1184 1185
  static uint32_t GetCapacityImpl(JSObject* holder,
                                  FixedArrayBase* backing_store) {
1186
    return backing_store->length();
1187 1188
  }

1189
  uint32_t GetCapacity(JSObject* holder, FixedArrayBase* backing_store) final {
1190
    return Subclass::GetCapacityImpl(holder, backing_store);
1191 1192
  }

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
  static Maybe<bool> IncludesValueImpl(Isolate* isolate,
                                       Handle<JSObject> receiver,
                                       Handle<Object> value,
                                       uint32_t start_from, uint32_t length) {
    return IncludesValueSlowPath(isolate, receiver, value, start_from, length);
  }

  Maybe<bool> IncludesValue(Isolate* isolate, Handle<JSObject> receiver,
                            Handle<Object> value, uint32_t start_from,
                            uint32_t length) final {
    return Subclass::IncludesValueImpl(isolate, receiver, value, start_from,
                                       length);
  }

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
  static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
                                         Handle<JSObject> receiver,
                                         Handle<Object> value,
                                         uint32_t start_from, uint32_t length) {
    return IndexOfValueSlowPath(isolate, receiver, value, start_from, length);
  }

  Maybe<int64_t> IndexOfValue(Isolate* isolate, Handle<JSObject> receiver,
                              Handle<Object> value, uint32_t start_from,
                              uint32_t length) final {
    return Subclass::IndexOfValueImpl(isolate, receiver, value, start_from,
                                      length);
  }

1221 1222 1223
  static uint32_t GetIndexForEntryImpl(FixedArrayBase* backing_store,
                                       uint32_t entry) {
    return entry;
1224 1225
  }

1226
  static uint32_t GetEntryForIndexImpl(Isolate* isolate, JSObject* holder,
1227
                                       FixedArrayBase* backing_store,
1228
                                       uint32_t index, PropertyFilter filter) {
1229
    uint32_t length = Subclass::GetMaxIndex(holder, backing_store);
1230
    if (IsHoleyElementsKind(kind())) {
1231
      return index < length &&
1232 1233
                     !BackingStore::cast(backing_store)
                          ->is_the_hole(isolate, index)
1234 1235 1236 1237 1238
                 ? index
                 : kMaxUInt32;
    } else {
      return index < length ? index : kMaxUInt32;
    }
1239 1240
  }

1241 1242
  uint32_t GetEntryForIndex(Isolate* isolate, JSObject* holder,
                            FixedArrayBase* backing_store,
1243
                            uint32_t index) final {
1244
    return Subclass::GetEntryForIndexImpl(isolate, holder, backing_store, index,
1245
                                          ALL_PROPERTIES);
1246 1247 1248
  }

  static PropertyDetails GetDetailsImpl(FixedArrayBase* backing_store,
1249
                                        uint32_t entry) {
1250 1251 1252
    return PropertyDetails(NONE, DATA, 0, PropertyCellType::kNoCell);
  }

1253 1254 1255 1256 1257
  static PropertyDetails GetDetailsImpl(JSObject* holder, uint32_t entry) {
    return PropertyDetails(NONE, DATA, 0, PropertyCellType::kNoCell);
  }

  PropertyDetails GetDetails(JSObject* holder, uint32_t entry) final {
1258
    return Subclass::GetDetailsImpl(holder, entry);
1259 1260
  }

1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
  Handle<FixedArray> CreateListFromArray(Isolate* isolate,
                                         Handle<JSArray> array) final {
    return Subclass::CreateListFromArrayImpl(isolate, array);
  };

  static Handle<FixedArray> CreateListFromArrayImpl(Isolate* isolate,
                                                    Handle<JSArray> array) {
    UNREACHABLE();
    return Handle<FixedArray>();
  }

1272 1273 1274 1275 1276
 private:
  DISALLOW_COPY_AND_ASSIGN(ElementsAccessorBase);
};


1277 1278 1279 1280 1281 1282 1283 1284
class DictionaryElementsAccessor
    : public ElementsAccessorBase<DictionaryElementsAccessor,
                                  ElementsKindTraits<DICTIONARY_ELEMENTS> > {
 public:
  explicit DictionaryElementsAccessor(const char* name)
      : ElementsAccessorBase<DictionaryElementsAccessor,
                             ElementsKindTraits<DICTIONARY_ELEMENTS> >(name) {}

1285 1286 1287 1288 1289 1290 1291
  static uint32_t GetMaxIndex(JSObject* receiver, FixedArrayBase* elements) {
    // We cannot properly estimate this for dictionaries.
    UNREACHABLE();
  }

  static uint32_t GetMaxNumberOfEntries(JSObject* receiver,
                                        FixedArrayBase* backing_store) {
1292 1293 1294 1295 1296
    return NumberOfElementsImpl(receiver, backing_store);
  }

  static uint32_t NumberOfElementsImpl(JSObject* receiver,
                                       FixedArrayBase* backing_store) {
1297 1298
    SeededNumberDictionary* dict = SeededNumberDictionary::cast(backing_store);
    return dict->NumberOfElements();
1299 1300
  }

1301 1302
  static void SetLengthImpl(Isolate* isolate, Handle<JSArray> array,
                            uint32_t length,
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
                            Handle<FixedArrayBase> backing_store) {
    Handle<SeededNumberDictionary> dict =
        Handle<SeededNumberDictionary>::cast(backing_store);
    int capacity = dict->Capacity();
    uint32_t old_length = 0;
    CHECK(array->length()->ToArrayLength(&old_length));
    if (length < old_length) {
      if (dict->requires_slow_elements()) {
        // Find last non-deletable element in range of elements to be
        // deleted and adjust range accordingly.
1313
        for (int entry = 0; entry < capacity; entry++) {
1314
          DisallowHeapAllocation no_gc;
1315 1316 1317
          Object* index = dict->KeyAt(entry);
          if (index->IsNumber()) {
            uint32_t number = static_cast<uint32_t>(index->Number());
1318
            if (length <= number && number < old_length) {
1319
              PropertyDetails details = dict->DetailsAt(entry);
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
              if (!details.IsConfigurable()) length = number + 1;
            }
          }
        }
      }

      if (length == 0) {
        // Flush the backing store.
        JSObject::ResetElements(array);
      } else {
        DisallowHeapAllocation no_gc;
        // Remove elements that should be deleted.
        int removed_entries = 0;
        Handle<Object> the_hole_value = isolate->factory()->the_hole_value();
1334 1335 1336 1337
        for (int entry = 0; entry < capacity; entry++) {
          Object* index = dict->KeyAt(entry);
          if (index->IsNumber()) {
            uint32_t number = static_cast<uint32_t>(index->Number());
1338
            if (length <= number && number < old_length) {
1339
              dict->SetEntry(entry, the_hole_value, the_hole_value);
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
              removed_entries++;
            }
          }
        }

        // Update the number of elements.
        dict->ElementsRemoved(removed_entries);
      }
    }

    Handle<Object> length_obj = isolate->factory()->NewNumberFromUint(length);
    array->set_length(*length_obj);
  }

  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
                               int copy_size) {
    UNREACHABLE();
  }


1362 1363
  static void DeleteImpl(Handle<JSObject> obj, uint32_t entry) {
    // TODO(verwaest): Remove reliance on index in Shrink.
1364 1365
    Handle<SeededNumberDictionary> dict(
        SeededNumberDictionary::cast(obj->elements()));
1366 1367
    uint32_t index = GetIndexForEntryImpl(*dict, entry);
    Handle<Object> result = SeededNumberDictionary::DeleteProperty(dict, entry);
1368
    USE(result);
1369
    DCHECK(result->IsTrue(dict->GetIsolate()));
1370 1371
    Handle<FixedArray> new_elements =
        SeededNumberDictionary::Shrink(dict, index);
1372
    obj->set_elements(*new_elements);
1373 1374
  }

1375 1376
  static bool HasAccessorsImpl(JSObject* holder,
                               FixedArrayBase* backing_store) {
1377
    DisallowHeapAllocation no_gc;
1378 1379 1380
    SeededNumberDictionary* dict = SeededNumberDictionary::cast(backing_store);
    if (!dict->requires_slow_elements()) return false;
    int capacity = dict->Capacity();
1381
    Isolate* isolate = dict->GetIsolate();
1382 1383
    for (int i = 0; i < capacity; i++) {
      Object* key = dict->KeyAt(i);
1384
      if (!dict->IsKey(isolate, key)) continue;
1385 1386 1387 1388 1389 1390 1391
      DCHECK(!dict->IsDeleted(i));
      PropertyDetails details = dict->DetailsAt(i);
      if (details.type() == ACCESSOR_CONSTANT) return true;
    }
    return false;
  }

1392 1393 1394 1395 1396
  static Object* GetRaw(FixedArrayBase* store, uint32_t entry) {
    SeededNumberDictionary* backing_store = SeededNumberDictionary::cast(store);
    return backing_store->ValueAt(entry);
  }

1397 1398 1399
  static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* backing_store,
                                uint32_t entry) {
    return handle(GetRaw(backing_store, entry), isolate);
1400 1401 1402
  }

  static inline void SetImpl(Handle<JSObject> holder, uint32_t entry,
1403
                             Object* value) {
1404 1405 1406 1407 1408 1409
    SetImpl(holder->elements(), entry, value);
  }

  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value) {
    SeededNumberDictionary::cast(backing_store)->ValueAtPut(entry, value);
1410 1411 1412
  }

  static void ReconfigureImpl(Handle<JSObject> object,
1413
                              Handle<FixedArrayBase> store, uint32_t entry,
1414 1415 1416
                              Handle<Object> value,
                              PropertyAttributes attributes) {
    SeededNumberDictionary* dictionary = SeededNumberDictionary::cast(*store);
1417
    if (attributes != NONE) object->RequireSlowElements(dictionary);
1418 1419
    dictionary->ValueAtPut(entry, *value);
    PropertyDetails details = dictionary->DetailsAt(entry);
1420 1421
    details = PropertyDetails(attributes, DATA, details.dictionary_index(),
                              PropertyCellType::kNoCell);
1422
    dictionary->DetailsAtPut(entry, details);
1423 1424
  }

1425
  static void AddImpl(Handle<JSObject> object, uint32_t index,
1426 1427 1428 1429
                      Handle<Object> value, PropertyAttributes attributes,
                      uint32_t new_capacity) {
    PropertyDetails details(attributes, DATA, 0, PropertyCellType::kNoCell);
    Handle<SeededNumberDictionary> dictionary =
1430
        object->HasFastElements() || object->HasFastStringWrapperElements()
1431 1432 1433
            ? JSObject::NormalizeElements(object)
            : handle(SeededNumberDictionary::cast(object->elements()));
    Handle<SeededNumberDictionary> new_dictionary =
1434 1435
        SeededNumberDictionary::AddNumberEntry(dictionary, index, value,
                                               details, object);
1436
    if (attributes != NONE) object->RequireSlowElements(*new_dictionary);
1437 1438 1439 1440
    if (dictionary.is_identical_to(new_dictionary)) return;
    object->set_elements(*new_dictionary);
  }

1441 1442
  static bool HasEntryImpl(Isolate* isolate, FixedArrayBase* store,
                           uint32_t entry) {
1443 1444
    DisallowHeapAllocation no_gc;
    SeededNumberDictionary* dict = SeededNumberDictionary::cast(store);
1445
    Object* index = dict->KeyAt(entry);
1446
    return !index->IsTheHole(isolate);
1447 1448
  }

1449
  static uint32_t GetIndexForEntryImpl(FixedArrayBase* store, uint32_t entry) {
1450 1451 1452
    DisallowHeapAllocation no_gc;
    SeededNumberDictionary* dict = SeededNumberDictionary::cast(store);
    uint32_t result = 0;
1453
    CHECK(dict->KeyAt(entry)->ToArrayIndex(&result));
1454 1455 1456
    return result;
  }

1457 1458 1459
  static uint32_t GetEntryForIndexImpl(Isolate* isolate, JSObject* holder,
                                       FixedArrayBase* store, uint32_t index,
                                       PropertyFilter filter) {
1460
    DisallowHeapAllocation no_gc;
1461
    SeededNumberDictionary* dictionary = SeededNumberDictionary::cast(store);
1462
    int entry = dictionary->FindEntry(isolate, index);
1463
    if (entry == SeededNumberDictionary::kNotFound) return kMaxUInt32;
1464
    if (filter != ALL_PROPERTIES) {
1465 1466 1467 1468 1469
      PropertyDetails details = dictionary->DetailsAt(entry);
      PropertyAttributes attr = details.attributes();
      if ((attr & filter) != 0) return kMaxUInt32;
    }
    return static_cast<uint32_t>(entry);
1470 1471
  }

1472 1473 1474 1475
  static PropertyDetails GetDetailsImpl(JSObject* holder, uint32_t entry) {
    return GetDetailsImpl(holder->elements(), entry);
  }

1476
  static PropertyDetails GetDetailsImpl(FixedArrayBase* backing_store,
1477 1478
                                        uint32_t entry) {
    return SeededNumberDictionary::cast(backing_store)->DetailsAt(entry);
1479
  }
1480

1481 1482
  static uint32_t FilterKey(Handle<SeededNumberDictionary> dictionary,
                            int entry, Object* raw_key, PropertyFilter filter) {
1483
    DCHECK(!dictionary->IsDeleted(entry));
1484 1485 1486 1487 1488
    DCHECK(raw_key->IsNumber());
    DCHECK_LE(raw_key->Number(), kMaxUInt32);
    PropertyDetails details = dictionary->DetailsAt(entry);
    PropertyAttributes attr = details.attributes();
    if ((attr & filter) != 0) return kMaxUInt32;
1489
    return static_cast<uint32_t>(raw_key->Number());
1490 1491
  }

1492 1493
  static uint32_t GetKeyForEntryImpl(Isolate* isolate,
                                     Handle<SeededNumberDictionary> dictionary,
1494 1495 1496
                                     int entry, PropertyFilter filter) {
    DisallowHeapAllocation no_gc;
    Object* raw_key = dictionary->KeyAt(entry);
1497
    if (!dictionary->IsKey(isolate, raw_key)) return kMaxUInt32;
1498 1499 1500
    return FilterKey(dictionary, entry, raw_key, filter);
  }

1501 1502
  static void CollectElementIndicesImpl(Handle<JSObject> object,
                                        Handle<FixedArrayBase> backing_store,
1503 1504
                                        KeyAccumulator* keys) {
    if (keys->filter() & SKIP_STRINGS) return;
1505
    Isolate* isolate = keys->isolate();
1506 1507 1508
    Handle<SeededNumberDictionary> dictionary =
        Handle<SeededNumberDictionary>::cast(backing_store);
    int capacity = dictionary->Capacity();
1509 1510
    Handle<FixedArray> elements = isolate->factory()->NewFixedArray(
        GetMaxNumberOfEntries(*object, *backing_store));
1511
    int insertion_index = 0;
1512
    PropertyFilter filter = keys->filter();
1513
    for (int i = 0; i < capacity; i++) {
1514 1515 1516 1517
      Object* raw_key = dictionary->KeyAt(i);
      if (!dictionary->IsKey(isolate, raw_key)) continue;
      uint32_t key = FilterKey(dictionary, i, raw_key, filter);
      if (key == kMaxUInt32) {
1518
        keys->AddShadowingKey(raw_key);
1519 1520 1521
        continue;
      }
      elements->set(insertion_index, raw_key);
1522 1523 1524 1525 1526
      insertion_index++;
    }
    SortIndices(elements, insertion_index);
    for (int i = 0; i < insertion_index; i++) {
      keys->AddKey(elements->get(i));
1527 1528
    }
  }
1529

1530 1531 1532
  static Handle<FixedArray> DirectCollectElementIndicesImpl(
      Isolate* isolate, Handle<JSObject> object,
      Handle<FixedArrayBase> backing_store, GetKeysConversion convert,
1533 1534
      PropertyFilter filter, Handle<FixedArray> list, uint32_t* nof_indices,
      uint32_t insertion_index = 0) {
1535 1536
    if (filter & SKIP_STRINGS) return list;
    if (filter & ONLY_ALL_CAN_READ) return list;
1537

1538 1539 1540 1541
    Handle<SeededNumberDictionary> dictionary =
        Handle<SeededNumberDictionary>::cast(backing_store);
    uint32_t capacity = dictionary->Capacity();
    for (uint32_t i = 0; i < capacity; i++) {
1542
      uint32_t key = GetKeyForEntryImpl(isolate, dictionary, i, filter);
1543 1544 1545 1546 1547 1548 1549 1550 1551
      if (key == kMaxUInt32) continue;
      Handle<Object> index = isolate->factory()->NewNumberFromUint(key);
      list->set(insertion_index, *index);
      insertion_index++;
    }
    *nof_indices = insertion_index;
    return list;
  }

1552 1553 1554
  static void AddElementsToKeyAccumulatorImpl(Handle<JSObject> receiver,
                                              KeyAccumulator* accumulator,
                                              AddKeyConversion convert) {
1555 1556 1557
    Isolate* isolate = accumulator->isolate();
    Handle<Object> undefined = isolate->factory()->undefined_value();
    Handle<Object> the_hole = isolate->factory()->the_hole_value();
1558 1559
    Handle<SeededNumberDictionary> dictionary(
        SeededNumberDictionary::cast(receiver->elements()), isolate);
1560 1561 1562
    int capacity = dictionary->Capacity();
    for (int i = 0; i < capacity; i++) {
      Object* k = dictionary->KeyAt(i);
1563 1564
      if (k == *undefined) continue;
      if (k == *the_hole) continue;
1565 1566
      if (dictionary->IsDeleted(i)) continue;
      Object* value = dictionary->ValueAt(i);
1567
      DCHECK(!value->IsTheHole(isolate));
1568 1569 1570 1571 1572
      DCHECK(!value->IsAccessorPair());
      DCHECK(!value->IsAccessorInfo());
      accumulator->AddKey(value, convert);
    }
  }
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636

  static bool IncludesValueFastPath(Isolate* isolate, Handle<JSObject> receiver,
                                    Handle<Object> value, uint32_t start_from,
                                    uint32_t length, Maybe<bool>* result) {
    DisallowHeapAllocation no_gc;
    SeededNumberDictionary* dictionary =
        SeededNumberDictionary::cast(receiver->elements());
    int capacity = dictionary->Capacity();
    Object* the_hole = isolate->heap()->the_hole_value();
    Object* undefined = isolate->heap()->undefined_value();

    // Scan for accessor properties. If accessors are present, then elements
    // must be accessed in order via the slow path.
    bool found = false;
    for (int i = 0; i < capacity; ++i) {
      Object* k = dictionary->KeyAt(i);
      if (k == the_hole) continue;
      if (k == undefined) continue;

      uint32_t index;
      if (!k->ToArrayIndex(&index) || index < start_from || index >= length) {
        continue;
      }

      if (dictionary->DetailsAt(i).type() == ACCESSOR_CONSTANT) {
        // Restart from beginning in slow path, otherwise we may observably
        // access getters out of order
        return false;
      } else if (!found) {
        Object* element_k = dictionary->ValueAt(i);
        if (value->SameValueZero(element_k)) found = true;
      }
    }

    *result = Just(found);
    return true;
  }

  static Maybe<bool> IncludesValueImpl(Isolate* isolate,
                                       Handle<JSObject> receiver,
                                       Handle<Object> value,
                                       uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
    bool search_for_hole = value->IsUndefined(isolate);

    if (!search_for_hole) {
      Maybe<bool> result = Nothing<bool>();
      if (DictionaryElementsAccessor::IncludesValueFastPath(
              isolate, receiver, value, start_from, length, &result)) {
        return result;
      }
    }

    Handle<SeededNumberDictionary> dictionary(
        SeededNumberDictionary::cast(receiver->elements()), isolate);
    // Iterate through entire range, as accessing elements out of order is
    // observable
    for (uint32_t k = start_from; k < length; ++k) {
      int entry = dictionary->FindEntry(k);
      if (entry == SeededNumberDictionary::kNotFound) {
        if (search_for_hole) return Just(true);
        continue;
      }

1637
      PropertyDetails details = GetDetailsImpl(*dictionary, entry);
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
      switch (details.kind()) {
        case kData: {
          Object* element_k = dictionary->ValueAt(entry);
          if (value->SameValueZero(element_k)) return Just(true);
          break;
        }
        case kAccessor: {
          LookupIterator it(isolate, receiver, k,
                            LookupIterator::OWN_SKIP_INTERCEPTOR);
          DCHECK(it.IsFound());
          DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
          Handle<Object> element_k;

          ASSIGN_RETURN_ON_EXCEPTION_VALUE(
              isolate, element_k, JSObject::GetPropertyWithAccessor(&it),
              Nothing<bool>());

          if (value->SameValueZero(*element_k)) return Just(true);

1657
          // Bailout to slow path if elements on prototype changed
1658 1659 1660 1661
          if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) {
            return IncludesValueSlowPath(isolate, receiver, value, k + 1,
                                         length);
          }
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678

          // Continue if elements unchanged
          if (*dictionary == receiver->elements()) continue;

          // Otherwise, bailout or update elements
          if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) {
            if (receiver->map()->GetInitialElements() == receiver->elements()) {
              // If switched to initial elements, return true if searching for
              // undefined, and false otherwise.
              return Just(search_for_hole);
            }
            // Otherwise, switch to slow path.
            return IncludesValueSlowPath(isolate, receiver, value, k + 1,
                                         length);
          }
          dictionary = handle(
              SeededNumberDictionary::cast(receiver->elements()), isolate);
1679 1680 1681 1682 1683 1684
          break;
        }
      }
    }
    return Just(false);
  }
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746

  static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
                                         Handle<JSObject> receiver,
                                         Handle<Object> value,
                                         uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));

    Handle<SeededNumberDictionary> dictionary(
        SeededNumberDictionary::cast(receiver->elements()), isolate);
    // Iterate through entire range, as accessing elements out of order is
    // observable.
    for (uint32_t k = start_from; k < length; ++k) {
      int entry = dictionary->FindEntry(k);
      if (entry == SeededNumberDictionary::kNotFound) {
        continue;
      }

      PropertyDetails details = GetDetailsImpl(*dictionary, entry);
      switch (details.kind()) {
        case kData: {
          Object* element_k = dictionary->ValueAt(entry);
          if (value->StrictEquals(element_k)) {
            return Just<int64_t>(k);
          }
          break;
        }
        case kAccessor: {
          LookupIterator it(isolate, receiver, k,
                            LookupIterator::OWN_SKIP_INTERCEPTOR);
          DCHECK(it.IsFound());
          DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
          Handle<Object> element_k;

          ASSIGN_RETURN_ON_EXCEPTION_VALUE(
              isolate, element_k, JSObject::GetPropertyWithAccessor(&it),
              Nothing<int64_t>());

          if (value->StrictEquals(*element_k)) return Just<int64_t>(k);

          // Bailout to slow path if elements on prototype changed.
          if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) {
            return IndexOfValueSlowPath(isolate, receiver, value, k + 1,
                                        length);
          }

          // Continue if elements unchanged.
          if (*dictionary == receiver->elements()) continue;

          // Otherwise, bailout or update elements.
          if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) {
            // Otherwise, switch to slow path.
            return IndexOfValueSlowPath(isolate, receiver, value, k + 1,
                                        length);
          }
          dictionary = handle(
              SeededNumberDictionary::cast(receiver->elements()), isolate);
          break;
        }
      }
    }
    return Just<int64_t>(-1);
  }
1747 1748
};

1749

1750
// Super class for all fast element arrays.
1751 1752
template <typename Subclass, typename KindTraits>
class FastElementsAccessor : public ElementsAccessorBase<Subclass, KindTraits> {
1753 1754
 public:
  explicit FastElementsAccessor(const char* name)
1755
      : ElementsAccessorBase<Subclass, KindTraits>(name) {}
1756

1757
  typedef typename KindTraits::BackingStore BackingStore;
1758

1759 1760 1761
  static Handle<SeededNumberDictionary> NormalizeImpl(
      Handle<JSObject> object, Handle<FixedArrayBase> store) {
    Isolate* isolate = store->GetIsolate();
1762
    ElementsKind kind = Subclass::kind();
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777

    // Ensure that notifications fire if the array or object prototypes are
    // normalizing.
    if (IsFastSmiOrObjectElementsKind(kind)) {
      isolate->UpdateArrayProtectorOnNormalizeElements(object);
    }

    int capacity = object->GetFastElementsUsage();
    Handle<SeededNumberDictionary> dictionary =
        SeededNumberDictionary::New(isolate, capacity);

    PropertyDetails details = PropertyDetails::Empty();
    int j = 0;
    for (int i = 0; j < capacity; i++) {
      if (IsHoleyElementsKind(kind)) {
1778
        if (BackingStore::cast(*store)->is_the_hole(isolate, i)) continue;
1779
      }
1780
      Handle<Object> value = Subclass::GetImpl(isolate, *store, i);
1781 1782
      dictionary = SeededNumberDictionary::AddNumberEntry(dictionary, i, value,
                                                          details, object);
1783 1784 1785 1786 1787
      j++;
    }
    return dictionary;
  }

1788 1789 1790
  static void DeleteAtEnd(Handle<JSObject> obj,
                          Handle<BackingStore> backing_store, uint32_t entry) {
    uint32_t length = static_cast<uint32_t>(backing_store->length());
1791
    Isolate* isolate = obj->GetIsolate();
1792
    for (; entry > 0; entry--) {
1793
      if (!backing_store->is_the_hole(isolate, entry - 1)) break;
1794 1795
    }
    if (entry == 0) {
1796
      FixedArray* empty = isolate->heap()->empty_fixed_array();
1797 1798 1799
      // Dynamically ask for the elements kind here since we manually redirect
      // the operations for argument backing stores.
      if (obj->GetElementsKind() == FAST_SLOPPY_ARGUMENTS_ELEMENTS) {
1800 1801 1802 1803 1804 1805 1806
        FixedArray::cast(obj->elements())->set(1, empty);
      } else {
        obj->set_elements(empty);
      }
      return;
    }

1807
    isolate->heap()->RightTrimFixedArray(*backing_store, length - entry);
1808 1809
  }

1810
  static void DeleteCommon(Handle<JSObject> obj, uint32_t entry,
1811
                           Handle<FixedArrayBase> store) {
1812 1813 1814
    DCHECK(obj->HasFastSmiOrObjectElements() || obj->HasFastDoubleElements() ||
           obj->HasFastArgumentsElements() ||
           obj->HasFastStringWrapperElements());
1815
    Handle<BackingStore> backing_store = Handle<BackingStore>::cast(store);
1816 1817 1818 1819 1820 1821
    if (!obj->IsJSArray() &&
        entry == static_cast<uint32_t>(store->length()) - 1) {
      DeleteAtEnd(obj, backing_store, entry);
      return;
    }

1822
    Isolate* isolate = obj->GetIsolate();
1823
    backing_store->set_the_hole(isolate, entry);
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837

    // TODO(verwaest): Move this out of elements.cc.
    // 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) return;
    if (backing_store->GetHeap()->InNewSpace(*backing_store)) return;
    uint32_t length = 0;
    if (obj->IsJSArray()) {
      JSArray::cast(*obj)->length()->ToArrayLength(&length);
    } else {
      length = static_cast<uint32_t>(store->length());
1838
    }
1839 1840 1841
    if ((entry > 0 && backing_store->is_the_hole(isolate, entry - 1)) ||
        (entry + 1 < length &&
         backing_store->is_the_hole(isolate, entry + 1))) {
1842 1843 1844
      if (!obj->IsJSArray()) {
        uint32_t i;
        for (i = entry + 1; i < length; i++) {
1845
          if (!backing_store->is_the_hole(isolate, i)) break;
1846 1847 1848 1849 1850 1851
        }
        if (i == length) {
          DeleteAtEnd(obj, backing_store, entry);
          return;
        }
      }
1852 1853
      int num_used = 0;
      for (int i = 0; i < backing_store->length(); ++i) {
1854
        if (!backing_store->is_the_hole(isolate, i)) {
1855 1856 1857 1858 1859 1860 1861 1862 1863
          ++num_used;
          // Bail out if a number dictionary wouldn't be able to save at least
          // 75% space.
          if (4 * SeededNumberDictionary::ComputeCapacity(num_used) *
                  SeededNumberDictionary::kEntrySize >
              backing_store->length()) {
            return;
          }
        }
1864
      }
1865
      JSObject::NormalizeElements(obj);
1866 1867 1868
    }
  }

1869
  static void ReconfigureImpl(Handle<JSObject> object,
1870
                              Handle<FixedArrayBase> store, uint32_t entry,
1871 1872 1873 1874
                              Handle<Object> value,
                              PropertyAttributes attributes) {
    Handle<SeededNumberDictionary> dictionary =
        JSObject::NormalizeElements(object);
1875 1876
    entry = dictionary->FindEntry(entry);
    DictionaryElementsAccessor::ReconfigureImpl(object, dictionary, entry,
1877
                                                value, attributes);
1878 1879
  }

1880
  static void AddImpl(Handle<JSObject> object, uint32_t index,
1881 1882 1883 1884
                      Handle<Object> value, PropertyAttributes attributes,
                      uint32_t new_capacity) {
    DCHECK_EQ(NONE, attributes);
    ElementsKind from_kind = object->GetElementsKind();
1885
    ElementsKind to_kind = Subclass::kind();
1886 1887 1888
    if (IsDictionaryElementsKind(from_kind) ||
        IsFastDoubleElementsKind(from_kind) !=
            IsFastDoubleElementsKind(to_kind) ||
1889 1890 1891
        Subclass::GetCapacityImpl(*object, object->elements()) !=
            new_capacity) {
      Subclass::GrowCapacityAndConvertImpl(object, new_capacity);
1892
    } else {
1893
      if (IsFastElementsKind(from_kind) && from_kind != to_kind) {
1894 1895 1896 1897 1898 1899 1900
        JSObject::TransitionElementsKind(object, to_kind);
      }
      if (IsFastSmiOrObjectElementsKind(from_kind)) {
        DCHECK(IsFastSmiOrObjectElementsKind(to_kind));
        JSObject::EnsureWritableFastElements(object);
      }
    }
1901
    Subclass::SetImpl(object, index, *value);
1902 1903
  }

1904
  static void DeleteImpl(Handle<JSObject> obj, uint32_t entry) {
1905 1906 1907 1908 1909 1910 1911
    ElementsKind kind = KindTraits::Kind;
    if (IsFastPackedElementsKind(kind)) {
      JSObject::TransitionElementsKind(obj, GetHoleyElementsKind(kind));
    }
    if (IsFastSmiOrObjectElementsKind(KindTraits::Kind)) {
      JSObject::EnsureWritableFastElements(obj);
    }
1912
    DeleteCommon(obj, entry, handle(obj->elements()));
1913 1914
  }

1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
  static bool HasEntryImpl(Isolate* isolate, FixedArrayBase* backing_store,
                           uint32_t entry) {
    return !BackingStore::cast(backing_store)->is_the_hole(isolate, entry);
  }

  static uint32_t NumberOfElementsImpl(JSObject* receiver,
                                       FixedArrayBase* backing_store) {
    uint32_t max_index = Subclass::GetMaxIndex(receiver, backing_store);
    if (IsFastPackedElementsKind(Subclass::kind())) return max_index;
    Isolate* isolate = receiver->GetIsolate();
    uint32_t count = 0;
    for (uint32_t i = 0; i < max_index; i++) {
      if (Subclass::HasEntryImpl(isolate, backing_store, i)) count++;
    }
    return count;
1930 1931
  }

1932 1933 1934
  static void AddElementsToKeyAccumulatorImpl(Handle<JSObject> receiver,
                                              KeyAccumulator* accumulator,
                                              AddKeyConversion convert) {
1935 1936
    Isolate* isolate = accumulator->isolate();
    Handle<FixedArrayBase> elements(receiver->elements(), isolate);
1937
    uint32_t length = Subclass::GetMaxNumberOfEntries(*receiver, *elements);
1938 1939
    for (uint32_t i = 0; i < length; i++) {
      if (IsFastPackedElementsKind(KindTraits::Kind) ||
1940
          HasEntryImpl(isolate, *elements, i)) {
1941
        accumulator->AddKey(Subclass::GetImpl(isolate, *elements, i), convert);
1942 1943 1944 1945
      }
    }
  }

1946
  static void ValidateContents(Handle<JSObject> holder, int length) {
1947
#if DEBUG
1948
    Isolate* isolate = holder->GetIsolate();
1949
    Heap* heap = isolate->heap();
1950 1951
    HandleScope scope(isolate);
    Handle<FixedArrayBase> elements(holder->elements(), isolate);
1952
    Map* map = elements->map();
1953 1954 1955 1956 1957 1958 1959 1960
    if (IsFastSmiOrObjectElementsKind(KindTraits::Kind)) {
      DCHECK_NE(map, heap->fixed_double_array_map());
    } else if (IsFastDoubleElementsKind(KindTraits::Kind)) {
      DCHECK_NE(map, heap->fixed_cow_array_map());
      if (map == heap->fixed_array_map()) DCHECK_EQ(0, length);
    } else {
      UNREACHABLE();
    }
1961
    if (length == 0) return;  // nothing to do!
1962
#if ENABLE_SLOW_DCHECKS
1963
    DisallowHeapAllocation no_gc;
1964
    Handle<BackingStore> backing_store = Handle<BackingStore>::cast(elements);
1965 1966
    if (IsFastSmiElementsKind(KindTraits::Kind)) {
      for (int i = 0; i < length; i++) {
1967
        DCHECK(BackingStore::get(*backing_store, i, isolate)->IsSmi() ||
1968
               (IsFastHoleyElementsKind(KindTraits::Kind) &&
1969
                backing_store->is_the_hole(isolate, i)));
1970
      }
1971 1972 1973
    } else if (KindTraits::Kind == FAST_ELEMENTS ||
               KindTraits::Kind == FAST_DOUBLE_ELEMENTS) {
      for (int i = 0; i < length; i++) {
1974
        DCHECK(!backing_store->is_the_hole(isolate, i));
1975 1976 1977
      }
    } else {
      DCHECK(IsFastHoleyElementsKind(KindTraits::Kind));
1978
    }
1979
#endif
1980 1981
#endif
  }
1982

1983
  static Handle<Object> PopImpl(Handle<JSArray> receiver) {
1984
    return Subclass::RemoveElement(receiver, AT_END);
1985 1986
  }

1987
  static Handle<Object> ShiftImpl(Handle<JSArray> receiver) {
1988
    return Subclass::RemoveElement(receiver, AT_START);
cbruni's avatar
cbruni committed
1989 1990
  }

1991
  static uint32_t PushImpl(Handle<JSArray> receiver,
1992
                           Arguments* args, uint32_t push_size) {
1993
    Handle<FixedArrayBase> backing_store(receiver->elements());
1994 1995
    return Subclass::AddArguments(receiver, backing_store, args, push_size,
                                  AT_END);
1996
  }
1997

1998 1999
  static uint32_t UnshiftImpl(Handle<JSArray> receiver,
                              Arguments* args, uint32_t unshift_size) {
2000
    Handle<FixedArrayBase> backing_store(receiver->elements());
2001 2002
    return Subclass::AddArguments(receiver, backing_store, args, unshift_size,
                                  AT_START);
2003 2004
  }

2005 2006 2007
  static Handle<JSArray> SliceImpl(Handle<JSObject> receiver,
                                   uint32_t start, uint32_t end) {
    Isolate* isolate = receiver->GetIsolate();
2008 2009
    Handle<FixedArrayBase> backing_store(receiver->elements(), isolate);
    int result_len = end < start ? 0u : end - start;
2010 2011 2012
    Handle<JSArray> result_array = isolate->factory()->NewJSArray(
        KindTraits::Kind, result_len, result_len);
    DisallowHeapAllocation no_gc;
2013 2014 2015 2016
    Subclass::CopyElementsImpl(*backing_store, start, result_array->elements(),
                               KindTraits::Kind, 0, kPackedSizeNotKnown,
                               result_len);
    Subclass::TryTransitionResultArrayToPacked(result_array);
2017 2018 2019
    return result_array;
  }

2020 2021
  static Handle<JSArray> SpliceImpl(Handle<JSArray> receiver,
                                    uint32_t start, uint32_t delete_count,
2022
                                    Arguments* args, uint32_t add_count) {
2023 2024
    Isolate* isolate = receiver->GetIsolate();
    Heap* heap = isolate->heap();
cbruni's avatar
cbruni committed
2025 2026
    uint32_t length = Smi::cast(receiver->length())->value();
    uint32_t new_length = length - delete_count + add_count;
2027

2028 2029 2030 2031 2032 2033 2034 2035 2036
    ElementsKind kind = KindTraits::Kind;
    if (new_length <= static_cast<uint32_t>(receiver->elements()->length()) &&
        IsFastSmiOrObjectElementsKind(kind)) {
      HandleScope scope(isolate);
      JSObject::EnsureWritableFastElements(receiver);
    }

    Handle<FixedArrayBase> backing_store(receiver->elements(), isolate);

2037 2038
    if (new_length == 0) {
      receiver->set_elements(heap->empty_fixed_array());
2039
      receiver->set_length(Smi::kZero);
2040 2041 2042 2043
      return isolate->factory()->NewJSArrayWithElements(
          backing_store, KindTraits::Kind, delete_count);
    }

cbruni's avatar
cbruni committed
2044
    // Construct the result array which holds the deleted elements.
2045 2046 2047 2048
    Handle<JSArray> deleted_elements = isolate->factory()->NewJSArray(
        KindTraits::Kind, delete_count, delete_count);
    if (delete_count > 0) {
      DisallowHeapAllocation no_gc;
2049 2050 2051
      Subclass::CopyElementsImpl(*backing_store, start,
                                 deleted_elements->elements(), KindTraits::Kind,
                                 0, kPackedSizeNotKnown, delete_count);
2052 2053
    }

cbruni's avatar
cbruni committed
2054
    // Delete and move elements to make space for add_count new elements.
2055
    if (add_count < delete_count) {
2056 2057
      Subclass::SpliceShrinkStep(isolate, receiver, backing_store, start,
                                 delete_count, add_count, length, new_length);
2058
    } else if (add_count > delete_count) {
2059 2060 2061
      backing_store =
          Subclass::SpliceGrowStep(isolate, receiver, backing_store, start,
                                   delete_count, add_count, length, new_length);
2062 2063
    }

cbruni's avatar
cbruni committed
2064
    // Copy over the arguments.
2065
    Subclass::CopyArguments(args, backing_store, add_count, 3, start);
2066 2067

    receiver->set_length(Smi::FromInt(new_length));
2068
    Subclass::TryTransitionResultArrayToPacked(deleted_elements);
2069 2070 2071
    return deleted_elements;
  }

2072 2073 2074 2075
  static Maybe<bool> CollectValuesOrEntriesImpl(
      Isolate* isolate, Handle<JSObject> object,
      Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items,
      PropertyFilter filter) {
2076 2077
    Handle<BackingStore> elements(BackingStore::cast(object->elements()),
                                  isolate);
2078
    int count = 0;
2079
    uint32_t length = elements->length();
2080
    for (uint32_t index = 0; index < length; ++index) {
2081
      if (!HasEntryImpl(isolate, *elements, index)) continue;
2082
      Handle<Object> value = Subclass::GetImpl(isolate, *elements, index);
2083 2084 2085 2086 2087 2088 2089 2090 2091
      if (get_entries) {
        value = MakeEntryPair(isolate, index, value);
      }
      values_or_entries->set(count++, *value);
    }
    *nof_items = count;
    return Just(true);
  }

2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
  static void MoveElements(Isolate* isolate, Handle<JSArray> receiver,
                           Handle<FixedArrayBase> backing_store, int dst_index,
                           int src_index, int len, int hole_start,
                           int hole_end) {
    Heap* heap = isolate->heap();
    Handle<BackingStore> dst_elms = Handle<BackingStore>::cast(backing_store);
    if (heap->CanMoveObjectStart(*dst_elms) && dst_index == 0) {
      // Update all the copies of this backing_store handle.
      *dst_elms.location() =
          BackingStore::cast(heap->LeftTrimFixedArray(*dst_elms, src_index));
      receiver->set_elements(*dst_elms);
      // Adjust the hole offset as the array has been shrunk.
      hole_end -= src_index;
      DCHECK_LE(hole_start, backing_store->length());
      DCHECK_LE(hole_end, backing_store->length());
    } else if (len != 0) {
      if (IsFastDoubleElementsKind(KindTraits::Kind)) {
        MemMove(dst_elms->data_start() + dst_index,
                dst_elms->data_start() + src_index, len * kDoubleSize);
      } else {
        DisallowHeapAllocation no_gc;
        heap->MoveElements(FixedArray::cast(*dst_elms), dst_index, src_index,
                           len);
      }
    }
    if (hole_start != hole_end) {
      dst_elms->FillWithHoles(hole_start, hole_end);
    }
  }

2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
  static Maybe<bool> IncludesValueImpl(Isolate* isolate,
                                       Handle<JSObject> receiver,
                                       Handle<Object> search_value,
                                       uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
    DisallowHeapAllocation no_gc;
    FixedArrayBase* elements_base = receiver->elements();
    Object* the_hole = isolate->heap()->the_hole_value();
    Object* undefined = isolate->heap()->undefined_value();
    Object* value = *search_value;

    // Elements beyond the capacity of the backing store treated as undefined.
    if (value == undefined &&
        static_cast<uint32_t>(elements_base->length()) < length) {
      return Just(true);
    }

    if (start_from >= length) return Just(false);

    length = std::min(static_cast<uint32_t>(elements_base->length()), length);

    if (!value->IsNumber()) {
      if (value == undefined) {
        // Only FAST_ELEMENTS, FAST_HOLEY_ELEMENTS, FAST_HOLEY_SMI_ELEMENTS, and
        // FAST_HOLEY_DOUBLE_ELEMENTS can have `undefined` as a value.
        if (!IsFastObjectElementsKind(Subclass::kind()) &&
            !IsFastHoleyElementsKind(Subclass::kind())) {
          return Just(false);
        }

        // Search for `undefined` or The Hole in FAST_ELEMENTS,
        // FAST_HOLEY_ELEMENTS or FAST_HOLEY_SMI_ELEMENTS
        if (IsFastSmiOrObjectElementsKind(Subclass::kind())) {
          auto elements = FixedArray::cast(receiver->elements());

          for (uint32_t k = start_from; k < length; ++k) {
            Object* element_k = elements->get(k);

            if (IsFastHoleyElementsKind(Subclass::kind()) &&
                element_k == the_hole) {
              return Just(true);
            }
            if (IsFastObjectElementsKind(Subclass::kind()) &&
                element_k == undefined) {
              return Just(true);
            }
          }
          return Just(false);
        } else {
          // Seach for The Hole in FAST_HOLEY_DOUBLE_ELEMENTS
          DCHECK_EQ(Subclass::kind(), FAST_HOLEY_DOUBLE_ELEMENTS);
          auto elements = FixedDoubleArray::cast(receiver->elements());

          for (uint32_t k = start_from; k < length; ++k) {
            if (IsFastHoleyElementsKind(Subclass::kind()) &&
                elements->is_the_hole(k)) {
              return Just(true);
            }
          }
          return Just(false);
        }
      } else if (!IsFastObjectElementsKind(Subclass::kind())) {
        // Search for non-number, non-Undefined value, with either
        // FAST_SMI_ELEMENTS, FAST_DOUBLE_ELEMENTS, FAST_HOLEY_SMI_ELEMENTS or
        // FAST_HOLEY_DOUBLE_ELEMENTS. Guaranteed to return false, since these
        // elements kinds can only contain Number values or undefined.
        return Just(false);
      } else {
        // Search for non-number, non-Undefined value with either
        // FAST_ELEMENTS or FAST_HOLEY_ELEMENTS.
        DCHECK(IsFastObjectElementsKind(Subclass::kind()));
        auto elements = FixedArray::cast(receiver->elements());

        for (uint32_t k = start_from; k < length; ++k) {
          Object* element_k = elements->get(k);
          if (IsFastHoleyElementsKind(Subclass::kind()) &&
              element_k == the_hole) {
            continue;
          }

          if (value->SameValueZero(element_k)) return Just(true);
        }
        return Just(false);
      }
    } else {
      if (!value->IsNaN()) {
        double search_value = value->Number();
        if (IsFastDoubleElementsKind(Subclass::kind())) {
          // Search for non-NaN Number in FAST_DOUBLE_ELEMENTS or
          // FAST_HOLEY_DOUBLE_ELEMENTS --- Skip TheHole, and trust UCOMISD or
          // similar operation for result.
          auto elements = FixedDoubleArray::cast(receiver->elements());

          for (uint32_t k = start_from; k < length; ++k) {
            if (IsFastHoleyElementsKind(Subclass::kind()) &&
                elements->is_the_hole(k)) {
              continue;
            }
            if (elements->get_scalar(k) == search_value) return Just(true);
          }
          return Just(false);
        } else {
          // Search for non-NaN Number in FAST_ELEMENTS, FAST_HOLEY_ELEMENTS,
          // FAST_SMI_ELEMENTS or FAST_HOLEY_SMI_ELEMENTS --- Skip non-Numbers,
          // and trust UCOMISD or similar operation for result
          auto elements = FixedArray::cast(receiver->elements());

          for (uint32_t k = start_from; k < length; ++k) {
            Object* element_k = elements->get(k);
            if (element_k->IsNumber() && element_k->Number() == search_value) {
              return Just(true);
            }
          }
          return Just(false);
        }
      } else {
        // Search for NaN --- NaN cannot be represented with Smi elements, so
        // abort if ElementsKind is FAST_SMI_ELEMENTS or FAST_HOLEY_SMI_ELEMENTS
        if (IsFastSmiElementsKind(Subclass::kind())) return Just(false);

        if (IsFastDoubleElementsKind(Subclass::kind())) {
          // Search for NaN in FAST_DOUBLE_ELEMENTS or
          // FAST_HOLEY_DOUBLE_ELEMENTS --- Skip The Hole and trust
          // std::isnan(elementK) for result
          auto elements = FixedDoubleArray::cast(receiver->elements());

          for (uint32_t k = start_from; k < length; ++k) {
            if (IsFastHoleyElementsKind(Subclass::kind()) &&
                elements->is_the_hole(k)) {
              continue;
            }
            if (std::isnan(elements->get_scalar(k))) return Just(true);
          }
          return Just(false);
        } else {
          // Search for NaN in FAST_ELEMENTS, FAST_HOLEY_ELEMENTS,
          // FAST_SMI_ELEMENTS or FAST_HOLEY_SMI_ELEMENTS. Return true if
          // elementK->IsHeapNumber() && std::isnan(elementK->Number())
          DCHECK(IsFastSmiOrObjectElementsKind(Subclass::kind()));
          auto elements = FixedArray::cast(receiver->elements());

          for (uint32_t k = start_from; k < length; ++k) {
            if (elements->get(k)->IsNaN()) return Just(true);
          }
          return Just(false);
        }
      }
    }
  }

2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
  static Handle<FixedArray> CreateListFromArrayImpl(Isolate* isolate,
                                                    Handle<JSArray> array) {
    uint32_t length = 0;
    array->length()->ToArrayLength(&length);
    Handle<FixedArray> result = isolate->factory()->NewFixedArray(length);
    Handle<FixedArrayBase> elements(array->elements(), isolate);
    for (uint32_t i = 0; i < length; i++) {
      if (!Subclass::HasElementImpl(isolate, array, i, elements)) continue;
      Handle<Object> value;
      value = Subclass::GetImpl(isolate, *elements, i);
      if (value->IsName()) {
        value = isolate->factory()->InternalizeName(Handle<Name>::cast(value));
      }
      result->set(i, *value);
    }
    return result;
  }

2290
 private:
2291 2292 2293
  // SpliceShrinkStep might modify the backing_store.
  static void SpliceShrinkStep(Isolate* isolate, Handle<JSArray> receiver,
                               Handle<FixedArrayBase> backing_store,
cbruni's avatar
cbruni committed
2294 2295 2296
                               uint32_t start, uint32_t delete_count,
                               uint32_t add_count, uint32_t len,
                               uint32_t new_length) {
2297 2298
    const int move_left_count = len - delete_count - start;
    const int move_left_dst_index = start + add_count;
2299 2300 2301
    Subclass::MoveElements(isolate, receiver, backing_store,
                           move_left_dst_index, start + delete_count,
                           move_left_count, new_length, len);
cbruni's avatar
cbruni committed
2302 2303
  }

2304
  // SpliceGrowStep might modify the backing_store.
cbruni's avatar
cbruni committed
2305
  static Handle<FixedArrayBase> SpliceGrowStep(
2306 2307 2308 2309
      Isolate* isolate, Handle<JSArray> receiver,
      Handle<FixedArrayBase> backing_store, uint32_t start,
      uint32_t delete_count, uint32_t add_count, uint32_t length,
      uint32_t new_length) {
cbruni's avatar
cbruni committed
2310 2311 2312 2313
    // Check we do not overflow the new_length.
    DCHECK((add_count - delete_count) <= (Smi::kMaxValue - length));
    // Check if backing_store is big enough.
    if (new_length <= static_cast<uint32_t>(backing_store->length())) {
2314 2315 2316
      Subclass::MoveElements(isolate, receiver, backing_store,
                             start + add_count, start + delete_count,
                             (length - delete_count - start), 0, 0);
2317
      // MoveElements updates the backing_store in-place.
cbruni's avatar
cbruni committed
2318
      return backing_store;
2319
    }
cbruni's avatar
cbruni committed
2320 2321 2322
    // New backing storage is needed.
    int capacity = JSObject::NewElementsCapacity(new_length);
    // Partially copy all elements up to start.
2323 2324
    Handle<FixedArrayBase> new_elms = Subclass::ConvertElementsWithCapacity(
        receiver, backing_store, KindTraits::Kind, capacity, start);
cbruni's avatar
cbruni committed
2325
    // Copy the trailing elements after start + delete_count
2326 2327 2328 2329
    Subclass::CopyElementsImpl(*backing_store, start + delete_count, *new_elms,
                               KindTraits::Kind, start + add_count,
                               kPackedSizeNotKnown,
                               ElementsAccessor::kCopyToEndAndInitializeToHole);
cbruni's avatar
cbruni committed
2330 2331
    receiver->set_elements(*new_elms);
    return new_elms;
2332 2333
  }

cbruni's avatar
cbruni committed
2334 2335
  static Handle<Object> RemoveElement(Handle<JSArray> receiver,
                                      Where remove_position) {
2336
    Isolate* isolate = receiver->GetIsolate();
2337 2338 2339 2340 2341 2342
    ElementsKind kind = KindTraits::Kind;
    if (IsFastSmiOrObjectElementsKind(kind)) {
      HandleScope scope(isolate);
      JSObject::EnsureWritableFastElements(receiver);
    }
    Handle<FixedArrayBase> backing_store(receiver->elements(), isolate);
cbruni's avatar
cbruni committed
2343 2344 2345 2346 2347
    uint32_t length =
        static_cast<uint32_t>(Smi::cast(receiver->length())->value());
    DCHECK(length > 0);
    int new_length = length - 1;
    int remove_index = remove_position == AT_START ? 0 : new_length;
2348 2349
    Handle<Object> result =
        Subclass::GetImpl(isolate, *backing_store, remove_index);
cbruni's avatar
cbruni committed
2350
    if (remove_position == AT_START) {
2351 2352
      Subclass::MoveElements(isolate, receiver, backing_store, 0, 1, new_length,
                             0, 0);
cbruni's avatar
cbruni committed
2353
    }
2354
    Subclass::SetLengthImpl(isolate, receiver, new_length, backing_store);
2355

2356
    if (IsHoleyElementsKind(kind) && result->IsTheHole(isolate)) {
2357
      return isolate->factory()->undefined_value();
cbruni's avatar
cbruni committed
2358 2359 2360 2361 2362 2363 2364
    }
    return result;
  }

  static uint32_t AddArguments(Handle<JSArray> receiver,
                               Handle<FixedArrayBase> backing_store,
                               Arguments* args, uint32_t add_size,
2365
                               Where add_position) {
cbruni's avatar
cbruni committed
2366
    uint32_t length = Smi::cast(receiver->length())->value();
2367
    DCHECK(0 < add_size);
cbruni's avatar
cbruni committed
2368 2369 2370 2371 2372 2373
    uint32_t elms_len = backing_store->length();
    // Check we do not overflow the new_length.
    DCHECK(add_size <= static_cast<uint32_t>(Smi::kMaxValue - length));
    uint32_t new_length = length + add_size;

    if (new_length > elms_len) {
2374
      // New backing storage is needed.
cbruni's avatar
cbruni committed
2375 2376
      uint32_t capacity = JSObject::NewElementsCapacity(new_length);
      // If we add arguments to the start we have to shift the existing objects.
2377
      int copy_dst_index = add_position == AT_START ? add_size : 0;
cbruni's avatar
cbruni committed
2378
      // Copy over all objects to a new backing_store.
2379
      backing_store = Subclass::ConvertElementsWithCapacity(
cbruni's avatar
cbruni committed
2380 2381 2382
          receiver, backing_store, KindTraits::Kind, capacity, 0,
          copy_dst_index, ElementsAccessor::kCopyToEndAndInitializeToHole);
      receiver->set_elements(*backing_store);
2383
    } else if (add_position == AT_START) {
cbruni's avatar
cbruni committed
2384 2385 2386
      // If the backing store has enough capacity and we add elements to the
      // start we have to shift the existing objects.
      Isolate* isolate = receiver->GetIsolate();
2387 2388
      Subclass::MoveElements(isolate, receiver, backing_store, add_size, 0,
                             length, 0, 0);
cbruni's avatar
cbruni committed
2389
    }
2390

2391
    int insertion_index = add_position == AT_START ? 0 : length;
cbruni's avatar
cbruni committed
2392
    // Copy the arguments to the start.
2393
    Subclass::CopyArguments(args, backing_store, add_size, 1, insertion_index);
cbruni's avatar
cbruni committed
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
    // Set the length.
    receiver->set_length(Smi::FromInt(new_length));
    return new_length;
  }

  static void CopyArguments(Arguments* args, Handle<FixedArrayBase> dst_store,
                            uint32_t copy_size, uint32_t src_index,
                            uint32_t dst_index) {
    // Add the provided values.
    DisallowHeapAllocation no_gc;
    FixedArrayBase* raw_backing_store = *dst_store;
    WriteBarrierMode mode = raw_backing_store->GetWriteBarrierMode(no_gc);
    for (uint32_t i = 0; i < copy_size; i++) {
2407
      Object* argument = (*args)[src_index + i];
2408
      DCHECK(!argument->IsTheHole(raw_backing_store->GetIsolate()));
2409
      Subclass::SetImpl(raw_backing_store, dst_index + i, argument, mode);
2410 2411
    }
  }
2412 2413
};

2414
template <typename Subclass, typename KindTraits>
2415
class FastSmiOrObjectElementsAccessor
2416
    : public FastElementsAccessor<Subclass, KindTraits> {
2417 2418
 public:
  explicit FastSmiOrObjectElementsAccessor(const char* name)
2419
      : FastElementsAccessor<Subclass, KindTraits>(name) {}
2420

2421 2422 2423 2424 2425
  static inline void SetImpl(Handle<JSObject> holder, uint32_t entry,
                             Object* value) {
    SetImpl(holder->elements(), entry, value);
  }

2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value) {
    FixedArray::cast(backing_store)->set(entry, value);
  }

  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value, WriteBarrierMode mode) {
    FixedArray::cast(backing_store)->set(entry, value, mode);
  }

2436
  static Object* GetRaw(FixedArray* backing_store, uint32_t entry) {
2437
    uint32_t index = Subclass::GetIndexForEntryImpl(backing_store, entry);
2438 2439 2440
    return backing_store->get(index);
  }

2441 2442 2443 2444 2445 2446 2447 2448
  // 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,
2449
                               int copy_size) {
2450
    DisallowHeapAllocation no_gc;
2451 2452 2453 2454 2455 2456
    ElementsKind to_kind = KindTraits::Kind;
    switch (from_kind) {
      case FAST_SMI_ELEMENTS:
      case FAST_HOLEY_SMI_ELEMENTS:
      case FAST_ELEMENTS:
      case FAST_HOLEY_ELEMENTS:
2457
        CopyObjectToObjectElements(from, from_kind, from_start, to, to_kind,
2458
                                   to_start, copy_size);
2459
        break;
2460
      case FAST_DOUBLE_ELEMENTS:
2461 2462
      case FAST_HOLEY_DOUBLE_ELEMENTS: {
        AllowHeapAllocation allow_allocation;
2463 2464
        DCHECK(IsFastObjectElementsKind(to_kind));
        CopyDoubleToObjectElements(from, from_start, to, to_start, copy_size);
2465
        break;
2466
      }
2467
      case DICTIONARY_ELEMENTS:
2468 2469
        CopyDictionaryToObjectElements(from, from_start, to, to_kind, to_start,
                                       copy_size);
2470
        break;
2471 2472
      case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
      case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
2473 2474
      case FAST_STRING_WRAPPER_ELEMENTS:
      case SLOW_STRING_WRAPPER_ELEMENTS:
2475
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) case TYPE##_ELEMENTS:
2476 2477
      TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
2478 2479 2480 2481 2482 2483
      // This function is currently only used for JSArrays with non-zero
      // length.
      UNREACHABLE();
      break;
      case NO_ELEMENTS:
        break;  // Nothing to do.
2484 2485
    }
  }
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512

  static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
                                         Handle<JSObject> receiver,
                                         Handle<Object> search_value,
                                         uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
    DisallowHeapAllocation no_gc;
    FixedArrayBase* elements_base = receiver->elements();
    Object* value = *search_value;

    if (start_from >= length) return Just<int64_t>(-1);

    length = std::min(static_cast<uint32_t>(elements_base->length()), length);

    // Only FAST_{,HOLEY_}ELEMENTS can store non-numbers.
    if (!value->IsNumber() && !IsFastObjectElementsKind(Subclass::kind())) {
      return Just<int64_t>(-1);
    }
    // NaN can never be found by strict equality.
    if (value->IsNaN()) return Just<int64_t>(-1);

    FixedArray* elements = FixedArray::cast(receiver->elements());
    for (uint32_t k = start_from; k < length; ++k) {
      if (value->StrictEquals(elements->get(k))) return Just<int64_t>(k);
    }
    return Just<int64_t>(-1);
  }
2513
};
2514

2515

2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536
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) {}
2537 2538 2539
};


2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
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) {}
};

2563
template <typename Subclass, typename KindTraits>
2564
class FastDoubleElementsAccessor
2565
    : public FastElementsAccessor<Subclass, KindTraits> {
2566 2567
 public:
  explicit FastDoubleElementsAccessor(const char* name)
2568
      : FastElementsAccessor<Subclass, KindTraits>(name) {}
2569

2570 2571
  static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* backing_store,
                                uint32_t entry) {
2572 2573 2574 2575 2576 2577 2578 2579 2580
    return FixedDoubleArray::get(FixedDoubleArray::cast(backing_store), entry,
                                 isolate);
  }

  static inline void SetImpl(Handle<JSObject> holder, uint32_t entry,
                             Object* value) {
    SetImpl(holder->elements(), entry, value);
  }

2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value) {
    FixedDoubleArray::cast(backing_store)->set(entry, value->Number());
  }

  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value, WriteBarrierMode mode) {
    FixedDoubleArray::cast(backing_store)->set(entry, value->Number());
  }

2591 2592 2593
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
2594
                               int copy_size) {
2595
    DisallowHeapAllocation no_allocation;
2596
    switch (from_kind) {
2597
      case FAST_SMI_ELEMENTS:
2598
        CopyPackedSmiToDoubleElements(from, from_start, to, to_start,
2599
                                      packed_size, copy_size);
2600
        break;
2601
      case FAST_HOLEY_SMI_ELEMENTS:
2602
        CopySmiToDoubleElements(from, from_start, to, to_start, copy_size);
2603
        break;
2604
      case FAST_DOUBLE_ELEMENTS:
2605
      case FAST_HOLEY_DOUBLE_ELEMENTS:
2606
        CopyDoubleToDoubleElements(from, from_start, to, to_start, copy_size);
2607 2608 2609
        break;
      case FAST_ELEMENTS:
      case FAST_HOLEY_ELEMENTS:
2610
        CopyObjectToDoubleElements(from, from_start, to, to_start, copy_size);
2611 2612
        break;
      case DICTIONARY_ELEMENTS:
2613
        CopyDictionaryToDoubleElements(from, from_start, to, to_start,
2614
                                       copy_size);
2615
        break;
2616 2617
      case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
      case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
2618 2619 2620 2621
      case FAST_STRING_WRAPPER_ELEMENTS:
      case SLOW_STRING_WRAPPER_ELEMENTS:
      case NO_ELEMENTS:
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) case TYPE##_ELEMENTS:
2622 2623
      TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
2624 2625 2626 2627
      // This function is currently only used for JSArrays with non-zero
      // length.
      UNREACHABLE();
      break;
2628 2629
    }
  }
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662

  static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
                                         Handle<JSObject> receiver,
                                         Handle<Object> search_value,
                                         uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
    DisallowHeapAllocation no_gc;
    FixedArrayBase* elements_base = receiver->elements();
    Object* value = *search_value;

    if (start_from >= length) return Just<int64_t>(-1);

    length = std::min(static_cast<uint32_t>(elements_base->length()), length);

    if (!value->IsNumber()) {
      return Just<int64_t>(-1);
    }
    if (value->IsNaN()) {
      return Just<int64_t>(-1);
    }
    double numeric_search_value = value->Number();
    FixedDoubleArray* elements = FixedDoubleArray::cast(receiver->elements());

    for (uint32_t k = start_from; k < length; ++k) {
      if (elements->is_the_hole(k)) {
        continue;
      }
      if (elements->get_scalar(k) == numeric_search_value) {
        return Just<int64_t>(k);
      }
    }
    return Just<int64_t>(-1);
  }
2663
};
2664

2665

2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686
class FastPackedDoubleElementsAccessor
    : public FastDoubleElementsAccessor<
        FastPackedDoubleElementsAccessor,
        ElementsKindTraits<FAST_DOUBLE_ELEMENTS> > {
 public:
  explicit FastPackedDoubleElementsAccessor(const char* name)
      : FastDoubleElementsAccessor<
          FastPackedDoubleElementsAccessor,
          ElementsKindTraits<FAST_DOUBLE_ELEMENTS> >(name) {}
};


class FastHoleyDoubleElementsAccessor
    : public FastDoubleElementsAccessor<
        FastHoleyDoubleElementsAccessor,
        ElementsKindTraits<FAST_HOLEY_DOUBLE_ELEMENTS> > {
 public:
  explicit FastHoleyDoubleElementsAccessor(const char* name)
      : FastDoubleElementsAccessor<
          FastHoleyDoubleElementsAccessor,
          ElementsKindTraits<FAST_HOLEY_DOUBLE_ELEMENTS> >(name) {}
2687 2688 2689 2690
};


// Super class for all external element arrays.
2691
template <ElementsKind Kind, typename ctype>
2692
class TypedElementsAccessor
2693 2694
    : public ElementsAccessorBase<TypedElementsAccessor<Kind, ctype>,
                                  ElementsKindTraits<Kind>> {
2695
 public:
2696
  explicit TypedElementsAccessor(const char* name)
2697
      : ElementsAccessorBase<AccessorClass,
2698
                             ElementsKindTraits<Kind> >(name) {}
2699

2700
  typedef typename ElementsKindTraits<Kind>::BackingStore BackingStore;
2701
  typedef TypedElementsAccessor<Kind, ctype> AccessorClass;
2702

2703 2704 2705 2706 2707
  static inline void SetImpl(Handle<JSObject> holder, uint32_t entry,
                             Object* value) {
    SetImpl(holder->elements(), entry, value);
  }

2708 2709 2710 2711 2712 2713 2714 2715 2716 2717
  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value) {
    BackingStore::cast(backing_store)->SetValue(entry, value);
  }

  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value, WriteBarrierMode mode) {
    BackingStore::cast(backing_store)->SetValue(entry, value);
  }

2718 2719
  static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* backing_store,
                                uint32_t entry) {
2720 2721 2722 2723 2724
    return BackingStore::get(BackingStore::cast(backing_store), entry);
  }

  static PropertyDetails GetDetailsImpl(JSObject* holder, uint32_t entry) {
    return PropertyDetails(DONT_DELETE, DATA, 0, PropertyCellType::kNoCell);
2725
  }
2726

2727
  static PropertyDetails GetDetailsImpl(FixedArrayBase* backing_store,
2728
                                        uint32_t entry) {
2729
    return PropertyDetails(DONT_DELETE, DATA, 0, PropertyCellType::kNoCell);
2730 2731
  }

2732 2733
  static bool HasElementImpl(Isolate* isolate, Handle<JSObject> holder,
                             uint32_t index,
2734 2735 2736 2737 2738
                             Handle<FixedArrayBase> backing_store,
                             PropertyFilter filter) {
    return index < AccessorClass::GetCapacityImpl(*holder, *backing_store);
  }

2739 2740 2741 2742 2743
  static bool HasAccessorsImpl(JSObject* holder,
                               FixedArrayBase* backing_store) {
    return false;
  }

2744 2745
  static void SetLengthImpl(Isolate* isolate, Handle<JSArray> array,
                            uint32_t length,
2746
                            Handle<FixedArrayBase> backing_store) {
2747 2748 2749 2750
    // External arrays do not support changing their length.
    UNREACHABLE();
  }

2751
  static void DeleteImpl(Handle<JSObject> obj, uint32_t entry) {
2752
    UNREACHABLE();
2753
  }
2754

2755 2756 2757 2758 2759
  static uint32_t GetIndexForEntryImpl(FixedArrayBase* backing_store,
                                       uint32_t entry) {
    return entry;
  }

2760
  static uint32_t GetEntryForIndexImpl(Isolate* isolate, JSObject* holder,
2761
                                       FixedArrayBase* backing_store,
2762
                                       uint32_t index, PropertyFilter filter) {
2763 2764
    return index < AccessorClass::GetCapacityImpl(holder, backing_store)
               ? index
2765
               : kMaxUInt32;
2766
  }
2767

2768 2769 2770
  static uint32_t GetCapacityImpl(JSObject* holder,
                                  FixedArrayBase* backing_store) {
    JSArrayBufferView* view = JSArrayBufferView::cast(holder);
2771 2772 2773
    if (view->WasNeutered()) return 0;
    return backing_store->length();
  }
2774

2775 2776 2777 2778 2779
  static uint32_t NumberOfElementsImpl(JSObject* receiver,
                                       FixedArrayBase* backing_store) {
    return AccessorClass::GetCapacityImpl(receiver, backing_store);
  }

2780 2781 2782
  static void AddElementsToKeyAccumulatorImpl(Handle<JSObject> receiver,
                                              KeyAccumulator* accumulator,
                                              AddKeyConversion convert) {
2783
    Isolate* isolate = receiver->GetIsolate();
2784
    Handle<FixedArrayBase> elements(receiver->elements());
2785 2786
    uint32_t length = AccessorClass::GetCapacityImpl(*receiver, *elements);
    for (uint32_t i = 0; i < length; i++) {
2787
      Handle<Object> value = AccessorClass::GetImpl(isolate, *elements, i);
2788 2789 2790
      accumulator->AddKey(value, convert);
    }
  }
2791 2792 2793 2794 2795 2796 2797 2798 2799 2800

  static Maybe<bool> CollectValuesOrEntriesImpl(
      Isolate* isolate, Handle<JSObject> object,
      Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items,
      PropertyFilter filter) {
    int count = 0;
    if ((filter & ONLY_CONFIGURABLE) == 0) {
      Handle<FixedArrayBase> elements(object->elements());
      uint32_t length = AccessorClass::GetCapacityImpl(*object, *elements);
      for (uint32_t index = 0; index < length; ++index) {
2801 2802
        Handle<Object> value =
            AccessorClass::GetImpl(isolate, *elements, index);
2803 2804 2805 2806 2807 2808 2809 2810 2811
        if (get_entries) {
          value = MakeEntryPair(isolate, index, value);
        }
        values_or_entries->set(count++, *value);
      }
    }
    *nof_items = count;
    return Just(true);
  }
2812

2813 2814 2815 2816 2817 2818
  static Maybe<bool> IncludesValueImpl(Isolate* isolate,
                                       Handle<JSObject> receiver,
                                       Handle<Object> value,
                                       uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
    DisallowHeapAllocation no_gc;
2819

2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
    BackingStore* elements = BackingStore::cast(receiver->elements());
    if (value->IsUndefined(isolate) &&
        length > static_cast<uint32_t>(elements->length())) {
      return Just(true);
    }
    if (!value->IsNumber()) return Just(false);

    double search_value = value->Number();

    if (!std::isfinite(search_value)) {
      // Integral types cannot represent +Inf or NaN
      if (AccessorClass::kind() < FLOAT32_ELEMENTS ||
          AccessorClass::kind() > FLOAT64_ELEMENTS) {
        return Just(false);
      }
    } else if (search_value < std::numeric_limits<ctype>::lowest() ||
               search_value > std::numeric_limits<ctype>::max()) {
      // Return false if value can't be represented in this space
      return Just(false);
    }

2841 2842 2843 2844 2845 2846
    // Prototype has no elements, and not searching for the hole --- limit
    // search to backing store length.
    if (static_cast<uint32_t>(elements->length()) < length) {
      length = elements->length();
    }

2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
    if (!std::isnan(search_value)) {
      for (uint32_t k = start_from; k < length; ++k) {
        double element_k = elements->get_scalar(k);
        if (element_k == search_value) return Just(true);
      }
      return Just(false);
    } else {
      for (uint32_t k = start_from; k < length; ++k) {
        double element_k = elements->get_scalar(k);
        if (std::isnan(element_k)) return Just(true);
      }
      return Just(false);
    }
  }
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906

  static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
                                         Handle<JSObject> receiver,
                                         Handle<Object> value,
                                         uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
    DisallowHeapAllocation no_gc;

    BackingStore* elements = BackingStore::cast(receiver->elements());
    if (!value->IsNumber()) return Just<int64_t>(-1);

    double search_value = value->Number();

    if (!std::isfinite(search_value)) {
      // Integral types cannot represent +Inf or NaN.
      if (AccessorClass::kind() < FLOAT32_ELEMENTS ||
          AccessorClass::kind() > FLOAT64_ELEMENTS) {
        return Just<int64_t>(-1);
      }
    } else if (search_value < std::numeric_limits<ctype>::lowest() ||
               search_value > std::numeric_limits<ctype>::max()) {
      // Return false if value can't be represented in this ElementsKind.
      return Just<int64_t>(-1);
    }

    // Prototype has no elements, and not searching for the hole --- limit
    // search to backing store length.
    if (static_cast<uint32_t>(elements->length()) < length) {
      length = elements->length();
    }

    if (std::isnan(search_value)) {
      return Just<int64_t>(-1);
    }

    ctype typed_search_value = static_cast<ctype>(search_value);
    if (static_cast<double>(typed_search_value) != search_value) {
      return Just<int64_t>(-1);  // Loss of precision.
    }

    for (uint32_t k = start_from; k < length; ++k) {
      ctype element_k = elements->get_scalar(k);
      if (element_k == typed_search_value) return Just<int64_t>(k);
    }
    return Just<int64_t>(-1);
  }
2907
};
2908

2909 2910
#define FIXED_ELEMENTS_ACCESSOR(Type, type, TYPE, ctype, size) \
  typedef TypedElementsAccessor<TYPE##_ELEMENTS, ctype>        \
2911
      Fixed##Type##ElementsAccessor;
2912

2913 2914
TYPED_ARRAYS(FIXED_ELEMENTS_ACCESSOR)
#undef FIXED_ELEMENTS_ACCESSOR
2915

2916
template <typename Subclass, typename ArgumentsAccessor, typename KindTraits>
2917
class SloppyArgumentsElementsAccessor
2918
    : public ElementsAccessorBase<Subclass, KindTraits> {
2919 2920
 public:
  explicit SloppyArgumentsElementsAccessor(const char* name)
2921
      : ElementsAccessorBase<Subclass, KindTraits>(name) {
2922 2923
    USE(KindTraits::Kind);
  }
2924

2925 2926
  static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* parameters,
                                uint32_t entry) {
2927
    Handle<FixedArray> parameter_map(FixedArray::cast(parameters), isolate);
2928 2929
    uint32_t length = parameter_map->length() - 2;
    if (entry < length) {
2930
      DisallowHeapAllocation no_gc;
2931
      Object* probe = parameter_map->get(entry + 2);
2932
      Context* context = Context::cast(parameter_map->get(0));
2933
      int context_entry = Smi::cast(probe)->value();
2934
      DCHECK(!context->get(context_entry)->IsTheHole(isolate));
2935
      return handle(context->get(context_entry), isolate);
2936 2937
    } else {
      // Object is not mapped, defer to the arguments.
2938
      Handle<Object> result = ArgumentsAccessor::GetImpl(
2939
          isolate, FixedArray::cast(parameter_map->get(1)), entry - length);
2940 2941 2942
      // Elements of the arguments object in slow mode might be slow aliases.
      if (result->IsAliasedArgumentsEntry()) {
        DisallowHeapAllocation no_gc;
2943
        AliasedArgumentsEntry* alias = AliasedArgumentsEntry::cast(*result);
2944
        Context* context = Context::cast(parameter_map->get(0));
2945
        int context_entry = alias->aliased_context_slot();
2946
        DCHECK(!context->get(context_entry)->IsTheHole(isolate));
2947
        return handle(context->get(context_entry), isolate);
2948
      }
2949
      return result;
2950 2951
    }
  }
2952

2953 2954 2955 2956 2957
  static void TransitionElementsKindImpl(Handle<JSObject> object,
                                         Handle<Map> map) {
    UNREACHABLE();
  }

2958 2959
  static void GrowCapacityAndConvertImpl(Handle<JSObject> object,
                                         uint32_t capacity) {
2960
    UNREACHABLE();
2961 2962
  }

2963 2964 2965 2966 2967
  static inline void SetImpl(Handle<JSObject> holder, uint32_t entry,
                             Object* value) {
    SetImpl(holder->elements(), entry, value);
  }

2968 2969
  static inline void SetImpl(FixedArrayBase* store, uint32_t entry,
                             Object* value) {
2970
    FixedArray* parameter_map = FixedArray::cast(store);
2971 2972 2973
    uint32_t length = parameter_map->length() - 2;
    if (entry < length) {
      Object* probe = parameter_map->get(entry + 2);
2974
      Context* context = Context::cast(parameter_map->get(0));
2975
      int context_entry = Smi::cast(probe)->value();
2976
      DCHECK(!context->get(context_entry)->IsTheHole(store->GetIsolate()));
2977
      context->set(context_entry, value);
2978
    } else {
2979
      FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
2980 2981 2982 2983 2984
      Object* current = ArgumentsAccessor::GetRaw(arguments, entry - length);
      if (current->IsAliasedArgumentsEntry()) {
        AliasedArgumentsEntry* alias = AliasedArgumentsEntry::cast(current);
        Context* context = Context::cast(parameter_map->get(0));
        int context_entry = alias->aliased_context_slot();
2985
        DCHECK(!context->get(context_entry)->IsTheHole(store->GetIsolate()));
2986 2987 2988 2989
        context->set(context_entry, value);
      } else {
        ArgumentsAccessor::SetImpl(arguments, entry - length, value);
      }
2990 2991 2992
    }
  }

2993 2994
  static void SetLengthImpl(Isolate* isolate, Handle<JSArray> array,
                            uint32_t length,
2995 2996 2997
                            Handle<FixedArrayBase> parameter_map) {
    // Sloppy arguments objects are not arrays.
    UNREACHABLE();
2998 2999
  }

3000 3001 3002 3003
  static uint32_t GetCapacityImpl(JSObject* holder,
                                  FixedArrayBase* backing_store) {
    FixedArray* parameter_map = FixedArray::cast(backing_store);
    FixedArrayBase* arguments = FixedArrayBase::cast(parameter_map->get(1));
3004
    return parameter_map->length() - 2 +
3005
           ArgumentsAccessor::GetCapacityImpl(holder, arguments);
3006 3007
  }

3008 3009 3010 3011 3012 3013 3014 3015
  static uint32_t GetMaxNumberOfEntries(JSObject* holder,
                                        FixedArrayBase* backing_store) {
    FixedArray* parameter_map = FixedArray::cast(backing_store);
    FixedArrayBase* arguments = FixedArrayBase::cast(parameter_map->get(1));
    return parameter_map->length() - 2 +
           ArgumentsAccessor::GetMaxNumberOfEntries(holder, arguments);
  }

3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
  static uint32_t NumberOfElementsImpl(JSObject* receiver,
                                       FixedArrayBase* backing_store) {
    FixedArray* parameter_map = FixedArray::cast(backing_store);
    FixedArrayBase* arguments = FixedArrayBase::cast(parameter_map->get(1));
    uint32_t nof_elements = 0;
    uint32_t length = parameter_map->length() - 2;
    for (uint32_t entry = 0; entry < length; entry++) {
      if (HasParameterMapArg(parameter_map, entry)) nof_elements++;
    }
    return nof_elements +
           ArgumentsAccessor::NumberOfElementsImpl(receiver, arguments);
  }

3029 3030 3031
  static void AddElementsToKeyAccumulatorImpl(Handle<JSObject> receiver,
                                              KeyAccumulator* accumulator,
                                              AddKeyConversion convert) {
3032 3033 3034
    Isolate* isolate = accumulator->isolate();
    Handle<FixedArrayBase> elements(receiver->elements(), isolate);
    uint32_t length = GetCapacityImpl(*receiver, *elements);
3035
    for (uint32_t entry = 0; entry < length; entry++) {
3036
      if (!HasEntryImpl(isolate, *elements, entry)) continue;
3037
      Handle<Object> value = GetImpl(isolate, *elements, entry);
3038 3039 3040 3041
      accumulator->AddKey(value, convert);
    }
  }

3042 3043
  static bool HasEntryImpl(Isolate* isolate, FixedArrayBase* parameters,
                           uint32_t entry) {
3044 3045
    FixedArray* parameter_map = FixedArray::cast(parameters);
    uint32_t length = parameter_map->length() - 2;
3046
    if (entry < length) {
3047
      return HasParameterMapArg(parameter_map, entry);
3048 3049 3050
    }

    FixedArrayBase* arguments = FixedArrayBase::cast(parameter_map->get(1));
3051
    return ArgumentsAccessor::HasEntryImpl(isolate, arguments, entry - length);
3052 3053
  }

3054 3055 3056 3057 3058 3059 3060
  static bool HasAccessorsImpl(JSObject* holder,
                               FixedArrayBase* backing_store) {
    FixedArray* parameter_map = FixedArray::cast(backing_store);
    FixedArrayBase* arguments = FixedArrayBase::cast(parameter_map->get(1));
    return ArgumentsAccessor::HasAccessorsImpl(holder, arguments);
  }

3061 3062
  static uint32_t GetIndexForEntryImpl(FixedArrayBase* parameters,
                                       uint32_t entry) {
3063 3064
    FixedArray* parameter_map = FixedArray::cast(parameters);
    uint32_t length = parameter_map->length() - 2;
3065
    if (entry < length) return entry;
3066 3067

    FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
3068
    return ArgumentsAccessor::GetIndexForEntryImpl(arguments, entry - length);
3069 3070
  }

3071
  static uint32_t GetEntryForIndexImpl(Isolate* isolate, JSObject* holder,
3072
                                       FixedArrayBase* parameters,
3073
                                       uint32_t index, PropertyFilter filter) {
3074
    FixedArray* parameter_map = FixedArray::cast(parameters);
3075
    if (HasParameterMapArg(parameter_map, index)) return index;
3076 3077

    FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
3078 3079
    uint32_t entry = ArgumentsAccessor::GetEntryForIndexImpl(
        isolate, holder, arguments, index, filter);
3080
    if (entry == kMaxUInt32) return kMaxUInt32;
3081
    return (parameter_map->length() - 2) + entry;
3082 3083
  }

3084 3085
  static PropertyDetails GetDetailsImpl(JSObject* holder, uint32_t entry) {
    FixedArray* parameter_map = FixedArray::cast(holder->elements());
3086
    uint32_t length = parameter_map->length() - 2;
3087
    if (entry < length) {
3088 3089 3090
      return PropertyDetails(NONE, DATA, 0, PropertyCellType::kNoCell);
    }
    FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
3091
    return ArgumentsAccessor::GetDetailsImpl(arguments, entry - length);
3092
  }
3093

3094
  static bool HasParameterMapArg(FixedArray* parameter_map, uint32_t index) {
3095
    uint32_t length = parameter_map->length() - 2;
3096 3097 3098
    if (index >= length) return false;
    return !parameter_map->get(index + 2)->IsTheHole(
        parameter_map->GetIsolate());
3099
  }
3100

3101
  static void DeleteImpl(Handle<JSObject> obj, uint32_t entry) {
3102 3103
    FixedArray* parameter_map = FixedArray::cast(obj->elements());
    uint32_t length = static_cast<uint32_t>(parameter_map->length()) - 2;
3104
    if (entry < length) {
3105 3106 3107
      // 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.
3108
      parameter_map->set_the_hole(entry + 2);
3109
    } else {
3110
      Subclass::DeleteFromArguments(obj, entry - length);
3111 3112
    }
  }
3113 3114 3115

  static void CollectElementIndicesImpl(Handle<JSObject> object,
                                        Handle<FixedArrayBase> backing_store,
3116
                                        KeyAccumulator* keys) {
3117 3118 3119 3120 3121
    Isolate* isolate = keys->isolate();
    uint32_t nof_indices = 0;
    Handle<FixedArray> indices = isolate->factory()->NewFixedArray(
        GetCapacityImpl(*object, *backing_store));
    DirectCollectElementIndicesImpl(isolate, object, backing_store,
3122 3123
                                    GetKeysConversion::kKeepNumbers,
                                    ENUMERABLE_STRINGS, indices, &nof_indices);
3124 3125 3126
    SortIndices(indices, nof_indices);
    for (uint32_t i = 0; i < nof_indices; i++) {
      keys->AddKey(indices->get(i));
3127 3128 3129 3130 3131 3132 3133 3134
    }
  }

  static Handle<FixedArray> DirectCollectElementIndicesImpl(
      Isolate* isolate, Handle<JSObject> object,
      Handle<FixedArrayBase> backing_store, GetKeysConversion convert,
      PropertyFilter filter, Handle<FixedArray> list, uint32_t* nof_indices,
      uint32_t insertion_index = 0) {
3135
    Handle<FixedArray> parameter_map(FixedArray::cast(*backing_store), isolate);
3136 3137 3138
    uint32_t length = parameter_map->length() - 2;

    for (uint32_t i = 0; i < length; ++i) {
3139
      if (parameter_map->get(i + 2)->IsTheHole(isolate)) continue;
3140
      if (convert == GetKeysConversion::kConvertToString) {
3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153
        Handle<String> index_string = isolate->factory()->Uint32ToString(i);
        list->set(insertion_index, *index_string);
      } else {
        list->set(insertion_index, Smi::FromInt(i), SKIP_WRITE_BARRIER);
      }
      insertion_index++;
    }

    Handle<FixedArrayBase> store(FixedArrayBase::cast(parameter_map->get(1)));
    return ArgumentsAccessor::DirectCollectElementIndicesImpl(
        isolate, object, store, convert, filter, list, nof_indices,
        insertion_index);
  }
3154 3155 3156 3157 3158 3159 3160

  static Maybe<bool> IncludesValueImpl(Isolate* isolate,
                                       Handle<JSObject> object,
                                       Handle<Object> value,
                                       uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *object));
    Handle<Map> original_map = handle(object->map(), isolate);
3161 3162
    Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()),
                                     isolate);
3163 3164 3165
    bool search_for_hole = value->IsUndefined(isolate);

    for (uint32_t k = start_from; k < length; ++k) {
3166 3167
      uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k,
                                            ALL_PROPERTIES);
3168 3169 3170 3171 3172
      if (entry == kMaxUInt32) {
        if (search_for_hole) return Just(true);
        continue;
      }

3173 3174
      Handle<Object> element_k =
          Subclass::GetImpl(isolate, *parameter_map, entry);
3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195

      if (element_k->IsAccessorPair()) {
        LookupIterator it(isolate, object, k, LookupIterator::OWN);
        DCHECK(it.IsFound());
        DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
        ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k,
                                         Object::GetPropertyWithAccessor(&it),
                                         Nothing<bool>());

        if (value->SameValueZero(*element_k)) return Just(true);

        if (object->map() != *original_map) {
          // Some mutation occurred in accessor. Abort "fast" path
          return IncludesValueSlowPath(isolate, object, value, k + 1, length);
        }
      } else if (value->SameValueZero(*element_k)) {
        return Just(true);
      }
    }
    return Just(false);
  }
3196 3197 3198 3199 3200 3201 3202

  static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
                                         Handle<JSObject> object,
                                         Handle<Object> value,
                                         uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *object));
    Handle<Map> original_map = handle(object->map(), isolate);
3203 3204
    Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()),
                                     isolate);
3205 3206

    for (uint32_t k = start_from; k < length; ++k) {
3207 3208
      uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k,
                                            ALL_PROPERTIES);
3209 3210 3211 3212
      if (entry == kMaxUInt32) {
        continue;
      }

3213 3214
      Handle<Object> element_k =
          Subclass::GetImpl(isolate, *parameter_map, entry);
3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237

      if (element_k->IsAccessorPair()) {
        LookupIterator it(isolate, object, k, LookupIterator::OWN);
        DCHECK(it.IsFound());
        DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
        ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k,
                                         Object::GetPropertyWithAccessor(&it),
                                         Nothing<int64_t>());

        if (value->StrictEquals(*element_k)) {
          return Just<int64_t>(k);
        }

        if (object->map() != *original_map) {
          // Some mutation occurred in accessor. Abort "fast" path.
          return IndexOfValueSlowPath(isolate, object, value, k + 1, length);
        }
      } else if (value->StrictEquals(*element_k)) {
        return Just<int64_t>(k);
      }
    }
    return Just<int64_t>(-1);
  }
3238 3239 3240
};


3241 3242 3243 3244 3245 3246 3247 3248 3249 3250
class SlowSloppyArgumentsElementsAccessor
    : public SloppyArgumentsElementsAccessor<
          SlowSloppyArgumentsElementsAccessor, DictionaryElementsAccessor,
          ElementsKindTraits<SLOW_SLOPPY_ARGUMENTS_ELEMENTS> > {
 public:
  explicit SlowSloppyArgumentsElementsAccessor(const char* name)
      : SloppyArgumentsElementsAccessor<
            SlowSloppyArgumentsElementsAccessor, DictionaryElementsAccessor,
            ElementsKindTraits<SLOW_SLOPPY_ARGUMENTS_ELEMENTS> >(name) {}

3251
  static void DeleteFromArguments(Handle<JSObject> obj, uint32_t entry) {
3252 3253 3254
    Handle<FixedArray> parameter_map(FixedArray::cast(obj->elements()));
    Handle<SeededNumberDictionary> dict(
        SeededNumberDictionary::cast(parameter_map->get(1)));
3255 3256 3257
    // TODO(verwaest): Remove reliance on index in Shrink.
    uint32_t index = GetIndexForEntryImpl(*dict, entry);
    Handle<Object> result = SeededNumberDictionary::DeleteProperty(dict, entry);
3258
    USE(result);
3259
    DCHECK(result->IsTrue(dict->GetIsolate()));
3260 3261
    Handle<FixedArray> new_elements =
        SeededNumberDictionary::Shrink(dict, index);
3262 3263 3264
    parameter_map->set(1, *new_elements);
  }

3265
  static void AddImpl(Handle<JSObject> object, uint32_t index,
3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276
                      Handle<Object> value, PropertyAttributes attributes,
                      uint32_t new_capacity) {
    Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()));
    Handle<FixedArrayBase> old_elements(
        FixedArrayBase::cast(parameter_map->get(1)));
    Handle<SeededNumberDictionary> dictionary =
        old_elements->IsSeededNumberDictionary()
            ? Handle<SeededNumberDictionary>::cast(old_elements)
            : JSObject::NormalizeElements(object);
    PropertyDetails details(attributes, DATA, 0, PropertyCellType::kNoCell);
    Handle<SeededNumberDictionary> new_dictionary =
3277 3278
        SeededNumberDictionary::AddNumberEntry(dictionary, index, value,
                                               details, object);
3279
    if (attributes != NONE) object->RequireSlowElements(*new_dictionary);
3280 3281 3282 3283 3284 3285
    if (*dictionary != *new_dictionary) {
      FixedArray::cast(object->elements())->set(1, *new_dictionary);
    }
  }

  static void ReconfigureImpl(Handle<JSObject> object,
3286
                              Handle<FixedArrayBase> store, uint32_t entry,
3287 3288 3289 3290
                              Handle<Object> value,
                              PropertyAttributes attributes) {
    Handle<FixedArray> parameter_map = Handle<FixedArray>::cast(store);
    uint32_t length = parameter_map->length() - 2;
3291
    Isolate* isolate = store->GetIsolate();
3292 3293
    if (entry < length) {
      Object* probe = parameter_map->get(entry + 2);
3294
      DCHECK(!probe->IsTheHole(isolate));
3295
      Context* context = Context::cast(parameter_map->get(0));
3296
      int context_entry = Smi::cast(probe)->value();
3297
      DCHECK(!context->get(context_entry)->IsTheHole(isolate));
3298
      context->set(context_entry, *value);
3299 3300

      // Redefining attributes of an aliased element destroys fast aliasing.
3301
      parameter_map->set_the_hole(isolate, entry + 2);
3302 3303
      // For elements that are still writable we re-establish slow aliasing.
      if ((attributes & READ_ONLY) == 0) {
3304
        value = isolate->factory()->NewAliasedArgumentsEntry(context_entry);
3305 3306 3307 3308
      }

      PropertyDetails details(attributes, DATA, 0, PropertyCellType::kNoCell);
      Handle<SeededNumberDictionary> arguments(
3309
          SeededNumberDictionary::cast(parameter_map->get(1)), isolate);
3310
      arguments = SeededNumberDictionary::AddNumberEntry(
3311
          arguments, entry, value, details, object);
3312 3313 3314 3315
      // If the attributes were NONE, we would have called set rather than
      // reconfigure.
      DCHECK_NE(NONE, attributes);
      object->RequireSlowElements(*arguments);
3316 3317 3318
      parameter_map->set(1, *arguments);
    } else {
      Handle<FixedArrayBase> arguments(
3319
          FixedArrayBase::cast(parameter_map->get(1)), isolate);
3320
      DictionaryElementsAccessor::ReconfigureImpl(
3321
          object, arguments, entry - length, value, attributes);
3322 3323 3324 3325 3326
    }
  }
};


3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337
class FastSloppyArgumentsElementsAccessor
    : public SloppyArgumentsElementsAccessor<
          FastSloppyArgumentsElementsAccessor, FastHoleyObjectElementsAccessor,
          ElementsKindTraits<FAST_SLOPPY_ARGUMENTS_ELEMENTS> > {
 public:
  explicit FastSloppyArgumentsElementsAccessor(const char* name)
      : SloppyArgumentsElementsAccessor<
            FastSloppyArgumentsElementsAccessor,
            FastHoleyObjectElementsAccessor,
            ElementsKindTraits<FAST_SLOPPY_ARGUMENTS_ELEMENTS> >(name) {}

3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354
  static Handle<FixedArray> GetArguments(Isolate* isolate,
                                         FixedArrayBase* backing_store) {
    FixedArray* parameter_map = FixedArray::cast(backing_store);
    return Handle<FixedArray>(FixedArray::cast(parameter_map->get(1)), isolate);
  }

  static Handle<JSArray> SliceImpl(Handle<JSObject> receiver, uint32_t start,
                                   uint32_t end) {
    Isolate* isolate = receiver->GetIsolate();
    uint32_t result_len = end < start ? 0u : end - start;
    Handle<JSArray> result_array = isolate->factory()->NewJSArray(
        FAST_HOLEY_ELEMENTS, result_len, result_len);
    DisallowHeapAllocation no_gc;
    FixedArray* elements = FixedArray::cast(result_array->elements());
    FixedArray* parameters = FixedArray::cast(receiver->elements());
    uint32_t insertion_index = 0;
    for (uint32_t i = start; i < end; i++) {
3355 3356 3357
      uint32_t entry = GetEntryForIndexImpl(isolate, *receiver, parameters, i,
                                            ALL_PROPERTIES);
      if (entry != kMaxUInt32 && HasEntryImpl(isolate, parameters, entry)) {
3358
        elements->set(insertion_index, *GetImpl(isolate, parameters, entry));
3359
      } else {
3360
        elements->set_the_hole(isolate, insertion_index);
3361 3362 3363 3364 3365 3366
      }
      insertion_index++;
    }
    return result_array;
  }

3367 3368
  static Handle<SeededNumberDictionary> NormalizeImpl(
      Handle<JSObject> object, Handle<FixedArrayBase> elements) {
3369 3370
    Handle<FixedArray> arguments =
        GetArguments(elements->GetIsolate(), *elements);
3371 3372 3373
    return FastHoleyObjectElementsAccessor::NormalizeImpl(object, arguments);
  }

3374
  static void DeleteFromArguments(Handle<JSObject> obj, uint32_t entry) {
3375 3376
    Handle<FixedArray> arguments =
        GetArguments(obj->GetIsolate(), obj->elements());
3377
    FastHoleyObjectElementsAccessor::DeleteCommon(obj, entry, arguments);
3378 3379
  }

3380
  static void AddImpl(Handle<JSObject> object, uint32_t index,
3381 3382 3383 3384 3385 3386 3387 3388 3389 3390
                      Handle<Object> value, PropertyAttributes attributes,
                      uint32_t new_capacity) {
    DCHECK_EQ(NONE, attributes);
    Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()));
    Handle<FixedArrayBase> old_elements(
        FixedArrayBase::cast(parameter_map->get(1)));
    if (old_elements->IsSeededNumberDictionary() ||
        static_cast<uint32_t>(old_elements->length()) < new_capacity) {
      GrowCapacityAndConvertImpl(object, new_capacity);
    }
3391 3392 3393 3394 3395 3396 3397
    FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
    // For fast holey objects, the entry equals the index. The code above made
    // sure that there's enough space to store the value. We cannot convert
    // index to entry explicitly since the slot still contains the hole, so the
    // current EntryForIndex would indicate that it is "absent" by returning
    // kMaxUInt32.
    FastHoleyObjectElementsAccessor::SetImpl(arguments, index, *value);
3398
  }
3399

3400
  static void ReconfigureImpl(Handle<JSObject> object,
3401
                              Handle<FixedArrayBase> store, uint32_t entry,
3402 3403 3404 3405 3406 3407
                              Handle<Object> value,
                              PropertyAttributes attributes) {
    Handle<SeededNumberDictionary> dictionary =
        JSObject::NormalizeElements(object);
    FixedArray::cast(*store)->set(1, *dictionary);
    uint32_t length = static_cast<uint32_t>(store->length()) - 2;
3408 3409
    if (entry >= length) {
      entry = dictionary->FindEntry(entry - length) + length;
3410
    }
3411
    SlowSloppyArgumentsElementsAccessor::ReconfigureImpl(object, store, entry,
3412
                                                         value, attributes);
3413
  }
3414

3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
                               int copy_size) {
    DCHECK(!to->IsDictionary());
    if (from_kind == SLOW_SLOPPY_ARGUMENTS_ELEMENTS) {
      CopyDictionaryToObjectElements(from, from_start, to, FAST_HOLEY_ELEMENTS,
                                     to_start, copy_size);
    } else {
      DCHECK_EQ(FAST_SLOPPY_ARGUMENTS_ELEMENTS, from_kind);
      CopyObjectToObjectElements(from, FAST_HOLEY_ELEMENTS, from_start, to,
                                 FAST_HOLEY_ELEMENTS, to_start, copy_size);
    }
  }

  static void GrowCapacityAndConvertImpl(Handle<JSObject> object,
                                         uint32_t capacity) {
    Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()));
    Handle<FixedArray> old_elements(FixedArray::cast(parameter_map->get(1)));
    ElementsKind from_kind = object->GetElementsKind();
    // This method should only be called if there's a reason to update the
    // elements.
    DCHECK(from_kind == SLOW_SLOPPY_ARGUMENTS_ELEMENTS ||
           static_cast<uint32_t>(old_elements->length()) < capacity);
    Handle<FixedArrayBase> elements =
        ConvertElementsWithCapacity(object, old_elements, from_kind, capacity);
    Handle<Map> new_map = JSObject::GetElementsTransitionMap(
        object, FAST_SLOPPY_ARGUMENTS_ELEMENTS);
    JSObject::MigrateToMap(object, new_map);
    parameter_map->set(1, *elements);
    JSObject::ValidateElements(object);
  }
};

3449
template <typename Subclass, typename BackingStoreAccessor, typename KindTraits>
3450
class StringWrapperElementsAccessor
3451
    : public ElementsAccessorBase<Subclass, KindTraits> {
3452 3453
 public:
  explicit StringWrapperElementsAccessor(const char* name)
3454
      : ElementsAccessorBase<Subclass, KindTraits>(name) {
3455 3456 3457
    USE(KindTraits::Kind);
  }

3458 3459 3460 3461 3462
  static Handle<Object> GetInternalImpl(Handle<JSObject> holder,
                                        uint32_t entry) {
    return GetImpl(holder, entry);
  }

3463 3464 3465 3466 3467 3468 3469 3470
  static Handle<Object> GetImpl(Handle<JSObject> holder, uint32_t entry) {
    Isolate* isolate = holder->GetIsolate();
    Handle<String> string(GetString(*holder), isolate);
    uint32_t length = static_cast<uint32_t>(string->length());
    if (entry < length) {
      return isolate->factory()->LookupSingleCharacterStringFromCode(
          String::Flatten(string)->Get(entry));
    }
3471 3472 3473 3474 3475 3476 3477 3478
    return BackingStoreAccessor::GetImpl(isolate, holder->elements(),
                                         entry - length);
  }

  static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* elements,
                                uint32_t entry) {
    UNREACHABLE();
    return Handle<Object>();
3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491
  }

  static PropertyDetails GetDetailsImpl(JSObject* holder, uint32_t entry) {
    uint32_t length = static_cast<uint32_t>(GetString(holder)->length());
    if (entry < length) {
      PropertyAttributes attributes =
          static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
      return PropertyDetails(attributes, v8::internal::DATA, 0,
                             PropertyCellType::kNoCell);
    }
    return BackingStoreAccessor::GetDetailsImpl(holder, entry - length);
  }

3492
  static uint32_t GetEntryForIndexImpl(Isolate* isolate, JSObject* holder,
3493 3494 3495 3496 3497
                                       FixedArrayBase* backing_store,
                                       uint32_t index, PropertyFilter filter) {
    uint32_t length = static_cast<uint32_t>(GetString(holder)->length());
    if (index < length) return index;
    uint32_t backing_store_entry = BackingStoreAccessor::GetEntryForIndexImpl(
3498
        isolate, holder, backing_store, index, filter);
3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523
    if (backing_store_entry == kMaxUInt32) return kMaxUInt32;
    DCHECK(backing_store_entry < kMaxUInt32 - length);
    return backing_store_entry + length;
  }

  static void DeleteImpl(Handle<JSObject> holder, uint32_t entry) {
    uint32_t length = static_cast<uint32_t>(GetString(*holder)->length());
    if (entry < length) {
      return;  // String contents can't be deleted.
    }
    BackingStoreAccessor::DeleteImpl(holder, entry - length);
  }

  static void SetImpl(Handle<JSObject> holder, uint32_t entry, Object* value) {
    uint32_t length = static_cast<uint32_t>(GetString(*holder)->length());
    if (entry < length) {
      return;  // String contents are read-only.
    }
    BackingStoreAccessor::SetImpl(holder->elements(), entry - length, value);
  }

  static void AddImpl(Handle<JSObject> object, uint32_t index,
                      Handle<Object> value, PropertyAttributes attributes,
                      uint32_t new_capacity) {
    DCHECK(index >= static_cast<uint32_t>(GetString(*object)->length()));
3524 3525 3526 3527 3528 3529
    // Explicitly grow fast backing stores if needed. Dictionaries know how to
    // extend their capacity themselves.
    if (KindTraits::Kind == FAST_STRING_WRAPPER_ELEMENTS &&
        (object->GetElementsKind() == SLOW_STRING_WRAPPER_ELEMENTS ||
         BackingStoreAccessor::GetCapacityImpl(*object, object->elements()) !=
             new_capacity)) {
3530
      GrowCapacityAndConvertImpl(object, new_capacity);
3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566
    }
    BackingStoreAccessor::AddImpl(object, index, value, attributes,
                                  new_capacity);
  }

  static void ReconfigureImpl(Handle<JSObject> object,
                              Handle<FixedArrayBase> store, uint32_t entry,
                              Handle<Object> value,
                              PropertyAttributes attributes) {
    uint32_t length = static_cast<uint32_t>(GetString(*object)->length());
    if (entry < length) {
      return;  // String contents can't be reconfigured.
    }
    BackingStoreAccessor::ReconfigureImpl(object, store, entry - length, value,
                                          attributes);
  }

  static void AddElementsToKeyAccumulatorImpl(Handle<JSObject> receiver,
                                              KeyAccumulator* accumulator,
                                              AddKeyConversion convert) {
    Isolate* isolate = receiver->GetIsolate();
    Handle<String> string(GetString(*receiver), isolate);
    string = String::Flatten(string);
    uint32_t length = static_cast<uint32_t>(string->length());
    for (uint32_t i = 0; i < length; i++) {
      accumulator->AddKey(
          isolate->factory()->LookupSingleCharacterStringFromCode(
              string->Get(i)),
          convert);
    }
    BackingStoreAccessor::AddElementsToKeyAccumulatorImpl(receiver, accumulator,
                                                          convert);
  }

  static void CollectElementIndicesImpl(Handle<JSObject> object,
                                        Handle<FixedArrayBase> backing_store,
3567
                                        KeyAccumulator* keys) {
3568
    uint32_t length = GetString(*object)->length();
3569
    Factory* factory = keys->isolate()->factory();
3570
    for (uint32_t i = 0; i < length; i++) {
3571
      keys->AddKey(factory->NewNumberFromUint(i));
3572
    }
3573 3574
    BackingStoreAccessor::CollectElementIndicesImpl(object, backing_store,
                                                    keys);
3575 3576
  }

3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589
  static void GrowCapacityAndConvertImpl(Handle<JSObject> object,
                                         uint32_t capacity) {
    Handle<FixedArrayBase> old_elements(object->elements());
    ElementsKind from_kind = object->GetElementsKind();
    // This method should only be called if there's a reason to update the
    // elements.
    DCHECK(from_kind == SLOW_STRING_WRAPPER_ELEMENTS ||
           static_cast<uint32_t>(old_elements->length()) < capacity);
    Subclass::BasicGrowCapacityAndConvertImpl(object, old_elements, from_kind,
                                              FAST_STRING_WRAPPER_ELEMENTS,
                                              capacity);
  }

3590 3591 3592 3593
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
                               int copy_size) {
3594 3595 3596 3597 3598 3599 3600 3601 3602
    DCHECK(!to->IsDictionary());
    if (from_kind == SLOW_STRING_WRAPPER_ELEMENTS) {
      CopyDictionaryToObjectElements(from, from_start, to, FAST_HOLEY_ELEMENTS,
                                     to_start, copy_size);
    } else {
      DCHECK_EQ(FAST_STRING_WRAPPER_ELEMENTS, from_kind);
      CopyObjectToObjectElements(from, FAST_HOLEY_ELEMENTS, from_start, to,
                                 FAST_HOLEY_ELEMENTS, to_start, copy_size);
    }
3603 3604
  }

3605 3606 3607 3608 3609 3610 3611
  static uint32_t NumberOfElementsImpl(JSObject* object,
                                       FixedArrayBase* backing_store) {
    uint32_t length = GetString(object)->length();
    return length +
           BackingStoreAccessor::NumberOfElementsImpl(object, backing_store);
  }

3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629
 private:
  static String* GetString(JSObject* holder) {
    DCHECK(holder->IsJSValue());
    JSValue* js_value = JSValue::cast(holder);
    DCHECK(js_value->value()->IsString());
    return String::cast(js_value->value());
  }
};

class FastStringWrapperElementsAccessor
    : public StringWrapperElementsAccessor<
          FastStringWrapperElementsAccessor, FastHoleyObjectElementsAccessor,
          ElementsKindTraits<FAST_STRING_WRAPPER_ELEMENTS>> {
 public:
  explicit FastStringWrapperElementsAccessor(const char* name)
      : StringWrapperElementsAccessor<
            FastStringWrapperElementsAccessor, FastHoleyObjectElementsAccessor,
            ElementsKindTraits<FAST_STRING_WRAPPER_ELEMENTS>>(name) {}
3630 3631 3632 3633 3634

  static Handle<SeededNumberDictionary> NormalizeImpl(
      Handle<JSObject> object, Handle<FixedArrayBase> elements) {
    return FastHoleyObjectElementsAccessor::NormalizeImpl(object, elements);
  }
3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645
};

class SlowStringWrapperElementsAccessor
    : public StringWrapperElementsAccessor<
          SlowStringWrapperElementsAccessor, DictionaryElementsAccessor,
          ElementsKindTraits<SLOW_STRING_WRAPPER_ELEMENTS>> {
 public:
  explicit SlowStringWrapperElementsAccessor(const char* name)
      : StringWrapperElementsAccessor<
            SlowStringWrapperElementsAccessor, DictionaryElementsAccessor,
            ElementsKindTraits<SLOW_STRING_WRAPPER_ELEMENTS>>(name) {}
3646 3647 3648 3649 3650

  static bool HasAccessorsImpl(JSObject* holder,
                               FixedArrayBase* backing_store) {
    return DictionaryElementsAccessor::HasAccessorsImpl(holder, backing_store);
  }
3651
};
3652

3653 3654 3655
}  // namespace


3656
void CheckArrayAbuse(Handle<JSObject> obj, const char* op, uint32_t index,
3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674
                     bool allow_appending) {
  DisallowHeapAllocation no_allocation;
  Object* raw_length = NULL;
  const char* elements_type = "array";
  if (obj->IsJSArray()) {
    JSArray* array = JSArray::cast(*obj);
    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);
      uint32_t compare_length = static_cast<uint32_t>(int32_length);
      if (allow_appending) compare_length++;
3675
      if (index >= compare_length) {
3676 3677
        PrintF("[OOB %s %s (%s length = %d, element accessed = %d) in ",
               elements_type, op, elements_type, static_cast<int>(int32_length),
3678
               static_cast<int>(index));
3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692
        TraceTopFrame(obj->GetIsolate());
        PrintF("]\n");
      }
    } else {
      PrintF("[%s elements length not integer value in ", elements_type);
      TraceTopFrame(obj->GetIsolate());
      PrintF("]\n");
    }
  } else {
    PrintF("[%s elements length not a number in ", elements_type);
    TraceTopFrame(obj->GetIsolate());
    PrintF("]\n");
  }
}
3693 3694


3695 3696
MaybeHandle<Object> ArrayConstructInitializeElements(Handle<JSArray> array,
                                                     Arguments* args) {
3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709
  if (args->length() == 0) {
    // Optimize the case where there are no parameters passed.
    JSArray::Initialize(array, JSArray::kPreallocatedArrayElements);
    return array;

  } else if (args->length() == 1 && args->at<Object>(0)->IsNumber()) {
    uint32_t length;
    if (!args->at<Object>(0)->ToArrayLength(&length)) {
      return ThrowArrayLengthRangeError(array->GetIsolate());
    }

    // Optimize the case where there is one argument and the argument is a small
    // smi.
3710
    if (length > 0 && length < JSArray::kInitialMaxFastElementArray) {
3711 3712 3713 3714 3715 3716
      ElementsKind elements_kind = array->GetElementsKind();
      JSArray::Initialize(array, length, length);

      if (!IsFastHoleyElementsKind(elements_kind)) {
        elements_kind = GetHoleyElementsKind(elements_kind);
        JSObject::TransitionElementsKind(array, elements_kind);
3717
      }
3718 3719
    } else if (length == 0) {
      JSArray::Initialize(array, JSArray::kPreallocatedArrayElements);
3720 3721 3722 3723
    } else {
      // Take the argument as the length.
      JSArray::Initialize(array, 0);
      JSArray::SetLength(array, length);
3724
    }
3725
    return array;
3726 3727
  }

3728 3729
  Factory* factory = array->GetIsolate()->factory();

3730 3731
  // Set length and elements on the array.
  int number_of_elements = args->length();
3732 3733
  JSObject::EnsureCanContainElements(
      array, args, 0, number_of_elements, ALLOW_CONVERTED_DOUBLE_ELEMENTS);
3734 3735 3736

  // Allocate an appropriately typed elements array.
  ElementsKind elements_kind = array->GetElementsKind();
3737
  Handle<FixedArrayBase> elms;
3738
  if (IsFastDoubleElementsKind(elements_kind)) {
3739 3740
    elms = Handle<FixedArrayBase>::cast(
        factory->NewFixedDoubleArray(number_of_elements));
3741
  } else {
3742 3743
    elms = Handle<FixedArrayBase>::cast(
        factory->NewFixedArrayWithHoles(number_of_elements));
3744 3745 3746
  }

  // Fill in the content
3747
  switch (elements_kind) {
3748 3749
    case FAST_HOLEY_SMI_ELEMENTS:
    case FAST_SMI_ELEMENTS: {
3750
      Handle<FixedArray> smi_elms = Handle<FixedArray>::cast(elms);
3751 3752
      for (int entry = 0; entry < number_of_elements; entry++) {
        smi_elms->set(entry, (*args)[entry], SKIP_WRITE_BARRIER);
3753 3754 3755 3756 3757
      }
      break;
    }
    case FAST_HOLEY_ELEMENTS:
    case FAST_ELEMENTS: {
3758
      DisallowHeapAllocation no_gc;
3759
      WriteBarrierMode mode = elms->GetWriteBarrierMode(no_gc);
3760
      Handle<FixedArray> object_elms = Handle<FixedArray>::cast(elms);
3761 3762
      for (int entry = 0; entry < number_of_elements; entry++) {
        object_elms->set(entry, (*args)[entry], mode);
3763 3764 3765 3766 3767
      }
      break;
    }
    case FAST_HOLEY_DOUBLE_ELEMENTS:
    case FAST_DOUBLE_ELEMENTS: {
3768 3769
      Handle<FixedDoubleArray> double_elms =
          Handle<FixedDoubleArray>::cast(elms);
3770 3771
      for (int entry = 0; entry < number_of_elements; entry++) {
        double_elms->set(entry, (*args)[entry]->Number());
3772 3773 3774 3775 3776 3777 3778 3779
      }
      break;
    }
    default:
      UNREACHABLE();
      break;
  }

3780
  array->set_elements(*elms);
3781 3782 3783 3784
  array->set_length(Smi::FromInt(number_of_elements));
  return array;
}

3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807

void ElementsAccessor::InitializeOncePerProcess() {
  static ElementsAccessor* accessor_array[] = {
#define ACCESSOR_ARRAY(Class, Kind, Store) new Class(#Kind),
      ELEMENTS_LIST(ACCESSOR_ARRAY)
#undef ACCESSOR_ARRAY
  };

  STATIC_ASSERT((sizeof(accessor_array) / sizeof(*accessor_array)) ==
                kElementsKindCount);

  elements_accessors_ = accessor_array;
}


void ElementsAccessor::TearDown() {
  if (elements_accessors_ == NULL) return;
#define ACCESSOR_DELETE(Class, Kind, Store) delete elements_accessors_[Kind];
  ELEMENTS_LIST(ACCESSOR_DELETE)
#undef ACCESSOR_DELETE
  elements_accessors_ = NULL;
}

3808
Handle<JSArray> ElementsAccessor::Concat(Isolate* isolate, Arguments* args,
3809 3810
                                         uint32_t concat_size,
                                         uint32_t result_len) {
3811
  ElementsKind result_elements_kind = GetInitialFastElementsKind();
3812
  bool has_raw_doubles = false;
3813 3814
  {
    DisallowHeapAllocation no_gc;
3815
    bool is_holey = false;
3816
    for (uint32_t i = 0; i < concat_size; i++) {
3817 3818
      Object* arg = (*args)[i];
      ElementsKind arg_kind = JSArray::cast(arg)->GetElementsKind();
3819
      has_raw_doubles = has_raw_doubles || IsFastDoubleElementsKind(arg_kind);
3820
      is_holey = is_holey || IsFastHoleyElementsKind(arg_kind);
3821 3822
      result_elements_kind =
          GetMoreGeneralElementsKind(result_elements_kind, arg_kind);
3823 3824
    }
    if (is_holey) {
3825
      result_elements_kind = GetHoleyElementsKind(result_elements_kind);
3826 3827 3828 3829 3830 3831
    }
  }

  // If a double array is concatted into a fast elements array, the fast
  // elements array needs to be initialized to contain proper holes, since
  // boxing doubles may cause incremental marking.
3832 3833 3834 3835 3836
  bool requires_double_boxing =
      has_raw_doubles && !IsFastDoubleElementsKind(result_elements_kind);
  ArrayStorageAllocationMode mode = requires_double_boxing
                                        ? INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
                                        : DONT_INITIALIZE_ARRAY_ELEMENTS;
3837
  Handle<JSArray> result_array = isolate->factory()->NewJSArray(
3838
      result_elements_kind, result_len, result_len, mode);
3839
  if (result_len == 0) return result_array;
3840 3841

  uint32_t insertion_index = 0;
3842
  Handle<FixedArrayBase> storage(result_array->elements(), isolate);
3843
  ElementsAccessor* accessor = ElementsAccessor::ForKind(result_elements_kind);
3844 3845 3846 3847
  for (uint32_t i = 0; i < concat_size; i++) {
    // It is crucial to keep |array| in a raw pointer form to avoid
    // performance degradation.
    JSArray* array = JSArray::cast((*args)[i]);
3848 3849 3850 3851 3852 3853
    uint32_t len = 0;
    array->length()->ToArrayLength(&len);
    if (len == 0) continue;
    ElementsKind from_kind = array->GetElementsKind();
    accessor->CopyElements(array, 0, from_kind, storage, insertion_index, len);
    insertion_index += len;
3854 3855
  }

3856
  DCHECK_EQ(insertion_index, result_len);
3857 3858 3859
  return result_array;
}

3860
ElementsAccessor** ElementsAccessor::elements_accessors_ = NULL;
3861 3862
}  // namespace internal
}  // namespace v8