factory.cc 85.1 KB
Newer Older
1 2 3 4
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/factory.h"
6

7
#include "src/allocation-site-scopes.h"
8
#include "src/base/bits.h"
9
#include "src/bootstrapper.h"
10
#include "src/conversions.h"
11
#include "src/isolate-inl.h"
12
#include "src/macro-assembler.h"
13

14 15
namespace v8 {
namespace internal {
16

17

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
// Calls the FUNCTION_CALL function and retries it up to three times
// to guarantee that any allocations performed during the call will
// succeed if there's enough memory.
//
// Warning: Do not use the identifiers __object__, __maybe_object__,
// __allocation__ or __scope__ in a call to this macro.

#define RETURN_OBJECT_UNLESS_RETRY(ISOLATE, TYPE)         \
  if (__allocation__.To(&__object__)) {                   \
    DCHECK(__object__ != (ISOLATE)->heap()->exception()); \
    return Handle<TYPE>(TYPE::cast(__object__), ISOLATE); \
  }

#define CALL_HEAP_FUNCTION(ISOLATE, FUNCTION_CALL, TYPE)                      \
  do {                                                                        \
    AllocationResult __allocation__ = FUNCTION_CALL;                          \
    Object* __object__ = NULL;                                                \
    RETURN_OBJECT_UNLESS_RETRY(ISOLATE, TYPE)                                 \
    /* Two GCs before panicking.  In newspace will almost always succeed. */  \
    for (int __i__ = 0; __i__ < 2; __i__++) {                                 \
      (ISOLATE)->heap()->CollectGarbage(__allocation__.RetrySpace(),          \
                                        "allocation failure");                \
      __allocation__ = FUNCTION_CALL;                                         \
      RETURN_OBJECT_UNLESS_RETRY(ISOLATE, TYPE)                               \
    }                                                                         \
    (ISOLATE)->counters()->gc_last_resort_from_handles()->Increment();        \
    (ISOLATE)->heap()->CollectAllAvailableGarbage("last resort gc");          \
    {                                                                         \
      AlwaysAllocateScope __scope__(ISOLATE);                                 \
      __allocation__ = FUNCTION_CALL;                                         \
    }                                                                         \
    RETURN_OBJECT_UNLESS_RETRY(ISOLATE, TYPE)                                 \
    /* TODO(1181417): Fix this. */                                            \
    v8::internal::Heap::FatalProcessOutOfMemory("CALL_AND_RETRY_LAST", true); \
    return Handle<TYPE>();                                                    \
  } while (false)


56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
template<typename T>
Handle<T> Factory::New(Handle<Map> map, AllocationSpace space) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->Allocate(*map, space),
      T);
}


template<typename T>
Handle<T> Factory::New(Handle<Map> map,
                       AllocationSpace space,
                       Handle<AllocationSite> allocation_site) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->Allocate(*map, space, *allocation_site),
      T);
}


76 77 78 79 80 81 82 83 84 85
Handle<HeapObject> Factory::NewFillerObject(int size,
                                            bool double_align,
                                            AllocationSpace space) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateFillerObject(size, double_align, space),
      HeapObject);
}


86 87 88 89
Handle<Box> Factory::NewBox(Handle<Object> value) {
  Handle<Box> result = Handle<Box>::cast(NewStruct(BOX_TYPE));
  result->set_value(*value);
  return result;
90 91 92
}


93 94 95 96
Handle<PrototypeInfo> Factory::NewPrototypeInfo() {
  Handle<PrototypeInfo> result =
      Handle<PrototypeInfo>::cast(NewStruct(PROTOTYPE_INFO_TYPE));
  result->set_prototype_users(WeakFixedArray::Empty());
97
  result->set_registry_slot(PrototypeInfo::UNREGISTERED);
98 99 100 101 102
  result->set_validity_cell(Smi::FromInt(0));
  return result;
}


103 104 105 106 107 108 109 110 111 112 113 114 115
Handle<SloppyBlockWithEvalContextExtension>
Factory::NewSloppyBlockWithEvalContextExtension(
    Handle<ScopeInfo> scope_info, Handle<JSObject> extension) {
  DCHECK(scope_info->is_declaration_scope());
  Handle<SloppyBlockWithEvalContextExtension> result =
      Handle<SloppyBlockWithEvalContextExtension>::cast(
          NewStruct(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE));
  result->set_scope_info(*scope_info);
  result->set_extension(*extension);
  return result;
}


116
Handle<Oddball> Factory::NewOddball(Handle<Map> map, const char* to_string,
117
                                    Handle<Object> to_number,
118
                                    const char* type_of, byte kind) {
119
  Handle<Oddball> oddball = New<Oddball>(map, OLD_SPACE);
120
  Oddball::Initialize(isolate(), oddball, to_string, to_number, type_of, kind);
121 122 123 124
  return oddball;
}


125
Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
126
  DCHECK(0 <= size);
127 128 129 130
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateFixedArray(size, pretenure),
      FixedArray);
131 132 133
}


134 135
Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
                                                   PretenureFlag pretenure) {
136
  DCHECK(0 <= size);
137 138
  CALL_HEAP_FUNCTION(
      isolate(),
139 140 141
      isolate()->heap()->AllocateFixedArrayWithFiller(size,
                                                      pretenure,
                                                      *the_hole_value()),
142
      FixedArray);
143 144 145
}


146 147 148 149 150 151 152 153
Handle<FixedArray> Factory::NewUninitializedFixedArray(int size) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateUninitializedFixedArray(size),
      FixedArray);
}


154
Handle<FixedArrayBase> Factory::NewFixedDoubleArray(int size,
155
                                                    PretenureFlag pretenure) {
156
  DCHECK(0 <= size);
157 158 159
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
160
      FixedArrayBase);
161 162 163
}


164
Handle<FixedArrayBase> Factory::NewFixedDoubleArrayWithHoles(
165 166
    int size,
    PretenureFlag pretenure) {
167
  DCHECK(0 <= size);
168 169 170 171 172 173 174
  Handle<FixedArrayBase> array = NewFixedDoubleArray(size, pretenure);
  if (size > 0) {
    Handle<FixedDoubleArray> double_array =
        Handle<FixedDoubleArray>::cast(array);
    for (int i = 0; i < size; ++i) {
      double_array->set_the_hole(i);
    }
175 176 177 178 179
  }
  return array;
}


180
Handle<OrderedHashSet> Factory::NewOrderedHashSet() {
181
  return OrderedHashSet::Allocate(isolate(), OrderedHashSet::kMinCapacity);
182 183 184 185
}


Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
186
  return OrderedHashMap::Allocate(isolate(), OrderedHashMap::kMinCapacity);
187 188 189
}


190
Handle<AccessorPair> Factory::NewAccessorPair() {
191 192 193 194 195
  Handle<AccessorPair> accessors =
      Handle<AccessorPair>::cast(NewStruct(ACCESSOR_PAIR_TYPE));
  accessors->set_getter(*the_hole_value(), SKIP_WRITE_BARRIER);
  accessors->set_setter(*the_hole_value(), SKIP_WRITE_BARRIER);
  return accessors;
196 197 198
}


199
Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
200 201 202 203
  Handle<TypeFeedbackInfo> info =
      Handle<TypeFeedbackInfo>::cast(NewStruct(TYPE_FEEDBACK_INFO_TYPE));
  info->initialize_storage();
  return info;
204 205 206
}


207 208
// Internalized strings are created in the old generation (data space).
Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
209 210
  Utf8StringKey key(string, isolate()->heap()->HashSeed());
  return InternalizeStringWithKey(&key);
211 212
}

213

214
Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
215 216
  OneByteStringKey key(string, isolate()->heap()->HashSeed());
  return InternalizeStringWithKey(&key);
217 218
}

219

220 221
Handle<String> Factory::InternalizeOneByteString(
    Handle<SeqOneByteString> string, int from, int length) {
222
  SeqOneByteSubStringKey key(string, from, length);
223
  return InternalizeStringWithKey(&key);
224 225 226
}


227
Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
228 229 230 231 232 233 234
  TwoByteStringKey key(string, isolate()->heap()->HashSeed());
  return InternalizeStringWithKey(&key);
}


template<class StringTableKey>
Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
235
  return StringTable::LookupKey(isolate(), key);
236 237
}

238

239 240 241
MaybeHandle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
                                                  PretenureFlag pretenure) {
  int length = string.length();
242
  if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
243 244
  Handle<SeqOneByteString> result;
  ASSIGN_RETURN_ON_EXCEPTION(
245
      isolate(),
246 247
      result,
      NewRawOneByteString(string.length(), pretenure),
248
      String);
249 250 251 252 253 254 255

  DisallowHeapAllocation no_gc;
  // Copy the characters into the new object.
  CopyChars(SeqOneByteString::cast(*result)->GetChars(),
            string.start(),
            length);
  return result;
256 257
}

258 259
MaybeHandle<String> Factory::NewStringFromUtf8(Vector<const char> string,
                                               PretenureFlag pretenure) {
260 261 262 263 264 265 266 267 268
  // Check for ASCII first since this is the common case.
  const char* start = string.start();
  int length = string.length();
  int non_ascii_start = String::NonAsciiStart(start, length);
  if (non_ascii_start >= length) {
    // If the string is ASCII, we do not need to convert the characters
    // since UTF8 is backwards compatible with ASCII.
    return NewStringFromOneByte(Vector<const uint8_t>::cast(string), pretenure);
  }
269

270
  // Non-ASCII and we need to decode.
271 272 273 274
  Access<UnicodeCache::Utf8Decoder>
      decoder(isolate()->unicode_cache()->utf8_decoder());
  decoder->Reset(string.start() + non_ascii_start,
                 length - non_ascii_start);
275
  int utf16_length = static_cast<int>(decoder->Utf16Length());
276
  DCHECK(utf16_length > 0);
277 278 279 280 281
  // Allocate string.
  Handle<SeqTwoByteString> result;
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate(), result,
      NewRawTwoByteString(non_ascii_start + utf16_length, pretenure),
282
      String);
283
  // Copy ASCII portion.
284 285 286 287 288 289 290 291
  uint16_t* data = result->GetChars();
  const char* ascii_data = string.start();
  for (int i = 0; i < non_ascii_start; i++) {
    *data++ = *ascii_data++;
  }
  // Now write the remainder.
  decoder->WriteUtf16(data, utf16_length);
  return result;
292 293 294
}


295 296
MaybeHandle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
                                                  PretenureFlag pretenure) {
297 298 299
  int length = string.length();
  const uc16* start = string.start();
  if (String::IsOneByte(start, length)) {
300
    if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    Handle<SeqOneByteString> result;
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate(),
        result,
        NewRawOneByteString(length, pretenure),
        String);
    CopyChars(result->GetChars(), start, length);
    return result;
  } else {
    Handle<SeqTwoByteString> result;
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate(),
        result,
        NewRawTwoByteString(length, pretenure),
        String);
    CopyChars(result->GetChars(), start, length);
    return result;
  }
319 320 321
}


322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
Handle<String> Factory::NewInternalizedStringFromUtf8(Vector<const char> str,
                                                      int chars,
                                                      uint32_t hash_field) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateInternalizedStringFromUtf8(
          str, chars, hash_field),
      String);
}


MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedString(
      Vector<const uint8_t> str,
      uint32_t hash_field) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateOneByteInternalizedString(str, hash_field),
      String);
}


