LCOV - code coverage report
Current view: top level - src/heap - factory.cc (source / functions) Hit Total Coverage
Test: app.info Lines: 1525 1602 95.2 %
Date: 2019-04-19 Functions: 242 255 94.9 %

          Line data    Source code
       1             : // Copyright 2014 the V8 project authors. All rights reserved.
       2             : // Use of this source code is governed by a BSD-style license that can be
       3             : // found in the LICENSE file.
       4             : 
       5             : #include "src/heap/factory.h"
       6             : 
       7             : #include "src/accessors.h"
       8             : #include "src/allocation-site-scopes.h"
       9             : #include "src/ast/ast-source-ranges.h"
      10             : #include "src/ast/ast.h"
      11             : #include "src/base/bits.h"
      12             : #include "src/bootstrapper.h"
      13             : #include "src/builtins/constants-table-builder.h"
      14             : #include "src/compiler.h"
      15             : #include "src/conversions.h"
      16             : #include "src/counters.h"
      17             : #include "src/hash-seed-inl.h"
      18             : #include "src/heap/heap-inl.h"
      19             : #include "src/heap/incremental-marking.h"
      20             : #include "src/heap/mark-compact-inl.h"
      21             : #include "src/heap/read-only-heap.h"
      22             : #include "src/ic/handler-configuration-inl.h"
      23             : #include "src/interpreter/interpreter.h"
      24             : #include "src/isolate-inl.h"
      25             : #include "src/log.h"
      26             : #include "src/objects/allocation-site-inl.h"
      27             : #include "src/objects/api-callbacks.h"
      28             : #include "src/objects/arguments-inl.h"
      29             : #include "src/objects/bigint.h"
      30             : #include "src/objects/cell-inl.h"
      31             : #include "src/objects/debug-objects-inl.h"
      32             : #include "src/objects/embedder-data-array-inl.h"
      33             : #include "src/objects/feedback-cell-inl.h"
      34             : #include "src/objects/fixed-array-inl.h"
      35             : #include "src/objects/foreign-inl.h"
      36             : #include "src/objects/frame-array-inl.h"
      37             : #include "src/objects/instance-type-inl.h"
      38             : #include "src/objects/js-array-inl.h"
      39             : #include "src/objects/js-collection-inl.h"
      40             : #include "src/objects/js-generator-inl.h"
      41             : #include "src/objects/js-regexp-inl.h"
      42             : #include "src/objects/js-weak-refs-inl.h"
      43             : #include "src/objects/literal-objects-inl.h"
      44             : #include "src/objects/microtask-inl.h"
      45             : #include "src/objects/module-inl.h"
      46             : #include "src/objects/promise-inl.h"
      47             : #include "src/objects/scope-info.h"
      48             : #include "src/objects/stack-frame-info-inl.h"
      49             : #include "src/objects/struct-inl.h"
      50             : #include "src/objects/template-objects-inl.h"
      51             : #include "src/transitions-inl.h"
      52             : #include "src/unicode-cache.h"
      53             : #include "src/unicode-inl.h"
      54             : 
      55             : namespace v8 {
      56             : namespace internal {
      57             : 
      58             : namespace {
      59             : 
      60             : int ComputeCodeObjectSize(const CodeDesc& desc) {
      61     1906978 :   bool has_unwinding_info = desc.unwinding_info != nullptr;
      62             :   DCHECK((has_unwinding_info && desc.unwinding_info_size > 0) ||
      63             :          (!has_unwinding_info && desc.unwinding_info_size == 0));
      64     1906978 :   int body_size = desc.instr_size;
      65             :   int unwinding_info_size_field_size = kInt64Size;
      66     1906978 :   if (has_unwinding_info) {
      67          27 :     body_size = RoundUp(body_size, kInt64Size) + desc.unwinding_info_size +
      68          27 :                 unwinding_info_size_field_size;
      69             :   }
      70             :   int object_size = Code::SizeFor(RoundUp(body_size, kObjectAlignment));
      71             :   DCHECK(IsAligned(static_cast<intptr_t>(object_size), kCodeAlignment));
      72             :   return object_size;
      73             : }
      74             : 
      75     1906976 : void InitializeCode(Heap* heap, Handle<Code> code, int object_size,
      76             :                     const CodeDesc& desc, Code::Kind kind,
      77             :                     Handle<Object> self_ref, int32_t builtin_index,
      78             :                     Handle<ByteArray> source_position_table,
      79             :                     Handle<DeoptimizationData> deopt_data,
      80             :                     Handle<ByteArray> reloc_info,
      81             :                     Handle<CodeDataContainer> data_container,
      82             :                     bool is_turbofanned, int stack_slots) {
      83             :   DCHECK(IsAligned(code->address(), kCodeAlignment));
      84             :   DCHECK_IMPLIES(
      85             :       !heap->memory_allocator()->code_range().is_empty(),
      86             :       heap->memory_allocator()->code_range().contains(code->address()));
      87             : 
      88             :   constexpr bool kIsNotOffHeapTrampoline = false;
      89     1906976 :   const bool has_unwinding_info = desc.unwinding_info != nullptr;
      90             : 
      91     1906976 :   code->set_raw_instruction_size(desc.instr_size);
      92     1906976 :   code->set_relocation_info(*reloc_info);
      93     5720940 :   code->initialize_flags(kind, has_unwinding_info, is_turbofanned, stack_slots,
      94     1906980 :                          kIsNotOffHeapTrampoline);
      95             :   code->set_builtin_index(builtin_index);
      96     1906980 :   code->set_code_data_container(*data_container);
      97     3813960 :   code->set_deoptimization_data(*deopt_data);
      98     3813960 :   code->set_source_position_table(*source_position_table);
      99     1906980 :   code->set_safepoint_table_offset(desc.safepoint_table_offset);
     100     1906980 :   code->set_handler_table_offset(desc.handler_table_offset);
     101             :   code->set_constant_pool_offset(desc.constant_pool_offset);
     102     1906980 :   code->set_code_comments_offset(desc.code_comments_offset);
     103             : 
     104             :   // Allow self references to created code object by patching the handle to
     105             :   // point to the newly allocated Code object.
     106     1906980 :   if (!self_ref.is_null()) {
     107             :     DCHECK(self_ref->IsOddball());
     108             :     DCHECK(Oddball::cast(*self_ref)->kind() == Oddball::kSelfReferenceMarker);
     109             :     if (FLAG_embedded_builtins) {
     110             :       auto builder = heap->isolate()->builtins_constants_table_builder();
     111      272133 :       if (builder != nullptr) builder->PatchSelfReference(self_ref, code);
     112             :     }
     113      272133 :     *(self_ref.location()) = code->ptr();
     114             :   }
     115             : 
     116             :   // Migrate generated code.
     117             :   // The generated code can contain embedded objects (typically from handles)
     118             :   // in a pointer-to-tagged-value format (i.e. with indirection like a handle)
     119             :   // that are dereferenced during the copy to point directly to the actual heap
     120             :   // objects. These pointers can include references to the code object itself,
     121             :   // through the self_reference parameter.
     122     1906980 :   code->CopyFromNoFlush(heap, desc);
     123             : 
     124     1906979 :   code->clear_padding();
     125             : 
     126             : #ifdef VERIFY_HEAP
     127             :   if (FLAG_verify_heap) code->ObjectVerify(heap->isolate());
     128             : #endif
     129     1906979 : }
     130             : 
     131             : }  // namespace
     132             : 
     133   163446902 : HeapObject Factory::AllocateRawWithImmortalMap(int size,
     134             :                                                AllocationType allocation,
     135             :                                                Map map,
     136             :                                                AllocationAlignment alignment) {
     137             :   HeapObject result = isolate()->heap()->AllocateRawWithRetryOrFail(
     138   163446902 :       size, allocation, alignment);
     139             :   result->set_map_after_allocation(map, SKIP_WRITE_BARRIER);
     140   163446648 :   return result;
     141             : }
     142             : 
     143    21368007 : HeapObject Factory::AllocateRawWithAllocationSite(
     144             :     Handle<Map> map, AllocationType allocation,
     145             :     Handle<AllocationSite> allocation_site) {
     146             :   DCHECK(map->instance_type() != MAP_TYPE);
     147             :   int size = map->instance_size();
     148    21368007 :   if (!allocation_site.is_null()) size += AllocationMemento::kSize;
     149             :   HeapObject result =
     150    21368007 :       isolate()->heap()->AllocateRawWithRetryOrFail(size, allocation);
     151             :   WriteBarrierMode write_barrier_mode = allocation == AllocationType::kYoung
     152             :                                             ? SKIP_WRITE_BARRIER
     153    21368008 :                                             : UPDATE_WRITE_BARRIER;
     154    21368008 :   result->set_map_after_allocation(*map, write_barrier_mode);
     155    21368001 :   if (!allocation_site.is_null()) {
     156             :     AllocationMemento alloc_memento = AllocationMemento::unchecked_cast(
     157       11393 :         Object(result->ptr() + map->instance_size()));
     158       11393 :     InitializeAllocationMemento(alloc_memento, *allocation_site);
     159             :   }
     160    21368001 :   return result;
     161             : }
     162             : 
     163     1514603 : void Factory::InitializeAllocationMemento(AllocationMemento memento,
     164             :                                           AllocationSite allocation_site) {
     165             :   memento->set_map_after_allocation(*allocation_memento_map(),
     166             :                                     SKIP_WRITE_BARRIER);
     167             :   memento->set_allocation_site(allocation_site, SKIP_WRITE_BARRIER);
     168     1514603 :   if (FLAG_allocation_site_pretenuring) {
     169             :     allocation_site->IncrementMementoCreateCount();
     170             :   }
     171     1514603 : }
     172             : 
     173    38247955 : HeapObject Factory::AllocateRawArray(int size, AllocationType allocation) {
     174             :   HeapObject result =
     175    38247955 :       isolate()->heap()->AllocateRawWithRetryOrFail(size, allocation);
     176    38247981 :   if (size > kMaxRegularHeapObjectSize && FLAG_use_marking_progress_bar) {
     177             :     MemoryChunk* chunk = MemoryChunk::FromHeapObject(result);
     178             :     chunk->SetFlag<AccessMode::ATOMIC>(MemoryChunk::HAS_PROGRESS_BAR);
     179             :   }
     180    38247981 :   return result;
     181             : }
     182             : 
     183    34624446 : HeapObject Factory::AllocateRawFixedArray(int length,
     184             :                                           AllocationType allocation) {
     185    34624446 :   if (length < 0 || length > FixedArray::kMaxLength) {
     186           0 :     isolate()->heap()->FatalProcessOutOfMemory("invalid array length");
     187             :   }
     188    34624446 :   return AllocateRawArray(FixedArray::SizeFor(length), allocation);
     189             : }
     190             : 
     191     1539468 : HeapObject Factory::AllocateRawWeakArrayList(int capacity,
     192             :                                              AllocationType allocation) {
     193     1539468 :   if (capacity < 0 || capacity > WeakArrayList::kMaxCapacity) {
     194           0 :     isolate()->heap()->FatalProcessOutOfMemory("invalid array length");
     195             :   }
     196     1539468 :   return AllocateRawArray(WeakArrayList::SizeForCapacity(capacity), allocation);
     197             : }
     198             : 
     199    49749007 : HeapObject Factory::New(Handle<Map> map, AllocationType allocation) {
     200             :   DCHECK(map->instance_type() != MAP_TYPE);
     201             :   int size = map->instance_size();
     202             :   HeapObject result =
     203    49749007 :       isolate()->heap()->AllocateRawWithRetryOrFail(size, allocation);
     204             :   // New space objects are allocated white.
     205             :   WriteBarrierMode write_barrier_mode = allocation == AllocationType::kYoung
     206             :                                             ? SKIP_WRITE_BARRIER
     207    49749006 :                                             : UPDATE_WRITE_BARRIER;
     208    49749006 :   result->set_map_after_allocation(*map, write_barrier_mode);
     209    49748988 :   return result;
     210             : }
     211             : 
     212      232835 : Handle<HeapObject> Factory::NewFillerObject(int size, bool double_align,
     213             :                                             AllocationType allocation) {
     214      232835 :   AllocationAlignment alignment = double_align ? kDoubleAligned : kWordAligned;
     215             :   Heap* heap = isolate()->heap();
     216             :   HeapObject result =
     217      232835 :       heap->AllocateRawWithRetryOrFail(size, allocation, alignment);
     218      232836 :   heap->CreateFillerObjectAt(result->address(), size, ClearRecordedSlots::kNo);
     219      232836 :   return Handle<HeapObject>(result, isolate());
     220             : }
     221             : 
     222      590827 : Handle<PrototypeInfo> Factory::NewPrototypeInfo() {
     223             :   Handle<PrototypeInfo> result = Handle<PrototypeInfo>::cast(
     224      590827 :       NewStruct(PROTOTYPE_INFO_TYPE, AllocationType::kOld));
     225      590829 :   result->set_prototype_users(Smi::kZero);
     226             :   result->set_registry_slot(PrototypeInfo::UNREGISTERED);
     227             :   result->set_bit_field(0);
     228     1181660 :   result->set_module_namespace(*undefined_value());
     229      590831 :   return result;
     230             : }
     231             : 
     232       47009 : Handle<EnumCache> Factory::NewEnumCache(Handle<FixedArray> keys,
     233             :                                         Handle<FixedArray> indices) {
     234             :   Handle<EnumCache> result = Handle<EnumCache>::cast(
     235       47009 :       NewStruct(ENUM_CACHE_TYPE, AllocationType::kOld));
     236       47009 :   result->set_keys(*keys);
     237       47009 :   result->set_indices(*indices);
     238       47009 :   return result;
     239             : }
     240             : 
     241       22454 : Handle<Tuple2> Factory::NewTuple2(Handle<Object> value1, Handle<Object> value2,
     242             :                                   AllocationType allocation) {
     243             :   Handle<Tuple2> result =
     244       22454 :       Handle<Tuple2>::cast(NewStruct(TUPLE2_TYPE, allocation));
     245       22454 :   result->set_value1(*value1);
     246       22454 :   result->set_value2(*value2);
     247       22454 :   return result;
     248             : }
     249             : 
     250           0 : Handle<Tuple3> Factory::NewTuple3(Handle<Object> value1, Handle<Object> value2,
     251             :                                   Handle<Object> value3,
     252             :                                   AllocationType allocation) {
     253             :   Handle<Tuple3> result =
     254           0 :       Handle<Tuple3>::cast(NewStruct(TUPLE3_TYPE, allocation));
     255           0 :   result->set_value1(*value1);
     256           0 :   result->set_value2(*value2);
     257           0 :   result->set_value3(*value3);
     258           0 :   return result;
     259             : }
     260             : 
     261      180665 : Handle<ArrayBoilerplateDescription> Factory::NewArrayBoilerplateDescription(
     262             :     ElementsKind elements_kind, Handle<FixedArrayBase> constant_values) {
     263             :   Handle<ArrayBoilerplateDescription> result =
     264             :       Handle<ArrayBoilerplateDescription>::cast(
     265      180665 :           NewStruct(ARRAY_BOILERPLATE_DESCRIPTION_TYPE, AllocationType::kOld));
     266             :   result->set_elements_kind(elements_kind);
     267      180671 :   result->set_constant_elements(*constant_values);
     268      180670 :   return result;
     269             : }
     270             : 
     271        1749 : Handle<TemplateObjectDescription> Factory::NewTemplateObjectDescription(
     272             :     Handle<FixedArray> raw_strings, Handle<FixedArray> cooked_strings) {
     273             :   DCHECK_EQ(raw_strings->length(), cooked_strings->length());
     274             :   DCHECK_LT(0, raw_strings->length());
     275             :   Handle<TemplateObjectDescription> result =
     276             :       Handle<TemplateObjectDescription>::cast(
     277        1749 :           NewStruct(TUPLE2_TYPE, AllocationType::kOld));
     278        1749 :   result->set_raw_strings(*raw_strings);
     279        1749 :   result->set_cooked_strings(*cooked_strings);
     280        1749 :   return result;
     281             : }
     282             : 
     283         392 : Handle<Oddball> Factory::NewOddball(Handle<Map> map, const char* to_string,
     284             :                                     Handle<Object> to_number,
     285             :                                     const char* type_of, byte kind,
     286             :                                     AllocationType allocation) {
     287         784 :   Handle<Oddball> oddball(Oddball::cast(New(map, allocation)), isolate());
     288         392 :   Oddball::Initialize(isolate(), oddball, to_string, to_number, type_of, kind);
     289         392 :   return oddball;
     290             : }
     291             : 
     292          56 : Handle<Oddball> Factory::NewSelfReferenceMarker(AllocationType allocation) {
     293             :   return NewOddball(self_reference_marker_map(), "self_reference_marker",
     294             :                     handle(Smi::FromInt(-1), isolate()), "undefined",
     295          56 :                     Oddball::kSelfReferenceMarker, allocation);
     296             : }
     297             : 
     298    13223702 : Handle<PropertyArray> Factory::NewPropertyArray(int length,
     299             :                                                 AllocationType allocation) {
     300             :   DCHECK_LE(0, length);
     301    13223702 :   if (length == 0) return empty_property_array();
     302     7441905 :   HeapObject result = AllocateRawFixedArray(length, allocation);
     303             :   result->set_map_after_allocation(*property_array_map(), SKIP_WRITE_BARRIER);
     304             :   Handle<PropertyArray> array(PropertyArray::cast(result), isolate());
     305             :   array->initialize_length(length);
     306             :   MemsetTagged(array->data_start(), *undefined_value(), length);
     307     7441907 :   return array;
     308             : }
     309             : 
     310    22993688 : Handle<FixedArray> Factory::NewFixedArrayWithFiller(RootIndex map_root_index,
     311             :                                                     int length, Object filler,
     312             :                                                     AllocationType allocation) {
     313    22993688 :   HeapObject result = AllocateRawFixedArray(length, allocation);
     314             :   DCHECK(RootsTable::IsImmortalImmovable(map_root_index));
     315             :   Map map = Map::cast(isolate()->root(map_root_index));
     316             :   result->set_map_after_allocation(map, SKIP_WRITE_BARRIER);
     317             :   Handle<FixedArray> array(FixedArray::cast(result), isolate());
     318             :   array->set_length(length);
     319             :   MemsetTagged(array->data_start(), filler, length);
     320    22993682 :   return array;
     321             : }
     322             : 
     323             : template <typename T>
     324     2524204 : Handle<T> Factory::NewFixedArrayWithMap(RootIndex map_root_index, int length,
     325             :                                         AllocationType allocation) {
     326             :   static_assert(std::is_base_of<FixedArray, T>::value,
     327             :                 "T must be a descendant of FixedArray");
     328             :   // Zero-length case must be handled outside, where the knowledge about
     329             :   // the map is.
     330             :   DCHECK_LT(0, length);
     331     5801327 :   return Handle<T>::cast(NewFixedArrayWithFiller(
     332     2524210 :       map_root_index, length, *undefined_value(), allocation));
     333             : }
     334             : 
     335             : template <typename T>
     336      484160 : Handle<T> Factory::NewWeakFixedArrayWithMap(RootIndex map_root_index,
     337             :                                             int length,
     338             :                                             AllocationType allocation) {
     339             :   static_assert(std::is_base_of<WeakFixedArray, T>::value,
     340             :                 "T must be a descendant of WeakFixedArray");
     341             : 
     342             :   // Zero-length case must be handled outside.
     343             :   DCHECK_LT(0, length);
     344             : 
     345             :   HeapObject result =
     346      484160 :       AllocateRawArray(WeakFixedArray::SizeFor(length), allocation);
     347             :   Map map = Map::cast(isolate()->root(map_root_index));
     348             :   result->set_map_after_allocation(map, SKIP_WRITE_BARRIER);
     349             : 
     350             :   Handle<WeakFixedArray> array(WeakFixedArray::cast(result), isolate());
     351             :   array->set_length(length);
     352             :   MemsetTagged(ObjectSlot(array->data_start()), *undefined_value(), length);
     353             : 
     354      484163 :   return Handle<T>::cast(array);
     355             : }
     356             : 
     357             : template Handle<FixedArray> Factory::NewFixedArrayWithMap<FixedArray>(
     358             :     RootIndex, int, AllocationType allocation);
     359             : 
     360    19112329 : Handle<FixedArray> Factory::NewFixedArray(int length,
     361             :                                           AllocationType allocation) {
     362             :   DCHECK_LE(0, length);
     363    19118678 :   if (length == 0) return empty_fixed_array();
     364             :   return NewFixedArrayWithFiller(RootIndex::kFixedArrayMap, length,
     365    12180552 :                                  *undefined_value(), allocation);
     366             : }
     367             : 
     368     1599900 : Handle<WeakFixedArray> Factory::NewWeakFixedArray(int length,
     369             :                                                   AllocationType allocation) {
     370             :   DCHECK_LE(0, length);
     371     1599900 :   if (length == 0) return empty_weak_fixed_array();
     372             :   HeapObject result =
     373     1599900 :       AllocateRawArray(WeakFixedArray::SizeFor(length), allocation);
     374             :   DCHECK(RootsTable::IsImmortalImmovable(RootIndex::kWeakFixedArrayMap));
     375             :   result->set_map_after_allocation(*weak_fixed_array_map(), SKIP_WRITE_BARRIER);
     376             :   Handle<WeakFixedArray> array(WeakFixedArray::cast(result), isolate());
     377             :   array->set_length(length);
     378             :   MemsetTagged(ObjectSlot(array->data_start()), *undefined_value(), length);
     379     1599904 :   return array;
     380             : }
     381             : 
     382      142717 : MaybeHandle<FixedArray> Factory::TryNewFixedArray(
     383             :     int length, AllocationType allocation_type) {
     384             :   DCHECK_LE(0, length);
     385      170410 :   if (length == 0) return empty_fixed_array();
     386             : 
     387             :   int size = FixedArray::SizeFor(length);
     388             :   Heap* heap = isolate()->heap();
     389      115024 :   AllocationResult allocation = heap->AllocateRaw(size, allocation_type);
     390             :   HeapObject result;
     391      115024 :   if (!allocation.To(&result)) return MaybeHandle<FixedArray>();
     392      114963 :   if (size > kMaxRegularHeapObjectSize && FLAG_use_marking_progress_bar) {
     393             :     MemoryChunk* chunk = MemoryChunk::FromHeapObject(result);
     394             :     chunk->SetFlag<AccessMode::ATOMIC>(MemoryChunk::HAS_PROGRESS_BAR);
     395             :   }
     396             :   result->set_map_after_allocation(*fixed_array_map(), SKIP_WRITE_BARRIER);
     397             :   Handle<FixedArray> array(FixedArray::cast(result), isolate());
     398             :   array->set_length(length);
     399             :   MemsetTagged(array->data_start(), ReadOnlyRoots(heap).undefined_value(),
     400             :                length);
     401      114963 :   return array;
     402             : }
     403             : 
     404     2440195 : Handle<FixedArray> Factory::NewFixedArrayWithHoles(int length,
     405             :                                                    AllocationType allocation) {
     406             :   DCHECK_LE(0, length);
     407     2495990 :   if (length == 0) return empty_fixed_array();
     408             :   return NewFixedArrayWithFiller(RootIndex::kFixedArrayMap, length,
     409     3432845 :                                  *the_hole_value(), allocation);
     410             : }
     411             : 
     412     1294130 : Handle<FixedArray> Factory::NewUninitializedFixedArray(
     413             :     int length, AllocationType allocation) {
     414             :   DCHECK_LE(0, length);
     415     1579507 :   if (length == 0) return empty_fixed_array();
     416             : 
     417             :   // TODO(ulan): As an experiment this temporarily returns an initialized fixed
     418             :   // array. After getting canary/performance coverage, either remove the
     419             :   // function or revert to returning uninitilized array.
     420             :   return NewFixedArrayWithFiller(RootIndex::kFixedArrayMap, length,
     421     1578983 :                                  *undefined_value(), allocation);
     422             : }
     423             : 
     424     3102044 : Handle<ClosureFeedbackCellArray> Factory::NewClosureFeedbackCellArray(
     425             :     int length, AllocationType allocation) {
     426     3102044 :   if (length == 0) return empty_closure_feedback_cell_array();
     427             : 
     428             :   Handle<ClosureFeedbackCellArray> feedback_cell_array =
     429             :       NewFixedArrayWithMap<ClosureFeedbackCellArray>(
     430             :           RootIndex::kClosureFeedbackCellArrayMap, length, allocation);
     431             : 
     432     1035586 :   return feedback_cell_array;
     433             : }
     434             : 
     435     3102039 : Handle<FeedbackVector> Factory::NewFeedbackVector(
     436             :     Handle<SharedFunctionInfo> shared,
     437             :     Handle<ClosureFeedbackCellArray> closure_feedback_cell_array,
     438             :     AllocationType allocation) {
     439             :   int length = shared->feedback_metadata()->slot_count();
     440             :   DCHECK_LE(0, length);
     441             :   int size = FeedbackVector::SizeFor(length);
     442             : 
     443             :   HeapObject result =
     444     3102039 :       AllocateRawWithImmortalMap(size, allocation, *feedback_vector_map());
     445             :   Handle<FeedbackVector> vector(FeedbackVector::cast(result), isolate());
     446     3102044 :   vector->set_shared_function_info(*shared);
     447     9306130 :   vector->set_optimized_code_weak_or_smi(MaybeObject::FromSmi(Smi::FromEnum(
     448             :       FLAG_log_function_events ? OptimizationMarker::kLogFirstExecution
     449     3102045 :                                : OptimizationMarker::kNone)));
     450             :   vector->set_length(length);
     451             :   vector->set_invocation_count(0);
     452             :   vector->set_profiler_ticks(0);
     453             :   vector->set_deopt_count(0);
     454     3102040 :   vector->set_closure_feedback_cell_array(*closure_feedback_cell_array);
     455             : 
     456             :   // TODO(leszeks): Initialize based on the feedback metadata.
     457     3102040 :   MemsetTagged(ObjectSlot(vector->slots_start()), *undefined_value(), length);
     458     3102038 :   return vector;
     459             : }
     460             : 
     461       61241 : Handle<EmbedderDataArray> Factory::NewEmbedderDataArray(
     462             :     int length, AllocationType allocation) {
     463             :   DCHECK_LE(0, length);
     464             :   int size = EmbedderDataArray::SizeFor(length);
     465             : 
     466             :   HeapObject result =
     467       61241 :       AllocateRawWithImmortalMap(size, allocation, *embedder_data_array_map());
     468             :   Handle<EmbedderDataArray> array(EmbedderDataArray::cast(result), isolate());
     469             :   array->set_length(length);
     470             : 
     471       61241 :   if (length > 0) {
     472             :     ObjectSlot start(array->slots_start());
     473             :     ObjectSlot end(array->slots_end());
     474             :     size_t slot_count = end - start;
     475             :     MemsetTagged(start, *undefined_value(), slot_count);
     476             :   }
     477       61241 :   return array;
     478             : }
     479             : 
     480      205858 : Handle<ObjectBoilerplateDescription> Factory::NewObjectBoilerplateDescription(
     481             :     int boilerplate, int all_properties, int index_keys, bool has_seen_proto) {
     482             :   DCHECK_GE(boilerplate, 0);
     483             :   DCHECK_GE(all_properties, index_keys);
     484             :   DCHECK_GE(index_keys, 0);
     485             : 
     486             :   int backing_store_size =
     487      205858 :       all_properties - index_keys - (has_seen_proto ? 1 : 0);
     488             :   DCHECK_GE(backing_store_size, 0);
     489             :   bool has_different_size_backing_store = boilerplate != backing_store_size;
     490             : 
     491             :   // Space for name and value for every boilerplate property + LiteralType flag.
     492             :   int size =
     493      205858 :       2 * boilerplate + ObjectBoilerplateDescription::kDescriptionStartIndex;
     494             : 
     495      205858 :   if (has_different_size_backing_store) {
     496             :     // An extra entry for the backing store size.
     497        2771 :     size++;
     498             :   }
     499             : 
     500             :   Handle<ObjectBoilerplateDescription> description =
     501             :       Handle<ObjectBoilerplateDescription>::cast(
     502             :           NewFixedArrayWithMap(RootIndex::kObjectBoilerplateDescriptionMap,
     503      205858 :                                size, AllocationType::kOld));
     504             : 
     505      205864 :   if (has_different_size_backing_store) {
     506             :     DCHECK_IMPLIES((boilerplate == (all_properties - index_keys)),
     507             :                    has_seen_proto);
     508        2771 :     description->set_backing_store_size(isolate(), backing_store_size);
     509             :   }
     510             : 
     511             :   description->set_flags(0);
     512             : 
     513      205864 :   return description;
     514             : }
     515             : 
     516      331390 : Handle<FixedArrayBase> Factory::NewFixedDoubleArray(int length,
     517             :                                                     AllocationType allocation) {
     518      331390 :   if (length == 0) return empty_fixed_array();
     519      331390 :   if (length < 0 || length > FixedDoubleArray::kMaxLength) {
     520           0 :     isolate()->heap()->FatalProcessOutOfMemory("invalid array length");
     521             :   }
     522             :   int size = FixedDoubleArray::SizeFor(length);
     523      331390 :   Map map = *fixed_double_array_map();
     524             :   HeapObject result =
     525      331390 :       AllocateRawWithImmortalMap(size, allocation, map, kDoubleAligned);
     526             :   Handle<FixedDoubleArray> array(FixedDoubleArray::cast(result), isolate());
     527             :   array->set_length(length);
     528      331390 :   return array;
     529             : }
     530             : 
     531          12 : Handle<FixedArrayBase> Factory::NewFixedDoubleArrayWithHoles(
     532             :     int length, AllocationType allocation) {
     533             :   DCHECK_LE(0, length);
     534          12 :   Handle<FixedArrayBase> array = NewFixedDoubleArray(length, allocation);
     535          12 :   if (length > 0) {
     536             :     Handle<FixedDoubleArray>::cast(array)->FillWithHoles(0, length);
     537             :   }
     538          12 :   return array;
     539             : }
     540             : 
     541     1613548 : Handle<FeedbackMetadata> Factory::NewFeedbackMetadata(
     542             :     int slot_count, int feedback_cell_count, AllocationType allocation) {
     543             :   DCHECK_LE(0, slot_count);
     544             :   int size = FeedbackMetadata::SizeFor(slot_count);
     545             :   HeapObject result =
     546     1613548 :       AllocateRawWithImmortalMap(size, allocation, *feedback_metadata_map());
     547             :   Handle<FeedbackMetadata> data(FeedbackMetadata::cast(result), isolate());
     548             :   data->set_slot_count(slot_count);
     549             :   data->set_closure_feedback_cell_count(feedback_cell_count);
     550             : 
     551             :   // Initialize the data section to 0.
     552     1613557 :   int data_size = size - FeedbackMetadata::kHeaderSize;
     553     1613557 :   Address data_start = data->address() + FeedbackMetadata::kHeaderSize;
     554     1613557 :   memset(reinterpret_cast<byte*>(data_start), 0, data_size);
     555             :   // Fields have been zeroed out but not initialized, so this object will not
     556             :   // pass object verification at this point.
     557     1613557 :   return data;
     558             : }
     559             : 
     560     1315670 : Handle<FrameArray> Factory::NewFrameArray(int number_of_frames,
     561             :                                           AllocationType allocation) {
     562             :   DCHECK_LE(0, number_of_frames);
     563             :   Handle<FixedArray> result = NewFixedArrayWithHoles(
     564             :       FrameArray::LengthFor(number_of_frames), allocation);
     565     1315670 :   result->set(FrameArray::kFrameCountIndex, Smi::kZero);
     566     1315670 :   return Handle<FrameArray>::cast(result);
     567             : }
     568             : 
     569             : template <typename T>
     570         443 : Handle<T> Factory::AllocateSmallOrderedHashTable(Handle<Map> map, int capacity,
     571             :                                                  AllocationType allocation) {
     572             :   // Capacity must be a power of two, since we depend on being able
     573             :   // to divide and multiple by 2 (kLoadFactor) to derive capacity
     574             :   // from number of buckets. If we decide to change kLoadFactor
     575             :   // to something other than 2, capacity should be stored as another
     576             :   // field of this object.
     577             :   DCHECK_EQ(T::kLoadFactor, 2);
     578         443 :   capacity = base::bits::RoundUpToPowerOfTwo32(Max(T::kMinCapacity, capacity));
     579             :   capacity = Min(capacity, T::kMaxCapacity);
     580             : 
     581             :   DCHECK_LT(0, capacity);
     582             :   DCHECK_EQ(0, capacity % T::kLoadFactor);
     583             : 
     584             :   int size = T::SizeFor(capacity);
     585         443 :   HeapObject result = AllocateRawWithImmortalMap(size, allocation, *map);
     586             :   Handle<T> table(T::cast(result), isolate());
     587         443 :   table->Initialize(isolate(), capacity);
     588         443 :   return table;
     589             : }
     590             : 
     591         119 : Handle<SmallOrderedHashSet> Factory::NewSmallOrderedHashSet(
     592             :     int capacity, AllocationType allocation) {
     593             :   return AllocateSmallOrderedHashTable<SmallOrderedHashSet>(
     594         119 :       small_ordered_hash_set_map(), capacity, allocation);
     595             : }
     596             : 
     597         119 : Handle<SmallOrderedHashMap> Factory::NewSmallOrderedHashMap(
     598             :     int capacity, AllocationType allocation) {
     599             :   return AllocateSmallOrderedHashTable<SmallOrderedHashMap>(
     600         119 :       small_ordered_hash_map_map(), capacity, allocation);
     601             : }
     602             : 
     603         205 : Handle<SmallOrderedNameDictionary> Factory::NewSmallOrderedNameDictionary(
     604             :     int capacity, AllocationType allocation) {
     605             :   Handle<SmallOrderedNameDictionary> dict =
     606             :       AllocateSmallOrderedHashTable<SmallOrderedNameDictionary>(
     607         205 :           small_ordered_name_dictionary_map(), capacity, allocation);
     608             :   dict->SetHash(PropertyArray::kNoHashSentinel);
     609         205 :   return dict;
     610             : }
     611             : 
     612       80136 : Handle<OrderedHashSet> Factory::NewOrderedHashSet() {
     613       80136 :   return OrderedHashSet::Allocate(isolate(), OrderedHashSet::kMinCapacity);
     614             : }
     615             : 
     616          33 : Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
     617          33 :   return OrderedHashMap::Allocate(isolate(), OrderedHashMap::kMinCapacity);
     618             : }
     619             : 
     620          35 : Handle<OrderedNameDictionary> Factory::NewOrderedNameDictionary() {
     621             :   return OrderedNameDictionary::Allocate(isolate(),
     622          35 :                                          OrderedNameDictionary::kMinCapacity);
     623             : }
     624             : 
     625     1562428 : Handle<AccessorPair> Factory::NewAccessorPair() {
     626             :   Handle<AccessorPair> accessors = Handle<AccessorPair>::cast(
     627     1562428 :       NewStruct(ACCESSOR_PAIR_TYPE, AllocationType::kOld));
     628             :   accessors->set_getter(*null_value(), SKIP_WRITE_BARRIER);
     629             :   accessors->set_setter(*null_value(), SKIP_WRITE_BARRIER);
     630     1562428 :   return accessors;
     631             : }
     632             : 
     633             : // Internalized strings are created in the old generation (data space).
     634    13501880 : Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
     635             :   Utf8StringKey key(string, HashSeed(isolate()));
     636    13501885 :   return InternalizeStringWithKey(&key);
     637             : }
     638             : 
     639       87323 : Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
     640             :   OneByteStringKey key(string, HashSeed(isolate()));
     641       87323 :   return InternalizeStringWithKey(&key);
     642             : }
     643             : 
     644      481079 : Handle<String> Factory::InternalizeOneByteString(
     645             :     Handle<SeqOneByteString> string, int from, int length) {
     646      481079 :   SeqOneByteSubStringKey key(isolate(), string, from, length);
     647      481079 :   return InternalizeStringWithKey(&key);
     648             : }
     649             : 
     650        1035 : Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
     651             :   TwoByteStringKey key(string, HashSeed(isolate()));
     652        1035 :   return InternalizeStringWithKey(&key);
     653             : }
     654             : 
     655             : template <class StringTableKey>
     656             : Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
     657    14071325 :   return StringTable::LookupKey(isolate(), key);
     658             : }
     659             : 
     660    47686099 : MaybeHandle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
     661             :                                                   AllocationType allocation) {
     662             :   DCHECK_NE(allocation, AllocationType::kReadOnly);
     663             :   int length = string.length();
     664    47696492 :   if (length == 0) return empty_string();
     665    47675706 :   if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
     666             :   Handle<SeqOneByteString> result;
     667    94254036 :   ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
     668             :                              NewRawOneByteString(string.length(), allocation),
     669             :                              String);
     670             : 
     671             :   DisallowHeapAllocation no_gc;
     672             :   // Copy the characters into the new object.
     673    47127003 :   CopyChars(SeqOneByteString::cast(*result)->GetChars(no_gc), string.start(),
     674             :             length);
     675    47127003 :   return result;
     676             : }
     677             : 
     678    10282595 : MaybeHandle<String> Factory::NewStringFromUtf8(Vector<const char> string,
     679             :                                                AllocationType allocation) {
     680             :   DCHECK_NE(allocation, AllocationType::kReadOnly);
     681             :   // Check for ASCII first since this is the common case.
     682             :   const char* ascii_data = string.start();
     683             :   int length = string.length();
     684    10282595 :   int non_ascii_start = String::NonAsciiStart(ascii_data, length);
     685    10282595 :   if (non_ascii_start >= length) {
     686             :     // If the string is ASCII, we do not need to convert the characters
     687             :     // since UTF8 is backwards compatible with ASCII.
     688             :     return NewStringFromOneByte(Vector<const uint8_t>::cast(string),
     689    10277155 :                                 allocation);
     690             :   }
     691             : 
     692        5440 :   std::unique_ptr<uint16_t[]> buffer(new uint16_t[length - non_ascii_start]);
     693             : 
     694             :   const uint8_t* cursor =
     695       10880 :       reinterpret_cast<const uint8_t*>(&string[non_ascii_start]);
     696             :   const uint8_t* end = reinterpret_cast<const uint8_t*>(string.end());
     697             : 
     698             :   uint16_t* output_cursor = buffer.get();
     699             : 
     700        5440 :   uint32_t incomplete_char = 0;
     701        5440 :   unibrow::Utf8::State state = unibrow::Utf8::State::kAccept;
     702             : 
     703     6892274 :   while (cursor < end) {
     704             :     unibrow::uchar t =
     705     6886834 :         unibrow::Utf8::ValueOfIncremental(&cursor, &state, &incomplete_char);
     706             : 
     707     6886834 :     if (V8_LIKELY(t <= unibrow::Utf16::kMaxNonSurrogateCharCode)) {
     708     4986218 :       *(output_cursor++) = static_cast<uc16>(t);  // The most frequent case.
     709     1900616 :     } else if (t == unibrow::Utf8::kIncomplete) {
     710             :       continue;
     711             :     } else {
     712      100439 :       *(output_cursor++) = unibrow::Utf16::LeadSurrogate(t);
     713      200878 :       *(output_cursor++) = unibrow::Utf16::TrailSurrogate(t);
     714             :     }
     715             :   }
     716             : 
     717        5440 :   unibrow::uchar t = unibrow::Utf8::ValueOfIncrementalFinish(&state);
     718        5440 :   if (t != unibrow::Utf8::kBufferEmpty) {
     719           6 :     *(output_cursor++) = static_cast<uc16>(t);
     720             :   }
     721             : 
     722             :   DCHECK_LE(output_cursor, buffer.get() + length - non_ascii_start);
     723        5440 :   int utf16_length = static_cast<int>(output_cursor - buffer.get());
     724             :   DCHECK_GT(utf16_length, 0);
     725             : 
     726             :   // Allocate string.
     727             :   Handle<SeqTwoByteString> result;
     728       10880 :   ASSIGN_RETURN_ON_EXCEPTION(
     729             :       isolate(), result,
     730             :       NewRawTwoByteString(non_ascii_start + utf16_length, allocation), String);
     731             : 
     732             :   DCHECK_LE(non_ascii_start + utf16_length, length);
     733             : 
     734             :   DisallowHeapAllocation no_gc;
     735             :   uint16_t* data = result->GetChars(no_gc);
     736             :   CopyChars(data, ascii_data, non_ascii_start);
     737        5440 :   CopyChars(data + non_ascii_start, buffer.get(), utf16_length);
     738             : 
     739        5440 :   return result;
     740             : }
     741             : 
     742          10 : MaybeHandle<String> Factory::NewStringFromUtf8SubString(
     743             :     Handle<SeqOneByteString> str, int begin, int length,
     744             :     AllocationType allocation) {
     745             :   Access<UnicodeCache::Utf8Decoder> decoder(
     746             :       isolate()->unicode_cache()->utf8_decoder());
     747             :   int non_ascii_start;
     748             :   int utf16_length = 0;
     749             :   {
     750             :     DisallowHeapAllocation no_gc;
     751             :     const char* ascii_data =
     752          10 :         reinterpret_cast<const char*>(str->GetChars(no_gc) + begin);
     753          10 :     non_ascii_start = String::NonAsciiStart(ascii_data, length);
     754          10 :     if (non_ascii_start < length) {
     755             :       // Non-ASCII and we need to decode.
     756             :       auto non_ascii = Vector<const char>(ascii_data + non_ascii_start,
     757           5 :                                           length - non_ascii_start);
     758             :       decoder->Reset(non_ascii);
     759             : 
     760           5 :       utf16_length = static_cast<int>(decoder->Utf16Length());
     761             :     }
     762             :   }
     763             : 
     764          10 :   if (non_ascii_start >= length) {
     765             :     // If the string is ASCII, we can just make a substring.
     766             :     // TODO(v8): the allocation flag is ignored in this case.
     767          10 :     return NewSubString(str, begin, begin + length);
     768             :   }
     769             : 
     770             :   DCHECK_GT(utf16_length, 0);
     771             : 
     772             :   // Allocate string.
     773             :   Handle<SeqTwoByteString> result;
     774          10 :   ASSIGN_RETURN_ON_EXCEPTION(
     775             :       isolate(), result,
     776             :       NewRawTwoByteString(non_ascii_start + utf16_length, allocation), String);
     777             : 
     778             :   // Update pointer references, since the original string may have moved after
     779             :   // allocation.
     780             :   DisallowHeapAllocation no_gc;
     781             :   const char* ascii_data =
     782           5 :       reinterpret_cast<const char*>(str->GetChars(no_gc) + begin);
     783             :   auto non_ascii = Vector<const char>(ascii_data + non_ascii_start,
     784           5 :                                       length - non_ascii_start);
     785             : 
     786             :   // Copy ASCII portion.
     787             :   uint16_t* data = result->GetChars(no_gc);
     788           5 :   for (int i = 0; i < non_ascii_start; i++) {
     789           0 :     *data++ = *ascii_data++;
     790             :   }
     791             : 
     792             :   // Now write the remainder.
     793           5 :   decoder->WriteUtf16(data, utf16_length, non_ascii);
     794           5 :   return result;
     795             : }
     796             : 
     797     1270419 : MaybeHandle<String> Factory::NewStringFromTwoByte(const uc16* string,
     798             :                                                   int length,
     799             :                                                   AllocationType allocation) {
     800             :   DCHECK_NE(allocation, AllocationType::kReadOnly);
     801     1270654 :   if (length == 0) return empty_string();
     802     1270184 :   if (String::IsOneByte(string, length)) {
     803     1252866 :     if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
     804             :     Handle<SeqOneByteString> result;
     805     2458957 :     ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
     806             :                                NewRawOneByteString(length, allocation), String);
     807             :     DisallowHeapAllocation no_gc;
     808             :     CopyChars(result->GetChars(no_gc), string, length);
     809     1229481 :     return result;
     810             :   } else {
     811             :     Handle<SeqTwoByteString> result;
     812       34636 :     ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
     813             :                                NewRawTwoByteString(length, allocation), String);
     814             :     DisallowHeapAllocation no_gc;
     815             :     CopyChars(result->GetChars(no_gc), string, length);
     816       17318 :     return result;
     817             :   }
     818             : }
     819             : 
     820     1270419 : MaybeHandle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
     821             :                                                   AllocationType allocation) {
     822     1270419 :   return NewStringFromTwoByte(string.start(), string.length(), allocation);
     823             : }
     824             : 
     825           0 : MaybeHandle<String> Factory::NewStringFromTwoByte(
     826             :     const ZoneVector<uc16>* string, AllocationType allocation) {
     827             :   return NewStringFromTwoByte(string->data(), static_cast<int>(string->size()),
     828           0 :                               allocation);
     829             : }
     830             : 
     831             : namespace {
     832             : 
     833             : bool inline IsOneByte(Vector<const char> str, int chars) {
     834             :   // TODO(dcarney): incorporate Latin-1 check when Latin-1 is supported?
     835             :   return chars == str.length();
     836             : }
     837             : 
     838             : bool inline IsOneByte(Handle<String> str) {
     839             :   return str->IsOneByteRepresentation();
     840             : }
     841             : 
     842             : inline void WriteOneByteData(Vector<const char> vector, uint8_t* chars,
     843             :                              int len) {
     844             :   // Only works for one byte strings.
     845             :   DCHECK(vector.length() == len);
     846             :   MemCopy(chars, vector.start(), len);
     847             : }
     848             : 
     849         495 : inline void WriteTwoByteData(Vector<const char> vector, uint16_t* chars,
     850             :                              int len) {
     851             :   unibrow::Utf8Iterator it = unibrow::Utf8Iterator(vector);
     852       25245 :   while (!it.Done()) {
     853             :     DCHECK_GT(len, 0);
     854             :     len -= 1;
     855             : 
     856       24750 :     uint16_t c = *it;
     857       24750 :     ++it;
     858             :     DCHECK_NE(unibrow::Utf8::kBadChar, c);
     859       24750 :     *chars++ = c;
     860             :   }
     861             :   DCHECK_EQ(len, 0);
     862         495 : }
     863             : 
     864             : inline void WriteOneByteData(Handle<String> s, uint8_t* chars, int len) {
     865             :   DCHECK(s->length() == len);
     866     4733222 :   String::WriteToFlat(*s, chars, 0, len);
     867             : }
     868             : 
     869             : inline void WriteTwoByteData(Handle<String> s, uint16_t* chars, int len) {
     870             :   DCHECK(s->length() == len);
     871       19647 :   String::WriteToFlat(*s, chars, 0, len);
     872             : }
     873             : 
     874             : }  // namespace
     875             : 
     876     9889698 : Handle<SeqOneByteString> Factory::AllocateRawOneByteInternalizedString(
     877             :     int length, uint32_t hash_field) {
     878     9889698 :   CHECK_GE(String::kMaxLength, length);
     879             :   // The canonical empty_string is the only zero-length string we allow.
     880             :   DCHECK_IMPLIES(
     881             :       length == 0,
     882             :       isolate()->roots_table()[RootIndex::kempty_string] == kNullAddress);
     883             : 
     884     9889698 :   Map map = *one_byte_internalized_string_map();
     885             :   int size = SeqOneByteString::SizeFor(length);
     886             :   HeapObject result =
     887             :       AllocateRawWithImmortalMap(size,
     888             :                                  isolate()->heap()->CanAllocateInReadOnlySpace()
     889             :                                      ? AllocationType::kReadOnly
     890             :                                      : AllocationType::kOld,
     891     9889698 :                                  map);
     892             :   Handle<SeqOneByteString> answer(SeqOneByteString::cast(result), isolate());
     893             :   answer->set_length(length);
     894             :   answer->set_hash_field(hash_field);
     895             :   DCHECK_EQ(size, answer->Size());
     896     9889705 :   return answer;
     897             : }
     898             : 
     899       53130 : Handle<String> Factory::AllocateTwoByteInternalizedString(
     900             :     Vector<const uc16> str, uint32_t hash_field) {
     901       53130 :   CHECK_GE(String::kMaxLength, str.length());
     902             :   DCHECK_NE(0, str.length());  // Use Heap::empty_string() instead.
     903             : 
     904       53130 :   Map map = *internalized_string_map();
     905             :   int size = SeqTwoByteString::SizeFor(str.length());
     906             :   HeapObject result =
     907       53130 :       AllocateRawWithImmortalMap(size, AllocationType::kOld, map);
     908             :   Handle<SeqTwoByteString> answer(SeqTwoByteString::cast(result), isolate());
     909             :   answer->set_length(str.length());
     910             :   answer->set_hash_field(hash_field);
     911             :   DCHECK_EQ(size, answer->Size());
     912             :   DisallowHeapAllocation no_gc;
     913             : 
     914             :   // Fill in the characters.
     915       53130 :   MemCopy(answer->GetChars(no_gc), str.start(), str.length() * kUC16Size);
     916             : 
     917       53130 :   return answer;
     918             : }
     919             : 
     920             : template <bool is_one_byte, typename T>
     921     4753367 : Handle<String> Factory::AllocateInternalizedStringImpl(T t, int chars,
     922             :                                                        uint32_t hash_field) {
     923             :   DCHECK_LE(0, chars);
     924             :   DCHECK_GE(String::kMaxLength, chars);
     925             : 
     926             :   // Compute map and object size.
     927             :   int size;
     928             :   Map map;
     929             :   if (is_one_byte) {
     930     4733225 :     map = *one_byte_internalized_string_map();
     931             :     size = SeqOneByteString::SizeFor(chars);
     932             :   } else {
     933       20142 :     map = *internalized_string_map();
     934             :     size = SeqTwoByteString::SizeFor(chars);
     935             :   }
     936             : 
     937             :   HeapObject result =
     938     4753367 :       AllocateRawWithImmortalMap(size,
     939             :                                  isolate()->heap()->CanAllocateInReadOnlySpace()
     940             :                                      ? AllocationType::kReadOnly
     941             :                                      : AllocationType::kOld,
     942     4753367 :                                  map);
     943             :   Handle<String> answer(String::cast(result), isolate());
     944             :   answer->set_length(chars);
     945             :   answer->set_hash_field(hash_field);
     946             :   DCHECK_EQ(size, answer->Size());
     947             :   DisallowHeapAllocation no_gc;
     948             : 
     949             :   if (is_one_byte) {
     950             :     WriteOneByteData(t, SeqOneByteString::cast(*answer)->GetChars(no_gc),
     951             :                      chars);
     952             :   } else {
     953         495 :     WriteTwoByteData(t, SeqTwoByteString::cast(*answer)->GetChars(no_gc),
     954             :                      chars);
     955             :   }
     956     4753365 :   return answer;
     957             : }
     958             : 
     959      730527 : Handle<String> Factory::NewInternalizedStringFromUtf8(Vector<const char> str,
     960             :                                                       int chars,
     961             :                                                       uint32_t hash_field) {
     962      730527 :   if (IsOneByte(str, chars)) {
     963             :     Handle<SeqOneByteString> result =
     964      730032 :         AllocateRawOneByteInternalizedString(str.length(), hash_field);
     965             :     DisallowHeapAllocation no_allocation;
     966      730034 :     MemCopy(result->GetChars(no_allocation), str.start(), str.length());
     967      730034 :     return result;
     968             :   }
     969         495 :   return AllocateInternalizedStringImpl<false>(str, chars, hash_field);
     970             : }
     971             : 
     972     8678593 : Handle<String> Factory::NewOneByteInternalizedString(Vector<const uint8_t> str,
     973             :                                                      uint32_t hash_field) {
     974             :   Handle<SeqOneByteString> result =
     975     8678593 :       AllocateRawOneByteInternalizedString(str.length(), hash_field);
     976             :   DisallowHeapAllocation no_allocation;
     977     8678589 :   MemCopy(result->GetChars(no_allocation), str.start(), str.length());
     978     8678589 :   return result;
     979             : }
     980             : 
     981      481079 : Handle<String> Factory::NewOneByteInternalizedSubString(
     982             :     Handle<SeqOneByteString> string, int offset, int length,
     983             :     uint32_t hash_field) {
     984             :   Handle<SeqOneByteString> result =
     985      481079 :       AllocateRawOneByteInternalizedString(length, hash_field);
     986             :   DisallowHeapAllocation no_allocation;
     987      962158 :   MemCopy(result->GetChars(no_allocation),
     988             :           string->GetChars(no_allocation) + offset, length);
     989      481079 :   return result;
     990             : }
     991             : 
     992       53130 : Handle<String> Factory::NewTwoByteInternalizedString(Vector<const uc16> str,
     993             :                                                      uint32_t hash_field) {
     994       53130 :   return AllocateTwoByteInternalizedString(str, hash_field);
     995             : }
     996             : 
     997     4752873 : Handle<String> Factory::NewInternalizedStringImpl(Handle<String> string,
     998             :                                                   int chars,
     999             :                                                   uint32_t hash_field) {
    1000     4752873 :   if (IsOneByte(string)) {
    1001     4733226 :     return AllocateInternalizedStringImpl<true>(string, chars, hash_field);
    1002             :   }
    1003       19647 :   return AllocateInternalizedStringImpl<false>(string, chars, hash_field);
    1004             : }
    1005             : 
    1006             : namespace {
    1007             : 
    1008       56877 : MaybeHandle<Map> GetInternalizedStringMap(Factory* f, Handle<String> string) {
    1009       56877 :   switch (string->map()->instance_type()) {
    1010             :     case STRING_TYPE:
    1011         317 :       return f->internalized_string_map();
    1012             :     case ONE_BYTE_STRING_TYPE:
    1013       56511 :       return f->one_byte_internalized_string_map();
    1014             :     case EXTERNAL_STRING_TYPE:
    1015          11 :       return f->external_internalized_string_map();
    1016             :     case EXTERNAL_ONE_BYTE_STRING_TYPE:
    1017          16 :       return f->external_one_byte_internalized_string_map();
    1018             :     case UNCACHED_EXTERNAL_STRING_TYPE:
    1019           0 :       return f->uncached_external_internalized_string_map();
    1020             :     case UNCACHED_EXTERNAL_ONE_BYTE_STRING_TYPE:
    1021           5 :       return f->uncached_external_one_byte_internalized_string_map();
    1022             :     default:
    1023          17 :       return MaybeHandle<Map>();  // No match found.
    1024             :   }
    1025             : }
    1026             : 
    1027             : }  // namespace
    1028             : 
    1029     4809732 : MaybeHandle<Map> Factory::InternalizedStringMapForString(
    1030             :     Handle<String> string) {
    1031             :   // If the string is in the young generation, it cannot be used as
    1032             :   // internalized.
    1033     4809732 :   if (Heap::InYoungGeneration(*string)) return MaybeHandle<Map>();
    1034             : 
    1035       56872 :   return GetInternalizedStringMap(this, string);
    1036             : }
    1037             : 
    1038             : template <class StringClass>
    1039           5 : Handle<StringClass> Factory::InternalizeExternalString(Handle<String> string) {
    1040             :   Handle<StringClass> cast_string = Handle<StringClass>::cast(string);
    1041          10 :   Handle<Map> map = GetInternalizedStringMap(this, string).ToHandleChecked();
    1042             :   Handle<StringClass> external_string(
    1043          10 :       StringClass::cast(New(map, AllocationType::kOld)), isolate());
    1044             :   external_string->set_length(cast_string->length());
    1045             :   external_string->set_hash_field(cast_string->hash_field());
    1046           5 :   external_string->SetResource(isolate(), nullptr);
    1047             :   isolate()->heap()->RegisterExternalString(*external_string);
    1048           5 :   return external_string;
    1049             : }
    1050             : 
    1051             : template Handle<ExternalOneByteString>
    1052             :     Factory::InternalizeExternalString<ExternalOneByteString>(Handle<String>);
    1053             : template Handle<ExternalTwoByteString>
    1054             :     Factory::InternalizeExternalString<ExternalTwoByteString>(Handle<String>);
    1055             : 
    1056    79560919 : MaybeHandle<SeqOneByteString> Factory::NewRawOneByteString(
    1057             :     int length, AllocationType allocation) {
    1058    79560919 :   if (length > String::kMaxLength || length < 0) {
    1059          19 :     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqOneByteString);
    1060             :   }
    1061             :   DCHECK_GT(length, 0);  // Use Factory::empty_string() instead.
    1062             :   int size = SeqOneByteString::SizeFor(length);
    1063             :   DCHECK_GE(SeqOneByteString::kMaxSize, size);
    1064             : 
    1065             :   HeapObject result =
    1066    79560900 :       AllocateRawWithImmortalMap(size, allocation, *one_byte_string_map());
    1067             :   Handle<SeqOneByteString> string(SeqOneByteString::cast(result), isolate());
    1068             :   string->set_length(length);
    1069             :   string->set_hash_field(String::kEmptyHashField);
    1070             :   DCHECK_EQ(size, string->Size());
    1071    79560885 :   return string;
    1072             : }
    1073             : 
    1074    10542301 : MaybeHandle<SeqTwoByteString> Factory::NewRawTwoByteString(
    1075             :     int length, AllocationType allocation) {
    1076    10542301 :   if (length > String::kMaxLength || length < 0) {
    1077           0 :     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqTwoByteString);
    1078             :   }
    1079             :   DCHECK_GT(length, 0);  // Use Factory::empty_string() instead.
    1080             :   int size = SeqTwoByteString::SizeFor(length);
    1081             :   DCHECK_GE(SeqTwoByteString::kMaxSize, size);
    1082             : 
    1083             :   HeapObject result =
    1084    10542301 :       AllocateRawWithImmortalMap(size, allocation, *string_map());
    1085             :   Handle<SeqTwoByteString> string(SeqTwoByteString::cast(result), isolate());
    1086             :   string->set_length(length);
    1087             :   string->set_hash_field(String::kEmptyHashField);
    1088             :   DCHECK_EQ(size, string->Size());
    1089    10542301 :   return string;
    1090             : }
    1091             : 
    1092     1154539 : Handle<String> Factory::LookupSingleCharacterStringFromCode(uint32_t code) {
    1093     1154539 :   if (code <= String::kMaxOneByteCharCodeU) {
    1094             :     {
    1095             :       DisallowHeapAllocation no_allocation;
    1096     1154226 :       Object value = single_character_string_cache()->get(code);
    1097     1154226 :       if (value != *undefined_value()) {
    1098             :         return handle(String::cast(value), isolate());
    1099             :       }
    1100             :     }
    1101             :     uint8_t buffer[1];
    1102       49112 :     buffer[0] = static_cast<uint8_t>(code);
    1103             :     Handle<String> result =
    1104       49112 :         InternalizeOneByteString(Vector<const uint8_t>(buffer, 1));
    1105       98224 :     single_character_string_cache()->set(code, *result);
    1106       49112 :     return result;
    1107             :   }
    1108             :   DCHECK_LE(code, String::kMaxUtf16CodeUnitU);
    1109             : 
    1110         626 :   Handle<SeqTwoByteString> result = NewRawTwoByteString(1).ToHandleChecked();
    1111             :   result->SeqTwoByteStringSet(0, static_cast<uint16_t>(code));
    1112         313 :   return result;
    1113             : }
    1114             : 
    1115             : // Returns true for a character in a range.  Both limits are inclusive.
    1116             : static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
    1117             :   // This makes uses of the the unsigned wraparound.
    1118     1707415 :   return character - from <= to - from;
    1119             : }
    1120             : 
    1121     1706399 : static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
    1122             :                                                           uint16_t c1,
    1123             :                                                           uint16_t c2) {
    1124             :   // Numeric strings have a different hash algorithm not known by
    1125             :   // LookupTwoCharsStringIfExists, so we skip this step for such strings.
    1126     3413814 :   if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
    1127             :     Handle<String> result;
    1128     3412060 :     if (StringTable::LookupTwoCharsStringIfExists(isolate, c1, c2)
    1129             :             .ToHandle(&result)) {
    1130       13646 :       return result;
    1131             :     }
    1132             :   }
    1133             : 
    1134             :   // Now we know the length is 2, we might as well make use of that fact
    1135             :   // when building the new string.
    1136     1692753 :   if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
    1137             :     // We can do this.
    1138             :     DCHECK(base::bits::IsPowerOfTwo(String::kMaxOneByteCharCodeU +
    1139             :                                     1));  // because of this.
    1140             :     Handle<SeqOneByteString> str =
    1141      910672 :         isolate->factory()->NewRawOneByteString(2).ToHandleChecked();
    1142             :     DisallowHeapAllocation no_allocation;
    1143             :     uint8_t* dest = str->GetChars(no_allocation);
    1144      455336 :     dest[0] = static_cast<uint8_t>(c1);
    1145      455336 :     dest[1] = static_cast<uint8_t>(c2);
    1146      455336 :     return str;
    1147             :   } else {
    1148             :     Handle<SeqTwoByteString> str =
    1149     2474834 :         isolate->factory()->NewRawTwoByteString(2).ToHandleChecked();
    1150             :     DisallowHeapAllocation no_allocation;
    1151             :     uc16* dest = str->GetChars(no_allocation);
    1152     1237417 :     dest[0] = c1;
    1153     1237417 :     dest[1] = c2;
    1154     1237417 :     return str;
    1155             :   }
    1156             : }
    1157             : 
    1158             : template <typename SinkChar, typename StringType>
    1159     5605596 : Handle<String> ConcatStringContent(Handle<StringType> result,
    1160             :                                    Handle<String> first,
    1161             :                                    Handle<String> second) {
    1162             :   DisallowHeapAllocation pointer_stays_valid;
    1163             :   SinkChar* sink = result->GetChars(pointer_stays_valid);
    1164     5605596 :   String::WriteToFlat(*first, sink, 0, first->length());
    1165     5605596 :   String::WriteToFlat(*second, sink + first->length(), 0, second->length());
    1166     5605596 :   return result;
    1167             : }
    1168             : 
    1169    33008260 : MaybeHandle<String> Factory::NewConsString(Handle<String> left,
    1170             :                                            Handle<String> right) {
    1171    33008260 :   if (left->IsThinString()) {
    1172             :     left = handle(Handle<ThinString>::cast(left)->actual(), isolate());
    1173             :   }
    1174    33008277 :   if (right->IsThinString()) {
    1175             :     right = handle(Handle<ThinString>::cast(right)->actual(), isolate());
    1176             :   }
    1177             :   int left_length = left->length();
    1178    33008277 :   if (left_length == 0) return right;
    1179             :   int right_length = right->length();
    1180    24237836 :   if (right_length == 0) return left;
    1181             : 
    1182    22375714 :   int length = left_length + right_length;
    1183             : 
    1184    22375714 :   if (length == 2) {
    1185             :     uint16_t c1 = left->Get(0);
    1186             :     uint16_t c2 = right->Get(0);
    1187     1244354 :     return MakeOrFindTwoCharacterString(isolate(), c1, c2);
    1188             :   }
    1189             : 
    1190             :   // Make sure that an out of memory exception is thrown if the length
    1191             :   // of the new cons string is too large.
    1192    21131360 :   if (length > String::kMaxLength || length < 0) {
    1193         187 :     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
    1194             :   }
    1195             : 
    1196             :   bool left_is_one_byte = left->IsOneByteRepresentation();
    1197             :   bool right_is_one_byte = right->IsOneByteRepresentation();
    1198    21131173 :   bool is_one_byte = left_is_one_byte && right_is_one_byte;
    1199             : 
    1200             :   // If the resulting string is small make a flat string.
    1201    21131173 :   if (length < ConsString::kMinLength) {
    1202             :     // Note that neither of the two inputs can be a slice because:
    1203             :     STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
    1204             :     DCHECK(left->IsFlat());
    1205             :     DCHECK(right->IsFlat());
    1206             : 
    1207             :     STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
    1208     8484008 :     if (is_one_byte) {
    1209             :       Handle<SeqOneByteString> result =
    1210     5756824 :           NewRawOneByteString(length).ToHandleChecked();
    1211             :       DisallowHeapAllocation no_gc;
    1212             :       uint8_t* dest = result->GetChars(no_gc);
    1213             :       // Copy left part.
    1214             :       const uint8_t* src =
    1215             :           left->IsExternalString()
    1216             :               ? Handle<ExternalOneByteString>::cast(left)->GetChars()
    1217     2878412 :               : Handle<SeqOneByteString>::cast(left)->GetChars(no_gc);
    1218    14711272 :       for (int i = 0; i < left_length; i++) *dest++ = src[i];
    1219             :       // Copy right part.
    1220             :       src = right->IsExternalString()
    1221             :                 ? Handle<ExternalOneByteString>::cast(right)->GetChars()
    1222     2878413 :                 : Handle<SeqOneByteString>::cast(right)->GetChars(no_gc);
    1223    12495738 :       for (int i = 0; i < right_length; i++) *dest++ = src[i];
    1224     2878412 :       return result;
    1225             :     }
    1226             : 
    1227             :     return ConcatStringContent<uc16>(
    1228    11211192 :         NewRawTwoByteString(length).ToHandleChecked(), left, right);
    1229             :   }
    1230             : 
    1231    12647165 :   return NewConsString(left, right, length, is_one_byte);
    1232             : }
    1233             : 
    1234    12647174 : Handle<String> Factory::NewConsString(Handle<String> left, Handle<String> right,
    1235             :                                       int length, bool one_byte) {
    1236             :   DCHECK(!left->IsThinString());
    1237             :   DCHECK(!right->IsThinString());
    1238             :   DCHECK_GE(length, ConsString::kMinLength);
    1239             :   DCHECK_LE(length, String::kMaxLength);
    1240             : 
    1241             :   Handle<ConsString> result(
    1242             :       ConsString::cast(
    1243             :           one_byte ? New(cons_one_byte_string_map(), AllocationType::kYoung)
    1244             :                    : New(cons_string_map(), AllocationType::kYoung)),
    1245    37941519 :       isolate());
    1246             : 
    1247             :   DisallowHeapAllocation no_gc;
    1248             :   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
    1249             : 
    1250             :   result->set_hash_field(String::kEmptyHashField);
    1251             :   result->set_length(length);
    1252    12647171 :   result->set_first(isolate(), *left, mode);
    1253    12647172 :   result->set_second(isolate(), *right, mode);
    1254    12647173 :   return result;
    1255             : }
    1256             : 
    1257           0 : Handle<String> Factory::NewSurrogatePairString(uint16_t lead, uint16_t trail) {
    1258             :   DCHECK_GE(lead, 0xD800);
    1259             :   DCHECK_LE(lead, 0xDBFF);
    1260             :   DCHECK_GE(trail, 0xDC00);
    1261             :   DCHECK_LE(trail, 0xDFFF);
    1262             : 
    1263             :   Handle<SeqTwoByteString> str =
    1264           0 :       isolate()->factory()->NewRawTwoByteString(2).ToHandleChecked();
    1265             :   DisallowHeapAllocation no_allocation;
    1266             :   uc16* dest = str->GetChars(no_allocation);
    1267           0 :   dest[0] = lead;
    1268           0 :   dest[1] = trail;
    1269           0 :   return str;
    1270             : }
    1271             : 
    1272     3015241 : Handle<String> Factory::NewProperSubString(Handle<String> str, int begin,
    1273             :                                            int end) {
    1274             : #if VERIFY_HEAP
    1275             :   if (FLAG_verify_heap) str->StringVerify(isolate());
    1276             : #endif
    1277             :   DCHECK(begin > 0 || end < str->length());
    1278             : 
    1279     3015241 :   str = String::Flatten(isolate(), str);
    1280             : 
    1281     3015241 :   int length = end - begin;
    1282     3015241 :   if (length <= 0) return empty_string();
    1283     2993420 :   if (length == 1) {
    1284      498760 :     return LookupSingleCharacterStringFromCode(str->Get(begin));
    1285             :   }
    1286     2494660 :   if (length == 2) {
    1287             :     // Optimization for 2-byte strings often used as keys in a decompression
    1288             :     // dictionary.  Check whether we already have the string in the string
    1289             :     // table to prevent creation of many unnecessary strings.
    1290             :     uint16_t c1 = str->Get(begin);
    1291      462045 :     uint16_t c2 = str->Get(begin + 1);
    1292      462045 :     return MakeOrFindTwoCharacterString(isolate(), c1, c2);
    1293             :   }
    1294             : 
    1295     2032615 :   if (!FLAG_string_slices || length < SlicedString::kMinLength) {
    1296      113333 :     if (str->IsOneByteRepresentation()) {
    1297             :       Handle<SeqOneByteString> result =
    1298      225200 :           NewRawOneByteString(length).ToHandleChecked();
    1299             :       DisallowHeapAllocation no_gc;
    1300             :       uint8_t* dest = result->GetChars(no_gc);
    1301      112600 :       String::WriteToFlat(*str, dest, begin, end);
    1302      112600 :       return result;
    1303             :     } else {
    1304             :       Handle<SeqTwoByteString> result =
    1305        1466 :           NewRawTwoByteString(length).ToHandleChecked();
    1306             :       DisallowHeapAllocation no_gc;
    1307             :       uc16* dest = result->GetChars(no_gc);
    1308         733 :       String::WriteToFlat(*str, dest, begin, end);
    1309         733 :       return result;
    1310             :     }
    1311             :   }
    1312             : 
    1313             :   int offset = begin;
    1314             : 
    1315     1919282 :   if (str->IsSlicedString()) {
    1316             :     Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
    1317             :     str = Handle<String>(slice->parent(), isolate());
    1318        1377 :     offset += slice->offset();
    1319             :   }
    1320     1919282 :   if (str->IsThinString()) {
    1321             :     Handle<ThinString> thin = Handle<ThinString>::cast(str);
    1322             :     str = handle(thin->actual(), isolate());
    1323             :   }
    1324             : 
    1325             :   DCHECK(str->IsSeqString() || str->IsExternalString());
    1326             :   Handle<Map> map = str->IsOneByteRepresentation()
    1327             :                         ? sliced_one_byte_string_map()
    1328     3838564 :                         : sliced_string_map();
    1329             :   Handle<SlicedString> slice(
    1330     3838564 :       SlicedString::cast(New(map, AllocationType::kYoung)), isolate());
    1331             : 
    1332             :   slice->set_hash_field(String::kEmptyHashField);
    1333             :   slice->set_length(length);
    1334     1919282 :   slice->set_parent(isolate(), *str);
    1335             :   slice->set_offset(offset);
    1336     1919282 :   return slice;
    1337             : }
    1338             : 
    1339        6008 : MaybeHandle<String> Factory::NewExternalStringFromOneByte(
    1340             :     const ExternalOneByteString::Resource* resource) {
    1341        6008 :   size_t length = resource->length();
    1342        6008 :   if (length > static_cast<size_t>(String::kMaxLength)) {
    1343           5 :     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
    1344             :   }
    1345        6013 :   if (length == 0) return empty_string();
    1346             : 
    1347        5993 :   Handle<Map> map = resource->IsCacheable()
    1348             :                         ? external_one_byte_string_map()
    1349       11986 :                         : uncached_external_one_byte_string_map();
    1350             :   Handle<ExternalOneByteString> external_string(
    1351       11987 :       ExternalOneByteString::cast(New(map, AllocationType::kOld)), isolate());
    1352        5994 :   external_string->set_length(static_cast<int>(length));
    1353             :   external_string->set_hash_field(String::kEmptyHashField);
    1354        5994 :   external_string->SetResource(isolate(), resource);
    1355             :   isolate()->heap()->RegisterExternalString(*external_string);
    1356             : 
    1357        5995 :   return external_string;
    1358             : }
    1359             : 
    1360       18934 : MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
    1361             :     const ExternalTwoByteString::Resource* resource) {
    1362       18934 :   size_t length = resource->length();
    1363       18934 :   if (length > static_cast<size_t>(String::kMaxLength)) {
    1364           5 :     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
    1365             :   }
    1366       18934 :   if (length == 0) return empty_string();
    1367             : 
    1368       18924 :   Handle<Map> map = resource->IsCacheable() ? external_string_map()
    1369       37848 :                                             : uncached_external_string_map();
    1370             :   Handle<ExternalTwoByteString> external_string(
    1371       37848 :       ExternalTwoByteString::cast(New(map, AllocationType::kOld)), isolate());
    1372       18924 :   external_string->set_length(static_cast<int>(length));
    1373             :   external_string->set_hash_field(String::kEmptyHashField);
    1374       18924 :   external_string->SetResource(isolate(), resource);
    1375             :   isolate()->heap()->RegisterExternalString(*external_string);
    1376             : 
    1377       18924 :   return external_string;
    1378             : }
    1379             : 
    1380         111 : Handle<ExternalOneByteString> Factory::NewNativeSourceString(
    1381             :     const ExternalOneByteString::Resource* resource) {
    1382         111 :   size_t length = resource->length();
    1383             :   DCHECK_LE(length, static_cast<size_t>(String::kMaxLength));
    1384             : 
    1385         111 :   Handle<Map> map = native_source_string_map();
    1386             :   Handle<ExternalOneByteString> external_string(
    1387         222 :       ExternalOneByteString::cast(New(map, AllocationType::kOld)), isolate());
    1388         111 :   external_string->set_length(static_cast<int>(length));
    1389             :   external_string->set_hash_field(String::kEmptyHashField);
    1390         111 :   external_string->SetResource(isolate(), resource);
    1391             :   isolate()->heap()->RegisterExternalString(*external_string);
    1392             : 
    1393         111 :   return external_string;
    1394             : }
    1395             : 
    1396           0 : Handle<JSStringIterator> Factory::NewJSStringIterator(Handle<String> string) {
    1397           0 :   Handle<Map> map(isolate()->native_context()->initial_string_iterator_map(),
    1398           0 :                   isolate());
    1399           0 :   Handle<String> flat_string = String::Flatten(isolate(), string);
    1400             :   Handle<JSStringIterator> iterator =
    1401           0 :       Handle<JSStringIterator>::cast(NewJSObjectFromMap(map));
    1402           0 :   iterator->set_string(*flat_string);
    1403             :   iterator->set_index(0);
    1404             : 
    1405           0 :   return iterator;
    1406             : }
    1407             : 
    1408       18216 : Handle<Symbol> Factory::NewSymbol(AllocationType allocation) {
    1409             :   DCHECK(allocation != AllocationType::kYoung);
    1410             :   // Statically ensure that it is safe to allocate symbols in paged spaces.
    1411             :   STATIC_ASSERT(Symbol::kSize <= kMaxRegularHeapObjectSize);
    1412             : 
    1413             :   HeapObject result =
    1414       18216 :       AllocateRawWithImmortalMap(Symbol::kSize, allocation, *symbol_map());
    1415             : 
    1416             :   // Generate a random hash value.
    1417       18216 :   int hash = isolate()->GenerateIdentityHash(Name::kHashBitMask);
    1418             : 
    1419             :   Handle<Symbol> symbol(Symbol::cast(result), isolate());
    1420       18216 :   symbol->set_hash_field(Name::kIsNotArrayIndexMask |
    1421       18216 :                          (hash << Name::kHashShift));
    1422       36432 :   symbol->set_name(*undefined_value());
    1423             :   symbol->set_flags(0);
    1424             :   DCHECK(!symbol->is_private());
    1425       18216 :   return symbol;
    1426             : }
    1427             : 
    1428        4904 : Handle<Symbol> Factory::NewPrivateSymbol(AllocationType allocation) {
    1429             :   DCHECK(allocation != AllocationType::kYoung);
    1430        4904 :   Handle<Symbol> symbol = NewSymbol(allocation);
    1431             :   symbol->set_is_private(true);
    1432        4904 :   return symbol;
    1433             : }
    1434             : 
    1435         988 : Handle<Symbol> Factory::NewPrivateNameSymbol(Handle<String> name) {
    1436         988 :   Handle<Symbol> symbol = NewSymbol();
    1437             :   symbol->set_is_private_name();
    1438        1976 :   symbol->set_name(*name);
    1439         988 :   return symbol;
    1440             : }
    1441             : 
    1442     1276655 : Handle<Context> Factory::NewContext(RootIndex map_root_index, int size,
    1443             :                                     int variadic_part_length,
    1444             :                                     AllocationType allocation) {
    1445             :   DCHECK(RootsTable::IsImmortalImmovable(map_root_index));
    1446             :   DCHECK_LE(Context::kTodoHeaderSize, size);
    1447             :   DCHECK(IsAligned(size, kTaggedSize));
    1448             :   DCHECK_LE(Context::MIN_CONTEXT_SLOTS, variadic_part_length);
    1449             :   DCHECK_LE(Context::SizeFor(variadic_part_length), size);
    1450             : 
    1451     1276655 :   Map map = Map::cast(isolate()->root(map_root_index));
    1452     1276655 :   HeapObject result = AllocateRawWithImmortalMap(size, allocation, map);
    1453             :   Handle<Context> context(Context::cast(result), isolate());
    1454             :   context->set_length(variadic_part_length);
    1455             :   DCHECK_EQ(context->SizeFromMap(map), size);
    1456     1276654 :   if (size > Context::kTodoHeaderSize) {
    1457             :     ObjectSlot start = context->RawField(Context::kTodoHeaderSize);
    1458             :     ObjectSlot end = context->RawField(size);
    1459             :     size_t slot_count = end - start;
    1460             :     MemsetTagged(start, *undefined_value(), slot_count);
    1461             :   }
    1462     1276653 :   return context;
    1463             : }
    1464             : 
    1465         167 : Handle<NativeContext> Factory::NewNativeContext() {
    1466             :   Handle<NativeContext> context = Handle<NativeContext>::cast(
    1467             :       NewContext(RootIndex::kNativeContextMap, NativeContext::kSize,
    1468         167 :                  NativeContext::NATIVE_CONTEXT_SLOTS, AllocationType::kOld));
    1469         167 :   context->set_scope_info(ReadOnlyRoots(isolate()).empty_scope_info());
    1470         167 :   context->set_previous(Context::unchecked_cast(Smi::zero()));
    1471         334 :   context->set_extension(*the_hole_value());
    1472         167 :   context->set_native_context(*context);
    1473         167 :   context->set_errors_thrown(Smi::zero());
    1474         167 :   context->set_math_random_index(Smi::zero());
    1475         167 :   context->set_serialized_objects(*empty_fixed_array());
    1476             :   context->set_microtask_queue(nullptr);
    1477         167 :   return context;
    1478             : }
    1479             : 
    1480       16255 : Handle<Context> Factory::NewScriptContext(Handle<NativeContext> outer,
    1481             :                                           Handle<ScopeInfo> scope_info) {
    1482             :   DCHECK_EQ(scope_info->scope_type(), SCRIPT_SCOPE);
    1483       16255 :   int variadic_part_length = scope_info->ContextLength();
    1484             :   Handle<Context> context = NewContext(
    1485             :       RootIndex::kScriptContextMap, Context::SizeFor(variadic_part_length),
    1486       16255 :       variadic_part_length, AllocationType::kOld);
    1487       16255 :   context->set_scope_info(*scope_info);
    1488       32510 :   context->set_previous(*outer);
    1489       32510 :   context->set_extension(*the_hole_value());
    1490       16255 :   context->set_native_context(*outer);
    1491             :   DCHECK(context->IsScriptContext());
    1492       16255 :   return context;
    1493             : }
    1494             : 
    1495         111 : Handle<ScriptContextTable> Factory::NewScriptContextTable() {
    1496             :   Handle<ScriptContextTable> context_table =
    1497             :       NewFixedArrayWithMap<ScriptContextTable>(
    1498             :           RootIndex::kScriptContextTableMap, ScriptContextTable::kMinLength);
    1499             :   context_table->set_used(0);
    1500         111 :   return context_table;
    1501             : }
    1502             : 
    1503        1604 : Handle<Context> Factory::NewModuleContext(Handle<Module> module,
    1504             :                                           Handle<NativeContext> outer,
    1505             :                                           Handle<ScopeInfo> scope_info) {
    1506             :   DCHECK_EQ(scope_info->scope_type(), MODULE_SCOPE);
    1507        1604 :   int variadic_part_length = scope_info->ContextLength();
    1508             :   Handle<Context> context = NewContext(
    1509             :       RootIndex::kModuleContextMap, Context::SizeFor(variadic_part_length),
    1510        1604 :       variadic_part_length, AllocationType::kOld);
    1511        1604 :   context->set_scope_info(*scope_info);
    1512        3208 :   context->set_previous(*outer);
    1513        3208 :   context->set_extension(*module);
    1514        1604 :   context->set_native_context(*outer);
    1515             :   DCHECK(context->IsModuleContext());
    1516        1604 :   return context;
    1517             : }
    1518             : 
    1519          23 : Handle<Context> Factory::NewFunctionContext(Handle<Context> outer,
    1520             :                                             Handle<ScopeInfo> scope_info) {
    1521             :   RootIndex mapRootIndex;
    1522          23 :   switch (scope_info->scope_type()) {
    1523             :     case EVAL_SCOPE:
    1524             :       mapRootIndex = RootIndex::kEvalContextMap;
    1525             :       break;
    1526             :     case FUNCTION_SCOPE:
    1527             :       mapRootIndex = RootIndex::kFunctionContextMap;
    1528          14 :       break;
    1529             :     default:
    1530           0 :       UNREACHABLE();
    1531             :   }
    1532          23 :   int variadic_part_length = scope_info->ContextLength();
    1533             :   Handle<Context> context =
    1534             :       NewContext(mapRootIndex, Context::SizeFor(variadic_part_length),
    1535          23 :                  variadic_part_length, AllocationType::kYoung);
    1536          23 :   context->set_scope_info(*scope_info);
    1537          23 :   context->set_previous(*outer);
    1538          46 :   context->set_extension(*the_hole_value());
    1539          23 :   context->set_native_context(outer->native_context());
    1540          23 :   return context;
    1541             : }
    1542             : 
    1543      813640 : Handle<Context> Factory::NewCatchContext(Handle<Context> previous,
    1544             :                                          Handle<ScopeInfo> scope_info,
    1545             :                                          Handle<Object> thrown_object) {
    1546             :   DCHECK_EQ(scope_info->scope_type(), CATCH_SCOPE);
    1547             :   STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
    1548             :   // TODO(ishell): Take the details from CatchContext class.
    1549             :   int variadic_part_length = Context::MIN_CONTEXT_SLOTS + 1;
    1550             :   Handle<Context> context = NewContext(
    1551             :       RootIndex::kCatchContextMap, Context::SizeFor(variadic_part_length),
    1552      813640 :       variadic_part_length, AllocationType::kYoung);
    1553      813640 :   context->set_scope_info(*scope_info);
    1554      813640 :   context->set_previous(*previous);
    1555     1627280 :   context->set_extension(*the_hole_value());
    1556      813640 :   context->set_native_context(previous->native_context());
    1557             :   context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
    1558      813640 :   return context;
    1559             : }
    1560             : 
    1561       12527 : Handle<Context> Factory::NewDebugEvaluateContext(Handle<Context> previous,
    1562             :                                                  Handle<ScopeInfo> scope_info,
    1563             :                                                  Handle<JSReceiver> extension,
    1564             :                                                  Handle<Context> wrapped,
    1565             :                                                  Handle<StringSet> whitelist) {
    1566             :   STATIC_ASSERT(Context::WHITE_LIST_INDEX == Context::MIN_CONTEXT_SLOTS + 1);
    1567             :   DCHECK(scope_info->IsDebugEvaluateScope());
    1568             :   Handle<HeapObject> ext = extension.is_null()
    1569             :                                ? Handle<HeapObject>::cast(the_hole_value())
    1570       12527 :                                : Handle<HeapObject>::cast(extension);
    1571             :   // TODO(ishell): Take the details from DebugEvaluateContextContext class.
    1572             :   int variadic_part_length = Context::MIN_CONTEXT_SLOTS + 2;
    1573             :   Handle<Context> c = NewContext(RootIndex::kDebugEvaluateContextMap,
    1574             :                                  Context::SizeFor(variadic_part_length),
    1575       12527 :                                  variadic_part_length, AllocationType::kYoung);
    1576       12527 :   c->set_scope_info(*scope_info);
    1577       12527 :   c->set_previous(*previous);
    1578       12527 :   c->set_native_context(previous->native_context());
    1579       12527 :   c->set_extension(*ext);
    1580       12527 :   if (!wrapped.is_null()) c->set(Context::WRAPPED_CONTEXT_INDEX, *wrapped);
    1581       12527 :   if (!whitelist.is_null()) c->set(Context::WHITE_LIST_INDEX, *whitelist);
    1582       12527 :   return c;
    1583             : }
    1584             : 
    1585      251064 : Handle<Context> Factory::NewWithContext(Handle<Context> previous,
    1586             :                                         Handle<ScopeInfo> scope_info,
    1587             :                                         Handle<JSReceiver> extension) {
    1588             :   DCHECK_EQ(scope_info->scope_type(), WITH_SCOPE);
    1589             :   // TODO(ishell): Take the details from WithContext class.
    1590             :   int variadic_part_length = Context::MIN_CONTEXT_SLOTS;
    1591             :   Handle<Context> context = NewContext(
    1592             :       RootIndex::kWithContextMap, Context::SizeFor(variadic_part_length),
    1593      251064 :       variadic_part_length, AllocationType::kYoung);
    1594      251064 :   context->set_scope_info(*scope_info);
    1595      251064 :   context->set_previous(*previous);
    1596      502128 :   context->set_extension(*extension);
    1597      251064 :   context->set_native_context(previous->native_context());
    1598      251064 :   return context;
    1599             : }
    1600             : 
    1601      179750 : Handle<Context> Factory::NewBlockContext(Handle<Context> previous,
    1602             :                                          Handle<ScopeInfo> scope_info) {
    1603             :   DCHECK_IMPLIES(scope_info->scope_type() != BLOCK_SCOPE,
    1604             :                  scope_info->scope_type() == CLASS_SCOPE);
    1605      179750 :   int variadic_part_length = scope_info->ContextLength();
    1606             :   Handle<Context> context = NewContext(
    1607             :       RootIndex::kBlockContextMap, Context::SizeFor(variadic_part_length),
    1608      179753 :       variadic_part_length, AllocationType::kYoung);
    1609      179751 :   context->set_scope_info(*scope_info);
    1610      179750 :   context->set_previous(*previous);
    1611      359500 :   context->set_extension(*the_hole_value());
    1612      179750 :   context->set_native_context(previous->native_context());
    1613      179751 :   return context;
    1614             : }
    1615             : 
    1616        1622 : Handle<Context> Factory::NewBuiltinContext(Handle<NativeContext> native_context,
    1617             :                                            int variadic_part_length) {
    1618             :   DCHECK_LE(Context::MIN_CONTEXT_SLOTS, variadic_part_length);
    1619             :   Handle<Context> context = NewContext(
    1620             :       RootIndex::kFunctionContextMap, Context::SizeFor(variadic_part_length),
    1621        1622 :       variadic_part_length, AllocationType::kYoung);
    1622        1622 :   context->set_scope_info(ReadOnlyRoots(isolate()).empty_scope_info());
    1623        3244 :   context->set_previous(*native_context);
    1624        3244 :   context->set_extension(*the_hole_value());
    1625        1622 :   context->set_native_context(*native_context);
    1626        1622 :   return context;
    1627             : }
    1628             : 
    1629    11248891 : Handle<Struct> Factory::NewStruct(InstanceType type,
    1630             :                                   AllocationType allocation) {
    1631             :   Map map;
    1632    11248891 :   switch (type) {
    1633             : #define MAKE_CASE(TYPE, Name, name) \
    1634             :   case TYPE:                        \
    1635             :     map = *name##_map();            \
    1636             :     break;
    1637    11248891 :     STRUCT_LIST(MAKE_CASE)
    1638             : #undef MAKE_CASE
    1639             :     default:
    1640           0 :       UNREACHABLE();
    1641             :   }
    1642             :   int size = map->instance_size();
    1643    11248891 :   HeapObject result = AllocateRawWithImmortalMap(size, allocation, map);
    1644             :   Handle<Struct> str(Struct::cast(result), isolate());
    1645    11248881 :   str->InitializeBody(size);
    1646    11248886 :   return str;
    1647             : }
    1648             : 
    1649          53 : Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
    1650             :     int aliased_context_slot) {
    1651             :   Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
    1652          53 :       NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE, AllocationType::kYoung));
    1653             :   entry->set_aliased_context_slot(aliased_context_slot);
    1654          53 :   return entry;
    1655             : }
    1656             : 
    1657       94053 : Handle<AccessorInfo> Factory::NewAccessorInfo() {
    1658             :   Handle<AccessorInfo> info = Handle<AccessorInfo>::cast(
    1659       94053 :       NewStruct(ACCESSOR_INFO_TYPE, AllocationType::kOld));
    1660      188106 :   info->set_name(*empty_string());
    1661             :   info->set_flags(0);  // Must clear the flags, it was initialized as undefined.
    1662       94053 :   info->set_is_sloppy(true);
    1663       94053 :   info->set_initial_property_attributes(NONE);
    1664       94053 :   return info;
    1665             : }
    1666             : 
    1667     1783482 : Handle<Script> Factory::NewScript(Handle<String> source,
    1668             :                                   AllocationType allocation) {
    1669     1783482 :   return NewScriptWithId(source, isolate()->heap()->NextScriptId(), allocation);
    1670             : }
    1671             : 
    1672     2903847 : Handle<Script> Factory::NewScriptWithId(Handle<String> source, int script_id,
    1673             :                                         AllocationType allocation) {
    1674             :   DCHECK(allocation == AllocationType::kOld ||
    1675             :          allocation == AllocationType::kReadOnly);
    1676             :   // Create and initialize script object.
    1677             :   Heap* heap = isolate()->heap();
    1678             :   ReadOnlyRoots roots(heap);
    1679             :   Handle<Script> script =
    1680     2903847 :       Handle<Script>::cast(NewStruct(SCRIPT_TYPE, allocation));
    1681     5807696 :   script->set_source(*source);
    1682     5807696 :   script->set_name(roots.undefined_value());
    1683             :   script->set_id(script_id);
    1684             :   script->set_line_offset(0);
    1685             :   script->set_column_offset(0);
    1686     5807696 :   script->set_context_data(roots.undefined_value());
    1687             :   script->set_type(Script::TYPE_NORMAL);
    1688     5807694 :   script->set_line_ends(roots.undefined_value());
    1689     5807692 :   script->set_eval_from_shared_or_wrapped_arguments(roots.undefined_value());
    1690             :   script->set_eval_from_position(0);
    1691             :   script->set_shared_function_infos(*empty_weak_fixed_array(),
    1692             :                                     SKIP_WRITE_BARRIER);
    1693             :   script->set_flags(0);
    1694     2903848 :   script->set_host_defined_options(*empty_fixed_array());
    1695             :   Handle<WeakArrayList> scripts = script_list();
    1696             :   scripts = WeakArrayList::AddToEnd(isolate(), scripts,
    1697     2903848 :                                     MaybeObjectHandle::Weak(script));
    1698             :   heap->set_script_list(*scripts);
    1699     2903847 :   LOG(isolate(), ScriptEvent(Logger::ScriptEventType::kCreate, script_id));
    1700     5807698 :   TRACE_EVENT_OBJECT_CREATED_WITH_ID(
    1701             :       TRACE_DISABLED_BY_DEFAULT("v8.compile"), "Script",
    1702             :       TRACE_ID_WITH_SCOPE(Script::kTraceScope, script_id));
    1703     2903849 :   return script;
    1704             : }
    1705             : 
    1706         761 : Handle<Script> Factory::CloneScript(Handle<Script> script) {
    1707             :   Heap* heap = isolate()->heap();
    1708             :   int script_id = isolate()->heap()->NextScriptId();
    1709             :   Handle<Script> new_script =
    1710         761 :       Handle<Script>::cast(NewStruct(SCRIPT_TYPE, AllocationType::kOld));
    1711         761 :   new_script->set_source(script->source());
    1712         761 :   new_script->set_name(script->name());
    1713             :   new_script->set_id(script_id);
    1714             :   new_script->set_line_offset(script->line_offset());
    1715             :   new_script->set_column_offset(script->column_offset());
    1716         761 :   new_script->set_context_data(script->context_data());
    1717             :   new_script->set_type(script->type());
    1718        1522 :   new_script->set_line_ends(ReadOnlyRoots(heap).undefined_value());
    1719        1522 :   new_script->set_eval_from_shared_or_wrapped_arguments(
    1720         761 :       script->eval_from_shared_or_wrapped_arguments());
    1721             :   new_script->set_shared_function_infos(*empty_weak_fixed_array(),
    1722             :                                         SKIP_WRITE_BARRIER);
    1723             :   new_script->set_eval_from_position(script->eval_from_position());
    1724             :   new_script->set_flags(script->flags());
    1725         761 :   new_script->set_host_defined_options(script->host_defined_options());
    1726             :   Handle<WeakArrayList> scripts = script_list();
    1727             :   scripts = WeakArrayList::AddToEnd(isolate(), scripts,
    1728         761 :                                     MaybeObjectHandle::Weak(new_script));
    1729             :   heap->set_script_list(*scripts);
    1730         761 :   LOG(isolate(), ScriptEvent(Logger::ScriptEventType::kCreate, script_id));
    1731         761 :   return new_script;
    1732             : }
    1733             : 
    1734         401 : Handle<CallableTask> Factory::NewCallableTask(Handle<JSReceiver> callable,
    1735             :                                               Handle<Context> context) {
    1736             :   DCHECK(callable->IsCallable());
    1737             :   Handle<CallableTask> microtask =
    1738         401 :       Handle<CallableTask>::cast(NewStruct(CALLABLE_TASK_TYPE));
    1739         401 :   microtask->set_callable(*callable);
    1740         401 :   microtask->set_context(*context);
    1741         401 :   return microtask;
    1742             : }
    1743             : 
    1744         463 : Handle<CallbackTask> Factory::NewCallbackTask(Handle<Foreign> callback,
    1745             :                                               Handle<Foreign> data) {
    1746             :   Handle<CallbackTask> microtask =
    1747         463 :       Handle<CallbackTask>::cast(NewStruct(CALLBACK_TASK_TYPE));
    1748         463 :   microtask->set_callback(*callback);
    1749         463 :   microtask->set_data(*data);
    1750         463 :   return microtask;
    1751             : }
    1752             : 
    1753        1615 : Handle<PromiseResolveThenableJobTask> Factory::NewPromiseResolveThenableJobTask(
    1754             :     Handle<JSPromise> promise_to_resolve, Handle<JSReceiver> then,
    1755             :     Handle<JSReceiver> thenable, Handle<Context> context) {
    1756             :   DCHECK(then->IsCallable());
    1757             :   Handle<PromiseResolveThenableJobTask> microtask =
    1758             :       Handle<PromiseResolveThenableJobTask>::cast(
    1759        1615 :           NewStruct(PROMISE_RESOLVE_THENABLE_JOB_TASK_TYPE));
    1760        1615 :   microtask->set_promise_to_resolve(*promise_to_resolve);
    1761        1615 :   microtask->set_then(*then);
    1762        1615 :   microtask->set_thenable(*thenable);
    1763        1615 :   microtask->set_context(*context);
    1764        1615 :   return microtask;
    1765             : }
    1766             : 
    1767             : Handle<FinalizationGroupCleanupJobTask>
    1768         208 : Factory::NewFinalizationGroupCleanupJobTask(
    1769             :     Handle<JSFinalizationGroup> finalization_group) {
    1770             :   Handle<FinalizationGroupCleanupJobTask> microtask =
    1771             :       Handle<FinalizationGroupCleanupJobTask>::cast(
    1772         208 :           NewStruct(FINALIZATION_GROUP_CLEANUP_JOB_TASK_TYPE));
    1773         208 :   microtask->set_finalization_group(*finalization_group);
    1774         208 :   return microtask;
    1775             : }
    1776             : 
    1777    10601692 : Handle<Foreign> Factory::NewForeign(Address addr, AllocationType allocation) {
    1778             :   // Statically ensure that it is safe to allocate foreigns in paged spaces.
    1779             :   STATIC_ASSERT(Foreign::kSize <= kMaxRegularHeapObjectSize);
    1780             :   Map map = *foreign_map();
    1781             :   HeapObject result =
    1782    10601692 :       AllocateRawWithImmortalMap(map->instance_size(), allocation, map);
    1783             :   Handle<Foreign> foreign(Foreign::cast(result), isolate());
    1784             :   foreign->set_foreign_address(addr);
    1785    10601692 :   return foreign;
    1786             : }
    1787             : 
    1788     7142779 : Handle<ByteArray> Factory::NewByteArray(int length, AllocationType allocation) {
    1789             :   DCHECK_LE(0, length);
    1790     7142779 :   if (length > ByteArray::kMaxLength) {
    1791           0 :     isolate()->heap()->FatalProcessOutOfMemory("invalid array length");
    1792             :   }
    1793             :   int size = ByteArray::SizeFor(length);
    1794             :   HeapObject result =
    1795     7142779 :       AllocateRawWithImmortalMap(size, allocation, *byte_array_map());
    1796             :   Handle<ByteArray> array(ByteArray::cast(result), isolate());
    1797             :   array->set_length(length);
    1798     7142804 :   array->clear_padding();
    1799     7142787 :   return array;
    1800             : }
    1801             : 
    1802     2112600 : Handle<BytecodeArray> Factory::NewBytecodeArray(
    1803             :     int length, const byte* raw_bytecodes, int frame_size, int parameter_count,
    1804             :     Handle<FixedArray> constant_pool) {
    1805             :   DCHECK_LE(0, length);
    1806     2112600 :   if (length > BytecodeArray::kMaxLength) {
    1807           0 :     isolate()->heap()->FatalProcessOutOfMemory("invalid array length");
    1808             :   }
    1809             :   // Bytecode array is AllocationType::kOld, so constant pool array should be
    1810             :   // too.
    1811             :   DCHECK(!Heap::InYoungGeneration(*constant_pool));
    1812             : 
    1813             :   int size = BytecodeArray::SizeFor(length);
    1814             :   HeapObject result = AllocateRawWithImmortalMap(size, AllocationType::kOld,
    1815     2112600 :                                                  *bytecode_array_map());
    1816             :   Handle<BytecodeArray> instance(BytecodeArray::cast(result), isolate());
    1817             :   instance->set_length(length);
    1818             :   instance->set_frame_size(frame_size);
    1819             :   instance->set_parameter_count(parameter_count);
    1820             :   instance->set_incoming_new_target_or_generator_register(
    1821             :       interpreter::Register::invalid_value());
    1822             :   instance->set_osr_loop_nesting_level(0);
    1823             :   instance->set_bytecode_age(BytecodeArray::kNoAgeBytecodeAge);
    1824     2112600 :   instance->set_constant_pool(*constant_pool);
    1825     2112596 :   instance->set_handler_table(*empty_byte_array());
    1826     4225192 :   instance->set_source_position_table(*undefined_value());
    1827     2112599 :   CopyBytes(reinterpret_cast<byte*>(instance->GetFirstBytecodeAddress()),
    1828             :             raw_bytecodes, length);
    1829     2112583 :   instance->clear_padding();
    1830             : 
    1831     2112591 :   return instance;
    1832             : }
    1833             : 
    1834       17796 : Handle<FixedTypedArrayBase> Factory::NewFixedTypedArrayWithExternalPointer(
    1835             :     ExternalArrayType array_type, void* external_pointer,
    1836             :     AllocationType allocation) {
    1837             :   int size = FixedTypedArrayBase::kHeaderSize;
    1838             :   HeapObject result = AllocateRawWithImmortalMap(
    1839             :       size, allocation,
    1840       17796 :       ReadOnlyRoots(isolate()).MapForFixedTypedArray(array_type));
    1841             :   Handle<FixedTypedArrayBase> elements(FixedTypedArrayBase::cast(result),
    1842             :                                        isolate());
    1843             :   elements->set_base_pointer(Smi::kZero, SKIP_WRITE_BARRIER);
    1844             :   elements->set_external_pointer(external_pointer);
    1845             :   elements->set_length(0);
    1846       17796 :   return elements;
    1847             : }
    1848             : 
    1849          58 : Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
    1850             :     size_t length, size_t byte_length, ExternalArrayType array_type,
    1851             :     bool initialize, AllocationType allocation) {
    1852             :   // TODO(7881): Smi length check
    1853             :   DCHECK(0 <= length && length <= Smi::kMaxValue);
    1854          58 :   CHECK(byte_length <= kMaxInt - FixedTypedArrayBase::kDataOffset);
    1855             :   size_t size =
    1856          58 :       OBJECT_POINTER_ALIGN(byte_length + FixedTypedArrayBase::kDataOffset);
    1857          58 :   Map map = ReadOnlyRoots(isolate()).MapForFixedTypedArray(array_type);
    1858             :   AllocationAlignment alignment =
    1859          58 :       array_type == kExternalFloat64Array ? kDoubleAligned : kWordAligned;
    1860             :   HeapObject object = AllocateRawWithImmortalMap(static_cast<int>(size),
    1861          58 :                                                  allocation, map, alignment);
    1862             : 
    1863             :   Handle<FixedTypedArrayBase> elements(FixedTypedArrayBase::cast(object),
    1864             :                                        isolate());
    1865             :   elements->set_base_pointer(*elements, SKIP_WRITE_BARRIER);
    1866             :   elements->set_external_pointer(
    1867             :       FixedTypedArrayBase::ExternalPointerPtrForOnHeapArray());
    1868          58 :   elements->set_length(static_cast<int>(length));
    1869         174 :   if (initialize) memset(elements->DataPtr(), 0, elements->DataSize());
    1870          58 :   return elements;
    1871             : }
    1872             : 
    1873      829572 : Handle<Cell> Factory::NewCell(Handle<Object> value) {
    1874             :   AllowDeferredHandleDereference convert_to_cell;
    1875             :   STATIC_ASSERT(Cell::kSize <= kMaxRegularHeapObjectSize);
    1876             :   HeapObject result = AllocateRawWithImmortalMap(
    1877      829572 :       Cell::kSize, AllocationType::kOld, *cell_map());
    1878             :   Handle<Cell> cell(Cell::cast(result), isolate());
    1879      829573 :   cell->set_value(*value);
    1880      829571 :   return cell;
    1881             : }
    1882             : 
    1883     4125332 : Handle<FeedbackCell> Factory::NewNoClosuresCell(Handle<HeapObject> value) {
    1884             :   AllowDeferredHandleDereference convert_to_cell;
    1885             :   HeapObject result = AllocateRawWithImmortalMap(
    1886     4125332 :       FeedbackCell::kSize, AllocationType::kOld, *no_closures_cell_map());
    1887             :   Handle<FeedbackCell> cell(FeedbackCell::cast(result), isolate());
    1888     4125334 :   cell->set_value(*value);
    1889             :   cell->set_interrupt_budget(FeedbackCell::GetInitialInterruptBudget());
    1890             :   cell->clear_padding();
    1891     4125333 :   return cell;
    1892             : }
    1893             : 
    1894     1526541 : Handle<FeedbackCell> Factory::NewOneClosureCell(Handle<HeapObject> value) {
    1895             :   AllowDeferredHandleDereference convert_to_cell;
    1896             :   HeapObject result = AllocateRawWithImmortalMap(
    1897     1526541 :       FeedbackCell::kSize, AllocationType::kOld, *one_closure_cell_map());
    1898             :   Handle<FeedbackCell> cell(FeedbackCell::cast(result), isolate());
    1899     1526539 :   cell->set_value(*value);
    1900             :   cell->set_interrupt_budget(FeedbackCell::GetInitialInterruptBudget());
    1901             :   cell->clear_padding();
    1902     1526540 :   return cell;
    1903             : }
    1904             : 
    1905          56 : Handle<FeedbackCell> Factory::NewManyClosuresCell(Handle<HeapObject> value) {
    1906             :   AllowDeferredHandleDereference convert_to_cell;
    1907             :   HeapObject result = AllocateRawWithImmortalMap(
    1908          56 :       FeedbackCell::kSize, AllocationType::kOld, *many_closures_cell_map());
    1909             :   Handle<FeedbackCell> cell(FeedbackCell::cast(result), isolate());
    1910          56 :   cell->set_value(*value);
    1911             :   cell->set_interrupt_budget(FeedbackCell::GetInitialInterruptBudget());
    1912             :   cell->clear_padding();
    1913          56 :   return cell;
    1914             : }
    1915             : 
    1916     8348579 : Handle<PropertyCell> Factory::NewPropertyCell(Handle<Name> name,
    1917             :                                               AllocationType allocation) {
    1918             :   DCHECK(name->IsUniqueName());
    1919             :   STATIC_ASSERT(PropertyCell::kSize <= kMaxRegularHeapObjectSize);
    1920             :   HeapObject result = AllocateRawWithImmortalMap(
    1921     8348579 :       PropertyCell::kSize, allocation, *global_property_cell_map());
    1922             :   Handle<PropertyCell> cell(PropertyCell::cast(result), isolate());
    1923             :   cell->set_dependent_code(DependentCode::cast(*empty_weak_fixed_array()),
    1924             :                            SKIP_WRITE_BARRIER);
    1925    16697104 :   cell->set_property_details(PropertyDetails(Smi::zero()));
    1926     8348546 :   cell->set_name(*name);
    1927    16697078 :   cell->set_value(*the_hole_value());
    1928     8348527 :   return cell;
    1929             : }
    1930             : 
    1931    19186735 : Handle<DescriptorArray> Factory::NewDescriptorArray(int number_of_descriptors,
    1932             :                                                     int slack,
    1933             :                                                     AllocationType allocation) {
    1934             :   DCHECK(Heap::IsRegularObjectAllocation(allocation));
    1935    19186735 :   int number_of_all_descriptors = number_of_descriptors + slack;
    1936             :   // Zero-length case must be handled outside.
    1937             :   DCHECK_LT(0, number_of_all_descriptors);
    1938             :   int size = DescriptorArray::SizeFor(number_of_all_descriptors);
    1939             :   HeapObject obj =
    1940    19186735 :       isolate()->heap()->AllocateRawWithRetryOrFail(size, allocation);
    1941             :   obj->set_map_after_allocation(*descriptor_array_map(), SKIP_WRITE_BARRIER);
    1942    19186735 :   DescriptorArray array = DescriptorArray::cast(obj);
    1943    38373465 :   array->Initialize(*empty_enum_cache(), *undefined_value(),
    1944    19186735 :                     number_of_descriptors, slack);
    1945    19186726 :   return Handle<DescriptorArray>(array, isolate());
    1946             : }
    1947             : 
    1948      484163 : Handle<TransitionArray> Factory::NewTransitionArray(int number_of_transitions,
    1949             :                                                     int slack) {
    1950      484163 :   int capacity = TransitionArray::LengthFor(number_of_transitions + slack);
    1951             :   Handle<TransitionArray> array = NewWeakFixedArrayWithMap<TransitionArray>(
    1952      484163 :       RootIndex::kTransitionArrayMap, capacity, AllocationType::kOld);
    1953             :   // Transition arrays are AllocationType::kOld. When black allocation is on we
    1954             :   // have to add the transition array to the list of
    1955             :   // encountered_transition_arrays.
    1956             :   Heap* heap = isolate()->heap();
    1957      484163 :   if (heap->incremental_marking()->black_allocation()) {
    1958             :     heap->mark_compact_collector()->AddTransitionArray(*array);
    1959             :   }
    1960      968327 :   array->WeakFixedArray::Set(TransitionArray::kPrototypeTransitionsIndex,
    1961      484163 :                              MaybeObject::FromObject(Smi::kZero));
    1962      968331 :   array->WeakFixedArray::Set(
    1963             :       TransitionArray::kTransitionLengthIndex,
    1964      484164 :       MaybeObject::FromObject(Smi::FromInt(number_of_transitions)));
    1965      484167 :   return array;
    1966             : }
    1967             : 
    1968      112094 : Handle<AllocationSite> Factory::NewAllocationSite(bool with_weak_next) {
    1969             :   Handle<Map> map = with_weak_next ? allocation_site_map()
    1970      224188 :                                    : allocation_site_without_weaknext_map();
    1971             :   Handle<AllocationSite> site(
    1972      224191 :       AllocationSite::cast(New(map, AllocationType::kOld)), isolate());
    1973      112097 :   site->Initialize();
    1974             : 
    1975      112101 :   if (with_weak_next) {
    1976             :     // Link the site
    1977       96378 :     site->set_weak_next(isolate()->heap()->allocation_sites_list());
    1978             :     isolate()->heap()->set_allocation_sites_list(*site);
    1979             :   }
    1980      112101 :   return site;
    1981             : }
    1982             : 
    1983    30325996 : Handle<Map> Factory::NewMap(InstanceType type, int instance_size,
    1984             :                             ElementsKind elements_kind,
    1985             :                             int inobject_properties) {
    1986             :   STATIC_ASSERT(LAST_JS_OBJECT_TYPE == LAST_TYPE);
    1987             :   DCHECK_IMPLIES(InstanceTypeChecker::IsJSObject(type) &&
    1988             :                      !Map::CanHaveFastTransitionableElementsKind(type),
    1989             :                  IsDictionaryElementsKind(elements_kind) ||
    1990             :                      IsTerminalElementsKind(elements_kind));
    1991             :   HeapObject result = isolate()->heap()->AllocateRawWithRetryOrFail(
    1992    30325996 :       Map::kSize, AllocationType::kMap);
    1993             :   result->set_map_after_allocation(*meta_map(), SKIP_WRITE_BARRIER);
    1994             :   return handle(InitializeMap(Map::cast(result), type, instance_size,
    1995             :                               elements_kind, inobject_properties),
    1996    60652014 :                 isolate());
    1997             : }
    1998             : 
    1999    30935523 : Map Factory::InitializeMap(Map map, InstanceType type, int instance_size,
    2000             :                            ElementsKind elements_kind,
    2001             :                            int inobject_properties) {
    2002             :   map->set_instance_type(type);
    2003             :   map->set_prototype(*null_value(), SKIP_WRITE_BARRIER);
    2004             :   map->set_constructor_or_backpointer(*null_value(), SKIP_WRITE_BARRIER);
    2005    30935523 :   map->set_instance_size(instance_size);
    2006    30935506 :   if (map->IsJSObjectMap()) {
    2007             :     DCHECK(!ReadOnlyHeap::Contains(map));
    2008    30929624 :     map->SetInObjectPropertiesStartInWords(instance_size / kTaggedSize -
    2009    30929624 :                                            inobject_properties);
    2010             :     DCHECK_EQ(map->GetInObjectProperties(), inobject_properties);
    2011    30929632 :     map->set_prototype_validity_cell(*invalid_prototype_validity_cell());
    2012             :   } else {
    2013             :     DCHECK_EQ(inobject_properties, 0);
    2014        5882 :     map->set_inobject_properties_start_or_constructor_function_index(0);
    2015        5882 :     map->set_prototype_validity_cell(Smi::FromInt(Map::kPrototypeChainValid));
    2016             :   }
    2017             :   map->set_dependent_code(DependentCode::cast(*empty_weak_fixed_array()),
    2018             :                           SKIP_WRITE_BARRIER);
    2019    30935495 :   map->set_raw_transitions(MaybeObject::FromSmi(Smi::zero()));
    2020    30935489 :   map->SetInObjectUnusedPropertyFields(inobject_properties);
    2021    30935485 :   map->SetInstanceDescriptors(isolate(), *empty_descriptor_array(), 0);
    2022             :   if (FLAG_unbox_double_fields) {
    2023    30935515 :     map->set_layout_descriptor(LayoutDescriptor::FastPointerLayout());
    2024             :   }
    2025             :   // Must be called only after |instance_type|, |instance_size| and
    2026             :   // |layout_descriptor| are set.
    2027    30935514 :   map->set_visitor_id(Map::GetVisitorId(map));
    2028             :   map->set_bit_field(0);
    2029             :   map->set_bit_field2(Map::IsExtensibleBit::kMask);
    2030             :   DCHECK(!map->is_in_retained_map_list());
    2031             :   int bit_field3 = Map::EnumLengthBits::encode(kInvalidEnumCacheSentinel) |
    2032             :                    Map::OwnsDescriptorsBit::encode(true) |
    2033             :                    Map::ConstructionCounterBits::encode(Map::kNoSlackTracking);
    2034             :   map->set_bit_field3(bit_field3);
    2035             :   map->clear_padding();
    2036    30935502 :   map->set_elements_kind(elements_kind);
    2037    30935495 :   map->set_new_target_is_base(true);
    2038    30935501 :   isolate()->counters()->maps_created()->Increment();
    2039    30935510 :   if (FLAG_trace_maps) LOG(isolate(), MapCreate(map));
    2040    30935510 :   return map;
    2041             : }
    2042             : 
    2043      511894 : Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> source) {
    2044      511894 :   return CopyJSObjectWithAllocationSite(source, Handle<AllocationSite>());
    2045             : }
    2046             : 
    2047     2138987 : Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
    2048             :     Handle<JSObject> source, Handle<AllocationSite> site) {
    2049             :   Handle<Map> map(source->map(), isolate());
    2050             : 
    2051             :   // We can only clone regexps, normal objects, api objects, errors or arrays.
    2052             :   // Copying anything else will break invariants.
    2053     2138988 :   CHECK(map->instance_type() == JS_REGEXP_TYPE ||
    2054             :         map->instance_type() == JS_OBJECT_TYPE ||
    2055             :         map->instance_type() == JS_ERROR_TYPE ||
    2056             :         map->instance_type() == JS_ARRAY_TYPE ||
    2057             :         map->instance_type() == JS_API_OBJECT_TYPE ||
    2058             :         map->instance_type() == WASM_GLOBAL_TYPE ||
    2059             :         map->instance_type() == WASM_INSTANCE_TYPE ||
    2060             :         map->instance_type() == WASM_MEMORY_TYPE ||
    2061             :         map->instance_type() == WASM_MODULE_TYPE ||
    2062             :         map->instance_type() == WASM_TABLE_TYPE ||
    2063             :         map->instance_type() == JS_SPECIAL_API_OBJECT_TYPE);
    2064             :   DCHECK(site.is_null() || AllocationSite::CanTrack(map->instance_type()));
    2065             : 
    2066             :   int object_size = map->instance_size();
    2067             :   int adjusted_object_size =
    2068     2138988 :       site.is_null() ? object_size : object_size + AllocationMemento::kSize;
    2069             :   HeapObject raw_clone = isolate()->heap()->AllocateRawWithRetryOrFail(
    2070     2138988 :       adjusted_object_size, AllocationType::kYoung);
    2071             : 
    2072             :   DCHECK(Heap::InYoungGeneration(raw_clone));
    2073             :   // Since we know the clone is allocated in new space, we can copy
    2074             :   // the contents without worrying about updating the write barrier.
    2075             :   Heap::CopyBlock(raw_clone->address(), source->address(), object_size);
    2076             :   Handle<JSObject> clone(JSObject::cast(raw_clone), isolate());
    2077             : 
    2078     2138989 :   if (!site.is_null()) {
    2079             :     AllocationMemento alloc_memento = AllocationMemento::unchecked_cast(
    2080     1503212 :         Object(raw_clone->ptr() + object_size));
    2081     1503212 :     InitializeAllocationMemento(alloc_memento, *site);
    2082             :   }
    2083             : 
    2084             :   SLOW_DCHECK(clone->GetElementsKind() == source->GetElementsKind());
    2085             :   FixedArrayBase elements = source->elements();
    2086             :   // Update elements if necessary.
    2087     2138987 :   if (elements->length() > 0) {
    2088             :     FixedArrayBase elem;
    2089      529765 :     if (elements->map() == *fixed_cow_array_map()) {
    2090       37563 :       elem = elements;
    2091      492202 :     } else if (source->HasDoubleElements()) {
    2092        9940 :       elem = *CopyFixedDoubleArray(
    2093        4970 :           handle(FixedDoubleArray::cast(elements), isolate()));
    2094             :     } else {
    2095      974466 :       elem = *CopyFixedArray(handle(FixedArray::cast(elements), isolate()));
    2096             :     }
    2097      529767 :     clone->set_elements(elem);
    2098             :   }
    2099             : 
    2100             :   // Update properties if necessary.
    2101     2138989 :   if (source->HasFastProperties()) {
    2102     2138697 :     PropertyArray properties = source->property_array();
    2103     2138700 :     if (properties->length() > 0) {
    2104             :       // TODO(gsathya): Do not copy hash code.
    2105             :       Handle<PropertyArray> prop = CopyArrayWithMap(
    2106      218922 :           handle(properties, isolate()), handle(properties->map(), isolate()));
    2107      437844 :       clone->set_raw_properties_or_hash(*prop);
    2108             :     }
    2109             :   } else {
    2110             :     Handle<FixedArray> properties(
    2111         584 :         FixedArray::cast(source->property_dictionary()), isolate());
    2112         292 :     Handle<FixedArray> prop = CopyFixedArray(properties);
    2113         584 :     clone->set_raw_properties_or_hash(*prop);
    2114             :   }
    2115     2138992 :   return clone;
    2116             : }
    2117             : 
    2118             : namespace {
    2119             : template <typename T>
    2120             : void initialize_length(Handle<T> array, int length) {
    2121             :   array->set_length(length);
    2122             : }
    2123             : 
    2124             : template <>
    2125             : void initialize_length<PropertyArray>(Handle<PropertyArray> array, int length) {
    2126             :   array->initialize_length(length);
    2127             : }
    2128             : 
    2129             : }  // namespace
    2130             : 
    2131             : template <typename T>
    2132      989044 : Handle<T> Factory::CopyArrayWithMap(Handle<T> src, Handle<Map> map) {
    2133             :   int len = src->length();
    2134      989044 :   HeapObject obj = AllocateRawFixedArray(len, AllocationType::kYoung);
    2135             :   obj->set_map_after_allocation(*map, SKIP_WRITE_BARRIER);
    2136             : 
    2137             :   Handle<T> result(T::cast(obj), isolate());
    2138             :   DisallowHeapAllocation no_gc;
    2139             :   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
    2140             : 
    2141      989050 :   if (mode == SKIP_WRITE_BARRIER) {
    2142             :     // Eliminate the write barrier if possible.
    2143     1831892 :     Heap::CopyBlock(obj->address() + kTaggedSize, src->address() + kTaggedSize,
    2144             :                     T::SizeFor(len) - kTaggedSize);
    2145             :   } else {
    2146             :     // Slow case: Just copy the content one-by-one.
    2147             :     initialize_length(result, len);
    2148     3969926 :     for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
    2149             :   }
    2150      989049 :   return result;
    2151             : }
    2152             : 
    2153             : template <typename T>
    2154     2649881 : Handle<T> Factory::CopyArrayAndGrow(Handle<T> src, int grow_by,
    2155             :                                     AllocationType allocation) {
    2156             :   DCHECK_LT(0, grow_by);
    2157             :   DCHECK_LE(grow_by, kMaxInt - src->length());
    2158             :   int old_len = src->length();
    2159     2649881 :   int new_len = old_len + grow_by;
    2160     2649881 :   HeapObject obj = AllocateRawFixedArray(new_len, allocation);
    2161             :   obj->set_map_after_allocation(src->map(), SKIP_WRITE_BARRIER);
    2162             : 
    2163             :   Handle<T> result(T::cast(obj), isolate());
    2164             :   initialize_length(result, new_len);
    2165             : 
    2166             :   // Copy the content.
    2167             :   DisallowHeapAllocation no_gc;
    2168             :   WriteBarrierMode mode = obj->GetWriteBarrierMode(no_gc);
    2169   300999041 :   for (int i = 0; i < old_len; i++) result->set(i, src->get(i), mode);
    2170     2649881 :   MemsetTagged(result->data_start() + old_len, *undefined_value(), grow_by);
    2171     2649881 :   return result;
    2172             : }
    2173             : 
    2174       21002 : Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
    2175             :                                                   Handle<Map> map) {
    2176       21002 :   return CopyArrayWithMap(array, map);
    2177             : }
    2178             : 
    2179      390392 : Handle<FixedArray> Factory::CopyFixedArrayAndGrow(Handle<FixedArray> array,
    2180             :                                                   int grow_by,
    2181             :                                                   AllocationType allocation) {
    2182      390392 :   return CopyArrayAndGrow(array, grow_by, allocation);
    2183             : }
    2184             : 
    2185      548074 : Handle<WeakFixedArray> Factory::CopyWeakFixedArrayAndGrow(
    2186             :     Handle<WeakFixedArray> src, int grow_by, AllocationType allocation) {
    2187             :   DCHECK(
    2188             :       !src->IsTransitionArray());  // Compacted by GC, this code doesn't work.
    2189             :   int old_len = src->length();
    2190      548074 :   int new_len = old_len + grow_by;
    2191             :   DCHECK_GE(new_len, old_len);
    2192      548074 :   HeapObject obj = AllocateRawFixedArray(new_len, allocation);
    2193             :   DCHECK_EQ(old_len, src->length());
    2194             :   obj->set_map_after_allocation(src->map(), SKIP_WRITE_BARRIER);
    2195             : 
    2196      548074 :   WeakFixedArray result = WeakFixedArray::cast(obj);
    2197             :   result->set_length(new_len);
    2198             : 
    2199             :   // Copy the content.
    2200             :   DisallowHeapAllocation no_gc;
    2201             :   WriteBarrierMode mode = obj->GetWriteBarrierMode(no_gc);
    2202     5334736 :   for (int i = 0; i < old_len; i++) result->Set(i, src->Get(i), mode);
    2203      548074 :   MemsetTagged(ObjectSlot(result->RawFieldOfElementAt(old_len)),
    2204             :                ReadOnlyRoots(isolate()).undefined_value(), grow_by);
    2205      548074 :   return Handle<WeakFixedArray>(result, isolate());
    2206             : }
    2207             : 
    2208     1539468 : Handle<WeakArrayList> Factory::CopyWeakArrayListAndGrow(
    2209             :     Handle<WeakArrayList> src, int grow_by, AllocationType allocation) {
    2210             :   int old_capacity = src->capacity();
    2211     1539468 :   int new_capacity = old_capacity + grow_by;
    2212             :   DCHECK_GE(new_capacity, old_capacity);
    2213     1539468 :   HeapObject obj = AllocateRawWeakArrayList(new_capacity, allocation);
    2214             :   obj->set_map_after_allocation(src->map(), SKIP_WRITE_BARRIER);
    2215             : 
    2216     1539472 :   WeakArrayList result = WeakArrayList::cast(obj);
    2217             :   result->set_length(src->length());
    2218             :   result->set_capacity(new_capacity);
    2219             : 
    2220             :   // Copy the content.
    2221             :   DisallowHeapAllocation no_gc;
    2222             :   WriteBarrierMode mode = obj->GetWriteBarrierMode(no_gc);
    2223    28618212 :   for (int i = 0; i < old_capacity; i++) result->Set(i, src->Get(i), mode);
    2224     1539470 :   MemsetTagged(ObjectSlot(result->data_start() + old_capacity),
    2225             :                ReadOnlyRoots(isolate()).undefined_value(), grow_by);
    2226     1539467 :   return Handle<WeakArrayList>(result, isolate());
    2227             : }
    2228             : 
    2229     2259489 : Handle<PropertyArray> Factory::CopyPropertyArrayAndGrow(
    2230             :     Handle<PropertyArray> array, int grow_by, AllocationType allocation) {
    2231     2259489 :   return CopyArrayAndGrow(array, grow_by, allocation);
    2232             : }
    2233             : 
    2234        1893 : Handle<FixedArray> Factory::CopyFixedArrayUpTo(Handle<FixedArray> array,
    2235             :                                                int new_len,
    2236             :                                                AllocationType allocation) {
    2237             :   DCHECK_LE(0, new_len);
    2238             :   DCHECK_LE(new_len, array->length());
    2239        1893 :   if (new_len == 0) return empty_fixed_array();
    2240             : 
    2241        1888 :   HeapObject obj = AllocateRawFixedArray(new_len, allocation);
    2242             :   obj->set_map_after_allocation(*fixed_array_map(), SKIP_WRITE_BARRIER);
    2243             :   Handle<FixedArray> result(FixedArray::cast(obj), isolate());
    2244             :   result->set_length(new_len);
    2245             : 
    2246             :   // Copy the content.
    2247             :   DisallowHeapAllocation no_gc;
    2248             :   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
    2249       12344 :   for (int i = 0; i < new_len; i++) result->set(i, array->get(i), mode);
    2250        1888 :   return result;
    2251             : }
    2252             : 
    2253     1057201 : Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
    2254     1057201 :   if (array->length() == 0) return array;
    2255      749118 :   return CopyArrayWithMap(array, handle(array->map(), isolate()));
    2256             : }
    2257             : 
    2258        1610 : Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
    2259             :     Handle<FixedArray> array) {
    2260             :   DCHECK(Heap::InYoungGeneration(*array));
    2261             :   Handle<FixedArray> result =
    2262        1610 :       CopyFixedArrayUpTo(array, array->length(), AllocationType::kOld);
    2263             : 
    2264             :   // TODO(mvstanton): The map is set twice because of protection against calling
    2265             :   // set() on a COW FixedArray. Issue v8:3221 created to track this, and
    2266             :   // we might then be able to remove this whole method.
    2267             :   result->set_map_after_allocation(*fixed_cow_array_map(), SKIP_WRITE_BARRIER);
    2268        1610 :   return result;
    2269             : }
    2270             : 
    2271       19002 : Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
    2272             :     Handle<FixedDoubleArray> array) {
    2273             :   int len = array->length();
    2274       19002 :   if (len == 0) return array;
    2275             :   Handle<FixedDoubleArray> result = Handle<FixedDoubleArray>::cast(
    2276       19002 :       NewFixedDoubleArray(len, AllocationType::kYoung));
    2277       57006 :   Heap::CopyBlock(
    2278             :       result->address() + FixedDoubleArray::kLengthOffset,
    2279             :       array->address() + FixedDoubleArray::kLengthOffset,
    2280             :       FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
    2281       19002 :   return result;
    2282             : }
    2283             : 
    2284           0 : Handle<FeedbackVector> Factory::CopyFeedbackVector(
    2285             :     Handle<FeedbackVector> array) {
    2286             :   int len = array->length();
    2287             :   HeapObject obj = AllocateRawWithImmortalMap(FeedbackVector::SizeFor(len),
    2288             :                                               AllocationType::kYoung,
    2289           0 :                                               *feedback_vector_map());
    2290             :   Handle<FeedbackVector> result(FeedbackVector::cast(obj), isolate());
    2291             : 
    2292             :   DisallowHeapAllocation no_gc;
    2293             :   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
    2294             : 
    2295             :   // Eliminate the write barrier if possible.
    2296           0 :   if (mode == SKIP_WRITE_BARRIER) {
    2297           0 :     Heap::CopyBlock(result->address() + kTaggedSize,
    2298             :                     result->address() + kTaggedSize,
    2299             :                     FeedbackVector::SizeFor(len) - kTaggedSize);
    2300             :   } else {
    2301             :     // Slow case: Just copy the content one-by-one.
    2302           0 :     result->set_shared_function_info(array->shared_function_info());
    2303           0 :     result->set_optimized_code_weak_or_smi(array->optimized_code_weak_or_smi());
    2304             :     result->set_invocation_count(array->invocation_count());
    2305             :     result->set_profiler_ticks(array->profiler_ticks());
    2306             :     result->set_deopt_count(array->deopt_count());
    2307           0 :     for (int i = 0; i < len; i++) result->set(i, array->get(i), mode);
    2308             :   }
    2309           0 :   return result;
    2310             : }
    2311             : 
    2312    16226980 : Handle<Object> Factory::NewNumber(double value, AllocationType allocation) {
    2313             :   // Materialize as a SMI if possible.
    2314             :   int32_t int_value;
    2315    16226980 :   if (DoubleToSmiInteger(value, &int_value)) {
    2316    10272049 :     return handle(Smi::FromInt(int_value), isolate());
    2317             :   }
    2318     5954931 :   return NewHeapNumber(value, allocation);
    2319             : }
    2320             : 
    2321      355442 : Handle<Object> Factory::NewNumberFromInt(int32_t value,
    2322             :                                          AllocationType allocation) {
    2323      355442 :   if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
    2324             :   // Bypass NewNumber to avoid various redundant checks.
    2325             :   return NewHeapNumber(FastI2D(value), allocation);
    2326             : }
    2327             : 
    2328    12648765 : Handle<Object> Factory::NewNumberFromUint(uint32_t value,
    2329             :                                           AllocationType allocation) {
    2330    12648765 :   int32_t int32v = static_cast<int32_t>(value);
    2331    12648765 :   if (int32v >= 0 && Smi::IsValid(int32v)) {
    2332    12643598 :     return handle(Smi::FromInt(int32v), isolate());
    2333             :   }
    2334        5167 :   return NewHeapNumber(FastUI2D(value), allocation);
    2335             : }
    2336             : 
    2337     6041211 : Handle<HeapNumber> Factory::NewHeapNumber(AllocationType allocation) {
    2338             :   STATIC_ASSERT(HeapNumber::kSize <= kMaxRegularHeapObjectSize);
    2339     6041211 :   Map map = *heap_number_map();
    2340             :   HeapObject result = AllocateRawWithImmortalMap(HeapNumber::kSize, allocation,
    2341     6041211 :                                                  map, kDoubleUnaligned);
    2342     6041211 :   return handle(HeapNumber::cast(result), isolate());
    2343             : }
    2344             : 
    2345       11805 : Handle<MutableHeapNumber> Factory::NewMutableHeapNumber(
    2346             :     AllocationType allocation) {
    2347             :   STATIC_ASSERT(HeapNumber::kSize <= kMaxRegularHeapObjectSize);
    2348       11805 :   Map map = *mutable_heap_number_map();
    2349             :   HeapObject result = AllocateRawWithImmortalMap(
    2350       11805 :       MutableHeapNumber::kSize, allocation, map, kDoubleUnaligned);
    2351       11805 :   return handle(MutableHeapNumber::cast(result), isolate());
    2352             : }
    2353             : 
    2354      162763 : Handle<FreshlyAllocatedBigInt> Factory::NewBigInt(int length,
    2355             :                                                   AllocationType allocation) {
    2356      162763 :   if (length < 0 || length > BigInt::kMaxLength) {
    2357           0 :     isolate()->heap()->FatalProcessOutOfMemory("invalid BigInt length");
    2358             :   }
    2359             :   HeapObject result = AllocateRawWithImmortalMap(BigInt::SizeFor(length),
    2360      162763 :                                                  allocation, *bigint_map());
    2361             :   FreshlyAllocatedBigInt bigint = FreshlyAllocatedBigInt::cast(result);
    2362             :   bigint->clear_padding();
    2363      162763 :   return handle(bigint, isolate());
    2364             : }
    2365             : 
    2366     1156320 : Handle<Object> Factory::NewError(Handle<JSFunction> constructor,
    2367             :                                  MessageTemplate template_index,
    2368             :                                  Handle<Object> arg0, Handle<Object> arg1,
    2369             :                                  Handle<Object> arg2) {
    2370             :   HandleScope scope(isolate());
    2371     1156320 :   if (isolate()->bootstrapper()->IsActive()) {
    2372             :     // During bootstrapping we cannot construct error objects.
    2373             :     return scope.CloseAndEscape(NewStringFromAsciiChecked(
    2374          40 :         MessageFormatter::TemplateString(template_index)));
    2375             :   }
    2376             : 
    2377     1156280 :   if (arg0.is_null()) arg0 = undefined_value();
    2378     1156280 :   if (arg1.is_null()) arg1 = undefined_value();
    2379     1156280 :   if (arg2.is_null()) arg2 = undefined_value();
    2380             : 
    2381             :   Handle<Object> result;
    2382     2312560 :   if (!ErrorUtils::MakeGenericError(isolate(), constructor, template_index,
    2383             :                                     arg0, arg1, arg2, SKIP_NONE)
    2384             :            .ToHandle(&result)) {
    2385             :     // If an exception is thrown while
    2386             :     // running the factory method, use the exception as the result.
    2387             :     DCHECK(isolate()->has_pending_exception());
    2388           0 :     result = handle(isolate()->pending_exception(), isolate());
    2389             :     isolate()->clear_pending_exception();
    2390             :   }
    2391             : 
    2392     1156280 :   return scope.CloseAndEscape(result);
    2393             : }
    2394             : 
    2395       30597 : Handle<Object> Factory::NewError(Handle<JSFunction> constructor,
    2396             :                                  Handle<String> message) {
    2397             :   // Construct a new error object. If an exception is thrown, use the exception
    2398             :   // as the result.
    2399             : 
    2400             :   Handle<Object> no_caller;
    2401             :   MaybeHandle<Object> maybe_error =
    2402             :       ErrorUtils::Construct(isolate(), constructor, constructor, message,
    2403       30597 :                             SKIP_NONE, no_caller, false);
    2404       30597 :   if (maybe_error.is_null()) {
    2405             :     DCHECK(isolate()->has_pending_exception());
    2406             :     maybe_error = handle(isolate()->pending_exception(), isolate());
    2407             :     isolate()->clear_pending_exception();
    2408             :   }
    2409             : 
    2410       30597 :   return maybe_error.ToHandleChecked();
    2411             : }
    2412             : 
    2413         473 : Handle<Object> Factory::NewInvalidStringLengthError() {
    2414         473 :   if (FLAG_abort_on_stack_or_string_length_overflow) {
    2415           0 :     FATAL("Aborting on invalid string length");
    2416             :   }
    2417             :   // Invalidate the "string length" protector.
    2418         473 :   if (isolate()->IsStringLengthOverflowIntact()) {
    2419         143 :     isolate()->InvalidateStringLengthOverflowProtector();
    2420             :   }
    2421         473 :   return NewRangeError(MessageTemplate::kInvalidStringLength);
    2422             : }
    2423             : 
    2424             : #define DEFINE_ERROR(NAME, name)                                              \
    2425             :   Handle<Object> Factory::New##NAME(MessageTemplate template_index,           \
    2426             :                                     Handle<Object> arg0, Handle<Object> arg1, \
    2427             :                                     Handle<Object> arg2) {                    \
    2428             :     return NewError(isolate()->name##_function(), template_index, arg0, arg1, \
    2429             :                     arg2);                                                    \
    2430             :   }
    2431          63 : DEFINE_ERROR(Error, error)
    2432        3004 : DEFINE_ERROR(EvalError, eval_error)
    2433       17812 : DEFINE_ERROR(RangeError, range_error)
    2434      203796 : DEFINE_ERROR(ReferenceError, reference_error)
    2435      384264 : DEFINE_ERROR(SyntaxError, syntax_error)
    2436      390678 : DEFINE_ERROR(TypeError, type_error)
    2437           0 : DEFINE_ERROR(WasmCompileError, wasm_compile_error)
    2438           0 : DEFINE_ERROR(WasmLinkError, wasm_link_error)
    2439      151456 : DEFINE_ERROR(WasmRuntimeError, wasm_runtime_error)
    2440             : #undef DEFINE_ERROR
    2441             : 
    2442    15651774 : Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
    2443             :                                         Handle<SharedFunctionInfo> info,
    2444             :                                         Handle<Context> context,
    2445             :                                         AllocationType allocation) {
    2446    31303539 :   Handle<JSFunction> function(JSFunction::cast(New(map, allocation)),
    2447             :                               isolate());
    2448             : 
    2449    15651765 :   function->initialize_properties();
    2450    15651760 :   function->initialize_elements();
    2451    15651760 :   function->set_shared(*info);
    2452    31303533 :   function->set_code(info->GetCode());
    2453    31303542 :   function->set_context(*context);
    2454    15651766 :   function->set_raw_feedback_cell(*many_closures_cell());
    2455             :   int header_size;
    2456    15651769 :   if (map->has_prototype_slot()) {
    2457             :     header_size = JSFunction::kSizeWithPrototype;
    2458    22694722 :     function->set_prototype_or_initial_map(*the_hole_value());
    2459             :   } else {
    2460             :     header_size = JSFunction::kSizeWithoutPrototype;
    2461             :   }
    2462    15651766 :   InitializeJSObjectBody(function, map, header_size);
    2463    15651748 :   return function;
    2464             : }
    2465             : 
    2466         181 : Handle<JSFunction> Factory::NewFunctionForTest(Handle<String> name) {
    2467             :   NewFunctionArgs args = NewFunctionArgs::ForFunctionWithoutCode(
    2468         181 :       name, isolate()->sloppy_function_map(), LanguageMode::kSloppy);
    2469         181 :   Handle<JSFunction> result = NewFunction(args);
    2470             :   DCHECK(is_sloppy(result->shared()->language_mode()));
    2471         181 :   return result;
    2472             : }
    2473             : 
    2474     2270733 : Handle<JSFunction> Factory::NewFunction(const NewFunctionArgs& args) {
    2475             :   DCHECK(!args.name_.is_null());
    2476             : 
    2477             :   // Create the SharedFunctionInfo.
    2478     2270733 :   Handle<NativeContext> context(isolate()->native_context());
    2479     2270736 :   Handle<Map> map = args.GetMap(isolate());
    2480             :   Handle<SharedFunctionInfo> info =
    2481             :       NewSharedFunctionInfo(args.name_, args.maybe_exported_function_data_,
    2482     4541466 :                             args.maybe_builtin_id_, kNormalFunction);
    2483             : 
    2484             :   // Proper language mode in shared function info will be set later.
    2485             :   DCHECK(is_sloppy(info->language_mode()));
    2486             :   DCHECK(!map->IsUndefined(isolate()));
    2487             : 
    2488             : #ifdef DEBUG
    2489             :   if (isolate()->bootstrapper()->IsActive()) {
    2490             :     Handle<Code> code;
    2491             :     DCHECK(
    2492             :         // During bootstrapping some of these maps could be not created yet.
    2493             :         (*map == context->get(Context::STRICT_FUNCTION_MAP_INDEX)) ||
    2494             :         (*map ==
    2495             :          context->get(Context::STRICT_FUNCTION_WITHOUT_PROTOTYPE_MAP_INDEX)) ||
    2496             :         (*map ==
    2497             :          context->get(
    2498             :              Context::STRICT_FUNCTION_WITH_READONLY_PROTOTYPE_MAP_INDEX)) ||
    2499             :         // Check if it's a creation of an empty or Proxy function during
    2500             :         // bootstrapping.
    2501             :         (args.maybe_builtin_id_ == Builtins::kEmptyFunction ||
    2502             :          args.maybe_builtin_id_ == Builtins::kProxyConstructor));
    2503             :   } else {
    2504             :     DCHECK(
    2505             :         (*map == *isolate()->sloppy_function_map()) ||
    2506             :         (*map == *isolate()->sloppy_function_without_prototype_map()) ||
    2507             :         (*map == *isolate()->sloppy_function_with_readonly_prototype_map()) ||
    2508             :         (*map == *isolate()->strict_function_map()) ||
    2509             :         (*map == *isolate()->strict_function_without_prototype_map()) ||
    2510             :         (*map == *isolate()->native_function_map()));
    2511             :   }
    2512             : #endif
    2513             : 
    2514     2270734 :   Handle<JSFunction> result = NewFunction(map, info, context);
    2515             : 
    2516     2270728 :   if (args.should_set_prototype_) {
    2517      788784 :     result->set_prototype_or_initial_map(
    2518      262928 :         *args.maybe_prototype_.ToHandleChecked());
    2519             :   }
    2520             : 
    2521     2270728 :   if (args.should_set_language_mode_) {
    2522     4064664 :     result->shared()->set_language_mode(args.language_mode_);
    2523             :   }
    2524             : 
    2525     2270727 :   if (args.should_create_and_set_initial_map_) {
    2526             :     ElementsKind elements_kind;
    2527      262928 :     switch (args.type_) {
    2528             :       case JS_ARRAY_TYPE:
    2529             :         elements_kind = PACKED_SMI_ELEMENTS;
    2530             :         break;
    2531             :       case JS_ARGUMENTS_TYPE:
    2532             :         elements_kind = PACKED_ELEMENTS;
    2533         111 :         break;
    2534             :       default:
    2535             :         elements_kind = TERMINAL_FAST_ELEMENTS_KIND;
    2536      262595 :         break;
    2537             :     }
    2538      262928 :     Handle<Map> initial_map = NewMap(args.type_, args.instance_size_,
    2539      525856 :                                      elements_kind, args.inobject_properties_);
    2540      262928 :     result->shared()->set_expected_nof_properties(args.inobject_properties_);
    2541             :     // TODO(littledan): Why do we have this is_generator test when
    2542             :     // NewFunctionPrototype already handles finding an appropriately
    2543             :     // shared prototype?
    2544             :     Handle<HeapObject> prototype = args.maybe_prototype_.ToHandleChecked();
    2545      262928 :     if (!IsResumableFunction(result->shared()->kind())) {
    2546      262928 :       if (prototype->IsTheHole(isolate())) {
    2547      132577 :         prototype = NewFunctionPrototype(result);
    2548             :       }
    2549             :     }
    2550      262928 :     JSFunction::SetInitialMap(result, initial_map, prototype);
    2551             :   }
    2552             : 
    2553     2270727 :   return result;
    2554             : }
    2555             : 
    2556      387240 : Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
    2557             :   // Make sure to use globals from the function's context, since the function
    2558             :   // can be from a different context.
    2559             :   Handle<NativeContext> native_context(function->context()->native_context(),
    2560             :                                        isolate());
    2561             :   Handle<Map> new_map;
    2562      387240 :   if (V8_UNLIKELY(IsAsyncGeneratorFunction(function->shared()->kind()))) {
    2563        2840 :     new_map = handle(native_context->async_generator_object_prototype_map(),
    2564        2840 :                      isolate());
    2565      385820 :   } else if (IsResumableFunction(function->shared()->kind())) {
    2566             :     // Generator and async function prototypes can share maps since they
    2567             :     // don't have "constructor" properties.
    2568             :     new_map =
    2569       14728 :         handle(native_context->generator_object_prototype_map(), isolate());
    2570             :   } else {
    2571             :     // Each function prototype gets a fresh map to avoid unwanted sharing of
    2572             :     // maps between prototypes of different constructors.
    2573      756912 :     Handle<JSFunction> object_function(native_context->object_function(),
    2574      378456 :                                        isolate());
    2575             :     DCHECK(object_function->has_initial_map());
    2576      378456 :     new_map = handle(object_function->initial_map(), isolate());
    2577             :   }
    2578             : 
    2579             :   DCHECK(!new_map->is_prototype_map());
    2580      387240 :   Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
    2581             : 
    2582      387240 :   if (!IsResumableFunction(function->shared()->kind())) {
    2583      378456 :     JSObject::AddProperty(isolate(), prototype, constructor_string(), function,
    2584      378456 :                           DONT_ENUM);
    2585             :   }
    2586             : 
    2587      387240 :   return prototype;
    2588             : }
    2589             : 
    2590         445 : Handle<WeakCell> Factory::NewWeakCell() {
    2591             :   // Allocate the WeakCell object in the old space, because 1) WeakCell weakness
    2592             :   // handling is only implemented in the old space 2) they're supposedly
    2593             :   // long-living. TODO(marja, gsathya): Support WeakCells in Scavenger.
    2594             :   Handle<WeakCell> result(
    2595         890 :       WeakCell::cast(AllocateRawWithImmortalMap(
    2596             :           WeakCell::kSize, AllocationType::kOld, *weak_cell_map())),
    2597             :       isolate());
    2598         445 :   return result;
    2599             : }
    2600             : 
    2601     5314549 : Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
    2602             :     Handle<SharedFunctionInfo> info, Handle<Context> context,
    2603             :     AllocationType allocation) {
    2604             :   Handle<Map> initial_map(
    2605    10629104 :       Map::cast(context->native_context()->get(info->function_map_index())),
    2606             :       isolate());
    2607             :   return NewFunctionFromSharedFunctionInfo(initial_map, info, context,
    2608     5314552 :                                            allocation);
    2609             : }
    2610             : 
    2611     8064194 : Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
    2612             :     Handle<SharedFunctionInfo> info, Handle<Context> context,
    2613             :     Handle<FeedbackCell> feedback_cell, AllocationType allocation) {
    2614             :   Handle<Map> initial_map(
    2615    16128400 :       Map::cast(context->native_context()->get(info->function_map_index())),
    2616             :       isolate());
    2617             :   return NewFunctionFromSharedFunctionInfo(initial_map, info, context,
    2618     8064201 :                                            feedback_cell, allocation);
    2619             : }
    2620             : 
    2621     5316844 : Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
    2622             :     Handle<Map> initial_map, Handle<SharedFunctionInfo> info,
    2623             :     Handle<Context> context, AllocationType allocation) {
    2624             :   DCHECK_EQ(JS_FUNCTION_TYPE, initial_map->instance_type());
    2625             :   Handle<JSFunction> result =
    2626     5316844 :       NewFunction(initial_map, info, context, allocation);
    2627             : 
    2628             :   // Give compiler a chance to pre-initialize.
    2629     5316843 :   Compiler::PostInstantiation(result, allocation);
    2630             : 
    2631     5316848 :   return result;
    2632             : }
    2633             : 
    2634     8064199 : Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
    2635             :     Handle<Map> initial_map, Handle<SharedFunctionInfo> info,
    2636             :     Handle<Context> context, Handle<FeedbackCell> feedback_cell,
    2637             :     AllocationType allocation) {
    2638             :   DCHECK_EQ(JS_FUNCTION_TYPE, initial_map->instance_type());
    2639             :   Handle<JSFunction> result =
    2640     8064199 :       NewFunction(initial_map, info, context, allocation);
    2641             : 
    2642             :   // Bump the closure count that is encoded in the feedback cell's map.
    2643     8064171 :   if (feedback_cell->map() == *no_closures_cell_map()) {
    2644     2633252 :     feedback_cell->set_map(*one_closure_cell_map());
    2645     5430919 :   } else if (feedback_cell->map() == *one_closure_cell_map()) {
    2646      170086 :     feedback_cell->set_map(*many_closures_cell_map());
    2647             :   } else {
    2648             :     DCHECK(feedback_cell->map() == *many_closures_cell_map());
    2649             :   }
    2650             : 
    2651             :   // Check that the optimized code in the feedback cell wasn't marked for
    2652             :   // deoptimization while not pointed to by any live JSFunction.
    2653     8064170 :   if (feedback_cell->value()->IsFeedbackVector()) {
    2654     7787493 :     FeedbackVector::cast(feedback_cell->value())
    2655             :         ->EvictOptimizedCodeMarkedForDeoptimization(
    2656     3893748 :             *info, "new function from shared function info");
    2657             :   }
    2658     8064167 :   result->set_raw_feedback_cell(*feedback_cell);
    2659             : 
    2660             :   // Give compiler a chance to pre-initialize.
    2661     8064185 :   Compiler::PostInstantiation(result, allocation);
    2662             : 
    2663     8064180 :   return result;
    2664             : }
    2665             : 
    2666     2240169 : Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
    2667             :   return NewFixedArrayWithMap<ScopeInfo>(RootIndex::kScopeInfoMap, length,
    2668     2240178 :                                          AllocationType::kOld);
    2669             : }
    2670             : 
    2671        1257 : Handle<ModuleInfo> Factory::NewModuleInfo() {
    2672             :   return NewFixedArrayWithMap<ModuleInfo>(
    2673        1257 :       RootIndex::kModuleInfoMap, ModuleInfo::kLength, AllocationType::kOld);
    2674             : }
    2675             : 
    2676       63711 : Handle<PreparseData> Factory::NewPreparseData(int data_length,
    2677             :                                               int children_length) {
    2678             :   int size = PreparseData::SizeFor(data_length, children_length);
    2679             :   Handle<PreparseData> result(
    2680      127422 :       PreparseData::cast(AllocateRawWithImmortalMap(size, AllocationType::kOld,
    2681             :                                                     *preparse_data_map())),
    2682             :       isolate());
    2683             :   result->set_data_length(data_length);
    2684             :   result->set_children_length(children_length);
    2685       63711 :   MemsetTagged(result->inner_data_start(), *null_value(), children_length);
    2686       63711 :   result->clear_padding();
    2687       63711 :   return result;
    2688             : }
    2689             : 
    2690             : Handle<UncompiledDataWithoutPreparseData>
    2691     2054249 : Factory::NewUncompiledDataWithoutPreparseData(Handle<String> inferred_name,
    2692             :                                               int32_t start_position,
    2693             :                                               int32_t end_position,
    2694             :                                               int32_t function_literal_id) {
    2695             :   Handle<UncompiledDataWithoutPreparseData> result(
    2696     4108499 :       UncompiledDataWithoutPreparseData::cast(New(
    2697             :           uncompiled_data_without_preparse_data_map(), AllocationType::kOld)),
    2698             :       isolate());
    2699             : 
    2700     6162746 :   UncompiledData::Initialize(*result, *inferred_name, start_position,
    2701     2054250 :                              end_position, function_literal_id);
    2702     2054248 :   return result;
    2703             : }
    2704             : 
    2705             : Handle<UncompiledDataWithPreparseData>
    2706       59658 : Factory::NewUncompiledDataWithPreparseData(Handle<String> inferred_name,
    2707             :                                            int32_t start_position,
    2708             :                                            int32_t end_position,
    2709             :                                            int32_t function_literal_id,
    2710             :                                            Handle<PreparseData> preparse_data) {
    2711             :   Handle<UncompiledDataWithPreparseData> result(
    2712             :       UncompiledDataWithPreparseData::cast(
    2713      119316 :           New(uncompiled_data_with_preparse_data_map(), AllocationType::kOld)),
    2714             :       isolate());
    2715             : 
    2716       59658 :   UncompiledDataWithPreparseData::Initialize(
    2717             :       *result, *inferred_name, start_position, end_position,
    2718       59658 :       function_literal_id, *preparse_data);
    2719             : 
    2720       59658 :   return result;
    2721             : }
    2722             : 
    2723        3914 : Handle<JSObject> Factory::NewExternal(void* value) {
    2724        3914 :   Handle<Foreign> foreign = NewForeign(reinterpret_cast<Address>(value));
    2725        3914 :   Handle<JSObject> external = NewJSObjectFromMap(external_map());
    2726        7828 :   external->SetEmbedderField(0, *foreign);
    2727        3914 :   return external;
    2728             : }
    2729             : 
    2730     1907008 : Handle<CodeDataContainer> Factory::NewCodeDataContainer(int flags) {
    2731             :   Handle<CodeDataContainer> data_container(
    2732             :       CodeDataContainer::cast(
    2733     3814023 :           New(code_data_container_map(), AllocationType::kOld)),
    2734             :       isolate());
    2735             :   data_container->set_next_code_link(*undefined_value(), SKIP_WRITE_BARRIER);
    2736             :   data_container->set_kind_specific_flags(flags);
    2737             :   data_container->clear_padding();
    2738     1907015 :   return data_container;
    2739             : }
    2740             : 
    2741     1589578 : MaybeHandle<Code> Factory::TryNewCode(
    2742             :     const CodeDesc& desc, Code::Kind kind, Handle<Object> self_ref,
    2743             :     int32_t builtin_index, MaybeHandle<ByteArray> maybe_source_position_table,
    2744             :     MaybeHandle<DeoptimizationData> maybe_deopt_data, Movability movability,
    2745             :     bool is_turbofanned, int stack_slots) {
    2746             :   // Allocate objects needed for code initialization.
    2747             :   Handle<ByteArray> reloc_info =
    2748     1589578 :       NewByteArray(desc.reloc_size, Builtins::IsBuiltinId(builtin_index)
    2749             :                                         ? AllocationType::kReadOnly
    2750     3179156 :                                         : AllocationType::kOld);
    2751     1589581 :   Handle<CodeDataContainer> data_container = NewCodeDataContainer(0);
    2752             :   Handle<ByteArray> source_position_table =
    2753             :       maybe_source_position_table.is_null()
    2754             :           ? empty_byte_array()
    2755     3179172 :           : maybe_source_position_table.ToHandleChecked();
    2756             :   Handle<DeoptimizationData> deopt_data =
    2757             :       maybe_deopt_data.is_null() ? DeoptimizationData::Empty(isolate())
    2758     3179172 :                                  : maybe_deopt_data.ToHandleChecked();
    2759             :   Handle<Code> code;
    2760             :   {
    2761             :     int object_size = ComputeCodeObjectSize(desc);
    2762             : 
    2763             :     Heap* heap = isolate()->heap();
    2764     1589582 :     CodePageCollectionMemoryModificationScope code_allocation(heap);
    2765             :     HeapObject result =
    2766     1589583 :         heap->AllocateRawWithLightRetry(object_size, AllocationType::kCode);
    2767             : 
    2768             :     // Return an empty handle if we cannot allocate the code object.
    2769     1589579 :     if (result.is_null()) return MaybeHandle<Code>();
    2770             : 
    2771     1589579 :     if (movability == kImmovable) {
    2772           0 :       result = heap->EnsureImmovableCode(result, object_size);
    2773             :     }
    2774             : 
    2775             :     // The code object has not been fully initialized yet.  We rely on the
    2776             :     // fact that no allocation will happen from this point on.
    2777             :     DisallowHeapAllocation no_gc;
    2778             : 
    2779             :     result->set_map_after_allocation(*code_map(), SKIP_WRITE_BARRIER);
    2780             :     code = handle(Code::cast(result), isolate());
    2781             : 
    2782     1589581 :     InitializeCode(heap, code, object_size, desc, kind, self_ref, builtin_index,
    2783             :                    source_position_table, deopt_data, reloc_info,
    2784     1589581 :                    data_container, is_turbofanned, stack_slots);
    2785             : 
    2786             :     // Flush the instruction cache before changing the permissions.
    2787             :     // Note: we do this before setting permissions to ReadExecute because on
    2788             :     // some older ARM kernels there is a bug which causes an access error on
    2789             :     // cache flush instructions to trigger access error on non-writable memory.
    2790             :     // See https://bugs.chromium.org/p/v8/issues/detail?id=8157
    2791     1589585 :     code->FlushICache();
    2792             :   }
    2793             : 
    2794     1589584 :   return code;
    2795             : }
    2796             : 
    2797      317395 : Handle<Code> Factory::NewCode(
    2798             :     const CodeDesc& desc, Code::Kind kind, Handle<Object> self_ref,
    2799             :     int32_t builtin_index, MaybeHandle<ByteArray> maybe_source_position_table,
    2800             :     MaybeHandle<DeoptimizationData> maybe_deopt_data, Movability movability,
    2801             :     bool is_turbofanned, int stack_slots) {
    2802             :   // Allocate objects needed for code initialization.
    2803             :   Handle<ByteArray> reloc_info =
    2804      317395 :       NewByteArray(desc.reloc_size, Builtins::IsBuiltinId(builtin_index)
    2805             :                                         ? AllocationType::kReadOnly
    2806      634790 :                                         : AllocationType::kOld);
    2807      317395 :   Handle<CodeDataContainer> data_container = NewCodeDataContainer(0);
    2808             :   Handle<ByteArray> source_position_table =
    2809             :       maybe_source_position_table.is_null()
    2810             :           ? empty_byte_array()
    2811      634790 :           : maybe_source_position_table.ToHandleChecked();
    2812             :   Handle<DeoptimizationData> deopt_data =
    2813             :       maybe_deopt_data.is_null() ? DeoptimizationData::Empty(isolate())
    2814      321325 :                                  : maybe_deopt_data.ToHandleChecked();
    2815             : 
    2816             :   Handle<Code> code;
    2817             :   {
    2818             :     int object_size = ComputeCodeObjectSize(desc);
    2819             : 
    2820             :     Heap* heap = isolate()->heap();
    2821      317395 :     CodePageCollectionMemoryModificationScope code_allocation(heap);
    2822             :     HeapObject result =
    2823      317395 :         heap->AllocateRawWithRetryOrFail(object_size, AllocationType::kCode);
    2824      317395 :     if (movability == kImmovable) {
    2825       44794 :       result = heap->EnsureImmovableCode(result, object_size);
    2826             :     }
    2827             : 
    2828             :     // The code object has not been fully initialized yet.  We rely on the
    2829             :     // fact that no allocation will happen from this point on.
    2830             :     DisallowHeapAllocation no_gc;
    2831             : 
    2832             :     result->set_map_after_allocation(*code_map(), SKIP_WRITE_BARRIER);
    2833             :     code = handle(Code::cast(result), isolate());
    2834             : 
    2835      317395 :     InitializeCode(heap, code, object_size, desc, kind, self_ref, builtin_index,
    2836             :                    source_position_table, deopt_data, reloc_info,
    2837      317395 :                    data_container, is_turbofanned, stack_slots);
    2838             : 
    2839             :     // Flush the instruction cache before changing the permissions.
    2840             :     // Note: we do this before setting permissions to ReadExecute because on
    2841             :     // some older ARM kernels there is a bug which causes an access error on
    2842             :     // cache flush instructions to trigger access error on non-writable memory.
    2843             :     // See https://bugs.chromium.org/p/v8/issues/detail?id=8157
    2844      317395 :     code->FlushICache();
    2845             :   }
    2846             : 
    2847      317395 :   return code;
    2848             : }
    2849             : 
    2850       85232 : Handle<Code> Factory::NewOffHeapTrampolineFor(Handle<Code> code,
    2851             :                                               Address off_heap_entry) {
    2852       85232 :   CHECK_NOT_NULL(isolate()->embedded_blob());
    2853      170464 :   CHECK_NE(0, isolate()->embedded_blob_size());
    2854       85232 :   CHECK(Builtins::IsIsolateIndependentBuiltin(*code));
    2855             : 
    2856             :   Handle<Code> result =
    2857       85232 :       Builtins::GenerateOffHeapTrampolineFor(isolate(), off_heap_entry);
    2858             : 
    2859             :   // The trampoline code object must inherit specific flags from the original
    2860             :   // builtin (e.g. the safepoint-table offset). We set them manually here.
    2861             : 
    2862             :   {
    2863             :     MemoryChunk* chunk = MemoryChunk::FromHeapObject(*result);
    2864       85232 :     CodePageMemoryModificationScope code_allocation(chunk);
    2865             : 
    2866             :     const bool set_is_off_heap_trampoline = true;
    2867             :     const int stack_slots =
    2868       85232 :         code->has_safepoint_info() ? code->stack_slots() : 0;
    2869             :     result->code_data_container()->set_kind_specific_flags(
    2870             :         code->code_data_container()->kind_specific_flags());
    2871      340928 :     result->initialize_flags(code->kind(), code->has_unwinding_info(),
    2872             :                              code->is_turbofanned(), stack_slots,
    2873       85232 :                              set_is_off_heap_trampoline);
    2874             :     result->set_builtin_index(code->builtin_index());
    2875             :     result->set_safepoint_table_offset(code->safepoint_table_offset());
    2876             :     result->set_handler_table_offset(code->handler_table_offset());
    2877             :     result->set_constant_pool_offset(code->constant_pool_offset());
    2878             :     result->set_code_comments_offset(code->code_comments_offset());
    2879             : 
    2880             :     // Replace the newly generated trampoline's RelocInfo ByteArray with the
    2881             :     // canonical one stored in the roots to avoid duplicating it for every
    2882             :     // single builtin.
    2883             :     ByteArray canonical_reloc_info =
    2884       85232 :         ReadOnlyRoots(isolate()).off_heap_trampoline_relocation_info();
    2885             : #ifdef DEBUG
    2886             :     // Verify that the contents are the same.
    2887             :     ByteArray reloc_info = result->relocation_info();
    2888             :     DCHECK_EQ(reloc_info->length(), canonical_reloc_info->length());
    2889             :     for (int i = 0; i < reloc_info->length(); ++i) {
    2890             :       DCHECK_EQ(reloc_info->get(i), canonical_reloc_info->get(i));
    2891             :     }
    2892             : #endif
    2893       85232 :     result->set_relocation_info(canonical_reloc_info);
    2894             :   }
    2895             : 
    2896       85232 :   return result;
    2897             : }
    2898             : 
    2899          34 : Handle<Code> Factory::CopyCode(Handle<Code> code) {
    2900             :   Handle<CodeDataContainer> data_container =
    2901          34 :       NewCodeDataContainer(code->code_data_container()->kind_specific_flags());
    2902             : 
    2903             :   Heap* heap = isolate()->heap();
    2904             :   Handle<Code> new_code;
    2905             :   {
    2906          34 :     int obj_size = code->Size();
    2907          34 :     CodePageCollectionMemoryModificationScope code_allocation(heap);
    2908             :     HeapObject result =
    2909          34 :         heap->AllocateRawWithRetryOrFail(obj_size, AllocationType::kCode);
    2910             : 
    2911             :     // Copy code object.
    2912             :     Address old_addr = code->address();
    2913             :     Address new_addr = result->address();
    2914             :     Heap::CopyBlock(new_addr, old_addr, obj_size);
    2915             :     new_code = handle(Code::cast(result), isolate());
    2916             : 
    2917             :     // Set the {CodeDataContainer}, it cannot be shared.
    2918          34 :     new_code->set_code_data_container(*data_container);
    2919             : 
    2920          68 :     new_code->Relocate(new_addr - old_addr);
    2921             :     // We have to iterate over the object and process its pointers when black
    2922             :     // allocation is on.
    2923          68 :     heap->incremental_marking()->ProcessBlackAllocatedObject(*new_code);
    2924             :     // Record all references to embedded objects in the new code object.
    2925             :     WriteBarrierForCode(*new_code);
    2926             :   }
    2927             : 
    2928             : #ifdef VERIFY_HEAP
    2929             :   if (FLAG_verify_heap) new_code->ObjectVerify(isolate());
    2930             : #endif
    2931             :   DCHECK(IsAligned(new_code->address(), kCodeAlignment));
    2932             :   DCHECK_IMPLIES(
    2933             :       !heap->memory_allocator()->code_range().is_empty(),
    2934             :       heap->memory_allocator()->code_range().contains(new_code->address()));
    2935          34 :   return new_code;
    2936             : }
    2937             : 
    2938       10601 : Handle<BytecodeArray> Factory::CopyBytecodeArray(
    2939             :     Handle<BytecodeArray> bytecode_array) {
    2940             :   int size = BytecodeArray::SizeFor(bytecode_array->length());
    2941             :   HeapObject result = AllocateRawWithImmortalMap(size, AllocationType::kOld,
    2942       10601 :                                                  *bytecode_array_map());
    2943             : 
    2944             :   Handle<BytecodeArray> copy(BytecodeArray::cast(result), isolate());
    2945             :   copy->set_length(bytecode_array->length());
    2946             :   copy->set_frame_size(bytecode_array->frame_size());
    2947             :   copy->set_parameter_count(bytecode_array->parameter_count());
    2948             :   copy->set_incoming_new_target_or_generator_register(
    2949             :       bytecode_array->incoming_new_target_or_generator_register());
    2950       10601 :   copy->set_constant_pool(bytecode_array->constant_pool());
    2951       10601 :   copy->set_handler_table(bytecode_array->handler_table());
    2952       10601 :   copy->set_source_position_table(bytecode_array->source_position_table());
    2953             :   copy->set_osr_loop_nesting_level(bytecode_array->osr_loop_nesting_level());
    2954             :   copy->set_bytecode_age(bytecode_array->bytecode_age());
    2955       10601 :   bytecode_array->CopyBytecodesTo(*copy);
    2956       10601 :   return copy;
    2957             : }
    2958             : 
    2959    14972960 : Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
    2960             :                                       AllocationType allocation) {
    2961    14972960 :   JSFunction::EnsureHasInitialMap(constructor);
    2962             :   Handle<Map> map(constructor->initial_map(), isolate());
    2963    14972956 :   return NewJSObjectFromMap(map, allocation);
    2964             : }
    2965             : 
    2966      442150 : Handle<JSObject> Factory::NewJSObjectWithNullProto(AllocationType allocation) {
    2967             :   Handle<JSObject> result =
    2968      442150 :       NewJSObject(isolate()->object_function(), allocation);
    2969             :   Handle<Map> new_map = Map::Copy(
    2970      442148 :       isolate(), Handle<Map>(result->map(), isolate()), "ObjectWithNullProto");
    2971      442151 :   Map::SetPrototype(isolate(), new_map, null_value());
    2972      442152 :   JSObject::MigrateToMap(result, new_map);
    2973      442151 :   return result;
    2974             : }
    2975             : 
    2976       91736 : Handle<JSGlobalObject> Factory::NewJSGlobalObject(
    2977             :     Handle<JSFunction> constructor) {
    2978             :   DCHECK(constructor->has_initial_map());
    2979             :   Handle<Map> map(constructor->initial_map(), isolate());
    2980             :   DCHECK(map->is_dictionary_map());
    2981             : 
    2982             :   // Make sure no field properties are described in the initial map.
    2983             :   // This guarantees us that normalizing the properties does not
    2984             :   // require us to change property values to PropertyCells.
    2985             :   DCHECK_EQ(map->NextFreePropertyIndex(), 0);
    2986             : 
    2987             :   // Make sure we don't have a ton of pre-allocated slots in the
    2988             :   // global objects. They will be unused once we normalize the object.
    2989             :   DCHECK_EQ(map->UnusedPropertyFields(), 0);
    2990             :   DCHECK_EQ(map->GetInObjectProperties(), 0);
    2991             : 
    2992             :   // Initial size of the backing store to avoid resize of the storage during
    2993             :   // bootstrapping. The size differs between the JS global object ad the
    2994             :   // builtins object.
    2995             :   int initial_size = 64;
    2996             : 
    2997             :   // Allocate a dictionary object for backing storage.
    2998       91736 :   int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
    2999             :   Handle<GlobalDictionary> dictionary =
    3000       91736 :       GlobalDictionary::New(isolate(), at_least_space_for);
    3001             : 
    3002             :   // The global object might be created from an object template with accessors.
    3003             :   // Fill these accessors into the dictionary.
    3004             :   Handle<DescriptorArray> descs(map->instance_descriptors(), isolate());
    3005       91736 :   for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
    3006           0 :     PropertyDetails details = descs->GetDetails(i);
    3007             :     // Only accessors are expected.
    3008             :     DCHECK_EQ(kAccessor, details.kind());
    3009             :     PropertyDetails d(kAccessor, details.attributes(),
    3010             :                       PropertyCellType::kMutable);
    3011             :     Handle<Name> name(descs->GetKey(i), isolate());
    3012           0 :     Handle<PropertyCell> cell = NewPropertyCell(name);
    3013           0 :     cell->set_value(descs->GetStrongValue(i));
    3014             :     // |dictionary| already contains enough space for all properties.
    3015           0 :     USE(GlobalDictionary::Add(isolate(), dictionary, name, cell, d));
    3016             :   }
    3017             : 
    3018             :   // Allocate the global object and initialize it with the backing store.
    3019             :   Handle<JSGlobalObject> global(
    3020      183472 :       JSGlobalObject::cast(New(map, AllocationType::kOld)), isolate());
    3021       91736 :   InitializeJSObjectFromMap(global, dictionary, map);
    3022             : 
    3023             :   // Create a new map for the global object.
    3024       91736 :   Handle<Map> new_map = Map::CopyDropDescriptors(isolate(), map);
    3025       91736 :   new_map->set_may_have_interesting_symbols(true);
    3026       91736 :   new_map->set_is_dictionary_map(true);
    3027       91803 :   LOG(isolate(), MapDetails(*new_map));
    3028             : 
    3029             :   // Set up the global object as a normalized object.
    3030      183472 :   global->set_global_dictionary(*dictionary);
    3031       91736 :   global->synchronized_set_map(*new_map);
    3032             : 
    3033             :   // Make sure result is a global object with properties in dictionary.
    3034             :   DCHECK(global->IsJSGlobalObject() && !global->HasFastProperties());
    3035       91736 :   return global;
    3036             : }
    3037             : 
    3038    21551489 : void Factory::InitializeJSObjectFromMap(Handle<JSObject> obj,
    3039             :                                         Handle<Object> properties,
    3040             :                                         Handle<Map> map) {
    3041    21551489 :   obj->set_raw_properties_or_hash(*properties);
    3042    21551476 :   obj->initialize_elements();
    3043             :   // TODO(1240798): Initialize the object's body using valid initial values
    3044             :   // according to the object's initial map.  For example, if the map's
    3045             :   // instance type is JS_ARRAY_TYPE, the length field should be initialized
    3046             :   // to a number (e.g. Smi::kZero) and the elements initialized to a
    3047             :   // fixed array (e.g. Heap::empty_fixed_array()).  Currently, the object
    3048             :   // verification code has to cope with (temporarily) invalid objects.  See
    3049             :   // for example, JSArray::JSArrayVerify).
    3050    21551481 :   InitializeJSObjectBody(obj, map, JSObject::kHeaderSize);
    3051    21551474 : }
    3052             : 
    3053    37203233 : void Factory::InitializeJSObjectBody(Handle<JSObject> obj, Handle<Map> map,
    3054             :                                      int start_offset) {
    3055    53241078 :   if (start_offset == map->instance_size()) return;
    3056             :   DCHECK_LT(start_offset, map->instance_size());
    3057             : 
    3058             :   // We cannot always fill with one_pointer_filler_map because objects
    3059             :   // created from API functions expect their embedder fields to be initialized
    3060             :   // with undefined_value.
    3061             :   // Pre-allocated fields need to be initialized with undefined_value as well
    3062             :   // so that object accesses before the constructor completes (e.g. in the
    3063             :   // debugger) will not cause a crash.
    3064             : 
    3065             :   // In case of Array subclassing the |map| could already be transitioned
    3066             :   // to different elements kind from the initial map on which we track slack.
    3067             :   bool in_progress = map->IsInobjectSlackTrackingInProgress();
    3068             :   Object filler;
    3069    21165388 :   if (in_progress) {
    3070      231241 :     filler = *one_pointer_filler_map();
    3071             :   } else {
    3072    20934147 :     filler = *undefined_value();
    3073             :   }
    3074    42330776 :   obj->InitializeBody(*map, start_offset, *undefined_value(), filler);
    3075    21165379 :   if (in_progress) {
    3076      231242 :     map->FindRootMap(isolate())->InobjectSlackTrackingStep(isolate());
    3077             :   }
    3078             : }
    3079             : 
    3080    21368022 : Handle<JSObject> Factory::NewJSObjectFromMap(
    3081             :     Handle<Map> map, AllocationType allocation,
    3082             :     Handle<AllocationSite> allocation_site) {
    3083             :   // JSFunctions should be allocated using AllocateFunction to be
    3084             :   // properly initialized.
    3085             :   DCHECK(map->instance_type() != JS_FUNCTION_TYPE);
    3086             : 
    3087             :   // Both types of global objects should be allocated using
    3088             :   // AllocateGlobalObject to be properly initialized.
    3089             :   DCHECK(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
    3090             : 
    3091             :   HeapObject obj =
    3092    21368022 :       AllocateRawWithAllocationSite(map, allocation, allocation_site);
    3093             :   Handle<JSObject> js_obj(JSObject::cast(obj), isolate());
    3094             : 
    3095    21367995 :   InitializeJSObjectFromMap(js_obj, empty_fixed_array(), map);
    3096             : 
    3097             :   DCHECK(js_obj->HasFastElements() || js_obj->HasFixedTypedArrayElements() ||
    3098             :          js_obj->HasFastStringWrapperElements() ||
    3099             :          js_obj->HasFastArgumentsElements());
    3100    21367965 :   return js_obj;
    3101             : }
    3102             : 
    3103        3652 : Handle<JSObject> Factory::NewSlowJSObjectFromMap(Handle<Map> map, int capacity,
    3104             :                                                  AllocationType allocation) {
    3105             :   DCHECK(map->is_dictionary_map());
    3106             :   Handle<NameDictionary> object_properties =
    3107        3652 :       NameDictionary::New(isolate(), capacity);
    3108        3652 :   Handle<JSObject> js_object = NewJSObjectFromMap(map, allocation);
    3109        7304 :   js_object->set_raw_properties_or_hash(*object_properties);
    3110        3652 :   return js_object;
    3111             : }
    3112             : 
    3113          48 : Handle<JSObject> Factory::NewSlowJSObjectWithPropertiesAndElements(
    3114             :     Handle<HeapObject> prototype, Handle<NameDictionary> properties,
    3115             :     Handle<FixedArrayBase> elements, AllocationType allocation) {
    3116          48 :   Handle<Map> object_map = isolate()->slow_object_with_object_prototype_map();
    3117          48 :   if (object_map->prototype() != *prototype) {
    3118          48 :     object_map = Map::TransitionToPrototype(isolate(), object_map, prototype);
    3119             :   }
    3120             :   DCHECK(object_map->is_dictionary_map());
    3121          48 :   Handle<JSObject> object = NewJSObjectFromMap(object_map, allocation);
    3122          96 :   object->set_raw_properties_or_hash(*properties);
    3123          48 :   if (*elements != ReadOnlyRoots(isolate()).empty_fixed_array()) {
    3124             :     DCHECK(elements->IsNumberDictionary());
    3125             :     object_map =
    3126          12 :         JSObject::GetElementsTransitionMap(object, DICTIONARY_ELEMENTS);
    3127          12 :     JSObject::MigrateToMap(object, object_map);
    3128          12 :     object->set_elements(*elements);
    3129             :   }
    3130          48 :   return object;
    3131             : }
    3132             : 
    3133     1686836 : Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
    3134             :                                     AllocationType allocation) {
    3135     1686838 :   NativeContext native_context = isolate()->raw_native_context();
    3136     1686838 :   Map map = native_context->GetInitialJSArrayMap(elements_kind);
    3137     1686838 :   if (map.is_null()) {
    3138           0 :     JSFunction array_function = native_context->array_function();
    3139             :     map = array_function->initial_map();
    3140             :   }
    3141             :   return Handle<JSArray>::cast(
    3142     1686838 :       NewJSObjectFromMap(handle(map, isolate()), allocation));
    3143             : }
    3144             : 
    3145      563534 : Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind, int length,
    3146             :                                     int capacity,
    3147             :                                     ArrayStorageAllocationMode mode,
    3148             :                                     AllocationType allocation) {
    3149      563534 :   Handle<JSArray> array = NewJSArray(elements_kind, allocation);
    3150      563534 :   NewJSArrayStorage(array, length, capacity, mode);
    3151      563534 :   return array;
    3152             : }
    3153             : 
    3154     1123305 : Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
    3155             :                                                 ElementsKind elements_kind,
    3156             :                                                 int length,
    3157             :                                                 AllocationType allocation) {
    3158             :   DCHECK(length <= elements->length());
    3159     1123305 :   Handle<JSArray> array = NewJSArray(elements_kind, allocation);
    3160             : 
    3161     1123308 :   array->set_elements(*elements);
    3162             :   array->set_length(Smi::FromInt(length));
    3163     1123307 :   JSObject::ValidateElements(*array);
    3164     1123307 :   return array;
    3165             : }
    3166             : 
    3167     1017540 : void Factory::NewJSArrayStorage(Handle<JSArray> array, int length, int capacity,
    3168             :                                 ArrayStorageAllocationMode mode) {
    3169             :   DCHECK(capacity >= length);
    3170             : 
    3171     1017540 :   if (capacity == 0) {
    3172      677179 :     array->set_length(Smi::kZero);
    3173     1354358 :     array->set_elements(*empty_fixed_array());
    3174             :     return;
    3175             :   }
    3176             : 
    3177             :   HandleScope inner_scope(isolate());
    3178             :   Handle<FixedArrayBase> elms;
    3179             :   ElementsKind elements_kind = array->GetElementsKind();
    3180      340361 :   if (IsDoubleElementsKind(elements_kind)) {
    3181          81 :     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
    3182          69 :       elms = NewFixedDoubleArray(capacity);
    3183             :     } else {
    3184             :       DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
    3185          12 :       elms = NewFixedDoubleArrayWithHoles(capacity);
    3186             :     }
    3187             :   } else {
    3188             :     DCHECK(IsSmiOrObjectElementsKind(elements_kind));
    3189      340280 :     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
    3190             :       elms = NewUninitializedFixedArray(capacity);
    3191             :     } else {
    3192             :       DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
    3193             :       elms = NewFixedArrayWithHoles(capacity);
    3194             :     }
    3195             :   }
    3196             : 
    3197      340361 :   array->set_elements(*elms);
    3198             :   array->set_length(Smi::FromInt(length));
    3199             : }
    3200             : 
    3201       50114 : Handle<JSWeakMap> Factory::NewJSWeakMap() {
    3202       50114 :   NativeContext native_context = isolate()->raw_native_context();
    3203      100228 :   Handle<Map> map(native_context->js_weak_map_fun()->initial_map(), isolate());
    3204      100228 :   Handle<JSWeakMap> weakmap(JSWeakMap::cast(*NewJSObjectFromMap(map)),
    3205             :                             isolate());
    3206             :   {
    3207             :     // Do not leak handles for the hash table, it would make entries strong.
    3208             :     HandleScope scope(isolate());
    3209       50114 :     JSWeakCollection::Initialize(weakmap, isolate());
    3210             :   }
    3211       50114 :   return weakmap;
    3212             : }
    3213             : 
    3214         348 : Handle<JSModuleNamespace> Factory::NewJSModuleNamespace() {
    3215         348 :   Handle<Map> map = isolate()->js_module_namespace_map();
    3216             :   Handle<JSModuleNamespace> module_namespace(
    3217         348 :       Handle<JSModuleNamespace>::cast(NewJSObjectFromMap(map)));
    3218             :   FieldIndex index = FieldIndex::ForDescriptor(
    3219         348 :       *map, JSModuleNamespace::kToStringTagFieldIndex);
    3220         696 :   module_namespace->FastPropertyAtPut(index,
    3221        1044 :                                       ReadOnlyRoots(isolate()).Module_string());
    3222         348 :   return module_namespace;
    3223             : }
    3224             : 
    3225        8680 : Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
    3226             :     Handle<JSFunction> function) {
    3227             :   DCHECK(IsResumableFunction(function->shared()->kind()));
    3228        8680 :   JSFunction::EnsureHasInitialMap(function);
    3229             :   Handle<Map> map(function->initial_map(), isolate());
    3230             : 
    3231             :   DCHECK(map->instance_type() == JS_GENERATOR_OBJECT_TYPE ||
    3232             :          map->instance_type() == JS_ASYNC_GENERATOR_OBJECT_TYPE);
    3233             : 
    3234        8680 :   return Handle<JSGeneratorObject>::cast(NewJSObjectFromMap(map));
    3235             : }
    3236             : 
    3237        1822 : Handle<Module> Factory::NewModule(Handle<SharedFunctionInfo> code) {
    3238        3644 :   Handle<ModuleInfo> module_info(code->scope_info()->ModuleDescriptorInfo(),
    3239        1822 :                                  isolate());
    3240             :   Handle<ObjectHashTable> exports =
    3241        1822 :       ObjectHashTable::New(isolate(), module_info->RegularExportCount());
    3242             :   Handle<FixedArray> regular_exports =
    3243        3644 :       NewFixedArray(module_info->RegularExportCount());
    3244             :   Handle<FixedArray> regular_imports =
    3245             :       NewFixedArray(module_info->regular_imports()->length());
    3246             :   int requested_modules_length = module_info->module_requests()->length();
    3247             :   Handle<FixedArray> requested_modules =
    3248             :       requested_modules_length > 0 ? NewFixedArray(requested_modules_length)
    3249        1822 :                                    : empty_fixed_array();
    3250             : 
    3251             :   ReadOnlyRoots roots(isolate());
    3252             :   Handle<Module> module =
    3253        1822 :       Handle<Module>::cast(NewStruct(MODULE_TYPE, AllocationType::kOld));
    3254        3644 :   module->set_code(*code);
    3255        1822 :   module->set_exports(*exports);
    3256        1822 :   module->set_regular_exports(*regular_exports);
    3257        1822 :   module->set_regular_imports(*regular_imports);
    3258        1822 :   module->set_hash(isolate()->GenerateIdentityHash(Smi::kMaxValue));
    3259        3644 :   module->set_module_namespace(roots.undefined_value());
    3260        1822 :   module->set_requested_modules(*requested_modules);
    3261        3644 :   module->set_script(Script::cast(code->script()));
    3262             :   module->set_status(Module::kUninstantiated);
    3263        3644 :   module->set_exception(roots.the_hole_value());
    3264        3644 :   module->set_import_meta(roots.the_hole_value());
    3265             :   module->set_dfs_index(-1);
    3266             :   module->set_dfs_ancestor_index(-1);
    3267        1822 :   return module;
    3268             : }
    3269             : 
    3270      190102 : Handle<JSArrayBuffer> Factory::NewJSArrayBuffer(SharedFlag shared,
    3271             :                                                 AllocationType allocation) {
    3272             :   Handle<JSFunction> array_buffer_fun(
    3273             :       shared == SharedFlag::kShared
    3274      192534 :           ? isolate()->native_context()->shared_array_buffer_fun()
    3275      567874 :           : isolate()->native_context()->array_buffer_fun(),
    3276      380204 :       isolate());
    3277             :   Handle<Map> map(array_buffer_fun->initial_map(), isolate());
    3278      190102 :   return Handle<JSArrayBuffer>::cast(NewJSObjectFromMap(map, allocation));
    3279             : }
    3280             : 
    3281       18171 : Handle<JSIteratorResult> Factory::NewJSIteratorResult(Handle<Object> value,
    3282             :                                                       bool done) {
    3283       54513 :   Handle<Map> map(isolate()->native_context()->iterator_result_map(),
    3284       18171 :                   isolate());
    3285             :   Handle<JSIteratorResult> js_iter_result =
    3286       18171 :       Handle<JSIteratorResult>::cast(NewJSObjectFromMap(map));
    3287       18171 :   js_iter_result->set_value(*value);
    3288       18171 :   js_iter_result->set_done(*ToBoolean(done));
    3289       18171 :   return js_iter_result;
    3290             : }
    3291             : 
    3292         238 : Handle<JSAsyncFromSyncIterator> Factory::NewJSAsyncFromSyncIterator(
    3293             :     Handle<JSReceiver> sync_iterator, Handle<Object> next) {
    3294         714 :   Handle<Map> map(isolate()->native_context()->async_from_sync_iterator_map(),
    3295         238 :                   isolate());
    3296             :   Handle<JSAsyncFromSyncIterator> iterator =
    3297         238 :       Handle<JSAsyncFromSyncIterator>::cast(NewJSObjectFromMap(map));
    3298             : 
    3299         238 :   iterator->set_sync_iterator(*sync_iterator);
    3300         238 :   iterator->set_next(*next);
    3301         238 :   return iterator;
    3302             : }
    3303             : 
    3304          13 : Handle<JSMap> Factory::NewJSMap() {
    3305          39 :   Handle<Map> map(isolate()->native_context()->js_map_map(), isolate());
    3306          13 :   Handle<JSMap> js_map = Handle<JSMap>::cast(NewJSObjectFromMap(map));
    3307          13 :   JSMap::Initialize(js_map, isolate());
    3308          13 :   return js_map;
    3309             : }
    3310             : 
    3311       79706 : Handle<JSSet> Factory::NewJSSet() {
    3312      239118 :   Handle<Map> map(isolate()->native_context()->js_set_map(), isolate());
    3313       79706 :   Handle<JSSet> js_set = Handle<JSSet>::cast(NewJSObjectFromMap(map));
    3314       79706 :   JSSet::Initialize(js_set, isolate());
    3315       79706 :   return js_set;
    3316             : }
    3317             : 
    3318         620 : void Factory::TypeAndSizeForElementsKind(ElementsKind kind,
    3319             :                                          ExternalArrayType* array_type,
    3320             :                                          size_t* element_size) {
    3321         620 :   switch (kind) {
    3322             : #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) \
    3323             :   case TYPE##_ELEMENTS:                           \
    3324             :     *array_type = kExternal##Type##Array;         \
    3325             :     *element_size = sizeof(ctype);                \
    3326             :     break;
    3327           6 :     TYPED_ARRAYS(TYPED_ARRAY_CASE)
    3328             : #undef TYPED_ARRAY_CASE
    3329             : 
    3330             :     default:
    3331           0 :       UNREACHABLE();
    3332             :   }
    3333         620 : }
    3334             : 
    3335             : namespace {
    3336             : 
    3337         374 : static void ForFixedTypedArray(ExternalArrayType array_type,
    3338             :                                size_t* element_size,
    3339             :                                ElementsKind* element_kind) {
    3340         374 :   switch (array_type) {
    3341             : #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) \
    3342             :   case kExternal##Type##Array:                    \
    3343             :     *element_size = sizeof(ctype);                \
    3344             :     *element_kind = TYPE##_ELEMENTS;              \
    3345             :     return;
    3346             : 
    3347          83 :     TYPED_ARRAYS(TYPED_ARRAY_CASE)
    3348             : #undef TYPED_ARRAY_CASE
    3349             :   }
    3350           0 :   UNREACHABLE();
    3351             : }
    3352             : 
    3353         374 : JSFunction GetTypedArrayFun(ExternalArrayType type, Isolate* isolate) {
    3354         374 :   NativeContext native_context = isolate->context()->native_context();
    3355         374 :   switch (type) {
    3356             : #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype) \
    3357             :   case kExternal##Type##Array:                   \
    3358             :     return native_context->type##_array_fun();
    3359             : 
    3360          83 :     TYPED_ARRAYS(TYPED_ARRAY_FUN)
    3361             : #undef TYPED_ARRAY_FUN
    3362             :   }
    3363           0 :   UNREACHABLE();
    3364             : }
    3365             : 
    3366          58 : JSFunction GetTypedArrayFun(ElementsKind elements_kind, Isolate* isolate) {
    3367          58 :   NativeContext native_context = isolate->context()->native_context();
    3368          58 :   switch (elements_kind) {
    3369             : #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype) \
    3370             :   case TYPE##_ELEMENTS:                          \
    3371             :     return native_context->type##_array_fun();
    3372             : 
    3373           6 :     TYPED_ARRAYS(TYPED_ARRAY_FUN)
    3374             : #undef TYPED_ARRAY_FUN
    3375             : 
    3376             :     default:
    3377           0 :       UNREACHABLE();
    3378             :   }
    3379             : }
    3380             : 
    3381         399 : void SetupArrayBufferView(i::Isolate* isolate,
    3382             :                           i::Handle<i::JSArrayBufferView> obj,
    3383             :                           i::Handle<i::JSArrayBuffer> buffer,
    3384             :                           size_t byte_offset, size_t byte_length) {
    3385             :   DCHECK_LE(byte_offset + byte_length, buffer->byte_length());
    3386             :   DCHECK_EQ(obj->GetEmbedderFieldCount(),
    3387             :             v8::ArrayBufferView::kEmbedderFieldCount);
    3388        1995 :   for (int i = 0; i < v8::ArrayBufferView::kEmbedderFieldCount; i++) {
    3389         798 :     obj->SetEmbedderField(i, Smi::kZero);
    3390             :   }
    3391         798 :   obj->set_buffer(*buffer);
    3392             :   obj->set_byte_offset(byte_offset);
    3393             :   obj->set_byte_length(byte_length);
    3394         399 : }
    3395             : 
    3396             : }  // namespace
    3397             : 
    3398         374 : Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
    3399             :                                               AllocationType allocation) {
    3400             :   Handle<JSFunction> typed_array_fun(GetTypedArrayFun(type, isolate()),
    3401         374 :                                      isolate());
    3402             :   Handle<Map> map(typed_array_fun->initial_map(), isolate());
    3403         374 :   return Handle<JSTypedArray>::cast(NewJSObjectFromMap(map, allocation));
    3404             : }
    3405             : 
    3406          58 : Handle<JSTypedArray> Factory::NewJSTypedArray(ElementsKind elements_kind,
    3407             :                                               AllocationType allocation) {
    3408             :   Handle<JSFunction> typed_array_fun(GetTypedArrayFun(elements_kind, isolate()),
    3409          58 :                                      isolate());
    3410             :   Handle<Map> map(typed_array_fun->initial_map(), isolate());
    3411          58 :   return Handle<JSTypedArray>::cast(NewJSObjectFromMap(map, allocation));
    3412             : }
    3413             : 
    3414         374 : Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
    3415             :                                               Handle<JSArrayBuffer> buffer,
    3416             :                                               size_t byte_offset, size_t length,
    3417             :                                               AllocationType allocation) {
    3418         374 :   Handle<JSTypedArray> obj = NewJSTypedArray(type, allocation);
    3419             : 
    3420             :   size_t element_size;
    3421             :   ElementsKind elements_kind;
    3422         374 :   ForFixedTypedArray(type, &element_size, &elements_kind);
    3423             : 
    3424         748 :   CHECK_EQ(byte_offset % element_size, 0);
    3425             : 
    3426         374 :   CHECK(length <= (std::numeric_limits<size_t>::max() / element_size));
    3427             :   // TODO(7881): Smi length check
    3428         374 :   CHECK(length <= static_cast<size_t>(Smi::kMaxValue));
    3429         374 :   size_t byte_length = length * element_size;
    3430         374 :   SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
    3431             : 
    3432         374 :   obj->set_length(length);
    3433             : 
    3434             :   Handle<FixedTypedArrayBase> elements = NewFixedTypedArrayWithExternalPointer(
    3435         374 :       type, static_cast<uint8_t*>(buffer->backing_store()) + byte_offset,
    3436         374 :       allocation);
    3437         748 :   Handle<Map> map = JSObject::GetElementsTransitionMap(obj, elements_kind);
    3438         374 :   JSObject::SetMapAndElements(obj, map, elements);
    3439         374 :   return obj;
    3440             : }
    3441             : 
    3442          58 : Handle<JSTypedArray> Factory::NewJSTypedArray(ElementsKind elements_kind,
    3443             :                                               size_t number_of_elements,
    3444             :                                               AllocationType allocation) {
    3445          58 :   Handle<JSTypedArray> obj = NewJSTypedArray(elements_kind, allocation);
    3446             :   DCHECK_EQ(obj->GetEmbedderFieldCount(),
    3447             :             v8::ArrayBufferView::kEmbedderFieldCount);
    3448         290 :   for (int i = 0; i < v8::ArrayBufferView::kEmbedderFieldCount; i++) {
    3449         116 :     obj->SetEmbedderField(i, Smi::kZero);
    3450             :   }
    3451             : 
    3452             :   size_t element_size;
    3453             :   ExternalArrayType array_type;
    3454          58 :   TypeAndSizeForElementsKind(elements_kind, &array_type, &element_size);
    3455             : 
    3456          58 :   CHECK(number_of_elements <=
    3457             :         (std::numeric_limits<size_t>::max() / element_size));
    3458             :   // TODO(7881): Smi length check
    3459          58 :   CHECK(number_of_elements <= static_cast<size_t>(Smi::kMaxValue));
    3460          58 :   size_t byte_length = number_of_elements * element_size;
    3461             : 
    3462             :   obj->set_byte_offset(0);
    3463             :   obj->set_byte_length(byte_length);
    3464          58 :   obj->set_length(number_of_elements);
    3465             : 
    3466             :   Handle<JSArrayBuffer> buffer =
    3467          58 :       NewJSArrayBuffer(SharedFlag::kNotShared, allocation);
    3468             :   JSArrayBuffer::Setup(buffer, isolate(), true, nullptr, byte_length,
    3469          58 :                        SharedFlag::kNotShared);
    3470         116 :   obj->set_buffer(*buffer);
    3471             :   Handle<FixedTypedArrayBase> elements = NewFixedTypedArray(
    3472          58 :       number_of_elements, byte_length, array_type, true, allocation);
    3473         116 :   obj->set_elements(*elements);
    3474          58 :   return obj;
    3475             : }
    3476             : 
    3477          25 : Handle<JSDataView> Factory::NewJSDataView(Handle<JSArrayBuffer> buffer,
    3478             :                                           size_t byte_offset,
    3479             :                                           size_t byte_length) {
    3480          75 :   Handle<Map> map(isolate()->native_context()->data_view_fun()->initial_map(),
    3481             :                   isolate());
    3482          25 :   Handle<JSDataView> obj = Handle<JSDataView>::cast(NewJSObjectFromMap(map));
    3483          25 :   SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
    3484          25 :   return obj;
    3485             : }
    3486             : 
    3487         528 : MaybeHandle<JSBoundFunction> Factory::NewJSBoundFunction(
    3488             :     Handle<JSReceiver> target_function, Handle<Object> bound_this,
    3489             :     Vector<Handle<Object>> bound_args) {
    3490             :   DCHECK(target_function->IsCallable());
    3491             :   STATIC_ASSERT(Code::kMaxArguments <= FixedArray::kMaxLength);
    3492         528 :   if (bound_args.length() >= Code::kMaxArguments) {
    3493             :     THROW_NEW_ERROR(isolate(),
    3494             :                     NewRangeError(MessageTemplate::kTooManyArguments),
    3495             :                     JSBoundFunction);
    3496             :   }
    3497             : 
    3498             :   // Determine the prototype of the {target_function}.
    3499             :   Handle<HeapObject> prototype;
    3500        1056 :   ASSIGN_RETURN_ON_EXCEPTION(
    3501             :       isolate(), prototype,
    3502             :       JSReceiver::GetPrototype(isolate(), target_function), JSBoundFunction);
    3503             : 
    3504        1056 :   SaveAndSwitchContext save(isolate(), *target_function->GetCreationContext());
    3505             : 
    3506             :   // Create the [[BoundArguments]] for the result.
    3507             :   Handle<FixedArray> bound_arguments;
    3508         528 :   if (bound_args.length() == 0) {
    3509             :     bound_arguments = empty_fixed_array();
    3510             :   } else {
    3511             :     bound_arguments = NewFixedArray(bound_args.length());
    3512        1017 :     for (int i = 0; i < bound_args.length(); ++i) {
    3513         738 :       bound_arguments->set(i, *bound_args[i]);
    3514             :     }
    3515             :   }
    3516             : 
    3517             :   // Setup the map for the JSBoundFunction instance.
    3518             :   Handle<Map> map = target_function->IsConstructor()
    3519             :                         ? isolate()->bound_function_with_constructor_map()
    3520         528 :                         : isolate()->bound_function_without_constructor_map();
    3521         528 :   if (map->prototype() != *prototype) {
    3522         144 :     map = Map::TransitionToPrototype(isolate(), map, prototype);
    3523             :   }
    3524             :   DCHECK_EQ(target_function->IsConstructor(), map->is_constructor());
    3525             : 
    3526             :   // Setup the JSBoundFunction instance.
    3527             :   Handle<JSBoundFunction> result =
    3528         528 :       Handle<JSBoundFunction>::cast(NewJSObjectFromMap(map));
    3529         528 :   result->set_bound_target_function(*target_function);
    3530         528 :   result->set_bound_this(*bound_this);
    3531         528 :   result->set_bound_arguments(*bound_arguments);
    3532         528 :   return result;
    3533             : }
    3534             : 
    3535             : // ES6 section 9.5.15 ProxyCreate (target, handler)
    3536          29 : Handle<JSProxy> Factory::NewJSProxy(Handle<JSReceiver> target,
    3537             :                                     Handle<JSReceiver> handler) {
    3538             :   // Allocate the proxy object.
    3539             :   Handle<Map> map;
    3540          29 :   if (target->IsCallable()) {
    3541          12 :     if (target->IsConstructor()) {
    3542          12 :       map = Handle<Map>(isolate()->proxy_constructor_map());
    3543             :     } else {
    3544           0 :       map = Handle<Map>(isolate()->proxy_callable_map());
    3545             :     }
    3546             :   } else {
    3547          17 :     map = Handle<Map>(isolate()->proxy_map());
    3548             :   }
    3549             :   DCHECK(map->prototype()->IsNull(isolate()));
    3550          58 :   Handle<JSProxy> result(JSProxy::cast(New(map, AllocationType::kYoung)),
    3551             :                          isolate());
    3552          29 :   result->initialize_properties();
    3553          58 :   result->set_target(*target);
    3554          58 :   result->set_handler(*handler);
    3555          29 :   return result;
    3556             : }
    3557             : 
    3558       91726 : Handle<JSGlobalProxy> Factory::NewUninitializedJSGlobalProxy(int size) {
    3559             :   // Create an empty shell of a JSGlobalProxy that needs to be reinitialized
    3560             :   // via ReinitializeJSGlobalProxy later.
    3561       91726 :   Handle<Map> map = NewMap(JS_GLOBAL_PROXY_TYPE, size);
    3562             :   // Maintain invariant expected from any JSGlobalProxy.
    3563             :   map->set_is_access_check_needed(true);
    3564       91726 :   map->set_may_have_interesting_symbols(true);
    3565       91793 :   LOG(isolate(), MapDetails(*map));
    3566             :   return Handle<JSGlobalProxy>::cast(
    3567       91726 :       NewJSObjectFromMap(map, AllocationType::kYoung));
    3568             : }
    3569             : 
    3570       91772 : void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
    3571             :                                         Handle<JSFunction> constructor) {
    3572             :   DCHECK(constructor->has_initial_map());
    3573             :   Handle<Map> map(constructor->initial_map(), isolate());
    3574             :   Handle<Map> old_map(object->map(), isolate());
    3575             : 
    3576             :   // The proxy's hash should be retained across reinitialization.
    3577             :   Handle<Object> raw_properties_or_hash(object->raw_properties_or_hash(),
    3578             :                                         isolate());
    3579             : 
    3580       91772 :   if (old_map->is_prototype_map()) {
    3581           0 :     map = Map::Copy(isolate(), map, "CopyAsPrototypeForJSGlobalProxy");
    3582             :     map->set_is_prototype_map(true);
    3583             :   }
    3584       91772 :   JSObject::NotifyMapChange(old_map, map, isolate());
    3585       91772 :   old_map->NotifyLeafMapLayoutChange(isolate());
    3586             : 
    3587             :   // Check that the already allocated object has the same size and type as
    3588             :   // objects allocated using the constructor.
    3589             :   DCHECK(map->instance_size() == old_map->instance_size());
    3590             :   DCHECK(map->instance_type() == old_map->instance_type());
    3591             : 
    3592             :   // In order to keep heap in consistent state there must be no allocations
    3593             :   // before object re-initialization is finished.
    3594             :   DisallowHeapAllocation no_allocation;
    3595             : 
    3596             :   // Reset the map for the object.
    3597       91772 :   object->synchronized_set_map(*map);
    3598             : 
    3599             :   // Reinitialize the object from the constructor map.
    3600       91772 :   InitializeJSObjectFromMap(object, raw_properties_or_hash, map);
    3601       91772 : }
    3602             : 
    3603     3638561 : Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfoForLiteral(
    3604             :     FunctionLiteral* literal, Handle<Script> script, bool is_toplevel) {
    3605     3638561 :   FunctionKind kind = literal->kind();
    3606             :   Handle<SharedFunctionInfo> shared = NewSharedFunctionInfoForBuiltin(
    3607             :       literal->name(), Builtins::kCompileLazy, kind);
    3608     3638567 :   SharedFunctionInfo::InitFromFunctionLiteral(shared, literal, is_toplevel);
    3609     3638568 :   SharedFunctionInfo::SetScript(shared, script, literal->function_literal_id(),
    3610     3638566 :                                 false);
    3611     7277136 :   TRACE_EVENT_OBJECT_CREATED_WITH_ID(
    3612             :       TRACE_DISABLED_BY_DEFAULT("v8.compile"), "SharedFunctionInfo",
    3613             :       TRACE_ID_WITH_SCOPE(SharedFunctionInfo::kTraceScope, shared->TraceID()));
    3614     7277136 :   TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
    3615             :       TRACE_DISABLED_BY_DEFAULT("v8.compile"), "SharedFunctionInfo",
    3616             :       TRACE_ID_WITH_SCOPE(SharedFunctionInfo::kTraceScope, shared->TraceID()),
    3617             :       shared->ToTracedValue());
    3618     3638568 :   return shared;
    3619             : }
    3620             : 
    3621     1363609 : Handle<JSMessageObject> Factory::NewJSMessageObject(
    3622             :     MessageTemplate message, Handle<Object> argument, int start_position,
    3623             :     int end_position, Handle<Script> script, Handle<Object> stack_frames) {
    3624     1363609 :   Handle<Map> map = message_object_map();
    3625             :   Handle<JSMessageObject> message_obj(
    3626     2727218 :       JSMessageObject::cast(New(map, AllocationType::kYoung)), isolate());
    3627             :   message_obj->set_raw_properties_or_hash(*empty_fixed_array(),
    3628             :                                           SKIP_WRITE_BARRIER);
    3629     1363609 :   message_obj->initialize_elements();
    3630             :   message_obj->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
    3631             :   message_obj->set_type(message);
    3632     1363609 :   message_obj->set_argument(*argument);
    3633             :   message_obj->set_start_position(start_position);
    3634             :   message_obj->set_end_position(end_position);
    3635     1363609 :   message_obj->set_script(*script);
    3636     1363609 :   message_obj->set_stack_frames(*stack_frames);
    3637             :   message_obj->set_error_level(v8::Isolate::kMessageError);
    3638     1363609 :   return message_obj;
    3639             : }
    3640             : 
    3641     3696971 : Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfoForApiFunction(
    3642             :     MaybeHandle<String> maybe_name,
    3643             :     Handle<FunctionTemplateInfo> function_template_info, FunctionKind kind) {
    3644             :   Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(
    3645     7393942 :       maybe_name, function_template_info, Builtins::kNoBuiltinId, kind);
    3646     3696968 :   return shared;
    3647             : }
    3648             : 
    3649        4429 : Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfoForBuiltin(
    3650             :     MaybeHandle<String> maybe_name, int builtin_index, FunctionKind kind) {
    3651             :   Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(
    3652     7285986 :       maybe_name, MaybeHandle<Code>(), builtin_index, kind);
    3653     3642996 :   return shared;
    3654             : }
    3655             : 
    3656     9610693 : Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
    3657             :     MaybeHandle<String> maybe_name, MaybeHandle<HeapObject> maybe_function_data,
    3658             :     int maybe_builtin_index, FunctionKind kind) {
    3659             :   // Function names are assumed to be flat elsewhere. Must flatten before
    3660             :   // allocating SharedFunctionInfo to avoid GC seeing the uninitialized SFI.
    3661             :   Handle<String> shared_name;
    3662             :   bool has_shared_name = maybe_name.ToHandle(&shared_name);
    3663     9610693 :   if (has_shared_name) {
    3664     9600567 :     shared_name = String::Flatten(isolate(), shared_name, AllocationType::kOld);
    3665             :   }
    3666             : 
    3667     9610699 :   Handle<Map> map = shared_function_info_map();
    3668             :   Handle<SharedFunctionInfo> share(
    3669    19221393 :       SharedFunctionInfo::cast(New(map, AllocationType::kOld)), isolate());
    3670             :   {
    3671             :     DisallowHeapAllocation no_allocation;
    3672             : 
    3673             :     // Set pointer fields.
    3674    28842209 :     share->set_name_or_scope_info(
    3675             :         has_shared_name ? Object::cast(*shared_name)
    3676     9610694 :                         : SharedFunctionInfo::kNoSharedNameSentinel);
    3677             :     Handle<HeapObject> function_data;
    3678     9610692 :     if (maybe_function_data.ToHandle(&function_data)) {
    3679             :       // If we pass function_data then we shouldn't pass a builtin index, and
    3680             :       // the function_data should not be code with a builtin.
    3681             :       DCHECK(!Builtins::IsBuiltinId(maybe_builtin_index));
    3682             :       DCHECK_IMPLIES(function_data->IsCode(),
    3683             :                      !Code::cast(*function_data)->is_builtin());
    3684     7870726 :       share->set_function_data(*function_data);
    3685     5675329 :     } else if (Builtins::IsBuiltinId(maybe_builtin_index)) {
    3686             :       share->set_builtin_id(maybe_builtin_index);
    3687             :     } else {
    3688             :       share->set_builtin_id(Builtins::kIllegal);
    3689             :     }
    3690             :     // Generally functions won't have feedback, unless they have been created
    3691             :     // from a FunctionLiteral. Those can just reset this field to keep the
    3692             :     // SharedFunctionInfo in a consistent state.
    3693     9610694 :     if (maybe_builtin_index == Builtins::kCompileLazy) {
    3694             :       share->set_raw_outer_scope_info_or_feedback_metadata(*the_hole_value(),
    3695             :                                                            SKIP_WRITE_BARRIER);
    3696             :     } else {
    3697             :       share->set_raw_outer_scope_info_or_feedback_metadata(
    3698             :           *empty_feedback_metadata(), SKIP_WRITE_BARRIER);
    3699             :     }
    3700             :     share->set_script_or_debug_info(*undefined_value(), SKIP_WRITE_BARRIER);
    3701             : #if V8_SFI_HAS_UNIQUE_ID
    3702             :     Handle<SharedFunctionInfoWithID>::cast(share)->set_unique_id(
    3703             :         isolate()->GetNextUniqueSharedFunctionInfoId());
    3704             : #endif
    3705             : 
    3706             :     // Set integer fields (smi or int, depending on the architecture).
    3707             :     share->set_length(0);
    3708             :     share->set_internal_formal_parameter_count(0);
    3709             :     share->set_expected_nof_properties(0);
    3710             :     share->set_raw_function_token_offset(0);
    3711             :     // All flags default to false or 0.
    3712             :     share->set_flags(0);
    3713             :     // For lite mode disable optimization.
    3714             :     if (FLAG_lite_mode) {
    3715             :       share->set_flags(
    3716             :           SharedFunctionInfo::DisabledOptimizationReasonBits::encode(
    3717             :               BailoutReason::kNeverOptimize));
    3718             :     }
    3719     9610694 :     share->CalculateConstructAsBuiltin();
    3720    19221374 :     share->set_kind(kind);
    3721             : 
    3722             :     share->clear_padding();
    3723             :   }
    3724             :   // Link into the list.
    3725             :   Handle<WeakArrayList> noscript_list = noscript_shared_function_infos();
    3726             :   noscript_list = WeakArrayList::AddToEnd(isolate(), noscript_list,
    3727     9610692 :                                           MaybeObjectHandle::Weak(share));
    3728             :   isolate()->heap()->set_noscript_shared_function_infos(*noscript_list);
    3729             : 
    3730             : #ifdef VERIFY_HEAP
    3731             :   share->SharedFunctionInfoVerify(isolate());
    3732             : #endif
    3733     9610694 :   return share;
    3734             : }
    3735             : 
    3736             : namespace {
    3737             : inline int NumberToStringCacheHash(Handle<FixedArray> cache, Smi number) {
    3738    40144628 :   int mask = (cache->length() >> 1) - 1;
    3739    40144628 :   return number->value() & mask;
    3740             : }
    3741             : inline int NumberToStringCacheHash(Handle<FixedArray> cache, double number) {
    3742     1122803 :   int mask = (cache->length() >> 1) - 1;
    3743             :   int64_t bits = bit_cast<int64_t>(number);
    3744     1122803 :   return (static_cast<int>(bits) ^ static_cast<int>(bits >> 32)) & mask;
    3745             : }
    3746             : }  // namespace
    3747             : 
    3748    33685280 : Handle<String> Factory::NumberToStringCacheSet(Handle<Object> number, int hash,
    3749             :                                                const char* string,
    3750             :                                                bool check_cache) {
    3751             :   // We tenure the allocated string since it is referenced from the
    3752             :   // number-string cache which lives in the old space.
    3753             :   Handle<String> js_string = NewStringFromAsciiChecked(
    3754    33685280 :       string, check_cache ? AllocationType::kOld : AllocationType::kYoung);
    3755    33685280 :   if (!check_cache) return js_string;
    3756             : 
    3757    67283620 :   if (!number_string_cache()->get(hash * 2)->IsUndefined(isolate())) {
    3758             :     int full_size = isolate()->heap()->MaxNumberToStringCacheSize();
    3759    27785568 :     if (number_string_cache()->length() != full_size) {
    3760             :       Handle<FixedArray> new_cache =
    3761             :           NewFixedArray(full_size, AllocationType::kOld);
    3762             :       isolate()->heap()->set_number_string_cache(*new_cache);
    3763        1500 :       return js_string;
    3764             :     }
    3765             :   }
    3766    33640310 :   number_string_cache()->set(hash * 2, *number);
    3767    67280620 :   number_string_cache()->set(hash * 2 + 1, *js_string);
    3768    33640310 :   return js_string;
    3769             : }
    3770             : 
    3771    41267431 : Handle<Object> Factory::NumberToStringCacheGet(Object number, int hash) {
    3772             :   DisallowHeapAllocation no_gc;
    3773    41267431 :   Object key = number_string_cache()->get(hash * 2);
    3774    76569093 :   if (key == number || (key->IsHeapNumber() && number->IsHeapNumber() &&
    3775             :                         key->Number() == number->Number())) {
    3776             :     return Handle<String>(
    3777    15251242 :         String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
    3778             :   }
    3779    33641810 :   return undefined_value();
    3780             : }
    3781             : 
    3782    34027021 : Handle<String> Factory::NumberToString(Handle<Object> number,
    3783             :                                        bool check_cache) {
    3784    34027021 :   if (number->IsSmi()) return NumberToString(Smi::cast(*number), check_cache);
    3785             : 
    3786             :   double double_value = Handle<HeapNumber>::cast(number)->value();
    3787             :   // Try to canonicalize doubles.
    3788             :   int smi_value;
    3789     1257878 :   if (DoubleToSmiInteger(double_value, &smi_value)) {
    3790      270150 :     return NumberToString(Smi::FromInt(smi_value), check_cache);
    3791             :   }
    3792             : 
    3793             :   int hash = 0;
    3794     1122803 :   if (check_cache) {
    3795             :     hash = NumberToStringCacheHash(number_string_cache(), double_value);
    3796     1122803 :     Handle<Object> cached = NumberToStringCacheGet(*number, hash);
    3797     1122803 :     if (!cached->IsUndefined(isolate())) return Handle<String>::cast(cached);
    3798             :   }
    3799             : 
    3800             :   char arr[100];
    3801             :   Vector<char> buffer(arr, arraysize(arr));
    3802     1101695 :   const char* string = DoubleToCString(double_value, buffer);
    3803             : 
    3804     1101695 :   return NumberToStringCacheSet(number, hash, string, check_cache);
    3805             : }
    3806             : 
    3807    40188098 : Handle<String> Factory::NumberToString(Smi number, bool check_cache) {
    3808             :   int hash = 0;
    3809    40188098 :   if (check_cache) {
    3810             :     hash = NumberToStringCacheHash(number_string_cache(), number);
    3811    40144628 :     Handle<Object> cached = NumberToStringCacheGet(number, hash);
    3812    40144628 :     if (!cached->IsUndefined(isolate())) return Handle<String>::cast(cached);
    3813             :   }
    3814             : 
    3815             :   char arr[100];
    3816             :   Vector<char> buffer(arr, arraysize(arr));
    3817    32583585 :   const char* string = IntToCString(number->value(), buffer);
    3818             : 
    3819             :   return NumberToStringCacheSet(handle(number, isolate()), hash, string,
    3820    65167170 :                                 check_cache);
    3821             : }
    3822             : 
    3823       40387 : Handle<ClassPositions> Factory::NewClassPositions(int start, int end) {
    3824             :   Handle<ClassPositions> class_positions = Handle<ClassPositions>::cast(
    3825       40387 :       NewStruct(CLASS_POSITIONS_TYPE, AllocationType::kOld));
    3826             :   class_positions->set_start(start);
    3827             :   class_positions->set_end(end);
    3828       40387 :   return class_positions;
    3829             : }
    3830             : 
    3831       28670 : Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
    3832             :   DCHECK(!shared->HasDebugInfo());
    3833             :   Heap* heap = isolate()->heap();
    3834             : 
    3835             :   Handle<DebugInfo> debug_info =
    3836       28670 :       Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE, AllocationType::kOld));
    3837             :   debug_info->set_flags(DebugInfo::kNone);
    3838       28670 :   debug_info->set_shared(*shared);
    3839             :   debug_info->set_debugger_hints(0);
    3840             :   DCHECK_EQ(DebugInfo::kNoDebuggingId, debug_info->debugging_id());
    3841             :   DCHECK(!shared->HasDebugInfo());
    3842       28670 :   debug_info->set_script(shared->script_or_debug_info());
    3843       57340 :   debug_info->set_original_bytecode_array(
    3844       86010 :       ReadOnlyRoots(heap).undefined_value());
    3845       57340 :   debug_info->set_debug_bytecode_array(ReadOnlyRoots(heap).undefined_value());
    3846       28670 :   debug_info->set_break_points(ReadOnlyRoots(heap).empty_fixed_array());
    3847             : 
    3848             :   // Link debug info to function.
    3849       57340 :   shared->SetDebugInfo(*debug_info);
    3850             : 
    3851       28670 :   return debug_info;
    3852             : }
    3853             : 
    3854         892 : Handle<CoverageInfo> Factory::NewCoverageInfo(
    3855             :     const ZoneVector<SourceRange>& slots) {
    3856         892 :   const int slot_count = static_cast<int>(slots.size());
    3857             : 
    3858             :   const int length = CoverageInfo::FixedArrayLengthForSlotCount(slot_count);
    3859             :   Handle<CoverageInfo> info =
    3860             :       Handle<CoverageInfo>::cast(NewUninitializedFixedArray(length));
    3861             : 
    3862        5428 :   for (int i = 0; i < slot_count; i++) {
    3863        4536 :     SourceRange range = slots[i];
    3864        2268 :     info->InitializeSlot(i, range.start, range.end);
    3865             :   }
    3866             : 
    3867         892 :   return info;
    3868             : }
    3869             : 
    3870        2476 : Handle<BreakPointInfo> Factory::NewBreakPointInfo(int source_position) {
    3871             :   Handle<BreakPointInfo> new_break_point_info = Handle<BreakPointInfo>::cast(
    3872        2476 :       NewStruct(TUPLE2_TYPE, AllocationType::kOld));
    3873             :   new_break_point_info->set_source_position(source_position);
    3874        4952 :   new_break_point_info->set_break_points(*undefined_value());
    3875        2476 :   return new_break_point_info;
    3876             : }
    3877             : 
    3878        4854 : Handle<BreakPoint> Factory::NewBreakPoint(int id, Handle<String> condition) {
    3879             :   Handle<BreakPoint> new_break_point =
    3880        4854 :       Handle<BreakPoint>::cast(NewStruct(TUPLE2_TYPE, AllocationType::kOld));
    3881             :   new_break_point->set_id(id);
    3882        4854 :   new_break_point->set_condition(*condition);
    3883        4854 :   return new_break_point;
    3884             : }
    3885             : 
    3886       11020 : Handle<StackTraceFrame> Factory::NewStackTraceFrame(
    3887             :     Handle<FrameArray> frame_array, int index) {
    3888             :   Handle<StackTraceFrame> frame = Handle<StackTraceFrame>::cast(
    3889       11020 :       NewStruct(STACK_TRACE_FRAME_TYPE, AllocationType::kYoung));
    3890       22040 :   frame->set_frame_array(*frame_array);
    3891             :   frame->set_frame_index(index);
    3892       22040 :   frame->set_frame_info(*undefined_value());
    3893             : 
    3894       11020 :   int id = isolate()->last_stack_frame_info_id() + 1;
    3895             :   isolate()->set_last_stack_frame_info_id(id);
    3896             :   frame->set_id(id);
    3897       11020 :   return frame;
    3898             : }
    3899             : 
    3900           0 : Handle<StackFrameInfo> Factory::NewStackFrameInfo() {
    3901             :   Handle<StackFrameInfo> stack_frame_info = Handle<StackFrameInfo>::cast(
    3902           0 :       NewStruct(STACK_FRAME_INFO_TYPE, AllocationType::kYoung));
    3903             :   stack_frame_info->set_line_number(0);
    3904             :   stack_frame_info->set_column_number(0);
    3905             :   stack_frame_info->set_script_id(0);
    3906           0 :   stack_frame_info->set_script_name(Smi::kZero);
    3907           0 :   stack_frame_info->set_script_name_or_source_url(Smi::kZero);
    3908           0 :   stack_frame_info->set_function_name(Smi::kZero);
    3909             :   stack_frame_info->set_flag(0);
    3910           0 :   return stack_frame_info;
    3911             : }
    3912             : 
    3913       10770 : Handle<StackFrameInfo> Factory::NewStackFrameInfo(
    3914             :     Handle<FrameArray> frame_array, int index) {
    3915       10770 :   FrameArrayIterator it(isolate(), frame_array, index);
    3916             :   DCHECK(it.HasFrame());
    3917             : 
    3918             :   Handle<StackFrameInfo> info = Handle<StackFrameInfo>::cast(
    3919       10770 :       NewStruct(STACK_FRAME_INFO_TYPE, AllocationType::kYoung));
    3920             :   info->set_flag(0);
    3921             : 
    3922       10770 :   const bool is_wasm = frame_array->IsAnyWasmFrame(index);
    3923       21540 :   info->set_is_wasm(is_wasm);
    3924             : 
    3925             :   // Line numbers are 1-based, for Wasm we need to adjust.
    3926       10770 :   int line = it.Frame()->GetLineNumber();
    3927       10770 :   if (is_wasm && line >= 0) line++;
    3928             :   info->set_line_number(line);
    3929             : 
    3930             :   // Column numbers are 1-based. For Wasm we use the position
    3931             :   // as the iterator does not currently provide a column number.
    3932             :   const int column =
    3933       10770 :       is_wasm ? it.Frame()->GetPosition() + 1 : it.Frame()->GetColumnNumber();
    3934             :   info->set_column_number(column);
    3935             : 
    3936       10770 :   info->set_script_id(it.Frame()->GetScriptId());
    3937       21540 :   info->set_script_name(*it.Frame()->GetFileName());
    3938       21540 :   info->set_script_name_or_source_url(*it.Frame()->GetScriptNameOrSourceUrl());
    3939             : 
    3940             :   // TODO(szuend): Adjust this, once it is decided what name to use in both
    3941             :   //               "simple" and "detailed" stack traces. This code is for
    3942             :   //               backwards compatibility to fullfill test expectations.
    3943       10770 :   auto function_name = it.Frame()->GetFunctionName();
    3944       10770 :   if (!is_wasm) {
    3945       10322 :     Handle<Object> function = it.Frame()->GetFunction();
    3946       10322 :     if (function->IsJSFunction()) {
    3947             :       function_name =
    3948       10322 :           JSFunction::GetDebugName(Handle<JSFunction>::cast(function));
    3949             :     }
    3950             :   }
    3951       10770 :   info->set_function_name(*function_name);
    3952       21540 :   info->set_is_eval(it.Frame()->IsEval());
    3953       21540 :   info->set_is_constructor(it.Frame()->IsConstructor());
    3954             : 
    3955       21540 :   return info;
    3956             : }
    3957             : 
    3958             : Handle<SourcePositionTableWithFrameCache>
    3959        8194 : Factory::NewSourcePositionTableWithFrameCache(
    3960             :     Handle<ByteArray> source_position_table,
    3961             :     Handle<SimpleNumberDictionary> stack_frame_cache) {
    3962             :   Handle<SourcePositionTableWithFrameCache>
    3963             :       source_position_table_with_frame_cache =
    3964             :           Handle<SourcePositionTableWithFrameCache>::cast(
    3965        8194 :               NewStruct(TUPLE2_TYPE, AllocationType::kOld));
    3966       16388 :   source_position_table_with_frame_cache->set_source_position_table(
    3967        8194 :       *source_position_table);
    3968       16388 :   source_position_table_with_frame_cache->set_stack_frame_cache(
    3969        8194 :       *stack_frame_cache);
    3970        8194 :   return source_position_table_with_frame_cache;
    3971             : }
    3972             : 
    3973       64784 : Handle<JSObject> Factory::NewArgumentsObject(Handle<JSFunction> callee,
    3974             :                                              int length) {
    3975      129055 :   bool strict_mode_callee = is_strict(callee->shared()->language_mode()) ||
    3976      129055 :                             !callee->shared()->has_simple_parameters();
    3977             :   Handle<Map> map = strict_mode_callee ? isolate()->strict_arguments_map()
    3978       64784 :                                        : isolate()->sloppy_arguments_map();
    3979             :   AllocationSiteUsageContext context(isolate(), Handle<AllocationSite>(),
    3980             :                                      false);
    3981             :   DCHECK(!isolate()->has_pending_exception());
    3982       64784 :   Handle<JSObject> result = NewJSObjectFromMap(map);
    3983             :   Handle<Smi> value(Smi::FromInt(length), isolate());
    3984       64784 :   Object::SetProperty(isolate(), result, length_string(), value,
    3985             :                       StoreOrigin::kMaybeKeyed,
    3986       64784 :                       Just(ShouldThrow::kThrowOnError))
    3987             :       .Assert();
    3988       64784 :   if (!strict_mode_callee) {
    3989       64184 :     Object::SetProperty(isolate(), result, callee_string(), callee,
    3990             :                         StoreOrigin::kMaybeKeyed,
    3991       64184 :                         Just(ShouldThrow::kThrowOnError))
    3992             :         .Assert();
    3993             :   }
    3994       64784 :   return result;
    3995             : }
    3996             : 
    3997      361952 : Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<NativeContext> context,
    3998             :                                                int number_of_properties) {
    3999      361952 :   if (number_of_properties == 0) {
    4000             :     // Reuse the initial map of the Object function if the literal has no
    4001             :     // predeclared properties.
    4002       34362 :     return handle(context->object_function()->initial_map(), isolate());
    4003             :   }
    4004             : 
    4005             :   // We do not cache maps for too many properties or when running builtin code.
    4006      344771 :   if (isolate()->bootstrapper()->IsActive()) {
    4007           0 :     return Map::Create(isolate(), number_of_properties);
    4008             :   }
    4009             : 
    4010             :   // Use initial slow object proto map for too many properties.
    4011             :   const int kMapCacheSize = 128;
    4012      344771 :   if (number_of_properties > kMapCacheSize) {
    4013         382 :     return handle(context->slow_object_with_object_prototype_map(), isolate());
    4014             :   }
    4015             : 
    4016      344580 :   int cache_index = number_of_properties - 1;
    4017      689155 :   Handle<Object> maybe_cache(context->map_cache(), isolate());
    4018      344575 :   if (maybe_cache->IsUndefined(isolate())) {
    4019             :     // Allocate the new map cache for the native context.
    4020       47738 :     maybe_cache = NewWeakFixedArray(kMapCacheSize, AllocationType::kOld);
    4021       47738 :     context->set_map_cache(*maybe_cache);
    4022             :   } else {
    4023             :     // Check to see whether there is a matching element in the cache.
    4024             :     Handle<WeakFixedArray> cache = Handle<WeakFixedArray>::cast(maybe_cache);
    4025             :     MaybeObject result = cache->Get(cache_index);
    4026             :     HeapObject heap_object;
    4027      296837 :     if (result->GetHeapObjectIfWeak(&heap_object)) {
    4028             :       Map map = Map::cast(heap_object);
    4029             :       DCHECK(!map->is_dictionary_map());
    4030             :       return handle(map, isolate());
    4031             :     }
    4032             :   }
    4033             : 
    4034             :   // Create a new map and add it to the cache.
    4035             :   Handle<WeakFixedArray> cache = Handle<WeakFixedArray>::cast(maybe_cache);
    4036       93023 :   Handle<Map> map = Map::Create(isolate(), number_of_properties);
    4037             :   DCHECK(!map->is_dictionary_map());
    4038      186044 :   cache->Set(cache_index, HeapObjectReference::Weak(*map));
    4039       93024 :   return map;
    4040             : }
    4041             : 
    4042      484968 : Handle<LoadHandler> Factory::NewLoadHandler(int data_count) {
    4043             :   Handle<Map> map;
    4044      484968 :   switch (data_count) {
    4045             :     case 1:
    4046      442610 :       map = load_handler1_map();
    4047      442610 :       break;
    4048             :     case 2:
    4049       42353 :       map = load_handler2_map();
    4050       42353 :       break;
    4051             :     case 3:
    4052           5 :       map = load_handler3_map();
    4053           5 :       break;
    4054             :     default:
    4055           0 :       UNREACHABLE();
    4056             :       break;
    4057             :   }
    4058      969934 :   return handle(LoadHandler::cast(New(map, AllocationType::kOld)), isolate());
    4059             : }
    4060             : 
    4061      238787 : Handle<StoreHandler> Factory::NewStoreHandler(int data_count) {
    4062             :   Handle<Map> map;
    4063      238787 :   switch (data_count) {
    4064             :     case 0:
    4065       67153 :       map = store_handler0_map();
    4066       67153 :       break;
    4067             :     case 1:
    4068      169934 :       map = store_handler1_map();
    4069      169934 :       break;
    4070             :     case 2:
    4071        1695 :       map = store_handler2_map();
    4072        1695 :       break;
    4073             :     case 3:
    4074           5 :       map = store_handler3_map();
    4075           5 :       break;
    4076             :     default:
    4077           0 :       UNREACHABLE();
    4078             :       break;
    4079             :   }
    4080      477574 :   return handle(StoreHandler::cast(New(map, AllocationType::kOld)), isolate());
    4081             : }
    4082             : 
    4083      166088 : void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp, JSRegExp::Type type,
    4084             :                                 Handle<String> source, JSRegExp::Flags flags,
    4085             :                                 Handle<Object> data) {
    4086             :   Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
    4087             : 
    4088      166088 :   store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
    4089      332176 :   store->set(JSRegExp::kSourceIndex, *source);
    4090             :   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags));
    4091      166088 :   store->set(JSRegExp::kAtomPatternIndex, *data);
    4092      332176 :   regexp->set_data(*store);
    4093      166088 : }
    4094             : 
    4095       85574 : void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
    4096             :                                     JSRegExp::Type type, Handle<String> source,
    4097             :                                     JSRegExp::Flags flags, int capture_count) {
    4098             :   Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
    4099             :   Smi uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
    4100       85574 :   store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
    4101      171148 :   store->set(JSRegExp::kSourceIndex, *source);
    4102             :   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags));
    4103             :   store->set(JSRegExp::kIrregexpLatin1CodeIndex, uninitialized);
    4104             :   store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
    4105       85574 :   store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::kZero);
    4106             :   store->set(JSRegExp::kIrregexpCaptureCountIndex, Smi::FromInt(capture_count));
    4107             :   store->set(JSRegExp::kIrregexpCaptureNameMapIndex, uninitialized);
    4108      171148 :   regexp->set_data(*store);
    4109       85574 : }
    4110             : 
    4111         136 : Handle<RegExpMatchInfo> Factory::NewRegExpMatchInfo() {
    4112             :   // Initially, the last match info consists of all fixed fields plus space for
    4113             :   // the match itself (i.e., 2 capture indices).
    4114             :   static const int kInitialSize = RegExpMatchInfo::kFirstCaptureIndex +
    4115             :                                   RegExpMatchInfo::kInitialCaptureIndices;
    4116             : 
    4117             :   Handle<FixedArray> elems = NewFixedArray(kInitialSize);
    4118             :   Handle<RegExpMatchInfo> result = Handle<RegExpMatchInfo>::cast(elems);
    4119             : 
    4120             :   result->SetNumberOfCaptureRegisters(RegExpMatchInfo::kInitialCaptureIndices);
    4121         272 :   result->SetLastSubject(*empty_string());
    4122         272 :   result->SetLastInput(*undefined_value());
    4123             :   result->SetCapture(0, 0);
    4124             :   result->SetCapture(1, 0);
    4125             : 
    4126         136 :   return result;
    4127             : }
    4128             : 
    4129           0 : Handle<Object> Factory::GlobalConstantFor(Handle<Name> name) {
    4130           0 :   if (Name::Equals(isolate(), name, undefined_string())) {
    4131           0 :     return undefined_value();
    4132             :   }
    4133           0 :   if (Name::Equals(isolate(), name, NaN_string())) return nan_value();
    4134           0 :   if (Name::Equals(isolate(), name, Infinity_string())) return infinity_value();
    4135             :   return Handle<Object>::null();
    4136             : }
    4137             : 
    4138      229669 : Handle<Object> Factory::ToBoolean(bool value) {
    4139      477509 :   return value ? true_value() : false_value();
    4140             : }
    4141             : 
    4142        3622 : Handle<String> Factory::ToPrimitiveHintString(ToPrimitiveHint hint) {
    4143        3622 :   switch (hint) {
    4144             :     case ToPrimitiveHint::kDefault:
    4145             :       return default_string();
    4146             :     case ToPrimitiveHint::kNumber:
    4147             :       return number_string();
    4148             :     case ToPrimitiveHint::kString:
    4149             :       return string_string();
    4150             :   }
    4151           0 :   UNREACHABLE();
    4152             : }
    4153             : 
    4154         555 : Handle<Map> Factory::CreateSloppyFunctionMap(
    4155             :     FunctionMode function_mode, MaybeHandle<JSFunction> maybe_empty_function) {
    4156             :   bool has_prototype = IsFunctionModeWithPrototype(function_mode);
    4157             :   int header_size = has_prototype ? JSFunction::kSizeWithPrototype
    4158         555 :                                   : JSFunction::kSizeWithoutPrototype;
    4159         555 :   int descriptors_count = has_prototype ? 5 : 4;
    4160             :   int inobject_properties_count = 0;
    4161         555 :   if (IsFunctionModeWithName(function_mode)) ++inobject_properties_count;
    4162             : 
    4163             :   Handle<Map> map = NewMap(
    4164         555 :       JS_FUNCTION_TYPE, header_size + inobject_properties_count * kTaggedSize,
    4165         555 :       TERMINAL_FAST_ELEMENTS_KIND, inobject_properties_count);
    4166        1110 :   map->set_has_prototype_slot(has_prototype);
    4167             :   map->set_is_constructor(has_prototype);
    4168             :   map->set_is_callable(true);
    4169             :   Handle<JSFunction> empty_function;
    4170         555 :   if (maybe_empty_function.ToHandle(&empty_function)) {
    4171         444 :     Map::SetPrototype(isolate(), map, empty_function);
    4172             :   }
    4173             : 
    4174             :   //
    4175             :   // Setup descriptors array.
    4176             :   //
    4177         555 :   Map::EnsureDescriptorSlack(isolate(), map, descriptors_count);
    4178             : 
    4179             :   PropertyAttributes ro_attribs =
    4180             :       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
    4181             :   PropertyAttributes rw_attribs =
    4182             :       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
    4183             :   PropertyAttributes roc_attribs =
    4184             :       static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
    4185             : 
    4186             :   int field_index = 0;
    4187             :   STATIC_ASSERT(JSFunction::kLengthDescriptorIndex == 0);
    4188             :   {  // Add length accessor.
    4189             :     Descriptor d = Descriptor::AccessorConstant(
    4190         555 :         length_string(), function_length_accessor(), roc_attribs);
    4191         555 :     map->AppendDescriptor(isolate(), &d);
    4192             :   }
    4193             : 
    4194             :   STATIC_ASSERT(JSFunction::kNameDescriptorIndex == 1);
    4195         555 :   if (IsFunctionModeWithName(function_mode)) {
    4196             :     // Add name field.
    4197             :     Handle<Name> name = isolate()->factory()->name_string();
    4198             :     Descriptor d = Descriptor::DataField(isolate(), name, field_index++,
    4199         111 :                                          roc_attribs, Representation::Tagged());
    4200         111 :     map->AppendDescriptor(isolate(), &d);
    4201             : 
    4202             :   } else {
    4203             :     // Add name accessor.
    4204             :     Descriptor d = Descriptor::AccessorConstant(
    4205         444 :         name_string(), function_name_accessor(), roc_attribs);
    4206         444 :     map->AppendDescriptor(isolate(), &d);
    4207             :   }
    4208             :   {  // Add arguments accessor.
    4209             :     Descriptor d = Descriptor::AccessorConstant(
    4210         555 :         arguments_string(), function_arguments_accessor(), ro_attribs);
    4211         555 :     map->AppendDescriptor(isolate(), &d);
    4212             :   }
    4213             :   {  // Add caller accessor.
    4214             :     Descriptor d = Descriptor::AccessorConstant(
    4215         555 :         caller_string(), function_caller_accessor(), ro_attribs);
    4216         555 :     map->AppendDescriptor(isolate(), &d);
    4217             :   }
    4218         555 :   if (IsFunctionModeWithPrototype(function_mode)) {
    4219             :     // Add prototype accessor.
    4220             :     PropertyAttributes attribs =
    4221             :         IsFunctionModeWithWritablePrototype(function_mode) ? rw_attribs
    4222         333 :                                                            : ro_attribs;
    4223             :     Descriptor d = Descriptor::AccessorConstant(
    4224         333 :         prototype_string(), function_prototype_accessor(), attribs);
    4225         333 :     map->AppendDescriptor(isolate(), &d);
    4226             :   }
    4227             :   DCHECK_EQ(inobject_properties_count, field_index);
    4228         555 :   LOG(isolate(), MapDetails(*map));
    4229         555 :   return map;
    4230             : }
    4231             : 
    4232         999 : Handle<Map> Factory::CreateStrictFunctionMap(
    4233             :     FunctionMode function_mode, Handle<JSFunction> empty_function) {
    4234             :   bool has_prototype = IsFunctionModeWithPrototype(function_mode);
    4235             :   int header_size = has_prototype ? JSFunction::kSizeWithPrototype
    4236         999 :                                   : JSFunction::kSizeWithoutPrototype;
    4237             :   int inobject_properties_count = 0;
    4238         999 :   if (IsFunctionModeWithName(function_mode)) ++inobject_properties_count;
    4239         999 :   if (IsFunctionModeWithHomeObject(function_mode)) ++inobject_properties_count;
    4240         999 :   int descriptors_count = (IsFunctionModeWithPrototype(function_mode) ? 3 : 2) +
    4241         999 :                           inobject_properties_count;
    4242             : 
    4243             :   Handle<Map> map = NewMap(
    4244         999 :       JS_FUNCTION_TYPE, header_size + inobject_properties_count * kTaggedSize,
    4245         999 :       TERMINAL_FAST_ELEMENTS_KIND, inobject_properties_count);
    4246        1998 :   map->set_has_prototype_slot(has_prototype);
    4247             :   map->set_is_constructor(has_prototype);
    4248             :   map->set_is_callable(true);
    4249         999 :   Map::SetPrototype(isolate(), map, empty_function);
    4250             : 
    4251             :   //
    4252             :   // Setup descriptors array.
    4253             :   //
    4254         999 :   Map::EnsureDescriptorSlack(isolate(), map, descriptors_count);
    4255             : 
    4256             :   PropertyAttributes rw_attribs =
    4257             :       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
    4258             :   PropertyAttributes ro_attribs =
    4259             :       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
    4260             :   PropertyAttributes roc_attribs =
    4261             :       static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
    4262             : 
    4263             :   int field_index = 0;
    4264             :   STATIC_ASSERT(JSFunction::kLengthDescriptorIndex == 0);
    4265             :   {  // Add length accessor.
    4266             :     Descriptor d = Descriptor::AccessorConstant(
    4267         999 :         length_string(), function_length_accessor(), roc_attribs);
    4268         999 :     map->AppendDescriptor(isolate(), &d);
    4269             :   }
    4270             : 
    4271             :   STATIC_ASSERT(JSFunction::kNameDescriptorIndex == 1);
    4272         999 :   if (IsFunctionModeWithName(function_mode)) {
    4273             :     // Add name field.
    4274             :     Handle<Name> name = isolate()->factory()->name_string();
    4275             :     Descriptor d = Descriptor::DataField(isolate(), name, field_index++,
    4276         444 :                                          roc_attribs, Representation::Tagged());
    4277         444 :     map->AppendDescriptor(isolate(), &d);
    4278             : 
    4279             :   } else {
    4280             :     // Add name accessor.
    4281             :     Descriptor d = Descriptor::AccessorConstant(
    4282         555 :         name_string(), function_name_accessor(), roc_attribs);
    4283         555 :     map->AppendDescriptor(isolate(), &d);
    4284             :   }
    4285             : 
    4286             :   STATIC_ASSERT(JSFunction::kMaybeHomeObjectDescriptorIndex == 2);
    4287         999 :   if (IsFunctionModeWithHomeObject(function_mode)) {
    4288             :     // Add home object field.
    4289             :     Handle<Name> name = isolate()->factory()->home_object_symbol();
    4290             :     Descriptor d = Descriptor::DataField(isolate(), name, field_index++,
    4291         444 :                                          DONT_ENUM, Representation::Tagged());
    4292         444 :     map->AppendDescriptor(isolate(), &d);
    4293             :   }
    4294             : 
    4295         999 :   if (IsFunctionModeWithPrototype(function_mode)) {
    4296             :     // Add prototype accessor.
    4297             :     PropertyAttributes attribs =
    4298             :         IsFunctionModeWithWritablePrototype(function_mode) ? rw_attribs
    4299         555 :                                                            : ro_attribs;
    4300             :     Descriptor d = Descriptor::AccessorConstant(
    4301         555 :         prototype_string(), function_prototype_accessor(), attribs);
    4302         555 :     map->AppendDescriptor(isolate(), &d);
    4303             :   }
    4304             :   DCHECK_EQ(inobject_properties_count, field_index);
    4305         999 :   LOG(isolate(), MapDetails(*map));
    4306         999 :   return map;
    4307             : }
    4308             : 
    4309         111 : Handle<Map> Factory::CreateClassFunctionMap(Handle<JSFunction> empty_function) {
    4310         111 :   Handle<Map> map = NewMap(JS_FUNCTION_TYPE, JSFunction::kSizeWithPrototype);
    4311         111 :   map->set_has_prototype_slot(true);
    4312             :   map->set_is_constructor(true);
    4313             :   map->set_is_prototype_map(true);
    4314             :   map->set_is_callable(true);
    4315         111 :   Map::SetPrototype(isolate(), map, empty_function);
    4316             : 
    4317             :   //
    4318             :   // Setup descriptors array.
    4319             :   //
    4320         111 :   Map::EnsureDescriptorSlack(isolate(), map, 2);
    4321             : 
    4322             :   PropertyAttributes ro_attribs =
    4323             :       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
    4324             :   PropertyAttributes roc_attribs =
    4325             :       static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
    4326             : 
    4327             :   STATIC_ASSERT(JSFunction::kLengthDescriptorIndex == 0);
    4328             :   {  // Add length accessor.
    4329             :     Descriptor d = Descriptor::AccessorConstant(
    4330         111 :         length_string(), function_length_accessor(), roc_attribs);
    4331         111 :     map->AppendDescriptor(isolate(), &d);
    4332             :   }
    4333             : 
    4334             :   {
    4335             :     // Add prototype accessor.
    4336             :     Descriptor d = Descriptor::AccessorConstant(
    4337         111 :         prototype_string(), function_prototype_accessor(), ro_attribs);
    4338         111 :     map->AppendDescriptor(isolate(), &d);
    4339             :   }
    4340         111 :   LOG(isolate(), MapDetails(*map));
    4341         111 :   return map;
    4342             : }
    4343             : 
    4344       13856 : Handle<JSPromise> Factory::NewJSPromiseWithoutHook(AllocationType allocation) {
    4345             :   Handle<JSPromise> promise = Handle<JSPromise>::cast(
    4346       13856 :       NewJSObject(isolate()->promise_function(), allocation));
    4347       13856 :   promise->set_reactions_or_result(Smi::kZero);
    4348             :   promise->set_flags(0);
    4349             :   for (int i = 0; i < v8::Promise::kEmbedderFieldCount; i++) {
    4350             :     promise->SetEmbedderField(i, Smi::kZero);
    4351             :   }
    4352       13856 :   return promise;
    4353             : }
    4354             : 
    4355        9528 : Handle<JSPromise> Factory::NewJSPromise(AllocationType allocation) {
    4356        9528 :   Handle<JSPromise> promise = NewJSPromiseWithoutHook(allocation);
    4357        9528 :   isolate()->RunPromiseHook(PromiseHookType::kInit, promise, undefined_value());
    4358        9528 :   return promise;
    4359             : }
    4360             : 
    4361     3582575 : Handle<CallHandlerInfo> Factory::NewCallHandlerInfo(bool has_no_side_effect) {
    4362             :   Handle<Map> map = has_no_side_effect
    4363             :                         ? side_effect_free_call_handler_info_map()
    4364     7165150 :                         : side_effect_call_handler_info_map();
    4365             :   Handle<CallHandlerInfo> info(
    4366     7165148 :       CallHandlerInfo::cast(New(map, AllocationType::kOld)), isolate());
    4367     3582573 :   Object undefined_value = ReadOnlyRoots(isolate()).undefined_value();
    4368     3582573 :   info->set_callback(undefined_value);
    4369     3582573 :   info->set_js_callback(undefined_value);
    4370     3582573 :   info->set_data(undefined_value);
    4371     3582574 :   return info;
    4372             : }
    4373             : 
    4374             : // static
    4375      238399 : NewFunctionArgs NewFunctionArgs::ForWasm(
    4376             :     Handle<String> name,
    4377             :     Handle<WasmExportedFunctionData> exported_function_data, Handle<Map> map) {
    4378             :   NewFunctionArgs args;
    4379      238399 :   args.name_ = name;
    4380      238399 :   args.maybe_map_ = map;
    4381      238399 :   args.maybe_exported_function_data_ = exported_function_data;
    4382      238399 :   args.language_mode_ = LanguageMode::kSloppy;
    4383      238399 :   args.prototype_mutability_ = MUTABLE;
    4384             : 
    4385      238399 :   return args;
    4386             : }
    4387             : 
    4388             : // static
    4389         227 : NewFunctionArgs NewFunctionArgs::ForBuiltin(Handle<String> name,
    4390             :                                             Handle<Map> map, int builtin_id) {
    4391             :   DCHECK(Builtins::IsBuiltinId(builtin_id));
    4392             : 
    4393             :   NewFunctionArgs args;
    4394         227 :   args.name_ = name;
    4395         227 :   args.maybe_map_ = map;
    4396         227 :   args.maybe_builtin_id_ = builtin_id;
    4397         227 :   args.language_mode_ = LanguageMode::kStrict;
    4398         227 :   args.prototype_mutability_ = MUTABLE;
    4399             : 
    4400             :   args.SetShouldSetLanguageMode();
    4401             : 
    4402         227 :   return args;
    4403             : }
    4404             : 
    4405             : // static
    4406       84760 : NewFunctionArgs NewFunctionArgs::ForFunctionWithoutCode(
    4407             :     Handle<String> name, Handle<Map> map, LanguageMode language_mode) {
    4408             :   NewFunctionArgs args;
    4409       84941 :   args.name_ = name;
    4410       84941 :   args.maybe_map_ = map;
    4411       84941 :   args.maybe_builtin_id_ = Builtins::kIllegal;
    4412       84941 :   args.language_mode_ = language_mode;
    4413       84941 :   args.prototype_mutability_ = MUTABLE;
    4414             : 
    4415             :   args.SetShouldSetLanguageMode();
    4416             : 
    4417       84760 :   return args;
    4418             : }
    4419             : 
    4420             : // static
    4421      262928 : NewFunctionArgs NewFunctionArgs::ForBuiltinWithPrototype(
    4422             :     Handle<String> name, Handle<HeapObject> prototype, InstanceType type,
    4423             :     int instance_size, int inobject_properties, int builtin_id,
    4424             :     MutableMode prototype_mutability) {
    4425             :   DCHECK(Builtins::IsBuiltinId(builtin_id));
    4426             : 
    4427             :   NewFunctionArgs args;
    4428      262928 :   args.name_ = name;
    4429      262928 :   args.type_ = type;
    4430      262928 :   args.instance_size_ = instance_size;
    4431      262928 :   args.inobject_properties_ = inobject_properties;
    4432      262928 :   args.maybe_prototype_ = prototype;
    4433      262928 :   args.maybe_builtin_id_ = builtin_id;
    4434      262928 :   args.language_mode_ = LanguageMode::kStrict;
    4435      262928 :   args.prototype_mutability_ = prototype_mutability;
    4436             : 
    4437             :   args.SetShouldCreateAndSetInitialMap();
    4438             :   args.SetShouldSetPrototype();
    4439             :   args.SetShouldSetLanguageMode();
    4440             : 
    4441      262928 :   return args;
    4442             : }
    4443             : 
    4444             : // static
    4445     1684241 : NewFunctionArgs NewFunctionArgs::ForBuiltinWithoutPrototype(
    4446             :     Handle<String> name, int builtin_id, LanguageMode language_mode) {
    4447             :   DCHECK(Builtins::IsBuiltinId(builtin_id));
    4448             : 
    4449             :   NewFunctionArgs args;
    4450     1684241 :   args.name_ = name;
    4451     1684241 :   args.maybe_builtin_id_ = builtin_id;
    4452     1684241 :   args.language_mode_ = language_mode;
    4453     1684241 :   args.prototype_mutability_ = MUTABLE;
    4454             : 
    4455             :   args.SetShouldSetLanguageMode();
    4456             : 
    4457     1684241 :   return args;
    4458             : }
    4459             : 
    4460           0 : void NewFunctionArgs::SetShouldCreateAndSetInitialMap() {
    4461             :   // Needed to create the initial map.
    4462             :   maybe_prototype_.Assert();
    4463             :   DCHECK_NE(kUninitialized, instance_size_);
    4464             :   DCHECK_NE(kUninitialized, inobject_properties_);
    4465             : 
    4466      262928 :   should_create_and_set_initial_map_ = true;
    4467           0 : }
    4468             : 
    4469           0 : void NewFunctionArgs::SetShouldSetPrototype() {
    4470             :   maybe_prototype_.Assert();
    4471      262928 :   should_set_prototype_ = true;
    4472           0 : }
    4473             : 
    4474           0 : void NewFunctionArgs::SetShouldSetLanguageMode() {
    4475             :   DCHECK(language_mode_ == LanguageMode::kStrict ||
    4476             :          language_mode_ == LanguageMode::kSloppy);
    4477     2032337 :   should_set_language_mode_ = true;
    4478           0 : }
    4479             : 
    4480     2270735 : Handle<Map> NewFunctionArgs::GetMap(Isolate* isolate) const {
    4481     2270735 :   if (!maybe_map_.is_null()) {
    4482             :     return maybe_map_.ToHandleChecked();
    4483     1947169 :   } else if (maybe_prototype_.is_null()) {
    4484     1684241 :     return is_strict(language_mode_)
    4485             :                ? isolate->strict_function_without_prototype_map()
    4486     1684241 :                : isolate->sloppy_function_without_prototype_map();
    4487             :   } else {
    4488             :     DCHECK(!maybe_prototype_.is_null());
    4489      262928 :     switch (prototype_mutability_) {
    4490             :       case MUTABLE:
    4491       71506 :         return is_strict(language_mode_) ? isolate->strict_function_map()
    4492       71506 :                                          : isolate->sloppy_function_map();
    4493             :       case IMMUTABLE:
    4494      191422 :         return is_strict(language_mode_)
    4495             :                    ? isolate->strict_function_with_readonly_prototype_map()
    4496      191422 :                    : isolate->sloppy_function_with_readonly_prototype_map();
    4497             :     }
    4498             :   }
    4499           0 :   UNREACHABLE();
    4500             : }
    4501             : 
    4502             : }  // namespace internal
    4503      122036 : }  // namespace v8

Generated by: LCOV version 1.10