343 344 345 346 347 348 349 350 351 352 353
MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedSubString(
    Handle<SeqOneByteString> string, int offset, int length,
    uint32_t hash_field) {
  CALL_HEAP_FUNCTION(
      isolate(), isolate()->heap()->AllocateOneByteInternalizedString(
                     Vector<const uint8_t>(string->GetChars() + offset, length),
                     hash_field),
      String);
}


354 355 356 357 358 359 360 361 362 363 364
MUST_USE_RESULT Handle<String> Factory::NewTwoByteInternalizedString(
      Vector<const uc16> str,
      uint32_t hash_field) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateTwoByteInternalizedString(str, hash_field),
      String);
}


Handle<String> Factory::NewInternalizedStringImpl(
365
    Handle<String> string, int chars, uint32_t hash_field) {
366 367
  CALL_HEAP_FUNCTION(
      isolate(),
368 369
      isolate()->heap()->AllocateInternalizedStringImpl(
          *string, chars, hash_field),
370 371 372 373 374 375 376 377 378 379 380 381
      String);
}


MaybeHandle<Map> Factory::InternalizedStringMapForString(
    Handle<String> string) {
  // If the string is in new space it cannot be used as internalized.
  if (isolate()->heap()->InNewSpace(*string)) return MaybeHandle<Map>();

  // Find the corresponding internalized string map for strings.
  switch (string->map()->instance_type()) {
    case STRING_TYPE: return internalized_string_map();
382 383
    case ONE_BYTE_STRING_TYPE:
      return one_byte_internalized_string_map();
384
    case EXTERNAL_STRING_TYPE: return external_internalized_string_map();
385 386
    case EXTERNAL_ONE_BYTE_STRING_TYPE:
      return external_one_byte_internalized_string_map();
387 388 389 390
    case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
      return external_internalized_string_with_one_byte_data_map();
    case SHORT_EXTERNAL_STRING_TYPE:
      return short_external_internalized_string_map();
391 392
    case SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE:
      return short_external_one_byte_internalized_string_map();
393 394 395 396 397 398 399
    case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
      return short_external_internalized_string_with_one_byte_data_map();
    default: return MaybeHandle<Map>();  // No match found.
  }
}


400 401
MaybeHandle<SeqOneByteString> Factory::NewRawOneByteString(
    int length, PretenureFlag pretenure) {
402
  if (length > String::kMaxLength || length < 0) {
403
    THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqOneByteString);
404
  }
405 406
  CALL_HEAP_FUNCTION(
      isolate(),
407
      isolate()->heap()->AllocateRawOneByteString(length, pretenure),
408
      SeqOneByteString);
409 410 411
}


412 413
MaybeHandle<SeqTwoByteString> Factory::NewRawTwoByteString(
    int length, PretenureFlag pretenure) {
414
  if (length > String::kMaxLength || length < 0) {
415
    THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqTwoByteString);
416
  }
417 418 419
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
420
      SeqTwoByteString);
421 422 423
}


424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
Handle<String> Factory::LookupSingleCharacterStringFromCode(uint32_t code) {
  if (code <= String::kMaxOneByteCharCodeU) {
    {
      DisallowHeapAllocation no_allocation;
      Object* value = single_character_string_cache()->get(code);
      if (value != *undefined_value()) {
        return handle(String::cast(value), isolate());
      }
    }
    uint8_t buffer[1];
    buffer[0] = static_cast<uint8_t>(code);
    Handle<String> result =
        InternalizeOneByteString(Vector<const uint8_t>(buffer, 1));
    single_character_string_cache()->set(code, *result);
    return result;
  }
440
  DCHECK(code <= String::kMaxUtf16CodeUnitU);
441 442 443 444

  Handle<SeqTwoByteString> result = NewRawTwoByteString(1).ToHandleChecked();
  result->SeqTwoByteStringSet(0, static_cast<uint16_t>(code));
  return result;
445 446 447
}


448 449 450 451 452 453 454 455 456 457 458 459 460
// Returns true for a character in a range.  Both limits are inclusive.
static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
  // This makes uses of the the unsigned wraparound.
  return character - from <= to - from;
}


static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
                                                          uint16_t c1,
                                                          uint16_t c2) {
  // Numeric strings have a different hash algorithm not known by
  // LookupTwoCharsStringIfExists, so we skip this step for such strings.
  if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
461 462 463 464
    Handle<String> result;
    if (StringTable::LookupTwoCharsStringIfExists(isolate, c1, c2).
        ToHandle(&result)) {
      return result;
465 466 467 468 469 470 471
    }
  }

  // Now we know the length is 2, we might as well make use of that fact
  // when building the new string.
  if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
    // We can do this.
472 473
    DCHECK(base::bits::IsPowerOfTwo32(String::kMaxOneByteCharCodeU +
                                      1));  // because of this.
474 475
    Handle<SeqOneByteString> str =
        isolate->factory()->NewRawOneByteString(2).ToHandleChecked();
476 477 478 479 480
    uint8_t* dest = str->GetChars();
    dest[0] = static_cast<uint8_t>(c1);
    dest[1] = static_cast<uint8_t>(c2);
    return str;
  } else {
481 482
    Handle<SeqTwoByteString> str =
        isolate->factory()->NewRawTwoByteString(2).ToHandleChecked();
483 484 485 486 487
    uc16* dest = str->GetChars();
    dest[0] = c1;
    dest[1] = c2;
    return str;
  }
488 489 490
}


491 492 493 494 495 496 497 498 499 500 501 502
template<typename SinkChar, typename StringType>
Handle<String> ConcatStringContent(Handle<StringType> result,
                                   Handle<String> first,
                                   Handle<String> second) {
  DisallowHeapAllocation pointer_stays_valid;
  SinkChar* sink = result->GetChars();
  String::WriteToFlat(*first, sink, 0, first->length());
  String::WriteToFlat(*second, sink + first->length(), 0, second->length());
  return result;
}


503 504
MaybeHandle<String> Factory::NewConsString(Handle<String> left,
                                           Handle<String> right) {
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
  int left_length = left->length();
  if (left_length == 0) return right;
  int right_length = right->length();
  if (right_length == 0) return left;

  int length = left_length + right_length;

  if (length == 2) {
    uint16_t c1 = left->Get(0);
    uint16_t c2 = right->Get(0);
    return MakeOrFindTwoCharacterString(isolate(), c1, c2);
  }

  // Make sure that an out of memory exception is thrown if the length
  // of the new cons string is too large.
  if (length > String::kMaxLength || length < 0) {
521
    THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
522 523 524 525 526 527 528 529
  }

  bool left_is_one_byte = left->IsOneByteRepresentation();
  bool right_is_one_byte = right->IsOneByteRepresentation();
  bool is_one_byte = left_is_one_byte && right_is_one_byte;
  bool is_one_byte_data_in_two_byte_string = false;
  if (!is_one_byte) {
    // At least one of the strings uses two-byte representation so we
530 531
    // can't use the fast case code for short one-byte strings below, but
    // we can try to save memory if all chars actually fit in one-byte.
532 533 534
    is_one_byte_data_in_two_byte_string =
        left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
    if (is_one_byte_data_in_two_byte_string) {
535
      isolate()->counters()->string_add_runtime_ext_to_one_byte()->Increment();
536 537 538 539 540 541 542
    }
  }

  // If the resulting string is small make a flat string.
  if (length < ConsString::kMinLength) {
    // Note that neither of the two inputs can be a slice because:
    STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
543 544
    DCHECK(left->IsFlat());
    DCHECK(right->IsFlat());
545

546
    STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
547
    if (is_one_byte) {
548 549
      Handle<SeqOneByteString> result =
          NewRawOneByteString(length).ToHandleChecked();
550 551 552
      DisallowHeapAllocation no_gc;
      uint8_t* dest = result->GetChars();
      // Copy left part.
553 554 555 556
      const uint8_t* src =
          left->IsExternalString()
              ? Handle<ExternalOneByteString>::cast(left)->GetChars()
              : Handle<SeqOneByteString>::cast(left)->GetChars();
557 558 559
      for (int i = 0; i < left_length; i++) *dest++ = src[i];
      // Copy right part.
      src = right->IsExternalString()
560 561
                ? Handle<ExternalOneByteString>::cast(right)->GetChars()
                : Handle<SeqOneByteString>::cast(right)->GetChars();
562 563 564 565 566
      for (int i = 0; i < right_length; i++) *dest++ = src[i];
      return result;
    }

    return (is_one_byte_data_in_two_byte_string)
567 568 569 570
        ? ConcatStringContent<uint8_t>(
            NewRawOneByteString(length).ToHandleChecked(), left, right)
        : ConcatStringContent<uc16>(
            NewRawTwoByteString(length).ToHandleChecked(), left, right);
571 572
  }

573 574 575 576
  Handle<ConsString> result =
      (is_one_byte || is_one_byte_data_in_two_byte_string)
          ? New<ConsString>(cons_one_byte_string_map(), NEW_SPACE)
          : New<ConsString>(cons_string_map(), NEW_SPACE);
577 578 579 580 581 582 583 584 585 586 587 588

  DisallowHeapAllocation no_gc;
  WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);

  result->set_hash_field(String::kEmptyHashField);
  result->set_length(length);
  result->set_first(*left, mode);
  result->set_second(*right, mode);
  return result;
}


589
Handle<String> Factory::NewProperSubString(Handle<String> str,
590 591
                                           int begin,
                                           int end) {
592 593 594
#if VERIFY_HEAP
  if (FLAG_verify_heap) str->StringVerify();
#endif
595
  DCHECK(begin > 0 || end < str->length());
596

597 598
  str = String::Flatten(str);

599 600 601
  int length = end - begin;
  if (length <= 0) return empty_string();
  if (length == 1) {
602
    return LookupSingleCharacterStringFromCode(str->Get(begin));
603 604 605 606 607 608 609 610 611 612 613 614
  }
  if (length == 2) {
    // Optimization for 2-byte strings often used as keys in a decompression
    // dictionary.  Check whether we already have the string in the string
    // table to prevent creation of many unnecessary strings.
    uint16_t c1 = str->Get(begin);
    uint16_t c2 = str->Get(begin + 1);
    return MakeOrFindTwoCharacterString(isolate(), c1, c2);
  }

  if (!FLAG_string_slices || length < SlicedString::kMinLength) {
    if (str->IsOneByteRepresentation()) {
615 616
      Handle<SeqOneByteString> result =
          NewRawOneByteString(length).ToHandleChecked();
617 618 619 620 621
      uint8_t* dest = result->GetChars();
      DisallowHeapAllocation no_gc;
      String::WriteToFlat(*str, dest, begin, end);
      return result;
    } else {
622 623
      Handle<SeqTwoByteString> result =
          NewRawTwoByteString(length).ToHandleChecked();
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
      uc16* dest = result->GetChars();
      DisallowHeapAllocation no_gc;
      String::WriteToFlat(*str, dest, begin, end);
      return result;
    }
  }

  int offset = begin;

  if (str->IsSlicedString()) {
    Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
    str = Handle<String>(slice->parent(), isolate());
    offset += slice->offset();
  }

639
  DCHECK(str->IsSeqString() || str->IsExternalString());
640 641 642
  Handle<Map> map = str->IsOneByteRepresentation()
                        ? sliced_one_byte_string_map()
                        : sliced_string_map();
643
  Handle<SlicedString> slice = New<SlicedString>(map, NEW_SPACE);
644 645 646 647 648 649

  slice->set_hash_field(String::kEmptyHashField);
  slice->set_length(length);
  slice->set_parent(*str);
  slice->set_offset(offset);
  return slice;
650 651 652
}


653 654
MaybeHandle<String> Factory::NewExternalStringFromOneByte(
    const ExternalOneByteString::Resource* resource) {
655 656
  size_t length = resource->length();
  if (length > static_cast<size_t>(String::kMaxLength)) {
657
    THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
658 659
  }

660 661 662 663 664 665 666
  Handle<Map> map;
  if (resource->IsCompressible()) {
    // TODO(hajimehoshi): Rename this to 'uncached_external_one_byte_string_map'
    map = short_external_one_byte_string_map();
  } else {
    map = external_one_byte_string_map();
  }
667 668
  Handle<ExternalOneByteString> external_string =
      New<ExternalOneByteString>(map, NEW_SPACE);
669 670 671 672 673
  external_string->set_length(static_cast<int>(length));
  external_string->set_hash_field(String::kEmptyHashField);
  external_string->set_resource(resource);

  return external_string;
674 675 676
}


677
MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
678
    const ExternalTwoByteString::Resource* resource) {
679 680
  size_t length = resource->length();
  if (length > static_cast<size_t>(String::kMaxLength)) {
681
    THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
682 683 684 685 686 687 688
  }

  // For small strings we check whether the resource contains only
  // one byte characters.  If yes, we use a different string map.
  static const size_t kOneByteCheckLengthLimit = 32;
  bool is_one_byte = length <= kOneByteCheckLengthLimit &&
      String::IsOneByte(resource->data(), static_cast<int>(length));
689 690 691 692 693 694 695 696 697
  Handle<Map> map;
  if (resource->IsCompressible()) {
    // TODO(hajimehoshi): Rename these to 'uncached_external_string_...'.
    map = is_one_byte ? short_external_string_with_one_byte_data_map()
                      : short_external_string_map();
  } else {
    map = is_one_byte ? external_string_with_one_byte_data_map()
                      : external_string_map();
  }
698 699 700 701 702 703 704
  Handle<ExternalTwoByteString> external_string =
      New<ExternalTwoByteString>(map, NEW_SPACE);
  external_string->set_length(static_cast<int>(length));
  external_string->set_hash_field(String::kEmptyHashField);
  external_string->set_resource(resource);

  return external_string;
705 706 707
}


708 709 710 711 712 713 714 715
Handle<Symbol> Factory::NewSymbol() {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateSymbol(),
      Symbol);
}


716
Handle<Symbol> Factory::NewPrivateSymbol() {
717 718
  Handle<Symbol> symbol = NewSymbol();
  symbol->set_is_private(true);
719 720 721 722
  return symbol;
}


723
Handle<Context> Factory::NewNativeContext() {
724 725
  Handle<FixedArray> array =
      NewFixedArray(Context::NATIVE_CONTEXT_SLOTS, TENURED);
726 727
  array->set_map_no_write_barrier(*native_context_map());
  Handle<Context> context = Handle<Context>::cast(array);
728
  context->set_native_context(*context);
729
  context->set_errors_thrown(Smi::FromInt(0));
730 731
  Handle<WeakCell> weak_cell = NewWeakCell(context);
  context->set_self_weak_cell(*weak_cell);
732
  DCHECK(context->IsNativeContext());
733
  return context;
734 735 736
}


737
Handle<Context> Factory::NewScriptContext(Handle<JSFunction> function,
738
                                          Handle<ScopeInfo> scope_info) {
739 740
  Handle<FixedArray> array =
      NewFixedArray(scope_info->ContextLength(), TENURED);
741
  array->set_map_no_write_barrier(*script_context_map());
742 743 744 745
  Handle<Context> context = Handle<Context>::cast(array);
  context->set_closure(*function);
  context->set_previous(function->context());
  context->set_extension(*scope_info);
746
  context->set_native_context(function->native_context());
747
  DCHECK(context->IsScriptContext());
748
  return context;
749 750 751
}


752
Handle<ScriptContextTable> Factory::NewScriptContextTable() {
753
  Handle<FixedArray> array = NewFixedArray(1);
754 755 756
  array->set_map_no_write_barrier(*script_context_table_map());
  Handle<ScriptContextTable> context_table =
      Handle<ScriptContextTable>::cast(array);
757 758 759 760 761
  context_table->set_used(0);
  return context_table;
}


762
Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
763 764 765 766 767
  Handle<FixedArray> array =
      NewFixedArray(scope_info->ContextLength(), TENURED);
  array->set_map_no_write_barrier(*module_context_map());
  // Instance link will be set later.
  Handle<Context> context = Handle<Context>::cast(array);
768
  context->set_extension(*the_hole_value());
769
  return context;
770 771 772
}


773
Handle<Context> Factory::NewFunctionContext(int length,
774
                                            Handle<JSFunction> function) {
775
  DCHECK(length >= Context::MIN_CONTEXT_SLOTS);
776 777 778 779 780
  Handle<FixedArray> array = NewFixedArray(length);
  array->set_map_no_write_barrier(*function_context_map());
  Handle<Context> context = Handle<Context>::cast(array);
  context->set_closure(*function);
  context->set_previous(function->context());
781
  context->set_extension(*the_hole_value());
782
  context->set_native_context(function->native_context());
783
  return context;
784 785 786
}


787 788
Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
                                         Handle<Context> previous,
789 790
                                         Handle<String> name,
                                         Handle<Object> thrown_object) {
791 792 793 794 795 796 797
  STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
  Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
  array->set_map_no_write_barrier(*catch_context_map());
  Handle<Context> context = Handle<Context>::cast(array);
  context->set_closure(*function);
  context->set_previous(*previous);
  context->set_extension(*name);
798
  context->set_native_context(previous->native_context());
799 800
  context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
  return context;
801 802 803
}


804 805
Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
                                        Handle<Context> previous,
806 807 808 809 810 811 812
                                        Handle<JSReceiver> extension) {
  Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS);
  array->set_map_no_write_barrier(*with_context_map());
  Handle<Context> context = Handle<Context>::cast(array);
  context->set_closure(*function);
  context->set_previous(*previous);
  context->set_extension(*extension);
813
  context->set_native_context(previous->native_context());
814
  return context;
815 816 817
}


818 819 820
Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
                                         Handle<Context> previous,
                                         Handle<ScopeInfo> scope_info) {
821
  Handle<FixedArray> array = NewFixedArray(scope_info->ContextLength());
822 823 824 825 826
  array->set_map_no_write_barrier(*block_context_map());
  Handle<Context> context = Handle<Context>::cast(array);
  context->set_closure(*function);
  context->set_previous(*previous);
  context->set_extension(*scope_info);
827
  context->set_native_context(previous->native_context());
828
  return context;
829 830 831
}


832
Handle<Struct> Factory::NewStruct(InstanceType type) {
833 834 835 836
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateStruct(type),
      Struct);
837 838 839
}


840
Handle<CodeCache> Factory::NewCodeCache() {
841 842 843 844 845
  Handle<CodeCache> code_cache =
      Handle<CodeCache>::cast(NewStruct(CODE_CACHE_TYPE));
  code_cache->set_default_cache(*empty_fixed_array(), SKIP_WRITE_BARRIER);
  code_cache->set_normal_type_cache(*undefined_value(), SKIP_WRITE_BARRIER);
  return code_cache;
846 847 848
}


849 850 851 852 853 854 855 856 857
Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
    int aliased_context_slot) {
  Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
      NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
  entry->set_aliased_context_slot(aliased_context_slot);
  return entry;
}


858 859 860
Handle<AccessorInfo> Factory::NewAccessorInfo() {
  Handle<AccessorInfo> info =
      Handle<AccessorInfo>::cast(NewStruct(ACCESSOR_INFO_TYPE));
861 862 863 864 865 866
  info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
  return info;
}


Handle<Script> Factory::NewScript(Handle<String> source) {
867
  // Create and initialize script object.
868
  Heap* heap = isolate()->heap();
869 870
  Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
  script->set_source(*source);
871
  script->set_name(heap->undefined_value());
872
  script->set_id(isolate()->heap()->NextScriptId());
873 874
  script->set_line_offset(0);
  script->set_column_offset(0);
875
  script->set_context_data(heap->undefined_value());
876
  script->set_type(Script::TYPE_NORMAL);
877
  script->set_wrapper(heap->undefined_value());
878 879
  script->set_line_ends(heap->undefined_value());
  script->set_eval_from_shared(heap->undefined_value());
880
  script->set_eval_from_instructions_offset(0);
881
  script->set_shared_function_infos(Smi::FromInt(0));
882
  script->set_flags(0);
883

884
  heap->set_script_list(*WeakFixedArray::Add(script_list(), script));
885 886 887 888
  return script;
}


889
Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
890
  CALL_HEAP_FUNCTION(isolate(),
891 892
                     isolate()->heap()->AllocateForeign(addr, pretenure),
                     Foreign);
893 894 895
}


896 897
Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
  return NewForeign((Address) desc, TENURED);
898 899 900
}


901
Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
902
  DCHECK(0 <= length);
903 904 905 906
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateByteArray(length, pretenure),
      ByteArray);
907 908 909
}


910 911 912
Handle<BytecodeArray> Factory::NewBytecodeArray(
    int length, const byte* raw_bytecodes, int frame_size, int parameter_count,
    Handle<FixedArray> constant_pool) {
913
  DCHECK(0 <= length);
914 915 916
  CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateBytecodeArray(
                                    length, raw_bytecodes, frame_size,
                                    parameter_count, *constant_pool),
917 918 919 920
                     BytecodeArray);
}


921 922 923
Handle<FixedTypedArrayBase> Factory::NewFixedTypedArrayWithExternalPointer(
    int length, ExternalArrayType array_type, void* external_pointer,
    PretenureFlag pretenure) {
924
  DCHECK(0 <= length && length <= Smi::kMaxValue);
925
  CALL_HEAP_FUNCTION(
926 927 928
      isolate(), isolate()->heap()->AllocateFixedTypedArrayWithExternalPointer(
                     length, array_type, external_pointer, pretenure),
      FixedTypedArrayBase);
929 930 931
}


932
Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
933
    int length, ExternalArrayType array_type, bool initialize,
934
    PretenureFlag pretenure) {
935
  DCHECK(0 <= length && length <= Smi::kMaxValue);
936 937 938
  CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateFixedTypedArray(
                                    length, array_type, initialize, pretenure),
                     FixedTypedArrayBase);
939 940 941
}


942 943 944 945 946 947 948 949 950
Handle<Cell> Factory::NewCell(Handle<Object> value) {
  AllowDeferredHandleDereference convert_to_cell;
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateCell(*value),
      Cell);
}


951
Handle<PropertyCell> Factory::NewPropertyCell() {
952 953
  CALL_HEAP_FUNCTION(
      isolate(),
954
      isolate()->heap()->AllocatePropertyCell(),
955
      PropertyCell);
956 957 958
}


ulan@chromium.org's avatar
ulan@chromium.org committed
959
Handle<WeakCell> Factory::NewWeakCell(Handle<HeapObject> value) {
960 961
  // It is safe to dereference the value because we are embedding it
  // in cell and not inspecting its fields.
ulan@chromium.org's avatar
ulan@chromium.org committed
962 963 964 965 966 967
  AllowDeferredHandleDereference convert_to_cell;
  CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateWeakCell(*value),
                     WeakCell);
}


968 969 970 971 972 973 974
Handle<TransitionArray> Factory::NewTransitionArray(int capacity) {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateTransitionArray(capacity),
                     TransitionArray);
}


975
Handle<AllocationSite> Factory::NewAllocationSite() {
976
  Handle<Map> map = allocation_site_map();
977
  Handle<AllocationSite> site = New<AllocationSite>(map, OLD_SPACE);
978 979 980 981 982 983
  site->Initialize();

  // Link the site
  site->set_weak_next(isolate()->heap()->allocation_sites_list());
  isolate()->heap()->set_allocation_sites_list(*site);
  return site;
984 985 986
}


987 988 989
Handle<Map> Factory::NewMap(InstanceType type,
                            int instance_size,
                            ElementsKind elements_kind) {
990 991
  CALL_HEAP_FUNCTION(
      isolate(),
992
      isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
993
      Map);
994 995 996
}


997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> object) {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->CopyJSObject(*object, NULL),
                     JSObject);
}


Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
    Handle<JSObject> object,
    Handle<AllocationSite> site) {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->CopyJSObject(
                         *object,
                         site.is_null() ? NULL : *site),
                     JSObject);
}


1015 1016 1017 1018 1019
Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
                                                  Handle<Map> map) {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->CopyFixedArrayWithMap(*array, *map),
                     FixedArray);
1020 1021 1022
}


1023
Handle<FixedArray> Factory::CopyFixedArrayAndGrow(Handle<FixedArray> array,
1024 1025 1026 1027
                                                  int grow_by,
                                                  PretenureFlag pretenure) {
  CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->CopyFixedArrayAndGrow(
                                    *array, grow_by, pretenure),
1028 1029 1030
                     FixedArray);
}

1031 1032 1033 1034 1035 1036 1037
Handle<FixedArray> Factory::CopyFixedArrayUpTo(Handle<FixedArray> array,
                                               int new_len,
                                               PretenureFlag pretenure) {
  CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->CopyFixedArrayUpTo(
                                    *array, new_len, pretenure),
                     FixedArray);
}
1038

1039
Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
1040
  CALL_HEAP_FUNCTION(isolate(),
1041
                     isolate()->heap()->CopyFixedArray(*array),
1042 1043 1044 1045
                     FixedArray);
}


1046 1047
Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
    Handle<FixedArray> array) {
1048
  DCHECK(isolate()->heap()->InNewSpace(*array));
1049
  CALL_HEAP_FUNCTION(isolate(),
1050
                     isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
1051
                     FixedArray);
1052 1053 1054
}


1055 1056
Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
    Handle<FixedDoubleArray> array) {
1057 1058 1059
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->CopyFixedDoubleArray(*array),
                     FixedDoubleArray);
1060 1061 1062
}


1063 1064
Handle<Object> Factory::NewNumber(double value,
                                  PretenureFlag pretenure) {
1065 1066 1067
  // We need to distinguish the minus zero value and this cannot be
  // done after conversion to int. Doing this by comparing bit
  // patterns is faster than using fpclassify() et al.
1068
  if (IsMinusZero(value)) return NewHeapNumber(-0.0, IMMUTABLE, pretenure);
1069

1070
  int int_value = FastD2IChecked(value);
1071 1072 1073 1074 1075
  if (value == int_value && Smi::IsValid(int_value)) {
    return handle(Smi::FromInt(int_value), isolate());
  }

  // Materialize the value in the heap.
1076
  return NewHeapNumber(value, IMMUTABLE, pretenure);
1077 1078 1079
}


1080 1081
Handle<Object> Factory::NewNumberFromInt(int32_t value,
                                         PretenureFlag pretenure) {
1082
  if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
1083 1084
  // Bypass NewNumber to avoid various redundant checks.
  return NewHeapNumber(FastI2D(value), IMMUTABLE, pretenure);
1085 1086 1087
}


1088
Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1089 1090 1091 1092 1093
                                          PretenureFlag pretenure) {
  int32_t int32v = static_cast<int32_t>(value);
  if (int32v >= 0 && Smi::IsValid(int32v)) {
    return handle(Smi::FromInt(int32v), isolate());
  }
1094
  return NewHeapNumber(FastUI2D(value), IMMUTABLE, pretenure);
1095 1096 1097
}


1098
Handle<HeapNumber> Factory::NewHeapNumber(double value,
1099
                                          MutableMode mode,
1100 1101 1102
                                          PretenureFlag pretenure) {
  CALL_HEAP_FUNCTION(
      isolate(),
1103 1104
      isolate()->heap()->AllocateHeapNumber(value, mode, pretenure),
      HeapNumber);
1105 1106 1107
}


1108 1109 1110 1111 1112 1113 1114 1115
#define SIMD128_NEW_DEF(TYPE, Type, type, lane_count, lane_type)               \
  Handle<Type> Factory::New##Type(lane_type lanes[lane_count],                 \
                                  PretenureFlag pretenure) {                   \
    CALL_HEAP_FUNCTION(                                                        \
        isolate(), isolate()->heap()->Allocate##Type(lanes, pretenure), Type); \
  }
SIMD128_TYPES(SIMD128_NEW_DEF)
#undef SIMD128_NEW_DEF
1116 1117


1118
Handle<Object> Factory::NewError(Handle<JSFunction> constructor,
1119 1120 1121 1122
                                 MessageTemplate::Template template_index,
                                 Handle<Object> arg0, Handle<Object> arg1,
                                 Handle<Object> arg2) {
  HandleScope scope(isolate());
1123
  if (isolate()->bootstrapper()->IsActive()) {
1124 1125 1126
    // During bootstrapping we cannot construct error objects.
    return scope.CloseAndEscape(NewStringFromAsciiChecked(
        MessageTemplate::TemplateString(template_index)));
1127
  }
1128

1129
  Handle<JSFunction> fun = isolate()->make_error_function();
1130 1131 1132 1133
  Handle<Object> message_type(Smi::FromInt(template_index), isolate());
  if (arg0.is_null()) arg0 = undefined_value();
  if (arg1.is_null()) arg1 = undefined_value();
  if (arg2.is_null()) arg2 = undefined_value();
1134
  Handle<Object> argv[] = {constructor, message_type, arg0, arg1, arg2};
1135 1136 1137 1138 1139

  // Invoke the JavaScript factory method. If an exception is thrown while
  // running the factory method, use the exception as the result.
  Handle<Object> result;
  MaybeHandle<Object> exception;
1140 1141
  if (!Execution::TryCall(isolate(), fun, undefined_value(), arraysize(argv),
                          argv, &exception)
1142
           .ToHandle(&result)) {
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
    Handle<Object> exception_obj;
    if (exception.ToHandle(&exception_obj)) {
      result = exception_obj;
    } else {
      result = undefined_value();
    }
  }
  return scope.CloseAndEscape(result);
}


1154
Handle<Object> Factory::NewError(Handle<JSFunction> constructor,
1155
                                 Handle<String> message) {
1156
  Handle<Object> argv[] = { message };
1157 1158 1159

  // Invoke the JavaScript factory method. If an exception is thrown while
  // running the factory method, use the exception as the result.
1160
  Handle<Object> result;
1161
  MaybeHandle<Object> exception;
1162 1163
  if (!Execution::TryCall(isolate(), constructor, undefined_value(),
                          arraysize(argv), argv, &exception)
1164
           .ToHandle(&result)) {
1165 1166 1167
    Handle<Object> exception_obj;
    if (exception.ToHandle(&exception_obj)) return exception_obj;
    return undefined_value();
1168
  }
1169 1170 1171 1172
  return result;
}


1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
#define DEFINE_ERROR(NAME, name)                                              \
  Handle<Object> Factory::New##NAME(MessageTemplate::Template template_index, \
                                    Handle<Object> arg0, Handle<Object> arg1, \
                                    Handle<Object> arg2) {                    \
    return NewError(isolate()->name##_function(), template_index, arg0, arg1, \
                    arg2);                                                    \
  }
DEFINE_ERROR(Error, error)
DEFINE_ERROR(EvalError, eval_error)
DEFINE_ERROR(RangeError, range_error)
DEFINE_ERROR(ReferenceError, reference_error)
DEFINE_ERROR(SyntaxError, syntax_error)
DEFINE_ERROR(TypeError, type_error)
#undef DEFINE_ERROR


1189 1190 1191 1192 1193 1194 1195
Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
                                        Handle<SharedFunctionInfo> info,
                                        Handle<Context> context,
                                        PretenureFlag pretenure) {
  AllocationSpace space = pretenure == TENURED ? OLD_SPACE : NEW_SPACE;
  Handle<JSFunction> function = New<JSFunction>(map, space);

1196 1197 1198 1199 1200 1201
  function->initialize_properties();
  function->initialize_elements();
  function->set_shared(*info);
  function->set_code(info->code());
  function->set_context(*context);
  function->set_prototype_or_initial_map(*the_hole_value());
1202
  function->set_literals(LiteralsArray::cast(*empty_fixed_array()));
1203
  function->set_next_function_link(*undefined_value(), SKIP_WRITE_BARRIER);
1204 1205
  isolate()->heap()->InitializeJSObjectBody(*function, *map, JSFunction::kSize);
  return function;
1206 1207 1208
}


1209 1210 1211
Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
                                        Handle<String> name,
                                        MaybeHandle<Code> code) {
1212
  Handle<Context> context(isolate()->native_context());
1213 1214
  Handle<SharedFunctionInfo> info =
      NewSharedFunctionInfo(name, code, map->is_constructor());
1215
  DCHECK(is_sloppy(info->language_mode()));
1216
  DCHECK(!map->IsUndefined());
1217 1218 1219 1220 1221 1222
  DCHECK(
      map.is_identical_to(isolate()->sloppy_function_map()) ||
      map.is_identical_to(isolate()->sloppy_function_without_prototype_map()) ||
      map.is_identical_to(
          isolate()->sloppy_function_with_readonly_prototype_map()) ||
      map.is_identical_to(isolate()->strict_function_map()) ||
1223 1224
      // TODO(titzer): wasm_function_map() could be undefined here. ugly.
      (*map == context->get(Context::WASM_FUNCTION_MAP_INDEX)) ||
1225
      map.is_identical_to(isolate()->proxy_function_map()));
1226
  return NewFunction(map, info, context);
1227 1228 1229
}


1230
Handle<JSFunction> Factory::NewFunction(Handle<String> name) {
1231 1232
  return NewFunction(
      isolate()->sloppy_function_map(), name, MaybeHandle<Code>());
1233 1234 1235
}


1236
Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1237 1238 1239 1240 1241 1242
                                                        Handle<Code> code,
                                                        bool is_strict) {
  Handle<Map> map = is_strict
                        ? isolate()->strict_function_without_prototype_map()
                        : isolate()->sloppy_function_without_prototype_map();
  return NewFunction(map, name, code);
1243 1244 1245
}


1246
Handle<JSFunction> Factory::NewFunction(Handle<String> name, Handle<Code> code,
1247
                                        Handle<Object> prototype,
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
                                        bool read_only_prototype,
                                        bool is_strict) {
  // In strict mode, readonly strict map is only available during bootstrap
  DCHECK(!is_strict || !read_only_prototype ||
         isolate()->bootstrapper()->IsActive());
  Handle<Map> map =
      is_strict ? isolate()->strict_function_map()
                : read_only_prototype
                      ? isolate()->sloppy_function_with_readonly_prototype_map()
                      : isolate()->sloppy_function_map();
1258
  Handle<JSFunction> result = NewFunction(map, name, code);
1259 1260 1261 1262 1263
  result->set_prototype_or_initial_map(*prototype);
  return result;
}


1264
Handle<JSFunction> Factory::NewFunction(Handle<String> name, Handle<Code> code,
1265
                                        Handle<Object> prototype,
1266 1267
                                        InstanceType type, int instance_size,
                                        bool read_only_prototype,
1268 1269
                                        bool install_constructor,
                                        bool is_strict) {
1270
  // Allocate the function
1271 1272
  Handle<JSFunction> function =
      NewFunction(name, code, prototype, read_only_prototype, is_strict);
1273

1274 1275 1276
  ElementsKind elements_kind =
      type == JS_ARRAY_TYPE ? FAST_SMI_ELEMENTS : FAST_HOLEY_SMI_ELEMENTS;
  Handle<Map> initial_map = NewMap(type, instance_size, elements_kind);
1277 1278 1279 1280 1281 1282 1283
  if (!function->shared()->is_generator()) {
    if (prototype->IsTheHole()) {
      prototype = NewFunctionPrototype(function);
    } else if (install_constructor) {
      JSObject::AddProperty(Handle<JSObject>::cast(prototype),
                            constructor_string(), function, DONT_ENUM);
    }
1284
  }
1285

1286 1287
  JSFunction::SetInitialMap(function, initial_map,
                            Handle<JSReceiver>::cast(prototype));
1288 1289 1290 1291 1292

  return function;
}


1293
Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1294
                                        Handle<Code> code,
1295
                                        InstanceType type,
1296 1297
                                        int instance_size) {
  return NewFunction(name, code, the_hole_value(), type, instance_size);
1298 1299 1300
}


1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
  // Make sure to use globals from the function's context, since the function
  // can be from a different context.
  Handle<Context> native_context(function->context()->native_context());
  Handle<Map> new_map;
  if (function->shared()->is_generator()) {
    // Generator prototypes can share maps since they don't have "constructor"
    // properties.
    new_map = handle(native_context->generator_object_prototype_map());
  } else {
    // Each function prototype gets a fresh map to avoid unwanted sharing of
    // maps between prototypes of different constructors.
    Handle<JSFunction> object_function(native_context->object_function());
1314
    DCHECK(object_function->has_initial_map());
1315
    new_map = handle(object_function->initial_map());
1316 1317
  }

1318
  DCHECK(!new_map->is_prototype_map());
1319 1320 1321
  Handle<JSObject> prototype = NewJSObjectFromMap(new_map);

  if (!function->shared()->is_generator()) {
1322
    JSObject::AddProperty(prototype, constructor_string(), function, DONT_ENUM);
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
  }

  return prototype;
}


Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
    Handle<SharedFunctionInfo> info,
    Handle<Context> context,
    PretenureFlag pretenure) {
1333 1334
  int map_index =
      Context::FunctionMapIndex(info->language_mode(), info->kind());
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
  Handle<Map> initial_map(Map::cast(context->native_context()->get(map_index)));

  return NewFunctionFromSharedFunctionInfo(initial_map, info, context,
                                           pretenure);
}


Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
    Handle<Map> initial_map, Handle<SharedFunctionInfo> info,
    Handle<Context> context, PretenureFlag pretenure) {
  DCHECK_EQ(JS_FUNCTION_TYPE, initial_map->instance_type());
  Handle<JSFunction> result =
      NewFunction(initial_map, info, context, pretenure);
1348 1349 1350 1351 1352

  if (info->ic_age() != isolate()->heap()->global_ic_age()) {
    info->ResetForNewContext(isolate()->heap()->global_ic_age());
  }

1353 1354 1355 1356
  if (FLAG_always_opt && info->allows_lazy_compilation()) {
    result->MarkForOptimization();
  }

1357 1358 1359 1360 1361 1362 1363 1364 1365
  CodeAndLiterals cached = info->SearchOptimizedCodeMap(
      context->native_context(), BailoutId::None());
  if (cached.code != nullptr) {
    // Caching of optimized code enabled and optimized code found.
    DCHECK(!cached.code->marked_for_deoptimization());
    DCHECK(result->shared()->is_compiled());
    result->ReplaceCode(cached.code);
  }

1366 1367
  if (cached.literals != nullptr) {
    result->set_literals(cached.literals);
1368
  } else {
1369
    int number_of_literals = info->num_literals();
1370
    Handle<LiteralsArray> literals =
1371 1372
        LiteralsArray::New(isolate(), handle(info->feedback_vector()),
                           number_of_literals, pretenure);
1373
    result->set_literals(*literals);
1374

1375
    // Cache context-specific literals.
1376
    Handle<Context> native_context(context->native_context());
1377 1378
    SharedFunctionInfo::AddLiteralsToOptimizedCodeMap(info, native_context,
                                                      literals);
1379 1380 1381 1382 1383 1384
  }

  return result;
}


1385
Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1386 1387 1388 1389
  Handle<FixedArray> array = NewFixedArray(length, TENURED);
  array->set_map_no_write_barrier(*scope_info_map());
  Handle<ScopeInfo> scope_info = Handle<ScopeInfo>::cast(array);
  return scope_info;
1390 1391 1392
}


1393
Handle<JSObject> Factory::NewExternal(void* value) {
1394 1395 1396 1397
  Handle<Foreign> foreign = NewForeign(static_cast<Address>(value));
  Handle<JSObject> external = NewJSObjectFromMap(external_map());
  external->SetInternalField(0, *foreign);
  return external;
1398 1399 1400
}


1401 1402 1403
Handle<Code> Factory::NewCodeRaw(int object_size, bool immovable) {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateCode(object_size, immovable),
1404 1405 1406 1407
                     Code);
}


1408 1409
Handle<Code> Factory::NewCode(const CodeDesc& desc,
                              Code::Flags flags,
1410
                              Handle<Object> self_ref,
1411
                              bool immovable,
1412
                              bool crankshafted,
1413 1414
                              int prologue_offset,
                              bool is_debug) {
1415 1416 1417 1418 1419 1420
  Handle<ByteArray> reloc_info = NewByteArray(desc.reloc_size, TENURED);

  // Compute size.
  int body_size = RoundUp(desc.instr_size, kObjectAlignment);
  int obj_size = Code::SizeFor(body_size);

1421
  Handle<Code> code = NewCodeRaw(obj_size, immovable);
1422 1423 1424
  DCHECK(isolate()->code_range() == NULL || !isolate()->code_range()->valid() ||
         isolate()->code_range()->contains(code->address()) ||
         obj_size <= isolate()->heap()->code_space()->AreaSize());
1425 1426 1427 1428 1429

  // The code object has not been fully initialized yet.  We rely on the
  // fact that no allocation will happen from this point on.
  DisallowHeapAllocation no_gc;
  code->set_gc_metadata(Smi::FromInt(0));
ulan's avatar
ulan committed
1430
  code->set_ic_age(isolate()->heap()->global_ic_age());
1431 1432 1433 1434 1435 1436 1437
  code->set_instruction_size(desc.instr_size);
  code->set_relocation_info(*reloc_info);
  code->set_flags(flags);
  code->set_raw_kind_specific_flags1(0);
  code->set_raw_kind_specific_flags2(0);
  code->set_is_crankshafted(crankshafted);
  code->set_deoptimization_data(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1438
  code->set_raw_type_feedback_info(Smi::FromInt(0));
1439 1440 1441
  code->set_next_code_link(*undefined_value());
  code->set_handler_table(*empty_fixed_array(), SKIP_WRITE_BARRIER);
  code->set_prologue_offset(prologue_offset);
1442 1443
  code->set_constant_pool_offset(desc.instr_size - desc.constant_pool_size);

1444 1445 1446 1447
  if (code->kind() == Code::OPTIMIZED_FUNCTION) {
    code->set_marked_for_deoptimization(false);
  }

1448
  if (is_debug) {
1449
    DCHECK(code->kind() == Code::FUNCTION);
1450 1451 1452
    code->set_has_debug_break_slots(true);
  }

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
  // Allow self references to created code object by patching the handle to
  // point to the newly allocated Code object.
  if (!self_ref.is_null()) *(self_ref.location()) = *code;

  // Migrate generated code.
  // The generated code can contain Object** values (typically from handles)
  // that are dereferenced during the copy to point directly to the actual heap
  // objects. These pointers can include references to the code object itself,
  // through the self_reference parameter.
  code->CopyFrom(desc);

#ifdef VERIFY_HEAP
1465
  if (FLAG_verify_heap) code->ObjectVerify();
1466 1467
#endif
  return code;
1468 1469 1470 1471
}


Handle<Code> Factory::CopyCode(Handle<Code> code) {
1472 1473 1474
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->CopyCode(*code),
                     Code);
1475 1476 1477
}


1478
Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1479 1480 1481
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->CopyCode(*code, reloc_info),
                     Code);
1482 1483 1484
}


1485 1486
Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
                                      PretenureFlag pretenure) {
1487
  JSFunction::EnsureHasInitialMap(constructor);
1488 1489 1490
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1491 1492 1493
}


1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
Handle<JSObject> Factory::NewJSObjectWithMemento(
    Handle<JSFunction> constructor,
    Handle<AllocationSite> site) {
  JSFunction::EnsureHasInitialMap(constructor);
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
      JSObject);
}


1505 1506
Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
                                      Handle<ScopeInfo> scope_info) {
1507 1508 1509 1510 1511 1512 1513 1514
  // Allocate a fresh map. Modules do not have a prototype.
  Handle<Map> map = NewMap(JS_MODULE_TYPE, JSModule::kSize);
  // Allocate the object based on the map.
  Handle<JSModule> module =
      Handle<JSModule>::cast(NewJSObjectFromMap(map, TENURED));
  module->set_context(*context);
  module->set_scope_info(*scope_info);
  return module;
1515 1516 1517
}


1518 1519
Handle<JSGlobalObject> Factory::NewJSGlobalObject(
    Handle<JSFunction> constructor) {
1520
  DCHECK(constructor->has_initial_map());
1521
  Handle<Map> map(constructor->initial_map());
1522
  DCHECK(map->is_dictionary_map());
1523 1524 1525 1526

  // Make sure no field properties are described in the initial map.
  // This guarantees us that normalizing the properties does not
  // require us to change property values to PropertyCells.
1527
  DCHECK(map->NextFreePropertyIndex() == 0);
1528 1529 1530

  // Make sure we don't have a ton of pre-allocated slots in the
  // global objects. They will be unused once we normalize the object.
1531
  DCHECK(map->unused_property_fields() == 0);
1532
  DCHECK(map->GetInObjectProperties() == 0);
1533 1534 1535 1536

  // Initial size of the backing store to avoid resize of the storage during
  // bootstrapping. The size differs between the JS global object ad the
  // builtins object.
yangguo's avatar
yangguo committed
1537
  int initial_size = 64;
1538 1539 1540

  // Allocate a dictionary object for backing storage.
  int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1541 1542
  Handle<GlobalDictionary> dictionary =
      GlobalDictionary::New(isolate(), at_least_space_for);
1543 1544 1545 1546 1547 1548

  // The global object might be created from an object template with accessors.
  // Fill these accessors into the dictionary.
  Handle<DescriptorArray> descs(map->instance_descriptors());
  for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
    PropertyDetails details = descs->GetDetails(i);
1549 1550
    // Only accessors are expected.
    DCHECK_EQ(ACCESSOR_CONSTANT, details.type());
1551 1552
    PropertyDetails d(details.attributes(), ACCESSOR_CONSTANT, i + 1,
                      PropertyCellType::kMutable);
1553
    Handle<Name> name(descs->GetKey(i));
1554 1555
    Handle<PropertyCell> cell = NewPropertyCell();
    cell->set_value(descs->GetCallbacksObject(i));
1556
    // |dictionary| already contains enough space for all properties.
1557
    USE(GlobalDictionary::Add(dictionary, name, cell, d));
1558 1559 1560
  }

  // Allocate the global object and initialize it with the backing store.
1561
  Handle<JSGlobalObject> global = New<JSGlobalObject>(map, OLD_SPACE);
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
  isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);

  // Create a new map for the global object.
  Handle<Map> new_map = Map::CopyDropDescriptors(map);
  new_map->set_dictionary_map(true);

  // Set up the global object as a normalized object.
  global->set_map(*new_map);
  global->set_properties(*dictionary);

  // Make sure result is a global object with properties in dictionary.
1573
  DCHECK(global->IsJSGlobalObject() && !global->HasFastProperties());
1574 1575 1576
  return global;
}

1577

1578 1579 1580 1581
Handle<JSObject> Factory::NewJSObjectFromMap(
    Handle<Map> map,
    PretenureFlag pretenure,
    Handle<AllocationSite> allocation_site) {
1582 1583
  CALL_HEAP_FUNCTION(
      isolate(),
1584 1585 1586 1587
      isolate()->heap()->AllocateJSObjectFromMap(
          *map,
          pretenure,
          allocation_site.is_null() ? NULL : *allocation_site),
1588
      JSObject);
1589 1590 1591
}


1592
Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1593
                                    Strength strength,
1594
                                    PretenureFlag pretenure) {
1595 1596
  Map* map = isolate()->get_initial_js_array_map(elements_kind, strength);
  if (map == nullptr) {
1597
    DCHECK(strength == Strength::WEAK);
1598 1599 1600 1601
    Context* native_context = isolate()->context()->native_context();
    JSFunction* array_function = native_context->array_function();
    map = array_function->initial_map();
  }
1602
  return Handle<JSArray>::cast(NewJSObjectFromMap(handle(map), pretenure));
1603 1604 1605
}


1606
Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind, int length,
1607
                                    int capacity, Strength strength,
1608
                                    ArrayStorageAllocationMode mode,
1609
                                    PretenureFlag pretenure) {
1610
  Handle<JSArray> array = NewJSArray(elements_kind, strength, pretenure);
1611 1612
  NewJSArrayStorage(array, length, capacity, mode);
  return array;
1613 1614 1615
}


1616
Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1617
                                                ElementsKind elements_kind,
1618
                                                int length, Strength strength,
1619
                                                PretenureFlag pretenure) {
1620
  DCHECK(length <= elements->length());
1621
  Handle<JSArray> array = NewJSArray(elements_kind, strength, pretenure);
1622 1623 1624 1625 1626

  array->set_elements(*elements);
  array->set_length(Smi::FromInt(length));
  JSObject::ValidateElements(array);
  return array;
1627 1628 1629
}


1630
void Factory::NewJSArrayStorage(Handle<JSArray> array,
1631 1632 1633
                                int length,
                                int capacity,
                                ArrayStorageAllocationMode mode) {
1634
  DCHECK(capacity >= length);
1635 1636 1637 1638 1639 1640 1641

  if (capacity == 0) {
    array->set_length(Smi::FromInt(0));
    array->set_elements(*empty_fixed_array());
    return;
  }

1642
  HandleScope inner_scope(isolate());
1643 1644 1645 1646 1647 1648
  Handle<FixedArrayBase> elms;
  ElementsKind elements_kind = array->GetElementsKind();
  if (IsFastDoubleElementsKind(elements_kind)) {
    if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
      elms = NewFixedDoubleArray(capacity);
    } else {
1649
      DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1650 1651 1652
      elms = NewFixedDoubleArrayWithHoles(capacity);
    }
  } else {
1653
    DCHECK(IsFastSmiOrObjectElementsKind(elements_kind));
1654 1655 1656
    if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
      elms = NewUninitializedFixedArray(capacity);
    } else {
1657
      DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1658 1659 1660 1661 1662 1663
      elms = NewFixedArrayWithHoles(capacity);
    }
  }

  array->set_elements(*elms);
  array->set_length(Smi::FromInt(length));
1664 1665 1666
}


1667 1668
Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
    Handle<JSFunction> function) {
1669
  DCHECK(function->shared()->is_generator());
1670 1671
  JSFunction::EnsureHasInitialMap(function);
  Handle<Map> map(function->initial_map());
1672
  DCHECK_EQ(JS_GENERATOR_OBJECT_TYPE, map->instance_type());
1673 1674 1675 1676
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSObjectFromMap(*map),
      JSGeneratorObject);
1677 1678 1679
}


ben's avatar
ben committed
1680 1681
Handle<JSArrayBuffer> Factory::NewJSArrayBuffer(SharedFlag shared,
                                                PretenureFlag pretenure) {
1682
  Handle<JSFunction> array_buffer_fun(
binji's avatar
binji committed
1683 1684 1685
      shared == SharedFlag::kShared
          ? isolate()->native_context()->shared_array_buffer_fun()
          : isolate()->native_context()->array_buffer_fun());
ben's avatar
ben committed
1686 1687 1688
  CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateJSObject(
                                    *array_buffer_fun, pretenure),
                     JSArrayBuffer);
1689 1690 1691
}


1692
Handle<JSDataView> Factory::NewJSDataView() {
1693
  Handle<JSFunction> data_view_fun(
1694
      isolate()->native_context()->data_view_fun());
1695 1696 1697 1698
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSObject(*data_view_fun),
      JSDataView);
1699 1700 1701
}


1702 1703 1704
Handle<JSMap> Factory::NewJSMap() {
  Handle<Map> map(isolate()->native_context()->js_map_map());
  Handle<JSMap> js_map = Handle<JSMap>::cast(NewJSObjectFromMap(map));
1705
  JSMap::Initialize(js_map, isolate());
1706 1707 1708 1709 1710 1711 1712
  return js_map;
}


Handle<JSSet> Factory::NewJSSet() {
  Handle<Map> map(isolate()->native_context()->js_set_map());
  Handle<JSSet> js_set = Handle<JSSet>::cast(NewJSObjectFromMap(map));
1713
  JSSet::Initialize(js_set, isolate());
1714 1715 1716 1717
  return js_set;
}


1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
Handle<JSMapIterator> Factory::NewJSMapIterator() {
  Handle<Map> map(isolate()->native_context()->map_iterator_map());
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateJSObjectFromMap(*map),
                     JSMapIterator);
}


Handle<JSSetIterator> Factory::NewJSSetIterator() {
  Handle<Map> map(isolate()->native_context()->set_iterator_map());
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateJSObjectFromMap(*map),
                     JSSetIterator);
}


1734 1735 1736 1737 1738 1739
namespace {

ElementsKind GetExternalArrayElementsKind(ExternalArrayType type) {
  switch (type) {
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
  case kExternal##Type##Array:                          \
1740
    return TYPE##_ELEMENTS;
1741 1742 1743
    TYPED_ARRAYS(TYPED_ARRAY_CASE)
  }
  UNREACHABLE();
1744
  return FIRST_FIXED_TYPED_ARRAY_ELEMENTS_KIND;
1745 1746 1747 1748
#undef TYPED_ARRAY_CASE
}


1749 1750 1751 1752 1753 1754
size_t GetExternalArrayElementSize(ExternalArrayType type) {
  switch (type) {
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
  case kExternal##Type##Array:                          \
    return size;
    TYPED_ARRAYS(TYPED_ARRAY_CASE)
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
    default:
      UNREACHABLE();
      return 0;
  }
#undef TYPED_ARRAY_CASE
}


size_t GetFixedTypedArraysElementSize(ElementsKind kind) {
  switch (kind) {
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
  case TYPE##_ELEMENTS:                                 \
    return size;
    TYPED_ARRAYS(TYPED_ARRAY_CASE)
    default:
      UNREACHABLE();
      return 0;
  }
#undef TYPED_ARRAY_CASE
}


ExternalArrayType GetArrayTypeFromElementsKind(ElementsKind kind) {
  switch (kind) {
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
  case TYPE##_ELEMENTS:                                 \
    return kExternal##Type##Array;
    TYPED_ARRAYS(TYPED_ARRAY_CASE)
    default:
      UNREACHABLE();
      return kExternalInt8Array;
1786 1787 1788 1789 1790
  }
#undef TYPED_ARRAY_CASE
}


1791
JSFunction* GetTypedArrayFun(ExternalArrayType type, Isolate* isolate) {
1792
  Context* native_context = isolate->context()->native_context();
1793
  switch (type) {
1794 1795 1796
#define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size)                        \
    case kExternal##Type##Array:                                              \
      return native_context->type##_array_fun();
1797

1798 1799
    TYPED_ARRAYS(TYPED_ARRAY_FUN)
#undef TYPED_ARRAY_FUN
1800

1801 1802
    default:
      UNREACHABLE();
1803
      return NULL;
1804
  }
1805 1806
}

1807

1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
JSFunction* GetTypedArrayFun(ElementsKind elements_kind, Isolate* isolate) {
  Context* native_context = isolate->context()->native_context();
  switch (elements_kind) {
#define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
  case TYPE##_ELEMENTS:                                \
    return native_context->type##_array_fun();

    TYPED_ARRAYS(TYPED_ARRAY_FUN)
#undef TYPED_ARRAY_FUN

    default:
      UNREACHABLE();
      return NULL;
  }
}


1825 1826 1827
void SetupArrayBufferView(i::Isolate* isolate,
                          i::Handle<i::JSArrayBufferView> obj,
                          i::Handle<i::JSArrayBuffer> buffer,
ben's avatar
ben committed
1828 1829
                          size_t byte_offset, size_t byte_length,
                          PretenureFlag pretenure = NOT_TENURED) {
1830 1831 1832 1833 1834 1835
  DCHECK(byte_offset + byte_length <=
         static_cast<size_t>(buffer->byte_length()->Number()));

  obj->set_buffer(*buffer);

  i::Handle<i::Object> byte_offset_object =
ben's avatar
ben committed
1836
      isolate->factory()->NewNumberFromSize(byte_offset, pretenure);
1837 1838 1839
  obj->set_byte_offset(*byte_offset_object);

  i::Handle<i::Object> byte_length_object =
ben's avatar
ben committed
1840
      isolate->factory()->NewNumberFromSize(byte_length, pretenure);
1841 1842 1843 1844
  obj->set_byte_length(*byte_length_object);
}


1845 1846
}  // namespace

1847

ben's avatar
ben committed
1848 1849
Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
                                              PretenureFlag pretenure) {
1850
  Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1851

ben's avatar
ben committed
1852 1853 1854
  CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateJSObject(
                                    *typed_array_fun_handle, pretenure),
                     JSTypedArray);
1855 1856 1857
}


ben's avatar
ben committed
1858 1859
Handle<JSTypedArray> Factory::NewJSTypedArray(ElementsKind elements_kind,
                                              PretenureFlag pretenure) {
1860 1861 1862
  Handle<JSFunction> typed_array_fun_handle(
      GetTypedArrayFun(elements_kind, isolate()));

ben's avatar
ben committed
1863 1864 1865
  CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateJSObject(
                                    *typed_array_fun_handle, pretenure),
                     JSTypedArray);
1866 1867 1868
}


1869 1870
Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
                                              Handle<JSArrayBuffer> buffer,
ben's avatar
ben committed
1871 1872 1873
                                              size_t byte_offset, size_t length,
                                              PretenureFlag pretenure) {
  Handle<JSTypedArray> obj = NewJSTypedArray(type, pretenure);
1874 1875 1876 1877 1878 1879 1880 1881 1882

  size_t element_size = GetExternalArrayElementSize(type);
  ElementsKind elements_kind = GetExternalArrayElementsKind(type);

  CHECK(byte_offset % element_size == 0);

  CHECK(length <= (std::numeric_limits<size_t>::max() / element_size));
  CHECK(length <= static_cast<size_t>(Smi::kMaxValue));
  size_t byte_length = length * element_size;
ben's avatar
ben committed
1883 1884
  SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length,
                       pretenure);
1885

ben's avatar
ben committed
1886
  Handle<Object> length_object = NewNumberFromSize(length, pretenure);
1887 1888
  obj->set_length(*length_object);

1889
  Handle<FixedTypedArrayBase> elements = NewFixedTypedArrayWithExternalPointer(
1890
      static_cast<int>(length), type,
ben's avatar
ben committed
1891
      static_cast<uint8_t*>(buffer->backing_store()) + byte_offset, pretenure);
1892 1893 1894 1895 1896 1897
  Handle<Map> map = JSObject::GetElementsTransitionMap(obj, elements_kind);
  JSObject::SetMapAndElements(obj, map, elements);
  return obj;
}


1898
Handle<JSTypedArray> Factory::NewJSTypedArray(ElementsKind elements_kind,
ben's avatar
ben committed
1899 1900 1901
                                              size_t number_of_elements,
                                              PretenureFlag pretenure) {
  Handle<JSTypedArray> obj = NewJSTypedArray(elements_kind, pretenure);
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912

  size_t element_size = GetFixedTypedArraysElementSize(elements_kind);
  ExternalArrayType array_type = GetArrayTypeFromElementsKind(elements_kind);

  CHECK(number_of_elements <=
        (std::numeric_limits<size_t>::max() / element_size));
  CHECK(number_of_elements <= static_cast<size_t>(Smi::kMaxValue));
  size_t byte_length = number_of_elements * element_size;

  obj->set_byte_offset(Smi::FromInt(0));
  i::Handle<i::Object> byte_length_object =
ben's avatar
ben committed
1913
      NewNumberFromSize(byte_length, pretenure);
1914
  obj->set_byte_length(*byte_length_object);
ben's avatar
ben committed
1915 1916
  Handle<Object> length_object =
      NewNumberFromSize(number_of_elements, pretenure);
1917 1918
  obj->set_length(*length_object);

ben's avatar
ben committed
1919 1920
  Handle<JSArrayBuffer> buffer =
      NewJSArrayBuffer(SharedFlag::kNotShared, pretenure);
1921 1922
  JSArrayBuffer::Setup(buffer, isolate(), true, NULL, byte_length,
                       SharedFlag::kNotShared);
1923
  obj->set_buffer(*buffer);
ben's avatar
ben committed
1924 1925
  Handle<FixedTypedArrayBase> elements = NewFixedTypedArray(
      static_cast<int>(number_of_elements), array_type, true, pretenure);
1926 1927 1928 1929 1930
  obj->set_elements(*elements);
  return obj;
}


1931 1932 1933 1934 1935 1936
Handle<JSDataView> Factory::NewJSDataView(Handle<JSArrayBuffer> buffer,
                                          size_t byte_offset,
                                          size_t byte_length) {
  Handle<JSDataView> obj = NewJSDataView();
  SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
  return obj;
1937 1938 1939
}


1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
MaybeHandle<JSBoundFunction> Factory::NewJSBoundFunction(
    Handle<JSReceiver> target_function, Handle<Object> bound_this,
    Vector<Handle<Object>> bound_args) {
  DCHECK(target_function->IsCallable());
  STATIC_ASSERT(Code::kMaxArguments <= FixedArray::kMaxLength);
  if (bound_args.length() >= Code::kMaxArguments) {
    THROW_NEW_ERROR(isolate(),
                    NewRangeError(MessageTemplate::kTooManyArguments),
                    JSBoundFunction);
  }

  // Determine the prototype of the {target_function}.
  Handle<Object> prototype;
1953 1954 1955
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate(), prototype,
      JSReceiver::GetPrototype(isolate(), target_function), JSBoundFunction);
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992

  // Create the [[BoundArguments]] for the result.
  Handle<FixedArray> bound_arguments;
  if (bound_args.length() == 0) {
    bound_arguments = empty_fixed_array();
  } else {
    bound_arguments = NewFixedArray(bound_args.length());
    for (int i = 0; i < bound_args.length(); ++i) {
      bound_arguments->set(i, *bound_args[i]);
    }
  }

  // Setup the map for the JSBoundFunction instance.
  Handle<Map> map = handle(
      target_function->IsConstructor()
          ? isolate()->native_context()->bound_function_with_constructor_map()
          : isolate()
                ->native_context()
                ->bound_function_without_constructor_map(),
      isolate());
  if (map->prototype() != *prototype) {
    map = Map::TransitionToPrototype(map, prototype, REGULAR_PROTOTYPE);
  }
  DCHECK_EQ(target_function->IsConstructor(), map->is_constructor());

  // Setup the JSBoundFunction instance.
  Handle<JSBoundFunction> result =
      Handle<JSBoundFunction>::cast(NewJSObjectFromMap(map));
  result->set_bound_target_function(*target_function);
  result->set_bound_this(*bound_this);
  result->set_bound_arguments(*bound_arguments);
  result->set_length(Smi::FromInt(0));
  result->set_name(*undefined_value(), SKIP_WRITE_BARRIER);
  return result;
}


1993
// ES6 section 9.5.15 ProxyCreate (target, handler)
1994
Handle<JSProxy> Factory::NewJSProxy(Handle<JSReceiver> target,
1995
                                    Handle<JSReceiver> handler) {
1996
  // Allocate the proxy object.
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
  Handle<Map> map;
  if (target->IsCallable()) {
    if (target->IsConstructor()) {
      map = Handle<Map>(isolate()->proxy_constructor_map());
    } else {
      map = Handle<Map>(isolate()->proxy_callable_map());
    }
  } else {
    map = Handle<Map>(isolate()->proxy_map());
  }
2007
  DCHECK(map->prototype()->IsNull());
2008
  Handle<JSProxy> result = New<JSProxy>(map, NEW_SPACE);
2009
  result->initialize_properties();
2010
  result->set_target(*target);
2011 2012 2013
  result->set_handler(*handler);
  result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
  return result;
2014 2015 2016
}


2017 2018 2019 2020 2021 2022
Handle<JSGlobalProxy> Factory::NewUninitializedJSGlobalProxy() {
  // Create an empty shell of a JSGlobalProxy that needs to be reinitialized
  // via ReinitializeJSGlobalProxy later.
  Handle<Map> map = NewMap(JS_GLOBAL_PROXY_TYPE, JSGlobalProxy::kSize);
  // Maintain invariant expected from any JSGlobalProxy.
  map->set_is_access_check_needed(true);
2023 2024 2025
  CALL_HEAP_FUNCTION(
      isolate(), isolate()->heap()->AllocateJSObjectFromMap(*map, NOT_TENURED),
      JSGlobalProxy);
2026 2027 2028
}


2029 2030
void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
                                        Handle<JSFunction> constructor) {
2031
  DCHECK(constructor->has_initial_map());
2032
  Handle<Map> map(constructor->initial_map(), isolate());
2033
  Handle<Map> old_map(object->map(), isolate());
2034

2035 2036 2037
  // The proxy's hash should be retained across reinitialization.
  Handle<Object> hash(object->hash(), isolate());

2038 2039 2040 2041 2042 2043 2044
  JSObject::InvalidatePrototypeChains(*old_map);
  if (old_map->is_prototype_map()) {
    map = Map::Copy(map, "CopyAsPrototypeForJSGlobalProxy");
    map->set_is_prototype_map(true);
  }
  JSObject::UpdatePrototypeUserRegistration(old_map, map, isolate());

2045 2046
  // Check that the already allocated object has the same size and type as
  // objects allocated using the constructor.
2047 2048
  DCHECK(map->instance_size() == old_map->instance_size());
  DCHECK(map->instance_type() == old_map->instance_type());
2049 2050

  // Allocate the backing storage for the properties.
2051
  Handle<FixedArray> properties = empty_fixed_array();
2052 2053 2054 2055 2056 2057

  // In order to keep heap in consistent state there must be no allocations
  // before object re-initialization is finished.
  DisallowHeapAllocation no_allocation;

  // Reset the map for the object.
2058
  object->synchronized_set_map(*map);
2059 2060 2061 2062

  Heap* heap = isolate()->heap();
  // Reinitialize the object from the constructor map.
  heap->InitializeJSObjectFromMap(*object, *properties, *map);
2063 2064 2065

  // Restore the saved hash.
  object->set_hash(*hash);
2066 2067
}

2068

2069
Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2070 2071
    Handle<String> name, int number_of_literals, FunctionKind kind,
    Handle<Code> code, Handle<ScopeInfo> scope_info,
2072
    Handle<TypeFeedbackVector> feedback_vector) {
2073
  DCHECK(IsValidFunctionKind(kind));
2074 2075
  Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(
      name, code, IsConstructable(kind, scope_info->language_mode()));
2076
  shared->set_scope_info(*scope_info);
2077
  shared->set_feedback_vector(*feedback_vector);
2078
  shared->set_kind(kind);
2079
  shared->set_num_literals(number_of_literals);
2080
  if (IsGeneratorFunction(kind)) {
2081
    shared->set_instance_class_name(isolate()->heap()->Generator_string());
2082
    shared->DisableOptimization(kGenerator);
2083
  }
2084 2085 2086 2087
  return shared;
}


2088
Handle<JSMessageObject> Factory::NewJSMessageObject(
2089 2090
    MessageTemplate::Template message, Handle<Object> argument,
    int start_position, int end_position, Handle<Object> script,
2091
    Handle<Object> stack_frames) {
2092
  Handle<Map> map = message_object_map();
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
  Handle<JSMessageObject> message_obj = New<JSMessageObject>(map, NEW_SPACE);
  message_obj->set_properties(*empty_fixed_array(), SKIP_WRITE_BARRIER);
  message_obj->initialize_elements();
  message_obj->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
  message_obj->set_type(message);
  message_obj->set_argument(*argument);
  message_obj->set_start_position(start_position);
  message_obj->set_end_position(end_position);
  message_obj->set_script(*script);
  message_obj->set_stack_frames(*stack_frames);
  return message_obj;
2104 2105
}

2106

2107
Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2108
    Handle<String> name, MaybeHandle<Code> maybe_code, bool is_constructor) {
2109 2110 2111 2112
  // Function names are assumed to be flat elsewhere. Must flatten before
  // allocating SharedFunctionInfo to avoid GC seeing the uninitialized SFI.
  name = String::Flatten(name, TENURED);

2113
  Handle<Map> map = shared_function_info_map();
2114
  Handle<SharedFunctionInfo> share = New<SharedFunctionInfo>(map, OLD_SPACE);
2115 2116 2117

  // Set pointer fields.
  share->set_name(*name);
2118 2119
  Handle<Code> code;
  if (!maybe_code.ToHandle(&code)) {
2120
    code = isolate()->builtins()->Illegal();
2121 2122
  }
  share->set_code(*code);
2123
  share->set_optimized_code_map(*cleared_optimized_code_map());
2124
  share->set_scope_info(ScopeInfo::Empty(isolate()));
2125 2126 2127 2128
  Handle<Code> construct_stub =
      is_constructor ? isolate()->builtins()->JSConstructStubGeneric()
                     : isolate()->builtins()->ConstructedNonConstructable();
  share->set_construct_stub(*construct_stub);
2129 2130 2131 2132 2133
  share->set_instance_class_name(*Object_string());
  share->set_function_data(*undefined_value(), SKIP_WRITE_BARRIER);
  share->set_script(*undefined_value(), SKIP_WRITE_BARRIER);
  share->set_debug_info(*undefined_value(), SKIP_WRITE_BARRIER);
  share->set_inferred_name(*empty_string(), SKIP_WRITE_BARRIER);
2134
  StaticFeedbackVectorSpec empty_spec;
2135 2136
  Handle<TypeFeedbackMetadata> feedback_metadata =
      TypeFeedbackMetadata::New(isolate(), &empty_spec);
2137 2138 2139
  Handle<TypeFeedbackVector> feedback_vector =
      TypeFeedbackVector::New(isolate(), feedback_metadata);
  share->set_feedback_vector(*feedback_vector, SKIP_WRITE_BARRIER);
2140 2141 2142
#if TRACE_MAPS
  share->set_unique_id(isolate()->GetNextUniqueSharedFunctionInfoId());
#endif
2143
  share->set_profiler_ticks(0);
2144 2145 2146 2147 2148
  share->set_ast_node_count(0);
  share->set_counters(0);

  // Set integer fields (smi or int, depending on the architecture).
  share->set_length(0);
2149
  share->set_internal_formal_parameter_count(0);
2150 2151 2152 2153 2154 2155 2156 2157 2158
  share->set_expected_nof_properties(0);
  share->set_num_literals(0);
  share->set_start_position_and_type(0);
  share->set_end_position(0);
  share->set_function_token_position(0);
  // All compiler hints default to false or 0.
  share->set_compiler_hints(0);
  share->set_opt_count_and_bailout_reason(0);

2159 2160 2161 2162 2163
  // Link into the list.
  Handle<Object> new_noscript_list =
      WeakFixedArray::Add(noscript_shared_function_infos(), share);
  isolate()->heap()->set_noscript_shared_function_infos(*new_noscript_list);

2164
  return share;
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
static inline int NumberCacheHash(Handle<FixedArray> cache,
                                  Handle<Object> number) {
  int mask = (cache->length() >> 1) - 1;
  if (number->IsSmi()) {
    return Handle<Smi>::cast(number)->value() & mask;
  } else {
    DoubleRepresentation rep(number->Number());
    return
        (static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) & mask;
  }
}


Handle<Object> Factory::GetNumberStringCache(Handle<Object> number) {
  DisallowHeapAllocation no_gc;
  int hash = NumberCacheHash(number_string_cache(), number);
  Object* key = number_string_cache()->get(hash * 2);
  if (key == *number || (key->IsHeapNumber() && number->IsHeapNumber() &&
                         key->Number() == number->Number())) {
    return Handle<String>(
        String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
  }
  return undefined_value();
}


void Factory::SetNumberStringCache(Handle<Object> number,
                                   Handle<String> string) {
  int hash = NumberCacheHash(number_string_cache(), number);
  if (number_string_cache()->get(hash * 2) != *undefined_value()) {
    int full_size = isolate()->heap()->FullSizeNumberStringCacheLength();
    if (number_string_cache()->length() != full_size) {
      Handle<FixedArray> new_cache = NewFixedArray(full_size, TENURED);
      isolate()->heap()->set_number_string_cache(*new_cache);
      return;
    }
  }
  number_string_cache()->set(hash * 2, *number);
  number_string_cache()->set(hash * 2 + 1, *string);
}


2210 2211
Handle<String> Factory::NumberToString(Handle<Object> number,
                                       bool check_number_string_cache) {
2212 2213 2214 2215 2216
  isolate()->counters()->number_to_string_runtime()->Increment();
  if (check_number_string_cache) {
    Handle<Object> cached = GetNumberStringCache(number);
    if (!cached->IsUndefined()) return Handle<String>::cast(cached);
  }
2217

2218
  char arr[100];
2219
  Vector<char> buffer(arr, arraysize(arr));
2220 2221 2222 2223 2224 2225 2226 2227
  const char* str;
  if (number->IsSmi()) {
    int num = Handle<Smi>::cast(number)->value();
    str = IntToCString(num, buffer);
  } else {
    double num = Handle<HeapNumber>::cast(number)->value();
    str = DoubleToCString(num, buffer);
  }
2228

2229 2230
  // We tenure the allocated string since it is referenced from the
  // number-string cache which lives in the old space.
2231
  Handle<String> js_string = NewStringFromAsciiChecked(str, TENURED);
2232 2233
  SetNumberStringCache(number, js_string);
  return js_string;
2234 2235 2236
}


2237 2238 2239 2240 2241
Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
  // Allocate initial fixed array for active break points before allocating the
  // debug info object to avoid allocation while setting up the debug info
  // object.
  Handle<FixedArray> break_points(
2242
      NewFixedArray(DebugInfo::kEstimatedNofBreakPointsInFunction));
2243 2244 2245 2246 2247

  // Create and set up the debug info object. Debug info contains function, a
  // copy of the original code, the executing code and initial fixed array for
  // active break points.
  Handle<DebugInfo> debug_info =
2248
      Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
2249
  debug_info->set_shared(*shared);
2250 2251 2252 2253 2254
  if (shared->HasBytecodeArray()) {
    debug_info->set_abstract_code(AbstractCode::cast(shared->bytecode_array()));
  } else {
    debug_info->set_abstract_code(AbstractCode::cast(shared->code()));
  }
2255 2256 2257 2258 2259 2260 2261 2262 2263
  debug_info->set_break_points(*break_points);

  // Link debug info to function.
  shared->set_debug_info(*debug_info);

  return debug_info;
}


2264
Handle<JSObject> Factory::NewArgumentsObject(Handle<JSFunction> callee,
2265
                                             int length) {
2266
  bool strict_mode_callee = is_strict(callee->shared()->language_mode()) ||
2267
                            !callee->shared()->has_simple_parameters();
2268 2269 2270 2271
  Handle<Map> map = strict_mode_callee ? isolate()->strict_arguments_map()
                                       : isolate()->sloppy_arguments_map();
  AllocationSiteUsageContext context(isolate(), Handle<AllocationSite>(),
                                     false);
2272
  DCHECK(!isolate()->has_pending_exception());
2273 2274
  Handle<JSObject> result = NewJSObjectFromMap(map);
  Handle<Smi> value(Smi::FromInt(length), isolate());
2275
  Object::SetProperty(result, length_string(), value, STRICT).Assert();
2276
  if (!strict_mode_callee) {
2277
    Object::SetProperty(result, callee_string(), callee, STRICT).Assert();
2278 2279
  }
  return result;
2280 2281 2282
}


yurys's avatar
yurys committed
2283 2284 2285 2286 2287 2288 2289 2290 2291
Handle<JSWeakMap> Factory::NewJSWeakMap() {
  // TODO(adamk): Currently the map is only created three times per
  // isolate. If it's created more often, the map should be moved into the
  // strong root list.
  Handle<Map> map = NewMap(JS_WEAK_MAP_TYPE, JSWeakMap::kSize);
  return Handle<JSWeakMap>::cast(NewJSObjectFromMap(map));
}


2292
Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
2293
                                               int number_of_properties,
2294
                                               bool is_strong,
2295 2296 2297
                                               bool* is_result_from_cache) {
  const int kMapCacheSize = 128;

2298
  // We do not cache maps for too many properties or when running builtin code.
2299
  if (number_of_properties > kMapCacheSize ||
2300
      isolate()->bootstrapper()->IsActive()) {
2301
    *is_result_from_cache = false;
2302
    Handle<Map> map = Map::Create(isolate(), number_of_properties);
2303
    if (is_strong) map->set_is_strong();
2304
    return map;
2305 2306 2307 2308
  }
  *is_result_from_cache = true;
  if (number_of_properties == 0) {
    // Reuse the initial map of the Object function if the literal has no
2309 2310 2311 2312
    // predeclared properties, or the strong map if strong.
    return handle(is_strong
                      ? context->js_object_strong_map()
                      : context->object_function()->initial_map(), isolate());
2313
  }
2314

2315
  int cache_index = number_of_properties - 1;
2316 2317 2318 2319 2320 2321 2322 2323 2324
  Handle<Object> maybe_cache(is_strong ? context->strong_map_cache()
                                       : context->map_cache(), isolate());
  if (maybe_cache->IsUndefined()) {
    // Allocate the new map cache for the native context.
    maybe_cache = NewFixedArray(kMapCacheSize, TENURED);
    if (is_strong) {
      context->set_strong_map_cache(*maybe_cache);
    } else {
      context->set_map_cache(*maybe_cache);
2325 2326 2327
    }
  } else {
    // Check to see whether there is a matching element in the cache.
2328
    Handle<FixedArray> cache = Handle<FixedArray>::cast(maybe_cache);
2329 2330 2331 2332 2333 2334 2335 2336
    Object* result = cache->get(cache_index);
    if (result->IsWeakCell()) {
      WeakCell* cell = WeakCell::cast(result);
      if (!cell->cleared()) {
        return handle(Map::cast(cell->value()), isolate());
      }
    }
  }
2337 2338 2339 2340
  // Create a new map and add it to the cache.
  Handle<FixedArray> cache = Handle<FixedArray>::cast(maybe_cache);
  Handle<Map> map = Map::Create(isolate(), number_of_properties);
  if (is_strong) map->set_is_strong();
2341 2342
  Handle<WeakCell> cell = NewWeakCell(map);
  cache->set(cache_index, *cell);
2343
  return map;
2344 2345 2346
}


2347 2348 2349 2350 2351 2352 2353
void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
                                JSRegExp::Type type,
                                Handle<String> source,
                                JSRegExp::Flags flags,
                                Handle<Object> data) {
  Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);

2354 2355
  store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
  store->set(JSRegExp::kSourceIndex, *source);
2356
  store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags));
2357 2358 2359 2360
  store->set(JSRegExp::kAtomPatternIndex, *data);
  regexp->set_data(*store);
}

2361

2362 2363 2364 2365 2366 2367
void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
                                    JSRegExp::Type type,
                                    Handle<String> source,
                                    JSRegExp::Flags flags,
                                    int capture_count) {
  Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
2368
  Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
2369 2370
  store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
  store->set(JSRegExp::kSourceIndex, *source);
2371
  store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags));
2372
  store->set(JSRegExp::kIrregexpLatin1CodeIndex, uninitialized);
2373
  store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
2374
  store->set(JSRegExp::kIrregexpLatin1CodeSavedIndex, uninitialized);
2375
  store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
2376 2377 2378 2379 2380 2381 2382
  store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
  store->set(JSRegExp::kIrregexpCaptureCountIndex,
             Smi::FromInt(capture_count));
  regexp->set_data(*store);
}


2383 2384 2385 2386
Handle<Object> Factory::GlobalConstantFor(Handle<Name> name) {
  if (Name::Equals(name, undefined_string())) return undefined_value();
  if (Name::Equals(name, nan_string())) return nan_value();
  if (Name::Equals(name, infinity_string())) return infinity_value();
2387 2388 2389 2390
  return Handle<Object>::null();
}


2391
Handle<Object> Factory::ToBoolean(bool value) {
2392
  return value ? true_value() : false_value();
2393 2394
}

2395

2396 2397
}  // namespace internal
}  // namespace v8