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 1906425 : 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 1906425 : int body_size = desc.instr_size;
65 : int unwinding_info_size_field_size = kInt64Size;
66 1906425 : 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 1906423 : 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 1906423 : const bool has_unwinding_info = desc.unwinding_info != nullptr;
90 :
91 1906423 : code->set_raw_instruction_size(desc.instr_size);
92 1906423 : code->set_relocation_info(*reloc_info);
93 5719284 : code->initialize_flags(kind, has_unwinding_info, is_turbofanned, stack_slots,
94 1906428 : kIsNotOffHeapTrampoline);
95 : code->set_builtin_index(builtin_index);
96 1906428 : code->set_code_data_container(*data_container);
97 3812856 : code->set_deoptimization_data(*deopt_data);
98 3812856 : code->set_source_position_table(*source_position_table);
99 1906428 : code->set_safepoint_table_offset(desc.safepoint_table_offset);
100 1906428 : code->set_handler_table_offset(desc.handler_table_offset);
101 : code->set_constant_pool_offset(desc.constant_pool_offset);
102 1906428 : 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 1906428 : 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 272021 : if (builder != nullptr) builder->PatchSelfReference(self_ref, code);
112 : }
113 272021 : *(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 1906428 : code->CopyFromNoFlush(heap, desc);
123 :
124 1906428 : code->clear_padding();
125 :
126 : #ifdef VERIFY_HEAP
127 : if (FLAG_verify_heap) code->ObjectVerify(heap->isolate());
128 : #endif
129 1906428 : }
130 :
131 : } // namespace
132 :
133 163522313 : HeapObject Factory::AllocateRawWithImmortalMap(int size,
134 : AllocationType allocation,
135 : Map map,
136 : AllocationAlignment alignment) {
137 : HeapObject result = isolate()->heap()->AllocateRawWithRetryOrFail(
138 163522313 : size, allocation, alignment);
139 : result->set_map_after_allocation(map, SKIP_WRITE_BARRIER);
140 163522196 : return result;
141 : }
142 :
143 21360304 : 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 21360304 : if (!allocation_site.is_null()) size += AllocationMemento::kSize;
149 : HeapObject result =
150 21360304 : isolate()->heap()->AllocateRawWithRetryOrFail(size, allocation);
151 : WriteBarrierMode write_barrier_mode = allocation == AllocationType::kYoung
152 : ? SKIP_WRITE_BARRIER
153 21360316 : : UPDATE_WRITE_BARRIER;
154 21360316 : result->set_map_after_allocation(*map, write_barrier_mode);
155 21360302 : 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 21360302 : return result;
161 : }
162 :
163 1514331 : 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 1514331 : if (FLAG_allocation_site_pretenuring) {
169 : allocation_site->IncrementMementoCreateCount();
170 : }
171 1514331 : }
172 :
173 38286020 : HeapObject Factory::AllocateRawArray(int size, AllocationType allocation) {
174 : HeapObject result =
175 38286020 : isolate()->heap()->AllocateRawWithRetryOrFail(size, allocation);
176 38286060 : 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 38286060 : return result;
181 : }
182 :
183 34666254 : HeapObject Factory::AllocateRawFixedArray(int length,
184 : AllocationType allocation) {
185 34666254 : if (length < 0 || length > FixedArray::kMaxLength) {
186 0 : isolate()->heap()->FatalProcessOutOfMemory("invalid array length");
187 : }
188 34666254 : return AllocateRawArray(FixedArray::SizeFor(length), allocation);
189 : }
190 :
191 1539315 : HeapObject Factory::AllocateRawWeakArrayList(int capacity,
192 : AllocationType allocation) {
193 1539315 : if (capacity < 0 || capacity > WeakArrayList::kMaxCapacity) {
194 0 : isolate()->heap()->FatalProcessOutOfMemory("invalid array length");
195 : }
196 1539315 : return AllocateRawArray(WeakArrayList::SizeForCapacity(capacity), allocation);
197 : }
198 :
199 49741786 : 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 49741786 : 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 49741798 : : UPDATE_WRITE_BARRIER;
208 49741798 : result->set_map_after_allocation(*map, write_barrier_mode);
209 49741768 : return result;
210 : }
211 :
212 264874 : Handle<HeapObject> Factory::NewFillerObject(int size, bool double_align,
213 : AllocationType allocation) {
214 264874 : AllocationAlignment alignment = double_align ? kDoubleAligned : kWordAligned;
215 : Heap* heap = isolate()->heap();
216 : HeapObject result =
217 264874 : heap->AllocateRawWithRetryOrFail(size, allocation, alignment);
218 264874 : heap->CreateFillerObjectAt(result->address(), size, ClearRecordedSlots::kNo);
219 264874 : return Handle<HeapObject>(result, isolate());
220 : }
221 :
222 590205 : Handle<PrototypeInfo> Factory::NewPrototypeInfo() {
223 : Handle<PrototypeInfo> result = Handle<PrototypeInfo>::cast(
224 590205 : NewStruct(PROTOTYPE_INFO_TYPE, AllocationType::kOld));
225 590206 : result->set_prototype_users(Smi::kZero);
226 : result->set_registry_slot(PrototypeInfo::UNREGISTERED);
227 : result->set_bit_field(0);
228 1180414 : result->set_module_namespace(*undefined_value());
229 590207 : return result;
230 : }
231 :
232 47019 : Handle<EnumCache> Factory::NewEnumCache(Handle<FixedArray> keys,
233 : Handle<FixedArray> indices) {
234 : Handle<EnumCache> result = Handle<EnumCache>::cast(
235 47019 : NewStruct(ENUM_CACHE_TYPE, AllocationType::kOld));
236 47019 : result->set_keys(*keys);
237 47019 : result->set_indices(*indices);
238 47019 : 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 180149 : Handle<ArrayBoilerplateDescription> Factory::NewArrayBoilerplateDescription(
262 : ElementsKind elements_kind, Handle<FixedArrayBase> constant_values) {
263 : Handle<ArrayBoilerplateDescription> result =
264 : Handle<ArrayBoilerplateDescription>::cast(
265 180149 : NewStruct(ARRAY_BOILERPLATE_DESCRIPTION_TYPE, AllocationType::kOld));
266 : result->set_elements_kind(elements_kind);
267 180152 : result->set_constant_elements(*constant_values);
268 180150 : return result;
269 : }
270 :
271 1731 : 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 1731 : NewStruct(TUPLE2_TYPE, AllocationType::kOld));
278 1731 : result->set_raw_strings(*raw_strings);
279 1731 : result->set_cooked_strings(*cooked_strings);
280 1731 : 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 13220684 : Handle<PropertyArray> Factory::NewPropertyArray(int length,
299 : AllocationType allocation) {
300 : DCHECK_LE(0, length);
301 13220684 : if (length == 0) return empty_property_array();
302 7440457 : 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 7440463 : return array;
308 : }
309 :
310 23032319 : Handle<FixedArray> Factory::NewFixedArrayWithFiller(RootIndex map_root_index,
311 : int length, Object filler,
312 : AllocationType allocation) {
313 23032319 : 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 23032333 : return array;
321 : }
322 :
323 : template <typename T>
324 2523413 : 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 5799928 : return Handle<T>::cast(NewFixedArrayWithFiller(
332 2523418 : 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 484161 : return Handle<T>::cast(array);
355 : }
356 :
357 : template Handle<FixedArray> Factory::NewFixedArrayWithMap<FixedArray>(
358 : RootIndex, int, AllocationType allocation);
359 :
360 19107885 : Handle<FixedArray> Factory::NewFixedArray(int length,
361 : AllocationType allocation) {
362 : DCHECK_LE(0, length);
363 19114233 : if (length == 0) return empty_fixed_array();
364 : return NewFixedArrayWithFiller(RootIndex::kFixedArrayMap, length,
365 12215940 : *undefined_value(), allocation);
366 : }
367 :
368 1596328 : Handle<WeakFixedArray> Factory::NewWeakFixedArray(int length,
369 : AllocationType allocation) {
370 : DCHECK_LE(0, length);
371 1596328 : if (length == 0) return empty_weak_fixed_array();
372 : HeapObject result =
373 1596328 : 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 1596332 : 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 2437021 : Handle<FixedArray> Factory::NewFixedArrayWithHoles(int length,
405 : AllocationType allocation) {
406 : DCHECK_LE(0, length);
407 2492826 : if (length == 0) return empty_fixed_array();
408 : return NewFixedArrayWithFiller(RootIndex::kFixedArrayMap, length,
409 3430755 : *the_hole_value(), allocation);
410 : }
411 :
412 1300884 : Handle<FixedArray> Factory::NewUninitializedFixedArray(
413 : int length, AllocationType allocation) {
414 : DCHECK_LE(0, length);
415 1586261 : 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 1585737 : *undefined_value(), allocation);
422 : }
423 :
424 3101520 : Handle<ClosureFeedbackCellArray> Factory::NewClosureFeedbackCellArray(
425 : int length, AllocationType allocation) {
426 3101520 : 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 1036125 : return feedback_cell_array;
433 : }
434 :
435 3101510 : 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 3101510 : AllocateRawWithImmortalMap(size, allocation, *feedback_vector_map());
445 : Handle<FeedbackVector> vector(FeedbackVector::cast(result), isolate());
446 3101516 : vector->set_shared_function_info(*shared);
447 9304549 : vector->set_optimized_code_weak_or_smi(MaybeObject::FromSmi(Smi::FromEnum(
448 : FLAG_log_function_events ? OptimizationMarker::kLogFirstExecution
449 3101517 : : 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 3101515 : vector->set_closure_feedback_cell_array(*closure_feedback_cell_array);
455 :
456 : // TODO(leszeks): Initialize based on the feedback metadata.
457 3101529 : MemsetTagged(ObjectSlot(vector->slots_start()), *undefined_value(), length);
458 3101528 : return vector;
459 : }
460 :
461 61229 : 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 61229 : AllocateRawWithImmortalMap(size, allocation, *embedder_data_array_map());
468 : Handle<EmbedderDataArray> array(EmbedderDataArray::cast(result), isolate());
469 : array->set_length(length);
470 :
471 61229 : 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 61229 : return array;
478 : }
479 :
480 205763 : 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 205763 : 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 205763 : 2 * boilerplate + ObjectBoilerplateDescription::kDescriptionStartIndex;
494 :
495 205763 : if (has_different_size_backing_store) {
496 : // An extra entry for the backing store size.
497 2775 : size++;
498 : }
499 :
500 : Handle<ObjectBoilerplateDescription> description =
501 : Handle<ObjectBoilerplateDescription>::cast(
502 : NewFixedArrayWithMap(RootIndex::kObjectBoilerplateDescriptionMap,
503 205763 : size, AllocationType::kOld));
504 :
505 205765 : if (has_different_size_backing_store) {
506 : DCHECK_IMPLIES((boilerplate == (all_properties - index_keys)),
507 : has_seen_proto);
508 2775 : description->set_backing_store_size(isolate(), backing_store_size);
509 : }
510 :
511 : description->set_flags(0);
512 :
513 205765 : return description;
514 : }
515 :
516 332152 : Handle<FixedArrayBase> Factory::NewFixedDoubleArray(int length,
517 : AllocationType allocation) {
518 332152 : if (length == 0) return empty_fixed_array();
519 332152 : if (length < 0 || length > FixedDoubleArray::kMaxLength) {
520 0 : isolate()->heap()->FatalProcessOutOfMemory("invalid array length");
521 : }
522 : int size = FixedDoubleArray::SizeFor(length);
523 332152 : Map map = *fixed_double_array_map();
524 : HeapObject result =
525 332152 : AllocateRawWithImmortalMap(size, allocation, map, kDoubleAligned);
526 : Handle<FixedDoubleArray> array(FixedDoubleArray::cast(result), isolate());
527 : array->set_length(length);
528 332152 : 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 1614208 : 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 1614208 : 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 1614230 : int data_size = size - FeedbackMetadata::kHeaderSize;
553 1614230 : Address data_start = data->address() + FeedbackMetadata::kHeaderSize;
554 1614230 : 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 1614230 : return data;
558 : }
559 :
560 1315632 : 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 1315632 : result->set(FrameArray::kFrameCountIndex, Smi::kZero);
566 1315632 : 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 1562150 : Handle<AccessorPair> Factory::NewAccessorPair() {
626 : Handle<AccessorPair> accessors = Handle<AccessorPair>::cast(
627 1562150 : 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 1562153 : return accessors;
631 : }
632 :
633 : // Internalized strings are created in the old generation (data space).
634 13505013 : Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
635 : Utf8StringKey key(string, HashSeed(isolate()));
636 13505016 : return InternalizeStringWithKey(&key);
637 : }
638 :
639 87284 : Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
640 : OneByteStringKey key(string, HashSeed(isolate()));
641 87284 : return InternalizeStringWithKey(&key);
642 : }
643 :
644 480867 : Handle<String> Factory::InternalizeOneByteString(
645 : Handle<SeqOneByteString> string, int from, int length) {
646 480867 : SeqOneByteSubStringKey key(isolate(), string, from, length);
647 480867 : 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 14074207 : return StringTable::LookupKey(isolate(), key);
658 : }
659 :
660 47754759 : MaybeHandle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
661 : AllocationType allocation) {
662 : DCHECK_NE(allocation, AllocationType::kReadOnly);
663 : int length = string.length();
664 47765152 : if (length == 0) return empty_string();
665 47744366 : if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
666 : Handle<SeqOneByteString> result;
667 94391454 : 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 47195716 : CopyChars(SeqOneByteString::cast(*result)->GetChars(no_gc), string.start(),
674 : length);
675 47195716 : return result;
676 : }
677 :
678 10281951 : 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 10281951 : int non_ascii_start = String::NonAsciiStart(ascii_data, length);
685 10281952 : 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 10276512 : 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 6892317 : while (cursor < end) {
704 : unibrow::uchar t =
705 6886877 : unibrow::Utf8::ValueOfIncremental(&cursor, &state, &incomplete_char);
706 :
707 6886877 : if (V8_LIKELY(t <= unibrow::Utf16::kMaxNonSurrogateCharCode)) {
708 4986261 : *(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 1270305 : MaybeHandle<String> Factory::NewStringFromTwoByte(const uc16* string,
798 : int length,
799 : AllocationType allocation) {
800 : DCHECK_NE(allocation, AllocationType::kReadOnly);
801 1270540 : if (length == 0) return empty_string();
802 1270070 : if (String::IsOneByte(string, length)) {
803 1252752 : if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
804 : Handle<SeqOneByteString> result;
805 2458718 : ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
806 : NewRawOneByteString(length, allocation), String);
807 : DisallowHeapAllocation no_gc;
808 : CopyChars(result->GetChars(no_gc), string, length);
809 1229362 : 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 1270308 : MaybeHandle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
821 : AllocationType allocation) {
822 1270308 : 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 4743104 : 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 19640 : String::WriteToFlat(*s, chars, 0, len);
872 : }
873 :
874 : } // namespace
875 :
876 9917276 : Handle<SeqOneByteString> Factory::AllocateRawOneByteInternalizedString(
877 : int length, uint32_t hash_field) {
878 9917276 : 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 : Map map =
885 19834552 : length == 0 ? *empty_string_map() : *one_byte_internalized_string_map();
886 : int size = SeqOneByteString::SizeFor(length);
887 : HeapObject result =
888 : AllocateRawWithImmortalMap(size,
889 : isolate()->heap()->CanAllocateInReadOnlySpace()
890 : ? AllocationType::kReadOnly
891 : : AllocationType::kOld,
892 9917276 : map);
893 : Handle<SeqOneByteString> answer(SeqOneByteString::cast(result), isolate());
894 : answer->set_length(length);
895 : answer->set_hash_field(hash_field);
896 : DCHECK_EQ(size, answer->Size());
897 9917277 : return answer;
898 : }
899 :
900 53144 : Handle<String> Factory::AllocateTwoByteInternalizedString(
901 : Vector<const uc16> str, uint32_t hash_field) {
902 53144 : CHECK_GE(String::kMaxLength, str.length());
903 : DCHECK_NE(0, str.length()); // Use Heap::empty_string() instead.
904 :
905 53144 : Map map = *internalized_string_map();
906 : int size = SeqTwoByteString::SizeFor(str.length());
907 : HeapObject result =
908 53144 : AllocateRawWithImmortalMap(size, AllocationType::kOld, map);
909 : Handle<SeqTwoByteString> answer(SeqTwoByteString::cast(result), isolate());
910 : answer->set_length(str.length());
911 : answer->set_hash_field(hash_field);
912 : DCHECK_EQ(size, answer->Size());
913 : DisallowHeapAllocation no_gc;
914 :
915 : // Fill in the characters.
916 53144 : MemCopy(answer->GetChars(no_gc), str.start(), str.length() * kUC16Size);
917 :
918 53144 : return answer;
919 : }
920 :
921 : template <bool is_one_byte, typename T>
922 4763238 : Handle<String> Factory::AllocateInternalizedStringImpl(T t, int chars,
923 : uint32_t hash_field) {
924 : DCHECK_LE(0, chars);
925 : DCHECK_GE(String::kMaxLength, chars);
926 :
927 : // Compute map and object size.
928 : int size;
929 : Map map;
930 : if (is_one_byte) {
931 4743103 : map = *one_byte_internalized_string_map();
932 : size = SeqOneByteString::SizeFor(chars);
933 : } else {
934 20135 : map = *internalized_string_map();
935 : size = SeqTwoByteString::SizeFor(chars);
936 : }
937 :
938 : HeapObject result =
939 4763238 : AllocateRawWithImmortalMap(size,
940 : isolate()->heap()->CanAllocateInReadOnlySpace()
941 : ? AllocationType::kReadOnly
942 : : AllocationType::kOld,
943 4763238 : map);
944 : Handle<String> answer(String::cast(result), isolate());
945 : answer->set_length(chars);
946 : answer->set_hash_field(hash_field);
947 : DCHECK_EQ(size, answer->Size());
948 : DisallowHeapAllocation no_gc;
949 :
950 : if (is_one_byte) {
951 : WriteOneByteData(t, SeqOneByteString::cast(*answer)->GetChars(no_gc),
952 : chars);
953 : } else {
954 495 : WriteTwoByteData(t, SeqTwoByteString::cast(*answer)->GetChars(no_gc),
955 : chars);
956 : }
957 4763238 : return answer;
958 : }
959 :
960 730323 : Handle<String> Factory::NewInternalizedStringFromUtf8(Vector<const char> str,
961 : int chars,
962 : uint32_t hash_field) {
963 730323 : if (IsOneByte(str, chars)) {
964 : Handle<SeqOneByteString> result =
965 729828 : AllocateRawOneByteInternalizedString(str.length(), hash_field);
966 : DisallowHeapAllocation no_allocation;
967 729829 : MemCopy(result->GetChars(no_allocation), str.start(), str.length());
968 729829 : return result;
969 : }
970 495 : return AllocateInternalizedStringImpl<false>(str, chars, hash_field);
971 : }
972 :
973 8706586 : Handle<String> Factory::NewOneByteInternalizedString(Vector<const uint8_t> str,
974 : uint32_t hash_field) {
975 : Handle<SeqOneByteString> result =
976 8706586 : AllocateRawOneByteInternalizedString(str.length(), hash_field);
977 : DisallowHeapAllocation no_allocation;
978 8706587 : MemCopy(result->GetChars(no_allocation), str.start(), str.length());
979 8706587 : return result;
980 : }
981 :
982 480867 : Handle<String> Factory::NewOneByteInternalizedSubString(
983 : Handle<SeqOneByteString> string, int offset, int length,
984 : uint32_t hash_field) {
985 : Handle<SeqOneByteString> result =
986 480867 : AllocateRawOneByteInternalizedString(length, hash_field);
987 : DisallowHeapAllocation no_allocation;
988 961734 : MemCopy(result->GetChars(no_allocation),
989 : string->GetChars(no_allocation) + offset, length);
990 480867 : return result;
991 : }
992 :
993 53144 : Handle<String> Factory::NewTwoByteInternalizedString(Vector<const uc16> str,
994 : uint32_t hash_field) {
995 53144 : return AllocateTwoByteInternalizedString(str, hash_field);
996 : }
997 :
998 4762743 : Handle<String> Factory::NewInternalizedStringImpl(Handle<String> string,
999 : int chars,
1000 : uint32_t hash_field) {
1001 4762743 : if (IsOneByte(string)) {
1002 4743103 : return AllocateInternalizedStringImpl<true>(string, chars, hash_field);
1003 : }
1004 19640 : return AllocateInternalizedStringImpl<false>(string, chars, hash_field);
1005 : }
1006 :
1007 : namespace {
1008 :
1009 56345 : MaybeHandle<Map> GetInternalizedStringMap(Factory* f, Handle<String> string) {
1010 56345 : switch (string->map()->instance_type()) {
1011 : case STRING_TYPE:
1012 317 : return f->internalized_string_map();
1013 : case ONE_BYTE_STRING_TYPE:
1014 55979 : return f->one_byte_internalized_string_map();
1015 : case EXTERNAL_STRING_TYPE:
1016 11 : return f->external_internalized_string_map();
1017 : case EXTERNAL_ONE_BYTE_STRING_TYPE:
1018 16 : return f->external_one_byte_internalized_string_map();
1019 : case UNCACHED_EXTERNAL_STRING_TYPE:
1020 0 : return f->uncached_external_internalized_string_map();
1021 : case UNCACHED_EXTERNAL_ONE_BYTE_STRING_TYPE:
1022 5 : return f->uncached_external_one_byte_internalized_string_map();
1023 : default:
1024 17 : return MaybeHandle<Map>(); // No match found.
1025 : }
1026 : }
1027 :
1028 : } // namespace
1029 :
1030 4819071 : MaybeHandle<Map> Factory::InternalizedStringMapForString(
1031 : Handle<String> string) {
1032 : // If the string is in the young generation, it cannot be used as
1033 : // internalized.
1034 4819071 : if (Heap::InYoungGeneration(*string)) return MaybeHandle<Map>();
1035 :
1036 56340 : return GetInternalizedStringMap(this, string);
1037 : }
1038 :
1039 : template <class StringClass>
1040 5 : Handle<StringClass> Factory::InternalizeExternalString(Handle<String> string) {
1041 : Handle<StringClass> cast_string = Handle<StringClass>::cast(string);
1042 10 : Handle<Map> map = GetInternalizedStringMap(this, string).ToHandleChecked();
1043 : Handle<StringClass> external_string(
1044 10 : StringClass::cast(New(map, AllocationType::kOld)), isolate());
1045 : external_string->set_length(cast_string->length());
1046 : external_string->set_hash_field(cast_string->hash_field());
1047 5 : external_string->SetResource(isolate(), nullptr);
1048 : isolate()->heap()->RegisterExternalString(*external_string);
1049 5 : return external_string;
1050 : }
1051 :
1052 : template Handle<ExternalOneByteString>
1053 : Factory::InternalizeExternalString<ExternalOneByteString>(Handle<String>);
1054 : template Handle<ExternalTwoByteString>
1055 : Factory::InternalizeExternalString<ExternalTwoByteString>(Handle<String>);
1056 :
1057 79631095 : MaybeHandle<SeqOneByteString> Factory::NewRawOneByteString(
1058 : int length, AllocationType allocation) {
1059 79631095 : if (length > String::kMaxLength || length < 0) {
1060 19 : THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqOneByteString);
1061 : }
1062 : DCHECK_GT(length, 0); // Use Factory::empty_string() instead.
1063 : int size = SeqOneByteString::SizeFor(length);
1064 : DCHECK_GE(SeqOneByteString::kMaxSize, size);
1065 :
1066 : HeapObject result =
1067 79631076 : AllocateRawWithImmortalMap(size, allocation, *one_byte_string_map());
1068 : Handle<SeqOneByteString> string(SeqOneByteString::cast(result), isolate());
1069 : string->set_length(length);
1070 : string->set_hash_field(String::kEmptyHashField);
1071 : DCHECK_EQ(size, string->Size());
1072 79631064 : return string;
1073 : }
1074 :
1075 10543653 : MaybeHandle<SeqTwoByteString> Factory::NewRawTwoByteString(
1076 : int length, AllocationType allocation) {
1077 10543653 : if (length > String::kMaxLength || length < 0) {
1078 0 : THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqTwoByteString);
1079 : }
1080 : DCHECK_GT(length, 0); // Use Factory::empty_string() instead.
1081 : int size = SeqTwoByteString::SizeFor(length);
1082 : DCHECK_GE(SeqTwoByteString::kMaxSize, size);
1083 :
1084 : HeapObject result =
1085 10543653 : AllocateRawWithImmortalMap(size, allocation, *string_map());
1086 : Handle<SeqTwoByteString> string(SeqTwoByteString::cast(result), isolate());
1087 : string->set_length(length);
1088 : string->set_hash_field(String::kEmptyHashField);
1089 : DCHECK_EQ(size, string->Size());
1090 10543653 : return string;
1091 : }
1092 :
1093 1154496 : Handle<String> Factory::LookupSingleCharacterStringFromCode(uint32_t code) {
1094 1154496 : if (code <= String::kMaxOneByteCharCodeU) {
1095 : {
1096 : DisallowHeapAllocation no_allocation;
1097 1154183 : Object value = single_character_string_cache()->get(code);
1098 1154183 : if (value != *undefined_value()) {
1099 : return handle(String::cast(value), isolate());
1100 : }
1101 : }
1102 : uint8_t buffer[1];
1103 49073 : buffer[0] = static_cast<uint8_t>(code);
1104 : Handle<String> result =
1105 49073 : InternalizeOneByteString(Vector<const uint8_t>(buffer, 1));
1106 98146 : single_character_string_cache()->set(code, *result);
1107 49072 : return result;
1108 : }
1109 : DCHECK_LE(code, String::kMaxUtf16CodeUnitU);
1110 :
1111 626 : Handle<SeqTwoByteString> result = NewRawTwoByteString(1).ToHandleChecked();
1112 : result->SeqTwoByteStringSet(0, static_cast<uint16_t>(code));
1113 313 : return result;
1114 : }
1115 :
1116 : // Returns true for a character in a range. Both limits are inclusive.
1117 : static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
1118 : // This makes uses of the the unsigned wraparound.
1119 1707418 : return character - from <= to - from;
1120 : }
1121 :
1122 1706402 : static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
1123 : uint16_t c1,
1124 : uint16_t c2) {
1125 : // Numeric strings have a different hash algorithm not known by
1126 : // LookupTwoCharsStringIfExists, so we skip this step for such strings.
1127 3413820 : if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
1128 : Handle<String> result;
1129 3412066 : if (StringTable::LookupTwoCharsStringIfExists(isolate, c1, c2)
1130 : .ToHandle(&result)) {
1131 13539 : return result;
1132 : }
1133 : }
1134 :
1135 : // Now we know the length is 2, we might as well make use of that fact
1136 : // when building the new string.
1137 1692863 : if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
1138 : // We can do this.
1139 : DCHECK(base::bits::IsPowerOfTwo(String::kMaxOneByteCharCodeU +
1140 : 1)); // because of this.
1141 : Handle<SeqOneByteString> str =
1142 910892 : isolate->factory()->NewRawOneByteString(2).ToHandleChecked();
1143 : DisallowHeapAllocation no_allocation;
1144 : uint8_t* dest = str->GetChars(no_allocation);
1145 455446 : dest[0] = static_cast<uint8_t>(c1);
1146 455446 : dest[1] = static_cast<uint8_t>(c2);
1147 455446 : return str;
1148 : } else {
1149 : Handle<SeqTwoByteString> str =
1150 2474834 : isolate->factory()->NewRawTwoByteString(2).ToHandleChecked();
1151 : DisallowHeapAllocation no_allocation;
1152 : uc16* dest = str->GetChars(no_allocation);
1153 1237417 : dest[0] = c1;
1154 1237417 : dest[1] = c2;
1155 1237417 : return str;
1156 : }
1157 : }
1158 :
1159 : template <typename SinkChar, typename StringType>
1160 5606948 : Handle<String> ConcatStringContent(Handle<StringType> result,
1161 : Handle<String> first,
1162 : Handle<String> second) {
1163 : DisallowHeapAllocation pointer_stays_valid;
1164 : SinkChar* sink = result->GetChars(pointer_stays_valid);
1165 5606948 : String::WriteToFlat(*first, sink, 0, first->length());
1166 5606948 : String::WriteToFlat(*second, sink + first->length(), 0, second->length());
1167 5606948 : return result;
1168 : }
1169 :
1170 33007323 : MaybeHandle<String> Factory::NewConsString(Handle<String> left,
1171 : Handle<String> right) {
1172 33007323 : if (left->IsThinString()) {
1173 : left = handle(Handle<ThinString>::cast(left)->actual(), isolate());
1174 : }
1175 33007332 : if (right->IsThinString()) {
1176 : right = handle(Handle<ThinString>::cast(right)->actual(), isolate());
1177 : }
1178 : int left_length = left->length();
1179 33007332 : if (left_length == 0) return right;
1180 : int right_length = right->length();
1181 24237632 : if (right_length == 0) return left;
1182 :
1183 22375850 : int length = left_length + right_length;
1184 :
1185 22375850 : if (length == 2) {
1186 : uint16_t c1 = left->Get(0);
1187 : uint16_t c2 = right->Get(0);
1188 1244356 : return MakeOrFindTwoCharacterString(isolate(), c1, c2);
1189 : }
1190 :
1191 : // Make sure that an out of memory exception is thrown if the length
1192 : // of the new cons string is too large.
1193 21131494 : if (length > String::kMaxLength || length < 0) {
1194 187 : THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
1195 : }
1196 :
1197 : bool left_is_one_byte = left->IsOneByteRepresentation();
1198 : bool right_is_one_byte = right->IsOneByteRepresentation();
1199 21131307 : bool is_one_byte = left_is_one_byte && right_is_one_byte;
1200 :
1201 : // If the resulting string is small make a flat string.
1202 21131307 : if (length < ConsString::kMinLength) {
1203 : // Note that neither of the two inputs can be a slice because:
1204 : STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
1205 : DCHECK(left->IsFlat());
1206 : DCHECK(right->IsFlat());
1207 :
1208 : STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
1209 8484823 : if (is_one_byte) {
1210 : Handle<SeqOneByteString> result =
1211 5755747 : NewRawOneByteString(length).ToHandleChecked();
1212 : DisallowHeapAllocation no_gc;
1213 : uint8_t* dest = result->GetChars(no_gc);
1214 : // Copy left part.
1215 : const uint8_t* src =
1216 : left->IsExternalString()
1217 : ? Handle<ExternalOneByteString>::cast(left)->GetChars()
1218 2877872 : : Handle<SeqOneByteString>::cast(left)->GetChars(no_gc);
1219 14708863 : for (int i = 0; i < left_length; i++) *dest++ = src[i];
1220 : // Copy right part.
1221 : src = right->IsExternalString()
1222 : ? Handle<ExternalOneByteString>::cast(right)->GetChars()
1223 2877872 : : Handle<SeqOneByteString>::cast(right)->GetChars(no_gc);
1224 12493402 : for (int i = 0; i < right_length; i++) *dest++ = src[i];
1225 2877872 : return result;
1226 : }
1227 :
1228 : return ConcatStringContent<uc16>(
1229 11213896 : NewRawTwoByteString(length).ToHandleChecked(), left, right);
1230 : }
1231 :
1232 12646484 : return NewConsString(left, right, length, is_one_byte);
1233 : }
1234 :
1235 12646493 : Handle<String> Factory::NewConsString(Handle<String> left, Handle<String> right,
1236 : int length, bool one_byte) {
1237 : DCHECK_GT(left->length(), 0);
1238 : DCHECK_GT(right->length(), 0);
1239 : DCHECK(!left->IsThinString());
1240 : DCHECK(!right->IsThinString());
1241 : DCHECK_GE(length, ConsString::kMinLength);
1242 : DCHECK_LE(length, String::kMaxLength);
1243 :
1244 : Handle<ConsString> result(
1245 : ConsString::cast(
1246 : one_byte ? New(cons_one_byte_string_map(), AllocationType::kYoung)
1247 : : New(cons_string_map(), AllocationType::kYoung)),
1248 37939477 : isolate());
1249 :
1250 : DisallowHeapAllocation no_gc;
1251 : WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
1252 :
1253 : result->set_hash_field(String::kEmptyHashField);
1254 : result->set_length(length);
1255 12646491 : result->set_first(isolate(), *left, mode);
1256 12646492 : result->set_second(isolate(), *right, mode);
1257 12646492 : return result;
1258 : }
1259 :
1260 0 : Handle<String> Factory::NewSurrogatePairString(uint16_t lead, uint16_t trail) {
1261 : DCHECK_GE(lead, 0xD800);
1262 : DCHECK_LE(lead, 0xDBFF);
1263 : DCHECK_GE(trail, 0xDC00);
1264 : DCHECK_LE(trail, 0xDFFF);
1265 :
1266 : Handle<SeqTwoByteString> str =
1267 0 : isolate()->factory()->NewRawTwoByteString(2).ToHandleChecked();
1268 : DisallowHeapAllocation no_allocation;
1269 : uc16* dest = str->GetChars(no_allocation);
1270 0 : dest[0] = lead;
1271 0 : dest[1] = trail;
1272 0 : return str;
1273 : }
1274 :
1275 3015284 : Handle<String> Factory::NewProperSubString(Handle<String> str, int begin,
1276 : int end) {
1277 : #if VERIFY_HEAP
1278 : if (FLAG_verify_heap) str->StringVerify(isolate());
1279 : #endif
1280 : DCHECK(begin > 0 || end < str->length());
1281 :
1282 3015284 : str = String::Flatten(isolate(), str);
1283 :
1284 3015284 : int length = end - begin;
1285 3015284 : if (length <= 0) return empty_string();
1286 2993454 : if (length == 1) {
1287 498760 : return LookupSingleCharacterStringFromCode(str->Get(begin));
1288 : }
1289 2494694 : if (length == 2) {
1290 : // Optimization for 2-byte strings often used as keys in a decompression
1291 : // dictionary. Check whether we already have the string in the string
1292 : // table to prevent creation of many unnecessary strings.
1293 : uint16_t c1 = str->Get(begin);
1294 462046 : uint16_t c2 = str->Get(begin + 1);
1295 462046 : return MakeOrFindTwoCharacterString(isolate(), c1, c2);
1296 : }
1297 :
1298 2032648 : if (!FLAG_string_slices || length < SlicedString::kMinLength) {
1299 113343 : if (str->IsOneByteRepresentation()) {
1300 : Handle<SeqOneByteString> result =
1301 225220 : NewRawOneByteString(length).ToHandleChecked();
1302 : DisallowHeapAllocation no_gc;
1303 : uint8_t* dest = result->GetChars(no_gc);
1304 112610 : String::WriteToFlat(*str, dest, begin, end);
1305 112610 : return result;
1306 : } else {
1307 : Handle<SeqTwoByteString> result =
1308 1466 : NewRawTwoByteString(length).ToHandleChecked();
1309 : DisallowHeapAllocation no_gc;
1310 : uc16* dest = result->GetChars(no_gc);
1311 733 : String::WriteToFlat(*str, dest, begin, end);
1312 733 : return result;
1313 : }
1314 : }
1315 :
1316 : int offset = begin;
1317 :
1318 1919305 : if (str->IsSlicedString()) {
1319 : Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
1320 : str = Handle<String>(slice->parent(), isolate());
1321 1377 : offset += slice->offset();
1322 : }
1323 1919305 : if (str->IsThinString()) {
1324 : Handle<ThinString> thin = Handle<ThinString>::cast(str);
1325 : str = handle(thin->actual(), isolate());
1326 : }
1327 :
1328 : DCHECK(str->IsSeqString() || str->IsExternalString());
1329 : Handle<Map> map = str->IsOneByteRepresentation()
1330 : ? sliced_one_byte_string_map()
1331 3838610 : : sliced_string_map();
1332 : Handle<SlicedString> slice(
1333 3838610 : SlicedString::cast(New(map, AllocationType::kYoung)), isolate());
1334 :
1335 : slice->set_hash_field(String::kEmptyHashField);
1336 : slice->set_length(length);
1337 1919305 : slice->set_parent(isolate(), *str);
1338 : slice->set_offset(offset);
1339 1919305 : return slice;
1340 : }
1341 :
1342 5994 : MaybeHandle<String> Factory::NewExternalStringFromOneByte(
1343 : const ExternalOneByteString::Resource* resource) {
1344 5994 : size_t length = resource->length();
1345 5996 : if (length > static_cast<size_t>(String::kMaxLength)) {
1346 5 : THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
1347 : }
1348 6001 : if (length == 0) return empty_string();
1349 :
1350 5981 : Handle<Map> map = resource->IsCacheable()
1351 : ? external_one_byte_string_map()
1352 11960 : : uncached_external_one_byte_string_map();
1353 : Handle<ExternalOneByteString> external_string(
1354 11961 : ExternalOneByteString::cast(New(map, AllocationType::kOld)), isolate());
1355 5981 : external_string->set_length(static_cast<int>(length));
1356 : external_string->set_hash_field(String::kEmptyHashField);
1357 5981 : external_string->SetResource(isolate(), resource);
1358 : isolate()->heap()->RegisterExternalString(*external_string);
1359 :
1360 5986 : return external_string;
1361 : }
1362 :
1363 18934 : MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
1364 : const ExternalTwoByteString::Resource* resource) {
1365 18934 : size_t length = resource->length();
1366 18934 : if (length > static_cast<size_t>(String::kMaxLength)) {
1367 5 : THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
1368 : }
1369 18934 : if (length == 0) return empty_string();
1370 :
1371 18924 : Handle<Map> map = resource->IsCacheable() ? external_string_map()
1372 37848 : : uncached_external_string_map();
1373 : Handle<ExternalTwoByteString> external_string(
1374 37848 : ExternalTwoByteString::cast(New(map, AllocationType::kOld)), isolate());
1375 18924 : external_string->set_length(static_cast<int>(length));
1376 : external_string->set_hash_field(String::kEmptyHashField);
1377 18924 : external_string->SetResource(isolate(), resource);
1378 : isolate()->heap()->RegisterExternalString(*external_string);
1379 :
1380 18924 : return external_string;
1381 : }
1382 :
1383 111 : Handle<ExternalOneByteString> Factory::NewNativeSourceString(
1384 : const ExternalOneByteString::Resource* resource) {
1385 111 : size_t length = resource->length();
1386 : DCHECK_LE(length, static_cast<size_t>(String::kMaxLength));
1387 :
1388 111 : Handle<Map> map = native_source_string_map();
1389 : Handle<ExternalOneByteString> external_string(
1390 222 : ExternalOneByteString::cast(New(map, AllocationType::kOld)), isolate());
1391 111 : external_string->set_length(static_cast<int>(length));
1392 : external_string->set_hash_field(String::kEmptyHashField);
1393 111 : external_string->SetResource(isolate(), resource);
1394 : isolate()->heap()->RegisterExternalString(*external_string);
1395 :
1396 111 : return external_string;
1397 : }
1398 :
1399 0 : Handle<JSStringIterator> Factory::NewJSStringIterator(Handle<String> string) {
1400 0 : Handle<Map> map(isolate()->native_context()->initial_string_iterator_map(),
1401 0 : isolate());
1402 0 : Handle<String> flat_string = String::Flatten(isolate(), string);
1403 : Handle<JSStringIterator> iterator =
1404 0 : Handle<JSStringIterator>::cast(NewJSObjectFromMap(map));
1405 0 : iterator->set_string(*flat_string);
1406 : iterator->set_index(0);
1407 :
1408 0 : return iterator;
1409 : }
1410 :
1411 18300 : Handle<Symbol> Factory::NewSymbol(AllocationType allocation) {
1412 : DCHECK(allocation != AllocationType::kYoung);
1413 : // Statically ensure that it is safe to allocate symbols in paged spaces.
1414 : STATIC_ASSERT(Symbol::kSize <= kMaxRegularHeapObjectSize);
1415 :
1416 : HeapObject result =
1417 18300 : AllocateRawWithImmortalMap(Symbol::kSize, allocation, *symbol_map());
1418 :
1419 : // Generate a random hash value.
1420 18300 : int hash = isolate()->GenerateIdentityHash(Name::kHashBitMask);
1421 :
1422 : Handle<Symbol> symbol(Symbol::cast(result), isolate());
1423 18300 : symbol->set_hash_field(Name::kIsNotArrayIndexMask |
1424 18300 : (hash << Name::kHashShift));
1425 36600 : symbol->set_name(*undefined_value());
1426 : symbol->set_flags(0);
1427 : DCHECK(!symbol->is_private());
1428 18300 : return symbol;
1429 : }
1430 :
1431 4904 : Handle<Symbol> Factory::NewPrivateSymbol(AllocationType allocation) {
1432 : DCHECK(allocation != AllocationType::kYoung);
1433 4904 : Handle<Symbol> symbol = NewSymbol(allocation);
1434 : symbol->set_is_private(true);
1435 4904 : return symbol;
1436 : }
1437 :
1438 988 : Handle<Symbol> Factory::NewPrivateNameSymbol(Handle<String> name) {
1439 988 : Handle<Symbol> symbol = NewSymbol();
1440 : symbol->set_is_private_name();
1441 1976 : symbol->set_name(*name);
1442 988 : return symbol;
1443 : }
1444 :
1445 1275432 : Handle<Context> Factory::NewContext(RootIndex map_root_index, int size,
1446 : int variadic_part_length,
1447 : AllocationType allocation) {
1448 : DCHECK(RootsTable::IsImmortalImmovable(map_root_index));
1449 : DCHECK_LE(Context::kTodoHeaderSize, size);
1450 : DCHECK(IsAligned(size, kTaggedSize));
1451 : DCHECK_LE(Context::MIN_CONTEXT_SLOTS, variadic_part_length);
1452 : DCHECK_LE(Context::SizeFor(variadic_part_length), size);
1453 :
1454 1275432 : Map map = Map::cast(isolate()->root(map_root_index));
1455 1275432 : HeapObject result = AllocateRawWithImmortalMap(size, allocation, map);
1456 : Handle<Context> context(Context::cast(result), isolate());
1457 : context->set_length(variadic_part_length);
1458 : DCHECK_EQ(context->SizeFromMap(map), size);
1459 1275432 : if (size > Context::kTodoHeaderSize) {
1460 : ObjectSlot start = context->RawField(Context::kTodoHeaderSize);
1461 : ObjectSlot end = context->RawField(size);
1462 : size_t slot_count = end - start;
1463 : MemsetTagged(start, *undefined_value(), slot_count);
1464 : }
1465 1275432 : return context;
1466 : }
1467 :
1468 167 : Handle<NativeContext> Factory::NewNativeContext() {
1469 : Handle<NativeContext> context = Handle<NativeContext>::cast(
1470 : NewContext(RootIndex::kNativeContextMap, NativeContext::kSize,
1471 167 : NativeContext::NATIVE_CONTEXT_SLOTS, AllocationType::kOld));
1472 167 : context->set_scope_info(ReadOnlyRoots(isolate()).empty_scope_info());
1473 167 : context->set_previous(Context::unchecked_cast(Smi::zero()));
1474 334 : context->set_extension(*the_hole_value());
1475 167 : context->set_native_context(*context);
1476 167 : context->set_errors_thrown(Smi::zero());
1477 167 : context->set_math_random_index(Smi::zero());
1478 167 : context->set_serialized_objects(*empty_fixed_array());
1479 : context->set_microtask_queue(nullptr);
1480 167 : return context;
1481 : }
1482 :
1483 16235 : Handle<Context> Factory::NewScriptContext(Handle<NativeContext> outer,
1484 : Handle<ScopeInfo> scope_info) {
1485 : DCHECK_EQ(scope_info->scope_type(), SCRIPT_SCOPE);
1486 16235 : int variadic_part_length = scope_info->ContextLength();
1487 : Handle<Context> context = NewContext(
1488 : RootIndex::kScriptContextMap, Context::SizeFor(variadic_part_length),
1489 16235 : variadic_part_length, AllocationType::kOld);
1490 16235 : context->set_scope_info(*scope_info);
1491 32470 : context->set_previous(*outer);
1492 32470 : context->set_extension(*the_hole_value());
1493 16235 : context->set_native_context(*outer);
1494 : DCHECK(context->IsScriptContext());
1495 16235 : return context;
1496 : }
1497 :
1498 111 : Handle<ScriptContextTable> Factory::NewScriptContextTable() {
1499 : Handle<ScriptContextTable> context_table =
1500 : NewFixedArrayWithMap<ScriptContextTable>(
1501 : RootIndex::kScriptContextTableMap, ScriptContextTable::kMinLength);
1502 : context_table->set_used(0);
1503 111 : return context_table;
1504 : }
1505 :
1506 1604 : Handle<Context> Factory::NewModuleContext(Handle<Module> module,
1507 : Handle<NativeContext> outer,
1508 : Handle<ScopeInfo> scope_info) {
1509 : DCHECK_EQ(scope_info->scope_type(), MODULE_SCOPE);
1510 1604 : int variadic_part_length = scope_info->ContextLength();
1511 : Handle<Context> context = NewContext(
1512 : RootIndex::kModuleContextMap, Context::SizeFor(variadic_part_length),
1513 1604 : variadic_part_length, AllocationType::kOld);
1514 1604 : context->set_scope_info(*scope_info);
1515 3208 : context->set_previous(*outer);
1516 3208 : context->set_extension(*module);
1517 1604 : context->set_native_context(*outer);
1518 : DCHECK(context->IsModuleContext());
1519 1604 : return context;
1520 : }
1521 :
1522 23 : Handle<Context> Factory::NewFunctionContext(Handle<Context> outer,
1523 : Handle<ScopeInfo> scope_info) {
1524 : RootIndex mapRootIndex;
1525 23 : switch (scope_info->scope_type()) {
1526 : case EVAL_SCOPE:
1527 : mapRootIndex = RootIndex::kEvalContextMap;
1528 : break;
1529 : case FUNCTION_SCOPE:
1530 : mapRootIndex = RootIndex::kFunctionContextMap;
1531 14 : break;
1532 : default:
1533 0 : UNREACHABLE();
1534 : }
1535 23 : int variadic_part_length = scope_info->ContextLength();
1536 : Handle<Context> context =
1537 : NewContext(mapRootIndex, Context::SizeFor(variadic_part_length),
1538 23 : variadic_part_length, AllocationType::kYoung);
1539 23 : context->set_scope_info(*scope_info);
1540 23 : context->set_previous(*outer);
1541 46 : context->set_extension(*the_hole_value());
1542 23 : context->set_native_context(outer->native_context());
1543 23 : return context;
1544 : }
1545 :
1546 812878 : Handle<Context> Factory::NewCatchContext(Handle<Context> previous,
1547 : Handle<ScopeInfo> scope_info,
1548 : Handle<Object> thrown_object) {
1549 : DCHECK_EQ(scope_info->scope_type(), CATCH_SCOPE);
1550 : STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
1551 : // TODO(ishell): Take the details from CatchContext class.
1552 : int variadic_part_length = Context::MIN_CONTEXT_SLOTS + 1;
1553 : Handle<Context> context = NewContext(
1554 : RootIndex::kCatchContextMap, Context::SizeFor(variadic_part_length),
1555 812878 : variadic_part_length, AllocationType::kYoung);
1556 812878 : context->set_scope_info(*scope_info);
1557 812878 : context->set_previous(*previous);
1558 1625756 : context->set_extension(*the_hole_value());
1559 812878 : context->set_native_context(previous->native_context());
1560 : context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
1561 812878 : return context;
1562 : }
1563 :
1564 12527 : Handle<Context> Factory::NewDebugEvaluateContext(Handle<Context> previous,
1565 : Handle<ScopeInfo> scope_info,
1566 : Handle<JSReceiver> extension,
1567 : Handle<Context> wrapped,
1568 : Handle<StringSet> whitelist) {
1569 : STATIC_ASSERT(Context::WHITE_LIST_INDEX == Context::MIN_CONTEXT_SLOTS + 1);
1570 : DCHECK(scope_info->IsDebugEvaluateScope());
1571 : Handle<HeapObject> ext = extension.is_null()
1572 : ? Handle<HeapObject>::cast(the_hole_value())
1573 12527 : : Handle<HeapObject>::cast(extension);
1574 : // TODO(ishell): Take the details from DebugEvaluateContextContext class.
1575 : int variadic_part_length = Context::MIN_CONTEXT_SLOTS + 2;
1576 : Handle<Context> c = NewContext(RootIndex::kDebugEvaluateContextMap,
1577 : Context::SizeFor(variadic_part_length),
1578 12527 : variadic_part_length, AllocationType::kYoung);
1579 12527 : c->set_scope_info(*scope_info);
1580 12527 : c->set_previous(*previous);
1581 12527 : c->set_native_context(previous->native_context());
1582 12527 : c->set_extension(*ext);
1583 12527 : if (!wrapped.is_null()) c->set(Context::WRAPPED_CONTEXT_INDEX, *wrapped);
1584 12527 : if (!whitelist.is_null()) c->set(Context::WHITE_LIST_INDEX, *whitelist);
1585 12527 : return c;
1586 : }
1587 :
1588 249062 : Handle<Context> Factory::NewWithContext(Handle<Context> previous,
1589 : Handle<ScopeInfo> scope_info,
1590 : Handle<JSReceiver> extension) {
1591 : DCHECK_EQ(scope_info->scope_type(), WITH_SCOPE);
1592 : // TODO(ishell): Take the details from WithContext class.
1593 : int variadic_part_length = Context::MIN_CONTEXT_SLOTS;
1594 : Handle<Context> context = NewContext(
1595 : RootIndex::kWithContextMap, Context::SizeFor(variadic_part_length),
1596 249062 : variadic_part_length, AllocationType::kYoung);
1597 249062 : context->set_scope_info(*scope_info);
1598 249062 : context->set_previous(*previous);
1599 498124 : context->set_extension(*extension);
1600 249062 : context->set_native_context(previous->native_context());
1601 249062 : return context;
1602 : }
1603 :
1604 181310 : Handle<Context> Factory::NewBlockContext(Handle<Context> previous,
1605 : Handle<ScopeInfo> scope_info) {
1606 : DCHECK_IMPLIES(scope_info->scope_type() != BLOCK_SCOPE,
1607 : scope_info->scope_type() == CLASS_SCOPE);
1608 181310 : int variadic_part_length = scope_info->ContextLength();
1609 : Handle<Context> context = NewContext(
1610 : RootIndex::kBlockContextMap, Context::SizeFor(variadic_part_length),
1611 181317 : variadic_part_length, AllocationType::kYoung);
1612 181314 : context->set_scope_info(*scope_info);
1613 181315 : context->set_previous(*previous);
1614 362632 : context->set_extension(*the_hole_value());
1615 181315 : context->set_native_context(previous->native_context());
1616 181313 : return context;
1617 : }
1618 :
1619 1622 : Handle<Context> Factory::NewBuiltinContext(Handle<NativeContext> native_context,
1620 : int variadic_part_length) {
1621 : DCHECK_LE(Context::MIN_CONTEXT_SLOTS, variadic_part_length);
1622 : Handle<Context> context = NewContext(
1623 : RootIndex::kFunctionContextMap, Context::SizeFor(variadic_part_length),
1624 1622 : variadic_part_length, AllocationType::kYoung);
1625 1622 : context->set_scope_info(ReadOnlyRoots(isolate()).empty_scope_info());
1626 3244 : context->set_previous(*native_context);
1627 3244 : context->set_extension(*the_hole_value());
1628 1622 : context->set_native_context(*native_context);
1629 1622 : return context;
1630 : }
1631 :
1632 11244787 : Handle<Struct> Factory::NewStruct(InstanceType type,
1633 : AllocationType allocation) {
1634 : Map map;
1635 11244787 : switch (type) {
1636 : #define MAKE_CASE(TYPE, Name, name) \
1637 : case TYPE: \
1638 : map = *name##_map(); \
1639 : break;
1640 11244787 : STRUCT_LIST(MAKE_CASE)
1641 : #undef MAKE_CASE
1642 : default:
1643 0 : UNREACHABLE();
1644 : }
1645 : int size = map->instance_size();
1646 11244787 : HeapObject result = AllocateRawWithImmortalMap(size, allocation, map);
1647 : Handle<Struct> str(Struct::cast(result), isolate());
1648 11244790 : str->InitializeBody(size);
1649 11244790 : return str;
1650 : }
1651 :
1652 53 : Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
1653 : int aliased_context_slot) {
1654 : Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
1655 53 : NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE, AllocationType::kYoung));
1656 : entry->set_aliased_context_slot(aliased_context_slot);
1657 53 : return entry;
1658 : }
1659 :
1660 94041 : Handle<AccessorInfo> Factory::NewAccessorInfo() {
1661 : Handle<AccessorInfo> info = Handle<AccessorInfo>::cast(
1662 94041 : NewStruct(ACCESSOR_INFO_TYPE, AllocationType::kOld));
1663 188082 : info->set_name(*empty_string());
1664 : info->set_flags(0); // Must clear the flags, it was initialized as undefined.
1665 94041 : info->set_is_sloppy(true);
1666 94041 : info->set_initial_property_attributes(NONE);
1667 94041 : return info;
1668 : }
1669 :
1670 1783451 : Handle<Script> Factory::NewScript(Handle<String> source,
1671 : AllocationType allocation) {
1672 1783451 : return NewScriptWithId(source, isolate()->heap()->NextScriptId(), allocation);
1673 : }
1674 :
1675 2902497 : Handle<Script> Factory::NewScriptWithId(Handle<String> source, int script_id,
1676 : AllocationType allocation) {
1677 : DCHECK(allocation == AllocationType::kOld ||
1678 : allocation == AllocationType::kReadOnly);
1679 : // Create and initialize script object.
1680 : Heap* heap = isolate()->heap();
1681 : ReadOnlyRoots roots(heap);
1682 : Handle<Script> script =
1683 2902497 : Handle<Script>::cast(NewStruct(SCRIPT_TYPE, allocation));
1684 5805004 : script->set_source(*source);
1685 5804998 : script->set_name(roots.undefined_value());
1686 : script->set_id(script_id);
1687 : script->set_line_offset(0);
1688 : script->set_column_offset(0);
1689 5804998 : script->set_context_data(roots.undefined_value());
1690 : script->set_type(Script::TYPE_NORMAL);
1691 5804998 : script->set_line_ends(roots.undefined_value());
1692 5804998 : script->set_eval_from_shared_or_wrapped_arguments(roots.undefined_value());
1693 : script->set_eval_from_position(0);
1694 : script->set_shared_function_infos(*empty_weak_fixed_array(),
1695 : SKIP_WRITE_BARRIER);
1696 : script->set_flags(0);
1697 2902501 : script->set_host_defined_options(*empty_fixed_array());
1698 : Handle<WeakArrayList> scripts = script_list();
1699 : scripts = WeakArrayList::AddToEnd(isolate(), scripts,
1700 2902501 : MaybeObjectHandle::Weak(script));
1701 : heap->set_script_list(*scripts);
1702 2902501 : LOG(isolate(), ScriptEvent(Logger::ScriptEventType::kCreate, script_id));
1703 5805000 : TRACE_EVENT_OBJECT_CREATED_WITH_ID(
1704 : TRACE_DISABLED_BY_DEFAULT("v8.compile"), "Script",
1705 : TRACE_ID_WITH_SCOPE(Script::kTraceScope, script_id));
1706 2902500 : return script;
1707 : }
1708 :
1709 761 : Handle<Script> Factory::CloneScript(Handle<Script> script) {
1710 : Heap* heap = isolate()->heap();
1711 : int script_id = isolate()->heap()->NextScriptId();
1712 : Handle<Script> new_script =
1713 761 : Handle<Script>::cast(NewStruct(SCRIPT_TYPE, AllocationType::kOld));
1714 761 : new_script->set_source(script->source());
1715 761 : new_script->set_name(script->name());
1716 : new_script->set_id(script_id);
1717 : new_script->set_line_offset(script->line_offset());
1718 : new_script->set_column_offset(script->column_offset());
1719 761 : new_script->set_context_data(script->context_data());
1720 : new_script->set_type(script->type());
1721 1522 : new_script->set_line_ends(ReadOnlyRoots(heap).undefined_value());
1722 1522 : new_script->set_eval_from_shared_or_wrapped_arguments(
1723 761 : script->eval_from_shared_or_wrapped_arguments());
1724 : new_script->set_shared_function_infos(*empty_weak_fixed_array(),
1725 : SKIP_WRITE_BARRIER);
1726 : new_script->set_eval_from_position(script->eval_from_position());
1727 : new_script->set_flags(script->flags());
1728 761 : new_script->set_host_defined_options(script->host_defined_options());
1729 : Handle<WeakArrayList> scripts = script_list();
1730 : scripts = WeakArrayList::AddToEnd(isolate(), scripts,
1731 761 : MaybeObjectHandle::Weak(new_script));
1732 : heap->set_script_list(*scripts);
1733 761 : LOG(isolate(), ScriptEvent(Logger::ScriptEventType::kCreate, script_id));
1734 761 : return new_script;
1735 : }
1736 :
1737 401 : Handle<CallableTask> Factory::NewCallableTask(Handle<JSReceiver> callable,
1738 : Handle<Context> context) {
1739 : DCHECK(callable->IsCallable());
1740 : Handle<CallableTask> microtask =
1741 401 : Handle<CallableTask>::cast(NewStruct(CALLABLE_TASK_TYPE));
1742 401 : microtask->set_callable(*callable);
1743 401 : microtask->set_context(*context);
1744 401 : return microtask;
1745 : }
1746 :
1747 463 : Handle<CallbackTask> Factory::NewCallbackTask(Handle<Foreign> callback,
1748 : Handle<Foreign> data) {
1749 : Handle<CallbackTask> microtask =
1750 463 : Handle<CallbackTask>::cast(NewStruct(CALLBACK_TASK_TYPE));
1751 463 : microtask->set_callback(*callback);
1752 463 : microtask->set_data(*data);
1753 463 : return microtask;
1754 : }
1755 :
1756 1607 : Handle<PromiseResolveThenableJobTask> Factory::NewPromiseResolveThenableJobTask(
1757 : Handle<JSPromise> promise_to_resolve, Handle<JSReceiver> then,
1758 : Handle<JSReceiver> thenable, Handle<Context> context) {
1759 : DCHECK(then->IsCallable());
1760 : Handle<PromiseResolveThenableJobTask> microtask =
1761 : Handle<PromiseResolveThenableJobTask>::cast(
1762 1607 : NewStruct(PROMISE_RESOLVE_THENABLE_JOB_TASK_TYPE));
1763 1607 : microtask->set_promise_to_resolve(*promise_to_resolve);
1764 1607 : microtask->set_then(*then);
1765 1607 : microtask->set_thenable(*thenable);
1766 1607 : microtask->set_context(*context);
1767 1607 : return microtask;
1768 : }
1769 :
1770 : Handle<FinalizationGroupCleanupJobTask>
1771 208 : Factory::NewFinalizationGroupCleanupJobTask(
1772 : Handle<JSFinalizationGroup> finalization_group) {
1773 : Handle<FinalizationGroupCleanupJobTask> microtask =
1774 : Handle<FinalizationGroupCleanupJobTask>::cast(
1775 208 : NewStruct(FINALIZATION_GROUP_CLEANUP_JOB_TASK_TYPE));
1776 208 : microtask->set_finalization_group(*finalization_group);
1777 208 : return microtask;
1778 : }
1779 :
1780 10599858 : Handle<Foreign> Factory::NewForeign(Address addr, AllocationType allocation) {
1781 : // Statically ensure that it is safe to allocate foreigns in paged spaces.
1782 : STATIC_ASSERT(Foreign::kSize <= kMaxRegularHeapObjectSize);
1783 : Map map = *foreign_map();
1784 : HeapObject result =
1785 10599858 : AllocateRawWithImmortalMap(map->instance_size(), allocation, map);
1786 : Handle<Foreign> foreign(Foreign::cast(result), isolate());
1787 : foreign->set_foreign_address(addr);
1788 10599857 : return foreign;
1789 : }
1790 :
1791 7139389 : Handle<ByteArray> Factory::NewByteArray(int length, AllocationType allocation) {
1792 : DCHECK_LE(0, length);
1793 7139389 : if (length > ByteArray::kMaxLength) {
1794 0 : isolate()->heap()->FatalProcessOutOfMemory("invalid array length");
1795 : }
1796 : int size = ByteArray::SizeFor(length);
1797 : HeapObject result =
1798 7139389 : AllocateRawWithImmortalMap(size, allocation, *byte_array_map());
1799 : Handle<ByteArray> array(ByteArray::cast(result), isolate());
1800 : array->set_length(length);
1801 7139415 : array->clear_padding();
1802 7139391 : return array;
1803 : }
1804 :
1805 2111494 : Handle<BytecodeArray> Factory::NewBytecodeArray(
1806 : int length, const byte* raw_bytecodes, int frame_size, int parameter_count,
1807 : Handle<FixedArray> constant_pool) {
1808 : DCHECK_LE(0, length);
1809 2111494 : if (length > BytecodeArray::kMaxLength) {
1810 0 : isolate()->heap()->FatalProcessOutOfMemory("invalid array length");
1811 : }
1812 : // Bytecode array is AllocationType::kOld, so constant pool array should be
1813 : // too.
1814 : DCHECK(!Heap::InYoungGeneration(*constant_pool));
1815 :
1816 : int size = BytecodeArray::SizeFor(length);
1817 : HeapObject result = AllocateRawWithImmortalMap(size, AllocationType::kOld,
1818 2111494 : *bytecode_array_map());
1819 : Handle<BytecodeArray> instance(BytecodeArray::cast(result), isolate());
1820 : instance->set_length(length);
1821 : instance->set_frame_size(frame_size);
1822 : instance->set_parameter_count(parameter_count);
1823 : instance->set_incoming_new_target_or_generator_register(
1824 : interpreter::Register::invalid_value());
1825 : instance->set_osr_loop_nesting_level(0);
1826 : instance->set_bytecode_age(BytecodeArray::kNoAgeBytecodeAge);
1827 2111510 : instance->set_constant_pool(*constant_pool);
1828 2111495 : instance->set_handler_table(*empty_byte_array());
1829 4223004 : instance->set_source_position_table(*undefined_value());
1830 2111514 : CopyBytes(reinterpret_cast<byte*>(instance->GetFirstBytecodeAddress()),
1831 : raw_bytecodes, length);
1832 2111498 : instance->clear_padding();
1833 :
1834 2111507 : return instance;
1835 : }
1836 :
1837 17764 : Handle<FixedTypedArrayBase> Factory::NewFixedTypedArrayWithExternalPointer(
1838 : ExternalArrayType array_type, void* external_pointer,
1839 : AllocationType allocation) {
1840 : int size = FixedTypedArrayBase::kHeaderSize;
1841 : HeapObject result = AllocateRawWithImmortalMap(
1842 : size, allocation,
1843 17764 : ReadOnlyRoots(isolate()).MapForFixedTypedArray(array_type));
1844 : Handle<FixedTypedArrayBase> elements(FixedTypedArrayBase::cast(result),
1845 : isolate());
1846 : elements->set_base_pointer(Smi::kZero, SKIP_WRITE_BARRIER);
1847 : elements->set_external_pointer(external_pointer);
1848 : elements->set_length(0);
1849 17764 : return elements;
1850 : }
1851 :
1852 58 : Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
1853 : size_t length, size_t byte_length, ExternalArrayType array_type,
1854 : bool initialize, AllocationType allocation) {
1855 : // TODO(7881): Smi length check
1856 : DCHECK(0 <= length && length <= Smi::kMaxValue);
1857 58 : CHECK(byte_length <= kMaxInt - FixedTypedArrayBase::kDataOffset);
1858 : size_t size =
1859 58 : OBJECT_POINTER_ALIGN(byte_length + FixedTypedArrayBase::kDataOffset);
1860 58 : Map map = ReadOnlyRoots(isolate()).MapForFixedTypedArray(array_type);
1861 : AllocationAlignment alignment =
1862 58 : array_type == kExternalFloat64Array ? kDoubleAligned : kWordAligned;
1863 : HeapObject object = AllocateRawWithImmortalMap(static_cast<int>(size),
1864 58 : allocation, map, alignment);
1865 :
1866 : Handle<FixedTypedArrayBase> elements(FixedTypedArrayBase::cast(object),
1867 : isolate());
1868 : elements->set_base_pointer(*elements, SKIP_WRITE_BARRIER);
1869 : elements->set_external_pointer(
1870 : FixedTypedArrayBase::ExternalPointerPtrForOnHeapArray());
1871 58 : elements->set_length(static_cast<int>(length));
1872 174 : if (initialize) memset(elements->DataPtr(), 0, elements->DataSize());
1873 58 : return elements;
1874 : }
1875 :
1876 829167 : Handle<Cell> Factory::NewCell(Handle<Object> value) {
1877 : AllowDeferredHandleDereference convert_to_cell;
1878 : STATIC_ASSERT(Cell::kSize <= kMaxRegularHeapObjectSize);
1879 : HeapObject result = AllocateRawWithImmortalMap(
1880 829167 : Cell::kSize, AllocationType::kOld, *cell_map());
1881 : Handle<Cell> cell(Cell::cast(result), isolate());
1882 829169 : cell->set_value(*value);
1883 829169 : return cell;
1884 : }
1885 :
1886 4123792 : Handle<FeedbackCell> Factory::NewNoClosuresCell(Handle<HeapObject> value) {
1887 : AllowDeferredHandleDereference convert_to_cell;
1888 : HeapObject result = AllocateRawWithImmortalMap(
1889 4123792 : FeedbackCell::kSize, AllocationType::kOld, *no_closures_cell_map());
1890 : Handle<FeedbackCell> cell(FeedbackCell::cast(result), isolate());
1891 4123794 : cell->set_value(*value);
1892 : cell->set_interrupt_budget(FeedbackCell::GetInitialInterruptBudget());
1893 : cell->clear_padding();
1894 4123793 : return cell;
1895 : }
1896 :
1897 1526109 : Handle<FeedbackCell> Factory::NewOneClosureCell(Handle<HeapObject> value) {
1898 : AllowDeferredHandleDereference convert_to_cell;
1899 : HeapObject result = AllocateRawWithImmortalMap(
1900 1526109 : FeedbackCell::kSize, AllocationType::kOld, *one_closure_cell_map());
1901 : Handle<FeedbackCell> cell(FeedbackCell::cast(result), isolate());
1902 1526112 : cell->set_value(*value);
1903 : cell->set_interrupt_budget(FeedbackCell::GetInitialInterruptBudget());
1904 : cell->clear_padding();
1905 1526104 : return cell;
1906 : }
1907 :
1908 56 : Handle<FeedbackCell> Factory::NewManyClosuresCell(Handle<HeapObject> value) {
1909 : AllowDeferredHandleDereference convert_to_cell;
1910 : HeapObject result = AllocateRawWithImmortalMap(
1911 56 : FeedbackCell::kSize, AllocationType::kOld, *many_closures_cell_map());
1912 : Handle<FeedbackCell> cell(FeedbackCell::cast(result), isolate());
1913 56 : cell->set_value(*value);
1914 : cell->set_interrupt_budget(FeedbackCell::GetInitialInterruptBudget());
1915 : cell->clear_padding();
1916 56 : return cell;
1917 : }
1918 :
1919 8346505 : Handle<PropertyCell> Factory::NewPropertyCell(Handle<Name> name,
1920 : AllocationType allocation) {
1921 : DCHECK(name->IsUniqueName());
1922 : STATIC_ASSERT(PropertyCell::kSize <= kMaxRegularHeapObjectSize);
1923 : HeapObject result = AllocateRawWithImmortalMap(
1924 8346505 : PropertyCell::kSize, allocation, *global_property_cell_map());
1925 : Handle<PropertyCell> cell(PropertyCell::cast(result), isolate());
1926 : cell->set_dependent_code(DependentCode::cast(*empty_weak_fixed_array()),
1927 : SKIP_WRITE_BARRIER);
1928 16693005 : cell->set_property_details(PropertyDetails(Smi::zero()));
1929 8346500 : cell->set_name(*name);
1930 16692986 : cell->set_value(*the_hole_value());
1931 8346493 : return cell;
1932 : }
1933 :
1934 19181651 : Handle<DescriptorArray> Factory::NewDescriptorArray(int number_of_descriptors,
1935 : int slack,
1936 : AllocationType allocation) {
1937 : DCHECK(Heap::IsRegularObjectAllocation(allocation));
1938 19181651 : int number_of_all_descriptors = number_of_descriptors + slack;
1939 : // Zero-length case must be handled outside.
1940 : DCHECK_LT(0, number_of_all_descriptors);
1941 : int size = DescriptorArray::SizeFor(number_of_all_descriptors);
1942 : HeapObject obj =
1943 19181651 : isolate()->heap()->AllocateRawWithRetryOrFail(size, allocation);
1944 : obj->set_map_after_allocation(*descriptor_array_map(), SKIP_WRITE_BARRIER);
1945 19181659 : DescriptorArray array = DescriptorArray::cast(obj);
1946 38363294 : array->Initialize(*empty_enum_cache(), *undefined_value(),
1947 19181659 : number_of_descriptors, slack);
1948 19181632 : return Handle<DescriptorArray>(array, isolate());
1949 : }
1950 :
1951 484161 : Handle<TransitionArray> Factory::NewTransitionArray(int number_of_transitions,
1952 : int slack) {
1953 484161 : int capacity = TransitionArray::LengthFor(number_of_transitions + slack);
1954 : Handle<TransitionArray> array = NewWeakFixedArrayWithMap<TransitionArray>(
1955 484161 : RootIndex::kTransitionArrayMap, capacity, AllocationType::kOld);
1956 : // Transition arrays are AllocationType::kOld. When black allocation is on we
1957 : // have to add the transition array to the list of
1958 : // encountered_transition_arrays.
1959 : Heap* heap = isolate()->heap();
1960 484161 : if (heap->incremental_marking()->black_allocation()) {
1961 : heap->mark_compact_collector()->AddTransitionArray(*array);
1962 : }
1963 968327 : array->WeakFixedArray::Set(TransitionArray::kPrototypeTransitionsIndex,
1964 484161 : MaybeObject::FromObject(Smi::kZero));
1965 968331 : array->WeakFixedArray::Set(
1966 : TransitionArray::kTransitionLengthIndex,
1967 484166 : MaybeObject::FromObject(Smi::FromInt(number_of_transitions)));
1968 484165 : return array;
1969 : }
1970 :
1971 112070 : Handle<AllocationSite> Factory::NewAllocationSite(bool with_weak_next) {
1972 : Handle<Map> map = with_weak_next ? allocation_site_map()
1973 224140 : : allocation_site_without_weaknext_map();
1974 : Handle<AllocationSite> site(
1975 224142 : AllocationSite::cast(New(map, AllocationType::kOld)), isolate());
1976 112072 : site->Initialize();
1977 :
1978 112073 : if (with_weak_next) {
1979 : // Link the site
1980 96349 : site->set_weak_next(isolate()->heap()->allocation_sites_list());
1981 : isolate()->heap()->set_allocation_sites_list(*site);
1982 : }
1983 112074 : return site;
1984 : }
1985 :
1986 30317834 : Handle<Map> Factory::NewMap(InstanceType type, int instance_size,
1987 : ElementsKind elements_kind,
1988 : int inobject_properties) {
1989 : STATIC_ASSERT(LAST_JS_OBJECT_TYPE == LAST_TYPE);
1990 : DCHECK_IMPLIES(InstanceTypeChecker::IsJSObject(type) &&
1991 : !Map::CanHaveFastTransitionableElementsKind(type),
1992 : IsDictionaryElementsKind(elements_kind) ||
1993 : IsTerminalElementsKind(elements_kind));
1994 : HeapObject result = isolate()->heap()->AllocateRawWithRetryOrFail(
1995 30317834 : Map::kSize, AllocationType::kMap);
1996 : result->set_map_after_allocation(*meta_map(), SKIP_WRITE_BARRIER);
1997 : return handle(InitializeMap(Map::cast(result), type, instance_size,
1998 : elements_kind, inobject_properties),
1999 60635714 : isolate());
2000 : }
2001 :
2002 30927430 : Map Factory::InitializeMap(Map map, InstanceType type, int instance_size,
2003 : ElementsKind elements_kind,
2004 : int inobject_properties) {
2005 : map->set_instance_type(type);
2006 : map->set_prototype(*null_value(), SKIP_WRITE_BARRIER);
2007 : map->set_constructor_or_backpointer(*null_value(), SKIP_WRITE_BARRIER);
2008 30927430 : map->set_instance_size(instance_size);
2009 30927411 : if (map->IsJSObjectMap()) {
2010 : DCHECK(!ReadOnlyHeap::Contains(map));
2011 30921473 : map->SetInObjectPropertiesStartInWords(instance_size / kTaggedSize -
2012 30921473 : inobject_properties);
2013 : DCHECK_EQ(map->GetInObjectProperties(), inobject_properties);
2014 30921479 : map->set_prototype_validity_cell(*invalid_prototype_validity_cell());
2015 : } else {
2016 : DCHECK_EQ(inobject_properties, 0);
2017 5938 : map->set_inobject_properties_start_or_constructor_function_index(0);
2018 5938 : map->set_prototype_validity_cell(Smi::FromInt(Map::kPrototypeChainValid));
2019 : }
2020 : map->set_dependent_code(DependentCode::cast(*empty_weak_fixed_array()),
2021 : SKIP_WRITE_BARRIER);
2022 30927375 : map->set_raw_transitions(MaybeObject::FromSmi(Smi::zero()));
2023 30927388 : map->SetInObjectUnusedPropertyFields(inobject_properties);
2024 30927396 : map->SetInstanceDescriptors(isolate(), *empty_descriptor_array(), 0);
2025 : if (FLAG_unbox_double_fields) {
2026 30927417 : map->set_layout_descriptor(LayoutDescriptor::FastPointerLayout());
2027 : }
2028 : // Must be called only after |instance_type|, |instance_size| and
2029 : // |layout_descriptor| are set.
2030 30927417 : map->set_visitor_id(Map::GetVisitorId(map));
2031 : map->set_bit_field(0);
2032 : map->set_bit_field2(Map::IsExtensibleBit::kMask);
2033 : DCHECK(!map->is_in_retained_map_list());
2034 : int bit_field3 = Map::EnumLengthBits::encode(kInvalidEnumCacheSentinel) |
2035 : Map::OwnsDescriptorsBit::encode(true) |
2036 : Map::ConstructionCounterBits::encode(Map::kNoSlackTracking);
2037 : map->set_bit_field3(bit_field3);
2038 : map->clear_padding();
2039 30927391 : map->set_elements_kind(elements_kind);
2040 30927389 : map->set_new_target_is_base(true);
2041 30927403 : isolate()->counters()->maps_created()->Increment();
2042 30927407 : if (FLAG_trace_maps) LOG(isolate(), MapCreate(map));
2043 30927407 : return map;
2044 : }
2045 :
2046 511792 : Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> source) {
2047 511792 : return CopyJSObjectWithAllocationSite(source, Handle<AllocationSite>());
2048 : }
2049 :
2050 2138613 : Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
2051 : Handle<JSObject> source, Handle<AllocationSite> site) {
2052 : Handle<Map> map(source->map(), isolate());
2053 :
2054 : // We can only clone regexps, normal objects, api objects, errors or arrays.
2055 : // Copying anything else will break invariants.
2056 2138617 : CHECK(map->instance_type() == JS_REGEXP_TYPE ||
2057 : map->instance_type() == JS_OBJECT_TYPE ||
2058 : map->instance_type() == JS_ERROR_TYPE ||
2059 : map->instance_type() == JS_ARRAY_TYPE ||
2060 : map->instance_type() == JS_API_OBJECT_TYPE ||
2061 : map->instance_type() == WASM_GLOBAL_TYPE ||
2062 : map->instance_type() == WASM_INSTANCE_TYPE ||
2063 : map->instance_type() == WASM_MEMORY_TYPE ||
2064 : map->instance_type() == WASM_MODULE_TYPE ||
2065 : map->instance_type() == WASM_TABLE_TYPE ||
2066 : map->instance_type() == JS_SPECIAL_API_OBJECT_TYPE);
2067 : DCHECK(site.is_null() || AllocationSite::CanTrack(map->instance_type()));
2068 :
2069 : int object_size = map->instance_size();
2070 : int adjusted_object_size =
2071 2138617 : site.is_null() ? object_size : object_size + AllocationMemento::kSize;
2072 : HeapObject raw_clone = isolate()->heap()->AllocateRawWithRetryOrFail(
2073 2138617 : adjusted_object_size, AllocationType::kYoung);
2074 :
2075 : DCHECK(Heap::InYoungGeneration(raw_clone));
2076 : // Since we know the clone is allocated in new space, we can copy
2077 : // the contents without worrying about updating the write barrier.
2078 : Heap::CopyBlock(raw_clone->address(), source->address(), object_size);
2079 : Handle<JSObject> clone(JSObject::cast(raw_clone), isolate());
2080 :
2081 2138614 : if (!site.is_null()) {
2082 : AllocationMemento alloc_memento = AllocationMemento::unchecked_cast(
2083 1502938 : Object(raw_clone->ptr() + object_size));
2084 1502938 : InitializeAllocationMemento(alloc_memento, *site);
2085 : }
2086 :
2087 : SLOW_DCHECK(clone->GetElementsKind() == source->GetElementsKind());
2088 : FixedArrayBase elements = source->elements();
2089 : // Update elements if necessary.
2090 2138614 : if (elements->length() > 0) {
2091 : FixedArrayBase elem;
2092 530315 : if (elements->map() == *fixed_cow_array_map()) {
2093 37635 : elem = elements;
2094 492680 : } else if (source->HasDoubleElements()) {
2095 9940 : elem = *CopyFixedDoubleArray(
2096 4970 : handle(FixedDoubleArray::cast(elements), isolate()));
2097 : } else {
2098 975416 : elem = *CopyFixedArray(handle(FixedArray::cast(elements), isolate()));
2099 : }
2100 530313 : clone->set_elements(elem);
2101 : }
2102 :
2103 : // Update properties if necessary.
2104 2138613 : if (source->HasFastProperties()) {
2105 2138320 : PropertyArray properties = source->property_array();
2106 2138321 : if (properties->length() > 0) {
2107 : // TODO(gsathya): Do not copy hash code.
2108 : Handle<PropertyArray> prop = CopyArrayWithMap(
2109 218874 : handle(properties, isolate()), handle(properties->map(), isolate()));
2110 437748 : clone->set_raw_properties_or_hash(*prop);
2111 : }
2112 : } else {
2113 : Handle<FixedArray> properties(
2114 584 : FixedArray::cast(source->property_dictionary()), isolate());
2115 292 : Handle<FixedArray> prop = CopyFixedArray(properties);
2116 584 : clone->set_raw_properties_or_hash(*prop);
2117 : }
2118 2138613 : return clone;
2119 : }
2120 :
2121 : namespace {
2122 : template <typename T>
2123 : void initialize_length(Handle<T> array, int length) {
2124 : array->set_length(length);
2125 : }
2126 :
2127 : template <>
2128 : void initialize_length<PropertyArray>(Handle<PropertyArray> array, int length) {
2129 : array->initialize_length(length);
2130 : }
2131 :
2132 : } // namespace
2133 :
2134 : template <typename T>
2135 988440 : Handle<T> Factory::CopyArrayWithMap(Handle<T> src, Handle<Map> map) {
2136 : int len = src->length();
2137 988440 : HeapObject obj = AllocateRawFixedArray(len, AllocationType::kYoung);
2138 : obj->set_map_after_allocation(*map, SKIP_WRITE_BARRIER);
2139 :
2140 : Handle<T> result(T::cast(obj), isolate());
2141 : DisallowHeapAllocation no_gc;
2142 : WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
2143 :
2144 988442 : if (mode == SKIP_WRITE_BARRIER) {
2145 : // Eliminate the write barrier if possible.
2146 1833716 : Heap::CopyBlock(obj->address() + kTaggedSize, src->address() + kTaggedSize,
2147 : T::SizeFor(len) - kTaggedSize);
2148 : } else {
2149 : // Slow case: Just copy the content one-by-one.
2150 : initialize_length(result, len);
2151 4029974 : for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2152 : }
2153 988441 : return result;
2154 : }
2155 :
2156 : template <typename T>
2157 2650289 : Handle<T> Factory::CopyArrayAndGrow(Handle<T> src, int grow_by,
2158 : AllocationType allocation) {
2159 : DCHECK_LT(0, grow_by);
2160 : DCHECK_LE(grow_by, kMaxInt - src->length());
2161 : int old_len = src->length();
2162 2650289 : int new_len = old_len + grow_by;
2163 2650289 : HeapObject obj = AllocateRawFixedArray(new_len, allocation);
2164 : obj->set_map_after_allocation(src->map(), SKIP_WRITE_BARRIER);
2165 :
2166 : Handle<T> result(T::cast(obj), isolate());
2167 : initialize_length(result, new_len);
2168 :
2169 : // Copy the content.
2170 : DisallowHeapAllocation no_gc;
2171 : WriteBarrierMode mode = obj->GetWriteBarrierMode(no_gc);
2172 301001571 : for (int i = 0; i < old_len; i++) result->set(i, src->get(i), mode);
2173 2650289 : MemsetTagged(result->data_start() + old_len, *undefined_value(), grow_by);
2174 2650289 : return result;
2175 : }
2176 :
2177 21006 : Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
2178 : Handle<Map> map) {
2179 21006 : return CopyArrayWithMap(array, map);
2180 : }
2181 :
2182 390372 : Handle<FixedArray> Factory::CopyFixedArrayAndGrow(Handle<FixedArray> array,
2183 : int grow_by,
2184 : AllocationType allocation) {
2185 390372 : return CopyArrayAndGrow(array, grow_by, allocation);
2186 : }
2187 :
2188 552897 : Handle<WeakFixedArray> Factory::CopyWeakFixedArrayAndGrow(
2189 : Handle<WeakFixedArray> src, int grow_by, AllocationType allocation) {
2190 : DCHECK(
2191 : !src->IsTransitionArray()); // Compacted by GC, this code doesn't work.
2192 : int old_len = src->length();
2193 552897 : int new_len = old_len + grow_by;
2194 : DCHECK_GE(new_len, old_len);
2195 552897 : HeapObject obj = AllocateRawFixedArray(new_len, allocation);
2196 : DCHECK_EQ(old_len, src->length());
2197 : obj->set_map_after_allocation(src->map(), SKIP_WRITE_BARRIER);
2198 :
2199 552897 : WeakFixedArray result = WeakFixedArray::cast(obj);
2200 : result->set_length(new_len);
2201 :
2202 : // Copy the content.
2203 : DisallowHeapAllocation no_gc;
2204 : WriteBarrierMode mode = obj->GetWriteBarrierMode(no_gc);
2205 5410569 : for (int i = 0; i < old_len; i++) result->Set(i, src->Get(i), mode);
2206 552897 : MemsetTagged(ObjectSlot(result->RawFieldOfElementAt(old_len)),
2207 : ReadOnlyRoots(isolate()).undefined_value(), grow_by);
2208 552897 : return Handle<WeakFixedArray>(result, isolate());
2209 : }
2210 :
2211 1539315 : Handle<WeakArrayList> Factory::CopyWeakArrayListAndGrow(
2212 : Handle<WeakArrayList> src, int grow_by, AllocationType allocation) {
2213 : int old_capacity = src->capacity();
2214 1539315 : int new_capacity = old_capacity + grow_by;
2215 : DCHECK_GE(new_capacity, old_capacity);
2216 1539315 : HeapObject obj = AllocateRawWeakArrayList(new_capacity, allocation);
2217 : obj->set_map_after_allocation(src->map(), SKIP_WRITE_BARRIER);
2218 :
2219 1539314 : WeakArrayList result = WeakArrayList::cast(obj);
2220 : result->set_length(src->length());
2221 : result->set_capacity(new_capacity);
2222 :
2223 : // Copy the content.
2224 : DisallowHeapAllocation no_gc;
2225 : WriteBarrierMode mode = obj->GetWriteBarrierMode(no_gc);
2226 28606561 : for (int i = 0; i < old_capacity; i++) result->Set(i, src->Get(i), mode);
2227 1539315 : MemsetTagged(ObjectSlot(result->data_start() + old_capacity),
2228 : ReadOnlyRoots(isolate()).undefined_value(), grow_by);
2229 1539311 : return Handle<WeakArrayList>(result, isolate());
2230 : }
2231 :
2232 2259917 : Handle<PropertyArray> Factory::CopyPropertyArrayAndGrow(
2233 : Handle<PropertyArray> array, int grow_by, AllocationType allocation) {
2234 2259917 : return CopyArrayAndGrow(array, grow_by, allocation);
2235 : }
2236 :
2237 1891 : Handle<FixedArray> Factory::CopyFixedArrayUpTo(Handle<FixedArray> array,
2238 : int new_len,
2239 : AllocationType allocation) {
2240 : DCHECK_LE(0, new_len);
2241 : DCHECK_LE(new_len, array->length());
2242 1891 : if (new_len == 0) return empty_fixed_array();
2243 :
2244 1886 : HeapObject obj = AllocateRawFixedArray(new_len, allocation);
2245 : obj->set_map_after_allocation(*fixed_array_map(), SKIP_WRITE_BARRIER);
2246 : Handle<FixedArray> result(FixedArray::cast(obj), isolate());
2247 : result->set_length(new_len);
2248 :
2249 : // Copy the content.
2250 : DisallowHeapAllocation no_gc;
2251 : WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
2252 12338 : for (int i = 0; i < new_len; i++) result->set(i, array->get(i), mode);
2253 1886 : return result;
2254 : }
2255 :
2256 1056198 : Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
2257 1056198 : if (array->length() == 0) return array;
2258 748560 : return CopyArrayWithMap(array, handle(array->map(), isolate()));
2259 : }
2260 :
2261 1609 : Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
2262 : Handle<FixedArray> array) {
2263 : DCHECK(Heap::InYoungGeneration(*array));
2264 : Handle<FixedArray> result =
2265 1609 : CopyFixedArrayUpTo(array, array->length(), AllocationType::kOld);
2266 :
2267 : // TODO(mvstanton): The map is set twice because of protection against calling
2268 : // set() on a COW FixedArray. Issue v8:3221 created to track this, and
2269 : // we might then be able to remove this whole method.
2270 : result->set_map_after_allocation(*fixed_cow_array_map(), SKIP_WRITE_BARRIER);
2271 1609 : return result;
2272 : }
2273 :
2274 19002 : Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
2275 : Handle<FixedDoubleArray> array) {
2276 : int len = array->length();
2277 19002 : if (len == 0) return array;
2278 : Handle<FixedDoubleArray> result = Handle<FixedDoubleArray>::cast(
2279 19002 : NewFixedDoubleArray(len, AllocationType::kYoung));
2280 57006 : Heap::CopyBlock(
2281 : result->address() + FixedDoubleArray::kLengthOffset,
2282 : array->address() + FixedDoubleArray::kLengthOffset,
2283 : FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
2284 19002 : return result;
2285 : }
2286 :
2287 0 : Handle<FeedbackVector> Factory::CopyFeedbackVector(
2288 : Handle<FeedbackVector> array) {
2289 : int len = array->length();
2290 : HeapObject obj = AllocateRawWithImmortalMap(FeedbackVector::SizeFor(len),
2291 : AllocationType::kYoung,
2292 0 : *feedback_vector_map());
2293 : Handle<FeedbackVector> result(FeedbackVector::cast(obj), isolate());
2294 :
2295 : DisallowHeapAllocation no_gc;
2296 : WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
2297 :
2298 : // Eliminate the write barrier if possible.
2299 0 : if (mode == SKIP_WRITE_BARRIER) {
2300 0 : Heap::CopyBlock(result->address() + kTaggedSize,
2301 : result->address() + kTaggedSize,
2302 : FeedbackVector::SizeFor(len) - kTaggedSize);
2303 : } else {
2304 : // Slow case: Just copy the content one-by-one.
2305 0 : result->set_shared_function_info(array->shared_function_info());
2306 0 : result->set_optimized_code_weak_or_smi(array->optimized_code_weak_or_smi());
2307 : result->set_invocation_count(array->invocation_count());
2308 : result->set_profiler_ticks(array->profiler_ticks());
2309 : result->set_deopt_count(array->deopt_count());
2310 0 : for (int i = 0; i < len; i++) result->set(i, array->get(i), mode);
2311 : }
2312 0 : return result;
2313 : }
2314 :
2315 16208389 : Handle<Object> Factory::NewNumber(double value, AllocationType allocation) {
2316 : // Materialize as a SMI if possible.
2317 : int32_t int_value;
2318 16208389 : if (DoubleToSmiInteger(value, &int_value)) {
2319 10271988 : return handle(Smi::FromInt(int_value), isolate());
2320 : }
2321 5936401 : return NewHeapNumber(value, allocation);
2322 : }
2323 :
2324 355432 : Handle<Object> Factory::NewNumberFromInt(int32_t value,
2325 : AllocationType allocation) {
2326 355432 : if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
2327 : // Bypass NewNumber to avoid various redundant checks.
2328 : return NewHeapNumber(FastI2D(value), allocation);
2329 : }
2330 :
2331 12648393 : Handle<Object> Factory::NewNumberFromUint(uint32_t value,
2332 : AllocationType allocation) {
2333 12648393 : int32_t int32v = static_cast<int32_t>(value);
2334 12648393 : if (int32v >= 0 && Smi::IsValid(int32v)) {
2335 12643226 : return handle(Smi::FromInt(int32v), isolate());
2336 : }
2337 5167 : return NewHeapNumber(FastUI2D(value), allocation);
2338 : }
2339 :
2340 6022846 : Handle<HeapNumber> Factory::NewHeapNumber(AllocationType allocation) {
2341 : STATIC_ASSERT(HeapNumber::kSize <= kMaxRegularHeapObjectSize);
2342 6022846 : Map map = *heap_number_map();
2343 : HeapObject result = AllocateRawWithImmortalMap(HeapNumber::kSize, allocation,
2344 6022846 : map, kDoubleUnaligned);
2345 6022846 : return handle(HeapNumber::cast(result), isolate());
2346 : }
2347 :
2348 11809 : Handle<MutableHeapNumber> Factory::NewMutableHeapNumber(
2349 : AllocationType allocation) {
2350 : STATIC_ASSERT(HeapNumber::kSize <= kMaxRegularHeapObjectSize);
2351 11809 : Map map = *mutable_heap_number_map();
2352 : HeapObject result = AllocateRawWithImmortalMap(
2353 11809 : MutableHeapNumber::kSize, allocation, map, kDoubleUnaligned);
2354 11809 : return handle(MutableHeapNumber::cast(result), isolate());
2355 : }
2356 :
2357 162763 : Handle<FreshlyAllocatedBigInt> Factory::NewBigInt(int length,
2358 : AllocationType allocation) {
2359 162763 : if (length < 0 || length > BigInt::kMaxLength) {
2360 0 : isolate()->heap()->FatalProcessOutOfMemory("invalid BigInt length");
2361 : }
2362 : HeapObject result = AllocateRawWithImmortalMap(BigInt::SizeFor(length),
2363 162763 : allocation, *bigint_map());
2364 : FreshlyAllocatedBigInt bigint = FreshlyAllocatedBigInt::cast(result);
2365 : bigint->clear_padding();
2366 162763 : return handle(bigint, isolate());
2367 : }
2368 :
2369 1156302 : Handle<Object> Factory::NewError(Handle<JSFunction> constructor,
2370 : MessageTemplate template_index,
2371 : Handle<Object> arg0, Handle<Object> arg1,
2372 : Handle<Object> arg2) {
2373 : HandleScope scope(isolate());
2374 1156302 : if (isolate()->bootstrapper()->IsActive()) {
2375 : // During bootstrapping we cannot construct error objects.
2376 : return scope.CloseAndEscape(NewStringFromAsciiChecked(
2377 40 : MessageFormatter::TemplateString(template_index)));
2378 : }
2379 :
2380 1156262 : if (arg0.is_null()) arg0 = undefined_value();
2381 1156262 : if (arg1.is_null()) arg1 = undefined_value();
2382 1156262 : if (arg2.is_null()) arg2 = undefined_value();
2383 :
2384 : Handle<Object> result;
2385 2312524 : if (!ErrorUtils::MakeGenericError(isolate(), constructor, template_index,
2386 : arg0, arg1, arg2, SKIP_NONE)
2387 : .ToHandle(&result)) {
2388 : // If an exception is thrown while
2389 : // running the factory method, use the exception as the result.
2390 : DCHECK(isolate()->has_pending_exception());
2391 0 : result = handle(isolate()->pending_exception(), isolate());
2392 : isolate()->clear_pending_exception();
2393 : }
2394 :
2395 1156262 : return scope.CloseAndEscape(result);
2396 : }
2397 :
2398 30573 : Handle<Object> Factory::NewError(Handle<JSFunction> constructor,
2399 : Handle<String> message) {
2400 : // Construct a new error object. If an exception is thrown, use the exception
2401 : // as the result.
2402 :
2403 : Handle<Object> no_caller;
2404 : MaybeHandle<Object> maybe_error =
2405 : ErrorUtils::Construct(isolate(), constructor, constructor, message,
2406 30573 : SKIP_NONE, no_caller, false);
2407 30573 : if (maybe_error.is_null()) {
2408 : DCHECK(isolate()->has_pending_exception());
2409 : maybe_error = handle(isolate()->pending_exception(), isolate());
2410 : isolate()->clear_pending_exception();
2411 : }
2412 :
2413 30573 : return maybe_error.ToHandleChecked();
2414 : }
2415 :
2416 473 : Handle<Object> Factory::NewInvalidStringLengthError() {
2417 473 : if (FLAG_abort_on_stack_or_string_length_overflow) {
2418 0 : FATAL("Aborting on invalid string length");
2419 : }
2420 : // Invalidate the "string length" protector.
2421 473 : if (isolate()->IsStringLengthOverflowIntact()) {
2422 143 : isolate()->InvalidateStringLengthOverflowProtector();
2423 : }
2424 473 : return NewRangeError(MessageTemplate::kInvalidStringLength);
2425 : }
2426 :
2427 : #define DEFINE_ERROR(NAME, name) \
2428 : Handle<Object> Factory::New##NAME(MessageTemplate template_index, \
2429 : Handle<Object> arg0, Handle<Object> arg1, \
2430 : Handle<Object> arg2) { \
2431 : return NewError(isolate()->name##_function(), template_index, arg0, arg1, \
2432 : arg2); \
2433 : }
2434 63 : DEFINE_ERROR(Error, error)
2435 3004 : DEFINE_ERROR(EvalError, eval_error)
2436 17812 : DEFINE_ERROR(RangeError, range_error)
2437 203778 : DEFINE_ERROR(ReferenceError, reference_error)
2438 384264 : DEFINE_ERROR(SyntaxError, syntax_error)
2439 390678 : DEFINE_ERROR(TypeError, type_error)
2440 0 : DEFINE_ERROR(WasmCompileError, wasm_compile_error)
2441 0 : DEFINE_ERROR(WasmLinkError, wasm_link_error)
2442 151456 : DEFINE_ERROR(WasmRuntimeError, wasm_runtime_error)
2443 : #undef DEFINE_ERROR
2444 :
2445 15650891 : Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
2446 : Handle<SharedFunctionInfo> info,
2447 : Handle<Context> context,
2448 : AllocationType allocation) {
2449 31301799 : Handle<JSFunction> function(JSFunction::cast(New(map, allocation)),
2450 : isolate());
2451 :
2452 15650908 : function->initialize_properties();
2453 15650908 : function->initialize_elements();
2454 15650909 : function->set_shared(*info);
2455 31301804 : function->set_code(info->GetCode());
2456 31301820 : function->set_context(*context);
2457 15650906 : function->set_raw_feedback_cell(*many_closures_cell());
2458 : int header_size;
2459 15650909 : if (map->has_prototype_slot()) {
2460 : header_size = JSFunction::kSizeWithPrototype;
2461 22693922 : function->set_prototype_or_initial_map(*the_hole_value());
2462 : } else {
2463 : header_size = JSFunction::kSizeWithoutPrototype;
2464 : }
2465 15650909 : InitializeJSObjectBody(function, map, header_size);
2466 15650910 : return function;
2467 : }
2468 :
2469 181 : Handle<JSFunction> Factory::NewFunctionForTest(Handle<String> name) {
2470 : NewFunctionArgs args = NewFunctionArgs::ForFunctionWithoutCode(
2471 181 : name, isolate()->sloppy_function_map(), LanguageMode::kSloppy);
2472 181 : Handle<JSFunction> result = NewFunction(args);
2473 : DCHECK(is_sloppy(result->shared()->language_mode()));
2474 181 : return result;
2475 : }
2476 :
2477 2270573 : Handle<JSFunction> Factory::NewFunction(const NewFunctionArgs& args) {
2478 : DCHECK(!args.name_.is_null());
2479 :
2480 : // Create the SharedFunctionInfo.
2481 2270573 : Handle<NativeContext> context(isolate()->native_context());
2482 2270576 : Handle<Map> map = args.GetMap(isolate());
2483 : Handle<SharedFunctionInfo> info =
2484 : NewSharedFunctionInfo(args.name_, args.maybe_exported_function_data_,
2485 4541150 : args.maybe_builtin_id_, kNormalFunction);
2486 :
2487 : // Proper language mode in shared function info will be set later.
2488 : DCHECK(is_sloppy(info->language_mode()));
2489 : DCHECK(!map->IsUndefined(isolate()));
2490 :
2491 : #ifdef DEBUG
2492 : if (isolate()->bootstrapper()->IsActive()) {
2493 : Handle<Code> code;
2494 : DCHECK(
2495 : // During bootstrapping some of these maps could be not created yet.
2496 : (*map == context->get(Context::STRICT_FUNCTION_MAP_INDEX)) ||
2497 : (*map ==
2498 : context->get(Context::STRICT_FUNCTION_WITHOUT_PROTOTYPE_MAP_INDEX)) ||
2499 : (*map ==
2500 : context->get(
2501 : Context::STRICT_FUNCTION_WITH_READONLY_PROTOTYPE_MAP_INDEX)) ||
2502 : // Check if it's a creation of an empty or Proxy function during
2503 : // bootstrapping.
2504 : (args.maybe_builtin_id_ == Builtins::kEmptyFunction ||
2505 : args.maybe_builtin_id_ == Builtins::kProxyConstructor));
2506 : } else {
2507 : DCHECK(
2508 : (*map == *isolate()->sloppy_function_map()) ||
2509 : (*map == *isolate()->sloppy_function_without_prototype_map()) ||
2510 : (*map == *isolate()->sloppy_function_with_readonly_prototype_map()) ||
2511 : (*map == *isolate()->strict_function_map()) ||
2512 : (*map == *isolate()->strict_function_without_prototype_map()) ||
2513 : (*map == *isolate()->native_function_map()));
2514 : }
2515 : #endif
2516 :
2517 2270576 : Handle<JSFunction> result = NewFunction(map, info, context);
2518 :
2519 2270575 : if (args.should_set_prototype_) {
2520 788604 : result->set_prototype_or_initial_map(
2521 262868 : *args.maybe_prototype_.ToHandleChecked());
2522 : }
2523 :
2524 2270575 : if (args.should_set_language_mode_) {
2525 4064408 : result->shared()->set_language_mode(args.language_mode_);
2526 : }
2527 :
2528 2270574 : if (args.should_create_and_set_initial_map_) {
2529 : ElementsKind elements_kind;
2530 262868 : switch (args.type_) {
2531 : case JS_ARRAY_TYPE:
2532 : elements_kind = PACKED_SMI_ELEMENTS;
2533 : break;
2534 : case JS_ARGUMENTS_TYPE:
2535 : elements_kind = PACKED_ELEMENTS;
2536 111 : break;
2537 : default:
2538 : elements_kind = TERMINAL_FAST_ELEMENTS_KIND;
2539 262535 : break;
2540 : }
2541 262868 : Handle<Map> initial_map = NewMap(args.type_, args.instance_size_,
2542 525736 : elements_kind, args.inobject_properties_);
2543 262868 : result->shared()->set_expected_nof_properties(args.inobject_properties_);
2544 : // TODO(littledan): Why do we have this is_generator test when
2545 : // NewFunctionPrototype already handles finding an appropriately
2546 : // shared prototype?
2547 : Handle<HeapObject> prototype = args.maybe_prototype_.ToHandleChecked();
2548 262868 : if (!IsResumableFunction(result->shared()->kind())) {
2549 262867 : if (prototype->IsTheHole(isolate())) {
2550 132547 : prototype = NewFunctionPrototype(result);
2551 : }
2552 : }
2553 262868 : JSFunction::SetInitialMap(result, initial_map, prototype);
2554 : }
2555 :
2556 2270572 : return result;
2557 : }
2558 :
2559 386666 : Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
2560 : // Make sure to use globals from the function's context, since the function
2561 : // can be from a different context.
2562 : Handle<NativeContext> native_context(function->context()->native_context(),
2563 : isolate());
2564 : Handle<Map> new_map;
2565 386666 : if (V8_UNLIKELY(IsAsyncGeneratorFunction(function->shared()->kind()))) {
2566 2840 : new_map = handle(native_context->async_generator_object_prototype_map(),
2567 2840 : isolate());
2568 385246 : } else if (IsResumableFunction(function->shared()->kind())) {
2569 : // Generator and async function prototypes can share maps since they
2570 : // don't have "constructor" properties.
2571 : new_map =
2572 14728 : handle(native_context->generator_object_prototype_map(), isolate());
2573 : } else {
2574 : // Each function prototype gets a fresh map to avoid unwanted sharing of
2575 : // maps between prototypes of different constructors.
2576 755763 : Handle<JSFunction> object_function(native_context->object_function(),
2577 377882 : isolate());
2578 : DCHECK(object_function->has_initial_map());
2579 377881 : new_map = handle(object_function->initial_map(), isolate());
2580 : }
2581 :
2582 : DCHECK(!new_map->is_prototype_map());
2583 386665 : Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
2584 :
2585 386665 : if (!IsResumableFunction(function->shared()->kind())) {
2586 377882 : JSObject::AddProperty(isolate(), prototype, constructor_string(), function,
2587 377881 : DONT_ENUM);
2588 : }
2589 :
2590 386666 : return prototype;
2591 : }
2592 :
2593 445 : Handle<WeakCell> Factory::NewWeakCell() {
2594 : // Allocate the WeakCell object in the old space, because 1) WeakCell weakness
2595 : // handling is only implemented in the old space 2) they're supposedly
2596 : // long-living. TODO(marja, gsathya): Support WeakCells in Scavenger.
2597 : Handle<WeakCell> result(
2598 890 : WeakCell::cast(AllocateRawWithImmortalMap(
2599 : WeakCell::kSize, AllocationType::kOld, *weak_cell_map())),
2600 : isolate());
2601 445 : return result;
2602 : }
2603 :
2604 5313201 : Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
2605 : Handle<SharedFunctionInfo> info, Handle<Context> context,
2606 : AllocationType allocation) {
2607 : Handle<Map> initial_map(
2608 10626419 : Map::cast(context->native_context()->get(info->function_map_index())),
2609 : isolate());
2610 : return NewFunctionFromSharedFunctionInfo(initial_map, info, context,
2611 5313210 : allocation);
2612 : }
2613 :
2614 8064810 : Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
2615 : Handle<SharedFunctionInfo> info, Handle<Context> context,
2616 : Handle<FeedbackCell> feedback_cell, AllocationType allocation) {
2617 : Handle<Map> initial_map(
2618 16129627 : Map::cast(context->native_context()->get(info->function_map_index())),
2619 : isolate());
2620 : return NewFunctionFromSharedFunctionInfo(initial_map, info, context,
2621 8064814 : feedback_cell, allocation);
2622 : }
2623 :
2624 5315503 : Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
2625 : Handle<Map> initial_map, Handle<SharedFunctionInfo> info,
2626 : Handle<Context> context, AllocationType allocation) {
2627 : DCHECK_EQ(JS_FUNCTION_TYPE, initial_map->instance_type());
2628 : Handle<JSFunction> result =
2629 5315503 : NewFunction(initial_map, info, context, allocation);
2630 :
2631 : // Give compiler a chance to pre-initialize.
2632 5315513 : Compiler::PostInstantiation(result, allocation);
2633 :
2634 5315510 : return result;
2635 : }
2636 :
2637 8064810 : Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
2638 : Handle<Map> initial_map, Handle<SharedFunctionInfo> info,
2639 : Handle<Context> context, Handle<FeedbackCell> feedback_cell,
2640 : AllocationType allocation) {
2641 : DCHECK_EQ(JS_FUNCTION_TYPE, initial_map->instance_type());
2642 : Handle<JSFunction> result =
2643 8064810 : NewFunction(initial_map, info, context, allocation);
2644 :
2645 : // Bump the closure count that is encoded in the feedback cell's map.
2646 8064810 : if (feedback_cell->map() == *no_closures_cell_map()) {
2647 2632484 : feedback_cell->set_map(*one_closure_cell_map());
2648 5432326 : } else if (feedback_cell->map() == *one_closure_cell_map()) {
2649 169218 : feedback_cell->set_map(*many_closures_cell_map());
2650 : } else {
2651 : DCHECK(feedback_cell->map() == *many_closures_cell_map());
2652 : }
2653 :
2654 : // Check that the optimized code in the feedback cell wasn't marked for
2655 : // deoptimization while not pointed to by any live JSFunction.
2656 8064804 : if (feedback_cell->value()->IsFeedbackVector()) {
2657 7789429 : FeedbackVector::cast(feedback_cell->value())
2658 : ->EvictOptimizedCodeMarkedForDeoptimization(
2659 3894714 : *info, "new function from shared function info");
2660 : }
2661 8064805 : result->set_raw_feedback_cell(*feedback_cell);
2662 :
2663 : // Give compiler a chance to pre-initialize.
2664 8064811 : Compiler::PostInstantiation(result, allocation);
2665 :
2666 8064813 : return result;
2667 : }
2668 :
2669 2239022 : Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
2670 : return NewFixedArrayWithMap<ScopeInfo>(RootIndex::kScopeInfoMap, length,
2671 2239010 : AllocationType::kOld);
2672 : }
2673 :
2674 1257 : Handle<ModuleInfo> Factory::NewModuleInfo() {
2675 : return NewFixedArrayWithMap<ModuleInfo>(
2676 1257 : RootIndex::kModuleInfoMap, ModuleInfo::kLength, AllocationType::kOld);
2677 : }
2678 :
2679 63694 : Handle<PreparseData> Factory::NewPreparseData(int data_length,
2680 : int children_length) {
2681 : int size = PreparseData::SizeFor(data_length, children_length);
2682 : Handle<PreparseData> result(
2683 127388 : PreparseData::cast(AllocateRawWithImmortalMap(size, AllocationType::kOld,
2684 : *preparse_data_map())),
2685 : isolate());
2686 : result->set_data_length(data_length);
2687 : result->set_children_length(children_length);
2688 63694 : MemsetTagged(result->inner_data_start(), *null_value(), children_length);
2689 63694 : result->clear_padding();
2690 63694 : return result;
2691 : }
2692 :
2693 : Handle<UncompiledDataWithoutPreparseData>
2694 2053207 : Factory::NewUncompiledDataWithoutPreparseData(Handle<String> inferred_name,
2695 : int32_t start_position,
2696 : int32_t end_position,
2697 : int32_t function_literal_id) {
2698 : Handle<UncompiledDataWithoutPreparseData> result(
2699 4106414 : UncompiledDataWithoutPreparseData::cast(New(
2700 : uncompiled_data_without_preparse_data_map(), AllocationType::kOld)),
2701 : isolate());
2702 :
2703 6159618 : UncompiledData::Initialize(*result, *inferred_name, start_position,
2704 2053207 : end_position, function_literal_id);
2705 2053206 : return result;
2706 : }
2707 :
2708 : Handle<UncompiledDataWithPreparseData>
2709 59647 : Factory::NewUncompiledDataWithPreparseData(Handle<String> inferred_name,
2710 : int32_t start_position,
2711 : int32_t end_position,
2712 : int32_t function_literal_id,
2713 : Handle<PreparseData> preparse_data) {
2714 : Handle<UncompiledDataWithPreparseData> result(
2715 : UncompiledDataWithPreparseData::cast(
2716 119294 : New(uncompiled_data_with_preparse_data_map(), AllocationType::kOld)),
2717 : isolate());
2718 :
2719 59647 : UncompiledDataWithPreparseData::Initialize(
2720 : *result, *inferred_name, start_position, end_position,
2721 59647 : function_literal_id, *preparse_data);
2722 :
2723 59647 : return result;
2724 : }
2725 :
2726 3914 : Handle<JSObject> Factory::NewExternal(void* value) {
2727 3914 : Handle<Foreign> foreign = NewForeign(reinterpret_cast<Address>(value));
2728 3914 : Handle<JSObject> external = NewJSObjectFromMap(external_map());
2729 7828 : external->SetEmbedderField(0, *foreign);
2730 3914 : return external;
2731 : }
2732 :
2733 1906459 : Handle<CodeDataContainer> Factory::NewCodeDataContainer(int flags) {
2734 : Handle<CodeDataContainer> data_container(
2735 : CodeDataContainer::cast(
2736 3812921 : New(code_data_container_map(), AllocationType::kOld)),
2737 : isolate());
2738 : data_container->set_next_code_link(*undefined_value(), SKIP_WRITE_BARRIER);
2739 : data_container->set_kind_specific_flags(flags);
2740 : data_container->clear_padding();
2741 1906462 : return data_container;
2742 : }
2743 :
2744 1589157 : MaybeHandle<Code> Factory::TryNewCode(
2745 : const CodeDesc& desc, Code::Kind kind, Handle<Object> self_ref,
2746 : int32_t builtin_index, MaybeHandle<ByteArray> maybe_source_position_table,
2747 : MaybeHandle<DeoptimizationData> maybe_deopt_data, Movability movability,
2748 : bool is_turbofanned, int stack_slots) {
2749 : // Allocate objects needed for code initialization.
2750 : Handle<ByteArray> reloc_info =
2751 1589157 : NewByteArray(desc.reloc_size, Builtins::IsBuiltinId(builtin_index)
2752 : ? AllocationType::kReadOnly
2753 3178314 : : AllocationType::kOld);
2754 1589163 : Handle<CodeDataContainer> data_container = NewCodeDataContainer(0);
2755 : Handle<ByteArray> source_position_table =
2756 : maybe_source_position_table.is_null()
2757 : ? empty_byte_array()
2758 3178332 : : maybe_source_position_table.ToHandleChecked();
2759 : Handle<DeoptimizationData> deopt_data =
2760 : maybe_deopt_data.is_null() ? DeoptimizationData::Empty(isolate())
2761 3178332 : : maybe_deopt_data.ToHandleChecked();
2762 : Handle<Code> code;
2763 : {
2764 : int object_size = ComputeCodeObjectSize(desc);
2765 :
2766 : Heap* heap = isolate()->heap();
2767 1589163 : CodePageCollectionMemoryModificationScope code_allocation(heap);
2768 : HeapObject result =
2769 1589163 : heap->AllocateRawWithLightRetry(object_size, AllocationType::kCode);
2770 :
2771 : // Return an empty handle if we cannot allocate the code object.
2772 1589160 : if (result.is_null()) return MaybeHandle<Code>();
2773 :
2774 1589160 : if (movability == kImmovable) {
2775 0 : result = heap->EnsureImmovableCode(result, object_size);
2776 : }
2777 :
2778 : // The code object has not been fully initialized yet. We rely on the
2779 : // fact that no allocation will happen from this point on.
2780 : DisallowHeapAllocation no_gc;
2781 :
2782 : result->set_map_after_allocation(*code_map(), SKIP_WRITE_BARRIER);
2783 : code = handle(Code::cast(result), isolate());
2784 :
2785 1589159 : InitializeCode(heap, code, object_size, desc, kind, self_ref, builtin_index,
2786 : source_position_table, deopt_data, reloc_info,
2787 1589159 : data_container, is_turbofanned, stack_slots);
2788 :
2789 : // Flush the instruction cache before changing the permissions.
2790 : // Note: we do this before setting permissions to ReadExecute because on
2791 : // some older ARM kernels there is a bug which causes an access error on
2792 : // cache flush instructions to trigger access error on non-writable memory.
2793 : // See https://bugs.chromium.org/p/v8/issues/detail?id=8157
2794 1589166 : code->FlushICache();
2795 : }
2796 :
2797 1589163 : return code;
2798 : }
2799 :
2800 317262 : Handle<Code> Factory::NewCode(
2801 : const CodeDesc& desc, Code::Kind kind, Handle<Object> self_ref,
2802 : int32_t builtin_index, MaybeHandle<ByteArray> maybe_source_position_table,
2803 : MaybeHandle<DeoptimizationData> maybe_deopt_data, Movability movability,
2804 : bool is_turbofanned, int stack_slots) {
2805 : // Allocate objects needed for code initialization.
2806 : Handle<ByteArray> reloc_info =
2807 317262 : NewByteArray(desc.reloc_size, Builtins::IsBuiltinId(builtin_index)
2808 : ? AllocationType::kReadOnly
2809 634524 : : AllocationType::kOld);
2810 317262 : Handle<CodeDataContainer> data_container = NewCodeDataContainer(0);
2811 : Handle<ByteArray> source_position_table =
2812 : maybe_source_position_table.is_null()
2813 : ? empty_byte_array()
2814 634524 : : maybe_source_position_table.ToHandleChecked();
2815 : Handle<DeoptimizationData> deopt_data =
2816 : maybe_deopt_data.is_null() ? DeoptimizationData::Empty(isolate())
2817 321192 : : maybe_deopt_data.ToHandleChecked();
2818 :
2819 : Handle<Code> code;
2820 : {
2821 : int object_size = ComputeCodeObjectSize(desc);
2822 :
2823 : Heap* heap = isolate()->heap();
2824 317262 : CodePageCollectionMemoryModificationScope code_allocation(heap);
2825 : HeapObject result =
2826 317262 : heap->AllocateRawWithRetryOrFail(object_size, AllocationType::kCode);
2827 317262 : if (movability == kImmovable) {
2828 44773 : result = heap->EnsureImmovableCode(result, object_size);
2829 : }
2830 :
2831 : // The code object has not been fully initialized yet. We rely on the
2832 : // fact that no allocation will happen from this point on.
2833 : DisallowHeapAllocation no_gc;
2834 :
2835 : result->set_map_after_allocation(*code_map(), SKIP_WRITE_BARRIER);
2836 : code = handle(Code::cast(result), isolate());
2837 :
2838 317262 : InitializeCode(heap, code, object_size, desc, kind, self_ref, builtin_index,
2839 : source_position_table, deopt_data, reloc_info,
2840 317262 : data_container, is_turbofanned, stack_slots);
2841 :
2842 : // Flush the instruction cache before changing the permissions.
2843 : // Note: we do this before setting permissions to ReadExecute because on
2844 : // some older ARM kernels there is a bug which causes an access error on
2845 : // cache flush instructions to trigger access error on non-writable memory.
2846 : // See https://bugs.chromium.org/p/v8/issues/detail?id=8157
2847 317262 : code->FlushICache();
2848 : }
2849 :
2850 317262 : return code;
2851 : }
2852 :
2853 85176 : Handle<Code> Factory::NewOffHeapTrampolineFor(Handle<Code> code,
2854 : Address off_heap_entry) {
2855 85176 : CHECK_NOT_NULL(isolate()->embedded_blob());
2856 170352 : CHECK_NE(0, isolate()->embedded_blob_size());
2857 85176 : CHECK(Builtins::IsIsolateIndependentBuiltin(*code));
2858 :
2859 : Handle<Code> result =
2860 85176 : Builtins::GenerateOffHeapTrampolineFor(isolate(), off_heap_entry);
2861 :
2862 : // The trampoline code object must inherit specific flags from the original
2863 : // builtin (e.g. the safepoint-table offset). We set them manually here.
2864 :
2865 : {
2866 : MemoryChunk* chunk = MemoryChunk::FromHeapObject(*result);
2867 85176 : CodePageMemoryModificationScope code_allocation(chunk);
2868 :
2869 : const bool set_is_off_heap_trampoline = true;
2870 : const int stack_slots =
2871 85176 : code->has_safepoint_info() ? code->stack_slots() : 0;
2872 : result->code_data_container()->set_kind_specific_flags(
2873 : code->code_data_container()->kind_specific_flags());
2874 340704 : result->initialize_flags(code->kind(), code->has_unwinding_info(),
2875 : code->is_turbofanned(), stack_slots,
2876 85176 : set_is_off_heap_trampoline);
2877 : result->set_builtin_index(code->builtin_index());
2878 : result->set_safepoint_table_offset(code->safepoint_table_offset());
2879 : result->set_handler_table_offset(code->handler_table_offset());
2880 : result->set_constant_pool_offset(code->constant_pool_offset());
2881 : result->set_code_comments_offset(code->code_comments_offset());
2882 :
2883 : // Replace the newly generated trampoline's RelocInfo ByteArray with the
2884 : // canonical one stored in the roots to avoid duplicating it for every
2885 : // single builtin.
2886 : ByteArray canonical_reloc_info =
2887 85176 : ReadOnlyRoots(isolate()).off_heap_trampoline_relocation_info();
2888 : #ifdef DEBUG
2889 : // Verify that the contents are the same.
2890 : ByteArray reloc_info = result->relocation_info();
2891 : DCHECK_EQ(reloc_info->length(), canonical_reloc_info->length());
2892 : for (int i = 0; i < reloc_info->length(); ++i) {
2893 : DCHECK_EQ(reloc_info->get(i), canonical_reloc_info->get(i));
2894 : }
2895 : #endif
2896 85176 : result->set_relocation_info(canonical_reloc_info);
2897 : }
2898 :
2899 85176 : return result;
2900 : }
2901 :
2902 34 : Handle<Code> Factory::CopyCode(Handle<Code> code) {
2903 : Handle<CodeDataContainer> data_container =
2904 34 : NewCodeDataContainer(code->code_data_container()->kind_specific_flags());
2905 :
2906 : Heap* heap = isolate()->heap();
2907 : Handle<Code> new_code;
2908 : {
2909 34 : int obj_size = code->Size();
2910 34 : CodePageCollectionMemoryModificationScope code_allocation(heap);
2911 : HeapObject result =
2912 34 : heap->AllocateRawWithRetryOrFail(obj_size, AllocationType::kCode);
2913 :
2914 : // Copy code object.
2915 : Address old_addr = code->address();
2916 : Address new_addr = result->address();
2917 : Heap::CopyBlock(new_addr, old_addr, obj_size);
2918 : new_code = handle(Code::cast(result), isolate());
2919 :
2920 : // Set the {CodeDataContainer}, it cannot be shared.
2921 34 : new_code->set_code_data_container(*data_container);
2922 :
2923 68 : new_code->Relocate(new_addr - old_addr);
2924 : // We have to iterate over the object and process its pointers when black
2925 : // allocation is on.
2926 68 : heap->incremental_marking()->ProcessBlackAllocatedObject(*new_code);
2927 : // Record all references to embedded objects in the new code object.
2928 : WriteBarrierForCode(*new_code);
2929 : }
2930 :
2931 : #ifdef VERIFY_HEAP
2932 : if (FLAG_verify_heap) new_code->ObjectVerify(isolate());
2933 : #endif
2934 : DCHECK(IsAligned(new_code->address(), kCodeAlignment));
2935 : DCHECK_IMPLIES(
2936 : !heap->memory_allocator()->code_range().is_empty(),
2937 : heap->memory_allocator()->code_range().contains(new_code->address()));
2938 34 : return new_code;
2939 : }
2940 :
2941 10601 : Handle<BytecodeArray> Factory::CopyBytecodeArray(
2942 : Handle<BytecodeArray> bytecode_array) {
2943 : int size = BytecodeArray::SizeFor(bytecode_array->length());
2944 : HeapObject result = AllocateRawWithImmortalMap(size, AllocationType::kOld,
2945 10601 : *bytecode_array_map());
2946 :
2947 : Handle<BytecodeArray> copy(BytecodeArray::cast(result), isolate());
2948 : copy->set_length(bytecode_array->length());
2949 : copy->set_frame_size(bytecode_array->frame_size());
2950 : copy->set_parameter_count(bytecode_array->parameter_count());
2951 : copy->set_incoming_new_target_or_generator_register(
2952 : bytecode_array->incoming_new_target_or_generator_register());
2953 10601 : copy->set_constant_pool(bytecode_array->constant_pool());
2954 10601 : copy->set_handler_table(bytecode_array->handler_table());
2955 10601 : copy->set_source_position_table(bytecode_array->source_position_table());
2956 : copy->set_osr_loop_nesting_level(bytecode_array->osr_loop_nesting_level());
2957 : copy->set_bytecode_age(bytecode_array->bytecode_age());
2958 10601 : bytecode_array->CopyBytecodesTo(*copy);
2959 10601 : return copy;
2960 : }
2961 :
2962 14969624 : Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
2963 : AllocationType allocation) {
2964 14969624 : JSFunction::EnsureHasInitialMap(constructor);
2965 : Handle<Map> map(constructor->initial_map(), isolate());
2966 14969623 : return NewJSObjectFromMap(map, allocation);
2967 : }
2968 :
2969 442121 : Handle<JSObject> Factory::NewJSObjectWithNullProto(AllocationType allocation) {
2970 : Handle<JSObject> result =
2971 442121 : NewJSObject(isolate()->object_function(), allocation);
2972 : Handle<Map> new_map = Map::Copy(
2973 442124 : isolate(), Handle<Map>(result->map(), isolate()), "ObjectWithNullProto");
2974 442123 : Map::SetPrototype(isolate(), new_map, null_value());
2975 442125 : JSObject::MigrateToMap(result, new_map);
2976 442125 : return result;
2977 : }
2978 :
2979 91714 : Handle<JSGlobalObject> Factory::NewJSGlobalObject(
2980 : Handle<JSFunction> constructor) {
2981 : DCHECK(constructor->has_initial_map());
2982 : Handle<Map> map(constructor->initial_map(), isolate());
2983 : DCHECK(map->is_dictionary_map());
2984 :
2985 : // Make sure no field properties are described in the initial map.
2986 : // This guarantees us that normalizing the properties does not
2987 : // require us to change property values to PropertyCells.
2988 : DCHECK_EQ(map->NextFreePropertyIndex(), 0);
2989 :
2990 : // Make sure we don't have a ton of pre-allocated slots in the
2991 : // global objects. They will be unused once we normalize the object.
2992 : DCHECK_EQ(map->UnusedPropertyFields(), 0);
2993 : DCHECK_EQ(map->GetInObjectProperties(), 0);
2994 :
2995 : // Initial size of the backing store to avoid resize of the storage during
2996 : // bootstrapping. The size differs between the JS global object ad the
2997 : // builtins object.
2998 : int initial_size = 64;
2999 :
3000 : // Allocate a dictionary object for backing storage.
3001 91714 : int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
3002 : Handle<GlobalDictionary> dictionary =
3003 91714 : GlobalDictionary::New(isolate(), at_least_space_for);
3004 :
3005 : // The global object might be created from an object template with accessors.
3006 : // Fill these accessors into the dictionary.
3007 : Handle<DescriptorArray> descs(map->instance_descriptors(), isolate());
3008 91714 : for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
3009 0 : PropertyDetails details = descs->GetDetails(i);
3010 : // Only accessors are expected.
3011 : DCHECK_EQ(kAccessor, details.kind());
3012 : PropertyDetails d(kAccessor, details.attributes(),
3013 : PropertyCellType::kMutable);
3014 : Handle<Name> name(descs->GetKey(i), isolate());
3015 0 : Handle<PropertyCell> cell = NewPropertyCell(name);
3016 0 : cell->set_value(descs->GetStrongValue(i));
3017 : // |dictionary| already contains enough space for all properties.
3018 0 : USE(GlobalDictionary::Add(isolate(), dictionary, name, cell, d));
3019 : }
3020 :
3021 : // Allocate the global object and initialize it with the backing store.
3022 : Handle<JSGlobalObject> global(
3023 183429 : JSGlobalObject::cast(New(map, AllocationType::kOld)), isolate());
3024 91715 : InitializeJSObjectFromMap(global, dictionary, map);
3025 :
3026 : // Create a new map for the global object.
3027 91715 : Handle<Map> new_map = Map::CopyDropDescriptors(isolate(), map);
3028 91715 : new_map->set_may_have_interesting_symbols(true);
3029 91715 : new_map->set_is_dictionary_map(true);
3030 91782 : LOG(isolate(), MapDetails(*new_map));
3031 :
3032 : // Set up the global object as a normalized object.
3033 183430 : global->set_global_dictionary(*dictionary);
3034 91715 : global->synchronized_set_map(*new_map);
3035 :
3036 : // Make sure result is a global object with properties in dictionary.
3037 : DCHECK(global->IsJSGlobalObject() && !global->HasFastProperties());
3038 91715 : return global;
3039 : }
3040 :
3041 21543749 : void Factory::InitializeJSObjectFromMap(Handle<JSObject> obj,
3042 : Handle<Object> properties,
3043 : Handle<Map> map) {
3044 21543749 : obj->set_raw_properties_or_hash(*properties);
3045 21543753 : obj->initialize_elements();
3046 : // TODO(1240798): Initialize the object's body using valid initial values
3047 : // according to the object's initial map. For example, if the map's
3048 : // instance type is JS_ARRAY_TYPE, the length field should be initialized
3049 : // to a number (e.g. Smi::kZero) and the elements initialized to a
3050 : // fixed array (e.g. Heap::empty_fixed_array()). Currently, the object
3051 : // verification code has to cope with (temporarily) invalid objects. See
3052 : // for example, JSArray::JSArrayVerify).
3053 21543748 : InitializeJSObjectBody(obj, map, JSObject::kHeaderSize);
3054 21543734 : }
3055 :
3056 37194660 : void Factory::InitializeJSObjectBody(Handle<JSObject> obj, Handle<Map> map,
3057 : int start_offset) {
3058 53231544 : if (start_offset == map->instance_size()) return;
3059 : DCHECK_LT(start_offset, map->instance_size());
3060 :
3061 : // We cannot always fill with one_pointer_filler_map because objects
3062 : // created from API functions expect their embedder fields to be initialized
3063 : // with undefined_value.
3064 : // Pre-allocated fields need to be initialized with undefined_value as well
3065 : // so that object accesses before the constructor completes (e.g. in the
3066 : // debugger) will not cause a crash.
3067 :
3068 : // In case of Array subclassing the |map| could already be transitioned
3069 : // to different elements kind from the initial map on which we track slack.
3070 : bool in_progress = map->IsInobjectSlackTrackingInProgress();
3071 : Object filler;
3072 21157776 : if (in_progress) {
3073 230446 : filler = *one_pointer_filler_map();
3074 : } else {
3075 20927330 : filler = *undefined_value();
3076 : }
3077 42315552 : obj->InitializeBody(*map, start_offset, *undefined_value(), filler);
3078 21157760 : if (in_progress) {
3079 230447 : map->FindRootMap(isolate())->InobjectSlackTrackingStep(isolate());
3080 : }
3081 : }
3082 :
3083 21360313 : Handle<JSObject> Factory::NewJSObjectFromMap(
3084 : Handle<Map> map, AllocationType allocation,
3085 : Handle<AllocationSite> allocation_site) {
3086 : // JSFunctions should be allocated using AllocateFunction to be
3087 : // properly initialized.
3088 : DCHECK(map->instance_type() != JS_FUNCTION_TYPE);
3089 :
3090 : // Both types of global objects should be allocated using
3091 : // AllocateGlobalObject to be properly initialized.
3092 : DCHECK(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3093 :
3094 : HeapObject obj =
3095 21360313 : AllocateRawWithAllocationSite(map, allocation, allocation_site);
3096 : Handle<JSObject> js_obj(JSObject::cast(obj), isolate());
3097 :
3098 21360298 : InitializeJSObjectFromMap(js_obj, empty_fixed_array(), map);
3099 :
3100 : DCHECK(js_obj->HasFastElements() || js_obj->HasFixedTypedArrayElements() ||
3101 : js_obj->HasFastStringWrapperElements() ||
3102 : js_obj->HasFastArgumentsElements());
3103 21360270 : return js_obj;
3104 : }
3105 :
3106 3652 : Handle<JSObject> Factory::NewSlowJSObjectFromMap(Handle<Map> map, int capacity,
3107 : AllocationType allocation) {
3108 : DCHECK(map->is_dictionary_map());
3109 : Handle<NameDictionary> object_properties =
3110 3652 : NameDictionary::New(isolate(), capacity);
3111 3652 : Handle<JSObject> js_object = NewJSObjectFromMap(map, allocation);
3112 7304 : js_object->set_raw_properties_or_hash(*object_properties);
3113 3652 : return js_object;
3114 : }
3115 :
3116 48 : Handle<JSObject> Factory::NewSlowJSObjectWithPropertiesAndElements(
3117 : Handle<HeapObject> prototype, Handle<NameDictionary> properties,
3118 : Handle<FixedArrayBase> elements, AllocationType allocation) {
3119 48 : Handle<Map> object_map = isolate()->slow_object_with_object_prototype_map();
3120 48 : if (object_map->prototype() != *prototype) {
3121 48 : object_map = Map::TransitionToPrototype(isolate(), object_map, prototype);
3122 : }
3123 : DCHECK(object_map->is_dictionary_map());
3124 48 : Handle<JSObject> object = NewJSObjectFromMap(object_map, allocation);
3125 96 : object->set_raw_properties_or_hash(*properties);
3126 48 : if (*elements != ReadOnlyRoots(isolate()).empty_fixed_array()) {
3127 : DCHECK(elements->IsNumberDictionary());
3128 : object_map =
3129 12 : JSObject::GetElementsTransitionMap(object, DICTIONARY_ELEMENTS);
3130 12 : JSObject::MigrateToMap(object, object_map);
3131 12 : object->set_elements(*elements);
3132 : }
3133 48 : return object;
3134 : }
3135 :
3136 1685183 : Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
3137 : AllocationType allocation) {
3138 1685183 : NativeContext native_context = isolate()->raw_native_context();
3139 1685183 : Map map = native_context->GetInitialJSArrayMap(elements_kind);
3140 1685183 : if (map.is_null()) {
3141 0 : JSFunction array_function = native_context->array_function();
3142 : map = array_function->initial_map();
3143 : }
3144 : return Handle<JSArray>::cast(
3145 1685183 : NewJSObjectFromMap(handle(map, isolate()), allocation));
3146 : }
3147 :
3148 563532 : Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind, int length,
3149 : int capacity,
3150 : ArrayStorageAllocationMode mode,
3151 : AllocationType allocation) {
3152 563532 : Handle<JSArray> array = NewJSArray(elements_kind, allocation);
3153 563532 : NewJSArrayStorage(array, length, capacity, mode);
3154 563532 : return array;
3155 : }
3156 :
3157 1121651 : Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
3158 : ElementsKind elements_kind,
3159 : int length,
3160 : AllocationType allocation) {
3161 : DCHECK(length <= elements->length());
3162 1121651 : Handle<JSArray> array = NewJSArray(elements_kind, allocation);
3163 :
3164 1121654 : array->set_elements(*elements);
3165 : array->set_length(Smi::FromInt(length));
3166 1121653 : JSObject::ValidateElements(*array);
3167 1121650 : return array;
3168 : }
3169 :
3170 1016727 : void Factory::NewJSArrayStorage(Handle<JSArray> array, int length, int capacity,
3171 : ArrayStorageAllocationMode mode) {
3172 : DCHECK(capacity >= length);
3173 :
3174 1016727 : if (capacity == 0) {
3175 676356 : array->set_length(Smi::kZero);
3176 1352712 : array->set_elements(*empty_fixed_array());
3177 : return;
3178 : }
3179 :
3180 : HandleScope inner_scope(isolate());
3181 : Handle<FixedArrayBase> elms;
3182 : ElementsKind elements_kind = array->GetElementsKind();
3183 340371 : if (IsDoubleElementsKind(elements_kind)) {
3184 81 : if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3185 69 : elms = NewFixedDoubleArray(capacity);
3186 : } else {
3187 : DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3188 12 : elms = NewFixedDoubleArrayWithHoles(capacity);
3189 : }
3190 : } else {
3191 : DCHECK(IsSmiOrObjectElementsKind(elements_kind));
3192 340290 : if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3193 : elms = NewUninitializedFixedArray(capacity);
3194 : } else {
3195 : DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3196 : elms = NewFixedArrayWithHoles(capacity);
3197 : }
3198 : }
3199 :
3200 340371 : array->set_elements(*elms);
3201 : array->set_length(Smi::FromInt(length));
3202 : }
3203 :
3204 50114 : Handle<JSWeakMap> Factory::NewJSWeakMap() {
3205 50114 : NativeContext native_context = isolate()->raw_native_context();
3206 100228 : Handle<Map> map(native_context->js_weak_map_fun()->initial_map(), isolate());
3207 100228 : Handle<JSWeakMap> weakmap(JSWeakMap::cast(*NewJSObjectFromMap(map)),
3208 : isolate());
3209 : {
3210 : // Do not leak handles for the hash table, it would make entries strong.
3211 : HandleScope scope(isolate());
3212 50114 : JSWeakCollection::Initialize(weakmap, isolate());
3213 : }
3214 50114 : return weakmap;
3215 : }
3216 :
3217 348 : Handle<JSModuleNamespace> Factory::NewJSModuleNamespace() {
3218 348 : Handle<Map> map = isolate()->js_module_namespace_map();
3219 : Handle<JSModuleNamespace> module_namespace(
3220 348 : Handle<JSModuleNamespace>::cast(NewJSObjectFromMap(map)));
3221 : FieldIndex index = FieldIndex::ForDescriptor(
3222 348 : *map, JSModuleNamespace::kToStringTagFieldIndex);
3223 696 : module_namespace->FastPropertyAtPut(index,
3224 1044 : ReadOnlyRoots(isolate()).Module_string());
3225 348 : return module_namespace;
3226 : }
3227 :
3228 8680 : Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
3229 : Handle<JSFunction> function) {
3230 : DCHECK(IsResumableFunction(function->shared()->kind()));
3231 8680 : JSFunction::EnsureHasInitialMap(function);
3232 : Handle<Map> map(function->initial_map(), isolate());
3233 :
3234 : DCHECK(map->instance_type() == JS_GENERATOR_OBJECT_TYPE ||
3235 : map->instance_type() == JS_ASYNC_GENERATOR_OBJECT_TYPE);
3236 :
3237 8680 : return Handle<JSGeneratorObject>::cast(NewJSObjectFromMap(map));
3238 : }
3239 :
3240 1822 : Handle<Module> Factory::NewModule(Handle<SharedFunctionInfo> code) {
3241 3644 : Handle<ModuleInfo> module_info(code->scope_info()->ModuleDescriptorInfo(),
3242 1822 : isolate());
3243 : Handle<ObjectHashTable> exports =
3244 1822 : ObjectHashTable::New(isolate(), module_info->RegularExportCount());
3245 : Handle<FixedArray> regular_exports =
3246 3644 : NewFixedArray(module_info->RegularExportCount());
3247 : Handle<FixedArray> regular_imports =
3248 : NewFixedArray(module_info->regular_imports()->length());
3249 : int requested_modules_length = module_info->module_requests()->length();
3250 : Handle<FixedArray> requested_modules =
3251 : requested_modules_length > 0 ? NewFixedArray(requested_modules_length)
3252 1822 : : empty_fixed_array();
3253 :
3254 : ReadOnlyRoots roots(isolate());
3255 : Handle<Module> module =
3256 1822 : Handle<Module>::cast(NewStruct(MODULE_TYPE, AllocationType::kOld));
3257 3644 : module->set_code(*code);
3258 1822 : module->set_exports(*exports);
3259 1822 : module->set_regular_exports(*regular_exports);
3260 1822 : module->set_regular_imports(*regular_imports);
3261 1822 : module->set_hash(isolate()->GenerateIdentityHash(Smi::kMaxValue));
3262 3644 : module->set_module_namespace(roots.undefined_value());
3263 1822 : module->set_requested_modules(*requested_modules);
3264 3644 : module->set_script(Script::cast(code->script()));
3265 : module->set_status(Module::kUninstantiated);
3266 3644 : module->set_exception(roots.the_hole_value());
3267 3644 : module->set_import_meta(roots.the_hole_value());
3268 : module->set_dfs_index(-1);
3269 : module->set_dfs_ancestor_index(-1);
3270 1822 : return module;
3271 : }
3272 :
3273 190075 : Handle<JSArrayBuffer> Factory::NewJSArrayBuffer(SharedFlag shared,
3274 : AllocationType allocation) {
3275 : Handle<JSFunction> array_buffer_fun(
3276 : shared == SharedFlag::kShared
3277 192507 : ? isolate()->native_context()->shared_array_buffer_fun()
3278 567793 : : isolate()->native_context()->array_buffer_fun(),
3279 380150 : isolate());
3280 : Handle<Map> map(array_buffer_fun->initial_map(), isolate());
3281 190075 : return Handle<JSArrayBuffer>::cast(NewJSObjectFromMap(map, allocation));
3282 : }
3283 :
3284 18171 : Handle<JSIteratorResult> Factory::NewJSIteratorResult(Handle<Object> value,
3285 : bool done) {
3286 54513 : Handle<Map> map(isolate()->native_context()->iterator_result_map(),
3287 18171 : isolate());
3288 : Handle<JSIteratorResult> js_iter_result =
3289 18171 : Handle<JSIteratorResult>::cast(NewJSObjectFromMap(map));
3290 18171 : js_iter_result->set_value(*value);
3291 18171 : js_iter_result->set_done(*ToBoolean(done));
3292 18171 : return js_iter_result;
3293 : }
3294 :
3295 238 : Handle<JSAsyncFromSyncIterator> Factory::NewJSAsyncFromSyncIterator(
3296 : Handle<JSReceiver> sync_iterator, Handle<Object> next) {
3297 714 : Handle<Map> map(isolate()->native_context()->async_from_sync_iterator_map(),
3298 238 : isolate());
3299 : Handle<JSAsyncFromSyncIterator> iterator =
3300 238 : Handle<JSAsyncFromSyncIterator>::cast(NewJSObjectFromMap(map));
3301 :
3302 238 : iterator->set_sync_iterator(*sync_iterator);
3303 238 : iterator->set_next(*next);
3304 238 : return iterator;
3305 : }
3306 :
3307 13 : Handle<JSMap> Factory::NewJSMap() {
3308 39 : Handle<Map> map(isolate()->native_context()->js_map_map(), isolate());
3309 13 : Handle<JSMap> js_map = Handle<JSMap>::cast(NewJSObjectFromMap(map));
3310 13 : JSMap::Initialize(js_map, isolate());
3311 13 : return js_map;
3312 : }
3313 :
3314 79706 : Handle<JSSet> Factory::NewJSSet() {
3315 239118 : Handle<Map> map(isolate()->native_context()->js_set_map(), isolate());
3316 79706 : Handle<JSSet> js_set = Handle<JSSet>::cast(NewJSObjectFromMap(map));
3317 79706 : JSSet::Initialize(js_set, isolate());
3318 79706 : return js_set;
3319 : }
3320 :
3321 620 : void Factory::TypeAndSizeForElementsKind(ElementsKind kind,
3322 : ExternalArrayType* array_type,
3323 : size_t* element_size) {
3324 620 : switch (kind) {
3325 : #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) \
3326 : case TYPE##_ELEMENTS: \
3327 : *array_type = kExternal##Type##Array; \
3328 : *element_size = sizeof(ctype); \
3329 : break;
3330 6 : TYPED_ARRAYS(TYPED_ARRAY_CASE)
3331 : #undef TYPED_ARRAY_CASE
3332 :
3333 : default:
3334 0 : UNREACHABLE();
3335 : }
3336 620 : }
3337 :
3338 : namespace {
3339 :
3340 374 : static void ForFixedTypedArray(ExternalArrayType array_type,
3341 : size_t* element_size,
3342 : ElementsKind* element_kind) {
3343 374 : switch (array_type) {
3344 : #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) \
3345 : case kExternal##Type##Array: \
3346 : *element_size = sizeof(ctype); \
3347 : *element_kind = TYPE##_ELEMENTS; \
3348 : return;
3349 :
3350 83 : TYPED_ARRAYS(TYPED_ARRAY_CASE)
3351 : #undef TYPED_ARRAY_CASE
3352 : }
3353 0 : UNREACHABLE();
3354 : }
3355 :
3356 374 : JSFunction GetTypedArrayFun(ExternalArrayType type, Isolate* isolate) {
3357 374 : NativeContext native_context = isolate->context()->native_context();
3358 374 : switch (type) {
3359 : #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype) \
3360 : case kExternal##Type##Array: \
3361 : return native_context->type##_array_fun();
3362 :
3363 83 : TYPED_ARRAYS(TYPED_ARRAY_FUN)
3364 : #undef TYPED_ARRAY_FUN
3365 : }
3366 0 : UNREACHABLE();
3367 : }
3368 :
3369 58 : JSFunction GetTypedArrayFun(ElementsKind elements_kind, Isolate* isolate) {
3370 58 : NativeContext native_context = isolate->context()->native_context();
3371 58 : switch (elements_kind) {
3372 : #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype) \
3373 : case TYPE##_ELEMENTS: \
3374 : return native_context->type##_array_fun();
3375 :
3376 6 : TYPED_ARRAYS(TYPED_ARRAY_FUN)
3377 : #undef TYPED_ARRAY_FUN
3378 :
3379 : default:
3380 0 : UNREACHABLE();
3381 : }
3382 : }
3383 :
3384 399 : void SetupArrayBufferView(i::Isolate* isolate,
3385 : i::Handle<i::JSArrayBufferView> obj,
3386 : i::Handle<i::JSArrayBuffer> buffer,
3387 : size_t byte_offset, size_t byte_length) {
3388 : DCHECK_LE(byte_offset + byte_length, buffer->byte_length());
3389 : DCHECK_EQ(obj->GetEmbedderFieldCount(),
3390 : v8::ArrayBufferView::kEmbedderFieldCount);
3391 1995 : for (int i = 0; i < v8::ArrayBufferView::kEmbedderFieldCount; i++) {
3392 798 : obj->SetEmbedderField(i, Smi::kZero);
3393 : }
3394 798 : obj->set_buffer(*buffer);
3395 : obj->set_byte_offset(byte_offset);
3396 : obj->set_byte_length(byte_length);
3397 399 : }
3398 :
3399 : } // namespace
3400 :
3401 374 : Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
3402 : AllocationType allocation) {
3403 : Handle<JSFunction> typed_array_fun(GetTypedArrayFun(type, isolate()),
3404 374 : isolate());
3405 : Handle<Map> map(typed_array_fun->initial_map(), isolate());
3406 374 : return Handle<JSTypedArray>::cast(NewJSObjectFromMap(map, allocation));
3407 : }
3408 :
3409 58 : Handle<JSTypedArray> Factory::NewJSTypedArray(ElementsKind elements_kind,
3410 : AllocationType allocation) {
3411 : Handle<JSFunction> typed_array_fun(GetTypedArrayFun(elements_kind, isolate()),
3412 58 : isolate());
3413 : Handle<Map> map(typed_array_fun->initial_map(), isolate());
3414 58 : return Handle<JSTypedArray>::cast(NewJSObjectFromMap(map, allocation));
3415 : }
3416 :
3417 374 : Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
3418 : Handle<JSArrayBuffer> buffer,
3419 : size_t byte_offset, size_t length,
3420 : AllocationType allocation) {
3421 374 : Handle<JSTypedArray> obj = NewJSTypedArray(type, allocation);
3422 :
3423 : size_t element_size;
3424 : ElementsKind elements_kind;
3425 374 : ForFixedTypedArray(type, &element_size, &elements_kind);
3426 :
3427 748 : CHECK_EQ(byte_offset % element_size, 0);
3428 :
3429 374 : CHECK(length <= (std::numeric_limits<size_t>::max() / element_size));
3430 : // TODO(7881): Smi length check
3431 374 : CHECK(length <= static_cast<size_t>(Smi::kMaxValue));
3432 374 : size_t byte_length = length * element_size;
3433 374 : SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
3434 :
3435 374 : obj->set_length(length);
3436 :
3437 : Handle<FixedTypedArrayBase> elements = NewFixedTypedArrayWithExternalPointer(
3438 374 : type, static_cast<uint8_t*>(buffer->backing_store()) + byte_offset,
3439 374 : allocation);
3440 748 : Handle<Map> map = JSObject::GetElementsTransitionMap(obj, elements_kind);
3441 374 : JSObject::SetMapAndElements(obj, map, elements);
3442 374 : return obj;
3443 : }
3444 :
3445 58 : Handle<JSTypedArray> Factory::NewJSTypedArray(ElementsKind elements_kind,
3446 : size_t number_of_elements,
3447 : AllocationType allocation) {
3448 58 : Handle<JSTypedArray> obj = NewJSTypedArray(elements_kind, allocation);
3449 : DCHECK_EQ(obj->GetEmbedderFieldCount(),
3450 : v8::ArrayBufferView::kEmbedderFieldCount);
3451 290 : for (int i = 0; i < v8::ArrayBufferView::kEmbedderFieldCount; i++) {
3452 116 : obj->SetEmbedderField(i, Smi::kZero);
3453 : }
3454 :
3455 : size_t element_size;
3456 : ExternalArrayType array_type;
3457 58 : TypeAndSizeForElementsKind(elements_kind, &array_type, &element_size);
3458 :
3459 58 : CHECK(number_of_elements <=
3460 : (std::numeric_limits<size_t>::max() / element_size));
3461 : // TODO(7881): Smi length check
3462 58 : CHECK(number_of_elements <= static_cast<size_t>(Smi::kMaxValue));
3463 58 : size_t byte_length = number_of_elements * element_size;
3464 :
3465 : obj->set_byte_offset(0);
3466 : obj->set_byte_length(byte_length);
3467 58 : obj->set_length(number_of_elements);
3468 :
3469 : Handle<JSArrayBuffer> buffer =
3470 58 : NewJSArrayBuffer(SharedFlag::kNotShared, allocation);
3471 : JSArrayBuffer::Setup(buffer, isolate(), true, nullptr, byte_length,
3472 58 : SharedFlag::kNotShared);
3473 116 : obj->set_buffer(*buffer);
3474 : Handle<FixedTypedArrayBase> elements = NewFixedTypedArray(
3475 58 : number_of_elements, byte_length, array_type, true, allocation);
3476 116 : obj->set_elements(*elements);
3477 58 : return obj;
3478 : }
3479 :
3480 25 : Handle<JSDataView> Factory::NewJSDataView(Handle<JSArrayBuffer> buffer,
3481 : size_t byte_offset,
3482 : size_t byte_length) {
3483 75 : Handle<Map> map(isolate()->native_context()->data_view_fun()->initial_map(),
3484 : isolate());
3485 25 : Handle<JSDataView> obj = Handle<JSDataView>::cast(NewJSObjectFromMap(map));
3486 25 : SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
3487 25 : return obj;
3488 : }
3489 :
3490 528 : MaybeHandle<JSBoundFunction> Factory::NewJSBoundFunction(
3491 : Handle<JSReceiver> target_function, Handle<Object> bound_this,
3492 : Vector<Handle<Object>> bound_args) {
3493 : DCHECK(target_function->IsCallable());
3494 : STATIC_ASSERT(Code::kMaxArguments <= FixedArray::kMaxLength);
3495 528 : if (bound_args.length() >= Code::kMaxArguments) {
3496 : THROW_NEW_ERROR(isolate(),
3497 : NewRangeError(MessageTemplate::kTooManyArguments),
3498 : JSBoundFunction);
3499 : }
3500 :
3501 : // Determine the prototype of the {target_function}.
3502 : Handle<HeapObject> prototype;
3503 1056 : ASSIGN_RETURN_ON_EXCEPTION(
3504 : isolate(), prototype,
3505 : JSReceiver::GetPrototype(isolate(), target_function), JSBoundFunction);
3506 :
3507 1056 : SaveAndSwitchContext save(isolate(), *target_function->GetCreationContext());
3508 :
3509 : // Create the [[BoundArguments]] for the result.
3510 : Handle<FixedArray> bound_arguments;
3511 528 : if (bound_args.length() == 0) {
3512 : bound_arguments = empty_fixed_array();
3513 : } else {
3514 : bound_arguments = NewFixedArray(bound_args.length());
3515 1017 : for (int i = 0; i < bound_args.length(); ++i) {
3516 738 : bound_arguments->set(i, *bound_args[i]);
3517 : }
3518 : }
3519 :
3520 : // Setup the map for the JSBoundFunction instance.
3521 : Handle<Map> map = target_function->IsConstructor()
3522 : ? isolate()->bound_function_with_constructor_map()
3523 528 : : isolate()->bound_function_without_constructor_map();
3524 528 : if (map->prototype() != *prototype) {
3525 144 : map = Map::TransitionToPrototype(isolate(), map, prototype);
3526 : }
3527 : DCHECK_EQ(target_function->IsConstructor(), map->is_constructor());
3528 :
3529 : // Setup the JSBoundFunction instance.
3530 : Handle<JSBoundFunction> result =
3531 528 : Handle<JSBoundFunction>::cast(NewJSObjectFromMap(map));
3532 528 : result->set_bound_target_function(*target_function);
3533 528 : result->set_bound_this(*bound_this);
3534 528 : result->set_bound_arguments(*bound_arguments);
3535 528 : return result;
3536 : }
3537 :
3538 : // ES6 section 9.5.15 ProxyCreate (target, handler)
3539 29 : Handle<JSProxy> Factory::NewJSProxy(Handle<JSReceiver> target,
3540 : Handle<JSReceiver> handler) {
3541 : // Allocate the proxy object.
3542 : Handle<Map> map;
3543 29 : if (target->IsCallable()) {
3544 12 : if (target->IsConstructor()) {
3545 12 : map = Handle<Map>(isolate()->proxy_constructor_map());
3546 : } else {
3547 0 : map = Handle<Map>(isolate()->proxy_callable_map());
3548 : }
3549 : } else {
3550 17 : map = Handle<Map>(isolate()->proxy_map());
3551 : }
3552 : DCHECK(map->prototype()->IsNull(isolate()));
3553 58 : Handle<JSProxy> result(JSProxy::cast(New(map, AllocationType::kYoung)),
3554 : isolate());
3555 29 : result->initialize_properties();
3556 58 : result->set_target(*target);
3557 58 : result->set_handler(*handler);
3558 29 : return result;
3559 : }
3560 :
3561 91704 : Handle<JSGlobalProxy> Factory::NewUninitializedJSGlobalProxy(int size) {
3562 : // Create an empty shell of a JSGlobalProxy that needs to be reinitialized
3563 : // via ReinitializeJSGlobalProxy later.
3564 91704 : Handle<Map> map = NewMap(JS_GLOBAL_PROXY_TYPE, size);
3565 : // Maintain invariant expected from any JSGlobalProxy.
3566 : map->set_is_access_check_needed(true);
3567 91705 : map->set_may_have_interesting_symbols(true);
3568 91772 : LOG(isolate(), MapDetails(*map));
3569 : return Handle<JSGlobalProxy>::cast(
3570 91705 : NewJSObjectFromMap(map, AllocationType::kYoung));
3571 : }
3572 :
3573 91750 : void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
3574 : Handle<JSFunction> constructor) {
3575 : DCHECK(constructor->has_initial_map());
3576 : Handle<Map> map(constructor->initial_map(), isolate());
3577 : Handle<Map> old_map(object->map(), isolate());
3578 :
3579 : // The proxy's hash should be retained across reinitialization.
3580 : Handle<Object> raw_properties_or_hash(object->raw_properties_or_hash(),
3581 : isolate());
3582 :
3583 91750 : if (old_map->is_prototype_map()) {
3584 0 : map = Map::Copy(isolate(), map, "CopyAsPrototypeForJSGlobalProxy");
3585 : map->set_is_prototype_map(true);
3586 : }
3587 91750 : JSObject::NotifyMapChange(old_map, map, isolate());
3588 91751 : old_map->NotifyLeafMapLayoutChange(isolate());
3589 :
3590 : // Check that the already allocated object has the same size and type as
3591 : // objects allocated using the constructor.
3592 : DCHECK(map->instance_size() == old_map->instance_size());
3593 : DCHECK(map->instance_type() == old_map->instance_type());
3594 :
3595 : // In order to keep heap in consistent state there must be no allocations
3596 : // before object re-initialization is finished.
3597 : DisallowHeapAllocation no_allocation;
3598 :
3599 : // Reset the map for the object.
3600 91751 : object->synchronized_set_map(*map);
3601 :
3602 : // Reinitialize the object from the constructor map.
3603 91751 : InitializeJSObjectFromMap(object, raw_properties_or_hash, map);
3604 91751 : }
3605 :
3606 3636758 : Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfoForLiteral(
3607 : FunctionLiteral* literal, Handle<Script> script, bool is_toplevel) {
3608 3636758 : FunctionKind kind = literal->kind();
3609 : Handle<SharedFunctionInfo> shared = NewSharedFunctionInfoForBuiltin(
3610 : literal->name(), Builtins::kCompileLazy, kind);
3611 3636772 : SharedFunctionInfo::InitFromFunctionLiteral(shared, literal, is_toplevel);
3612 3636784 : SharedFunctionInfo::SetScript(shared, script, literal->function_literal_id(),
3613 3636780 : false);
3614 7273568 : TRACE_EVENT_OBJECT_CREATED_WITH_ID(
3615 : TRACE_DISABLED_BY_DEFAULT("v8.compile"), "SharedFunctionInfo",
3616 : TRACE_ID_WITH_SCOPE(SharedFunctionInfo::kTraceScope, shared->TraceID()));
3617 7273568 : TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
3618 : TRACE_DISABLED_BY_DEFAULT("v8.compile"), "SharedFunctionInfo",
3619 : TRACE_ID_WITH_SCOPE(SharedFunctionInfo::kTraceScope, shared->TraceID()),
3620 : shared->ToTracedValue());
3621 3636784 : return shared;
3622 : }
3623 :
3624 1363628 : Handle<JSMessageObject> Factory::NewJSMessageObject(
3625 : MessageTemplate message, Handle<Object> argument, int start_position,
3626 : int end_position, Handle<Script> script, Handle<Object> stack_frames) {
3627 1363628 : Handle<Map> map = message_object_map();
3628 : Handle<JSMessageObject> message_obj(
3629 2727256 : JSMessageObject::cast(New(map, AllocationType::kYoung)), isolate());
3630 : message_obj->set_raw_properties_or_hash(*empty_fixed_array(),
3631 : SKIP_WRITE_BARRIER);
3632 1363628 : message_obj->initialize_elements();
3633 : message_obj->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
3634 : message_obj->set_type(message);
3635 1363628 : message_obj->set_argument(*argument);
3636 : message_obj->set_start_position(start_position);
3637 : message_obj->set_end_position(end_position);
3638 1363628 : message_obj->set_script(*script);
3639 1363628 : message_obj->set_stack_frames(*stack_frames);
3640 : message_obj->set_error_level(v8::Isolate::kMessageError);
3641 1363628 : return message_obj;
3642 : }
3643 :
3644 3696079 : Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfoForApiFunction(
3645 : MaybeHandle<String> maybe_name,
3646 : Handle<FunctionTemplateInfo> function_template_info, FunctionKind kind) {
3647 : Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(
3648 7392158 : maybe_name, function_template_info, Builtins::kNoBuiltinId, kind);
3649 3696083 : return shared;
3650 : }
3651 :
3652 4434 : Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfoForBuiltin(
3653 : MaybeHandle<String> maybe_name, int builtin_index, FunctionKind kind) {
3654 : Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(
3655 7282388 : maybe_name, MaybeHandle<Code>(), builtin_index, kind);
3656 3641206 : return shared;
3657 : }
3658 :
3659 9607846 : Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
3660 : MaybeHandle<String> maybe_name, MaybeHandle<HeapObject> maybe_function_data,
3661 : int maybe_builtin_index, FunctionKind kind) {
3662 : // Function names are assumed to be flat elsewhere. Must flatten before
3663 : // allocating SharedFunctionInfo to avoid GC seeing the uninitialized SFI.
3664 : Handle<String> shared_name;
3665 : bool has_shared_name = maybe_name.ToHandle(&shared_name);
3666 9607846 : if (has_shared_name) {
3667 9597714 : shared_name = String::Flatten(isolate(), shared_name, AllocationType::kOld);
3668 : }
3669 :
3670 9607872 : Handle<Map> map = shared_function_info_map();
3671 : Handle<SharedFunctionInfo> share(
3672 19215721 : SharedFunctionInfo::cast(New(map, AllocationType::kOld)), isolate());
3673 : {
3674 : DisallowHeapAllocation no_allocation;
3675 :
3676 : // Set pointer fields.
3677 28833683 : share->set_name_or_scope_info(
3678 : has_shared_name ? Object::cast(*shared_name)
3679 9607849 : : SharedFunctionInfo::kNoSharedNameSentinel);
3680 : Handle<HeapObject> function_data;
3681 9607850 : if (maybe_function_data.ToHandle(&function_data)) {
3682 : // If we pass function_data then we shouldn't pass a builtin index, and
3683 : // the function_data should not be code with a builtin.
3684 : DCHECK(!Builtins::IsBuiltinId(maybe_builtin_index));
3685 : DCHECK_IMPLIES(function_data->IsCode(),
3686 : !Code::cast(*function_data)->is_builtin());
3687 7868900 : share->set_function_data(*function_data);
3688 5673400 : } else if (Builtins::IsBuiltinId(maybe_builtin_index)) {
3689 : share->set_builtin_id(maybe_builtin_index);
3690 : } else {
3691 : share->set_builtin_id(Builtins::kIllegal);
3692 : }
3693 : // Generally functions won't have feedback, unless they have been created
3694 : // from a FunctionLiteral. Those can just reset this field to keep the
3695 : // SharedFunctionInfo in a consistent state.
3696 9607851 : if (maybe_builtin_index == Builtins::kCompileLazy) {
3697 : share->set_raw_outer_scope_info_or_feedback_metadata(*the_hole_value(),
3698 : SKIP_WRITE_BARRIER);
3699 : } else {
3700 : share->set_raw_outer_scope_info_or_feedback_metadata(
3701 : *empty_feedback_metadata(), SKIP_WRITE_BARRIER);
3702 : }
3703 : share->set_script_or_debug_info(*undefined_value(), SKIP_WRITE_BARRIER);
3704 : #if V8_SFI_HAS_UNIQUE_ID
3705 : Handle<SharedFunctionInfoWithID>::cast(share)->set_unique_id(
3706 : isolate()->GetNextUniqueSharedFunctionInfoId());
3707 : #endif
3708 :
3709 : // Set integer fields (smi or int, depending on the architecture).
3710 : share->set_length(0);
3711 : share->set_internal_formal_parameter_count(0);
3712 : share->set_expected_nof_properties(0);
3713 : share->set_raw_function_token_offset(0);
3714 : // All flags default to false or 0.
3715 : share->set_flags(0);
3716 : // For lite mode disable optimization.
3717 : if (FLAG_lite_mode) {
3718 : share->set_flags(
3719 : SharedFunctionInfo::DisabledOptimizationReasonBits::encode(
3720 : BailoutReason::kNeverOptimize));
3721 : }
3722 9607851 : share->CalculateConstructAsBuiltin();
3723 19215690 : share->set_kind(kind);
3724 :
3725 : share->clear_padding();
3726 : }
3727 : // Link into the list.
3728 : Handle<WeakArrayList> noscript_list = noscript_shared_function_infos();
3729 : noscript_list = WeakArrayList::AddToEnd(isolate(), noscript_list,
3730 9607856 : MaybeObjectHandle::Weak(share));
3731 : isolate()->heap()->set_noscript_shared_function_infos(*noscript_list);
3732 :
3733 : #ifdef VERIFY_HEAP
3734 : share->SharedFunctionInfoVerify(isolate());
3735 : #endif
3736 9607860 : return share;
3737 : }
3738 :
3739 : namespace {
3740 : inline int NumberToStringCacheHash(Handle<FixedArray> cache, Smi number) {
3741 40188784 : int mask = (cache->length() >> 1) - 1;
3742 40188784 : return number->value() & mask;
3743 : }
3744 : inline int NumberToStringCacheHash(Handle<FixedArray> cache, double number) {
3745 1129263 : int mask = (cache->length() >> 1) - 1;
3746 : int64_t bits = bit_cast<int64_t>(number);
3747 1129263 : return (static_cast<int>(bits) ^ static_cast<int>(bits >> 32)) & mask;
3748 : }
3749 : } // namespace
3750 :
3751 33761600 : Handle<String> Factory::NumberToStringCacheSet(Handle<Object> number, int hash,
3752 : const char* string,
3753 : bool check_cache) {
3754 : // We tenure the allocated string since it is referenced from the
3755 : // number-string cache which lives in the old space.
3756 : Handle<String> js_string = NewStringFromAsciiChecked(
3757 33761600 : string, check_cache ? AllocationType::kOld : AllocationType::kYoung);
3758 33761599 : if (!check_cache) return js_string;
3759 :
3760 67436258 : if (!number_string_cache()->get(hash * 2)->IsUndefined(isolate())) {
3761 : int full_size = isolate()->heap()->MaxNumberToStringCacheSize();
3762 27752074 : if (number_string_cache()->length() != full_size) {
3763 : Handle<FixedArray> new_cache =
3764 : NewFixedArray(full_size, AllocationType::kOld);
3765 : isolate()->heap()->set_number_string_cache(*new_cache);
3766 1499 : return js_string;
3767 : }
3768 : }
3769 33716630 : number_string_cache()->set(hash * 2, *number);
3770 67433260 : number_string_cache()->set(hash * 2 + 1, *js_string);
3771 33716630 : return js_string;
3772 : }
3773 :
3774 41318047 : Handle<Object> Factory::NumberToStringCacheGet(Object number, int hash) {
3775 : DisallowHeapAllocation no_gc;
3776 41318047 : Object key = number_string_cache()->get(hash * 2);
3777 76706401 : if (key == number || (key->IsHeapNumber() && number->IsHeapNumber() &&
3778 : key->Number() == number->Number())) {
3779 : return Handle<String>(
3780 15199834 : String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
3781 : }
3782 33718130 : return undefined_value();
3783 : }
3784 :
3785 34077638 : Handle<String> Factory::NumberToString(Handle<Object> number,
3786 : bool check_cache) {
3787 34077638 : if (number->IsSmi()) return NumberToString(Smi::cast(*number), check_cache);
3788 :
3789 : double double_value = Handle<HeapNumber>::cast(number)->value();
3790 : // Try to canonicalize doubles.
3791 : int smi_value;
3792 1264345 : if (DoubleToSmiInteger(double_value, &smi_value)) {
3793 270164 : return NumberToString(Smi::FromInt(smi_value), check_cache);
3794 : }
3795 :
3796 : int hash = 0;
3797 1129263 : if (check_cache) {
3798 : hash = NumberToStringCacheHash(number_string_cache(), double_value);
3799 1129263 : Handle<Object> cached = NumberToStringCacheGet(*number, hash);
3800 1129263 : if (!cached->IsUndefined(isolate())) return Handle<String>::cast(cached);
3801 : }
3802 :
3803 : char arr[100];
3804 : Vector<char> buffer(arr, arraysize(arr));
3805 1108061 : const char* string = DoubleToCString(double_value, buffer);
3806 :
3807 1108061 : return NumberToStringCacheSet(number, hash, string, check_cache);
3808 : }
3809 :
3810 40232254 : Handle<String> Factory::NumberToString(Smi number, bool check_cache) {
3811 : int hash = 0;
3812 40232254 : if (check_cache) {
3813 : hash = NumberToStringCacheHash(number_string_cache(), number);
3814 40188784 : Handle<Object> cached = NumberToStringCacheGet(number, hash);
3815 40188784 : if (!cached->IsUndefined(isolate())) return Handle<String>::cast(cached);
3816 : }
3817 :
3818 : char arr[100];
3819 : Vector<char> buffer(arr, arraysize(arr));
3820 32653539 : const char* string = IntToCString(number->value(), buffer);
3821 :
3822 : return NumberToStringCacheSet(handle(number, isolate()), hash, string,
3823 65307078 : check_cache);
3824 : }
3825 :
3826 40338 : Handle<ClassPositions> Factory::NewClassPositions(int start, int end) {
3827 : Handle<ClassPositions> class_positions = Handle<ClassPositions>::cast(
3828 40338 : NewStruct(CLASS_POSITIONS_TYPE, AllocationType::kOld));
3829 : class_positions->set_start(start);
3830 : class_positions->set_end(end);
3831 40338 : return class_positions;
3832 : }
3833 :
3834 28670 : Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
3835 : DCHECK(!shared->HasDebugInfo());
3836 : Heap* heap = isolate()->heap();
3837 :
3838 : Handle<DebugInfo> debug_info =
3839 28670 : Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE, AllocationType::kOld));
3840 : debug_info->set_flags(DebugInfo::kNone);
3841 28670 : debug_info->set_shared(*shared);
3842 : debug_info->set_debugger_hints(0);
3843 : DCHECK_EQ(DebugInfo::kNoDebuggingId, debug_info->debugging_id());
3844 : DCHECK(!shared->HasDebugInfo());
3845 28670 : debug_info->set_script(shared->script_or_debug_info());
3846 57340 : debug_info->set_original_bytecode_array(
3847 86010 : ReadOnlyRoots(heap).undefined_value());
3848 57340 : debug_info->set_debug_bytecode_array(ReadOnlyRoots(heap).undefined_value());
3849 28670 : debug_info->set_break_points(ReadOnlyRoots(heap).empty_fixed_array());
3850 :
3851 : // Link debug info to function.
3852 57340 : shared->SetDebugInfo(*debug_info);
3853 :
3854 28670 : return debug_info;
3855 : }
3856 :
3857 892 : Handle<CoverageInfo> Factory::NewCoverageInfo(
3858 : const ZoneVector<SourceRange>& slots) {
3859 892 : const int slot_count = static_cast<int>(slots.size());
3860 :
3861 : const int length = CoverageInfo::FixedArrayLengthForSlotCount(slot_count);
3862 : Handle<CoverageInfo> info =
3863 : Handle<CoverageInfo>::cast(NewUninitializedFixedArray(length));
3864 :
3865 5428 : for (int i = 0; i < slot_count; i++) {
3866 4536 : SourceRange range = slots[i];
3867 2268 : info->InitializeSlot(i, range.start, range.end);
3868 : }
3869 :
3870 892 : return info;
3871 : }
3872 :
3873 2476 : Handle<BreakPointInfo> Factory::NewBreakPointInfo(int source_position) {
3874 : Handle<BreakPointInfo> new_break_point_info = Handle<BreakPointInfo>::cast(
3875 2476 : NewStruct(TUPLE2_TYPE, AllocationType::kOld));
3876 : new_break_point_info->set_source_position(source_position);
3877 4952 : new_break_point_info->set_break_points(*undefined_value());
3878 2476 : return new_break_point_info;
3879 : }
3880 :
3881 4854 : Handle<BreakPoint> Factory::NewBreakPoint(int id, Handle<String> condition) {
3882 : Handle<BreakPoint> new_break_point =
3883 4854 : Handle<BreakPoint>::cast(NewStruct(TUPLE2_TYPE, AllocationType::kOld));
3884 : new_break_point->set_id(id);
3885 4854 : new_break_point->set_condition(*condition);
3886 4854 : return new_break_point;
3887 : }
3888 :
3889 11020 : Handle<StackTraceFrame> Factory::NewStackTraceFrame(
3890 : Handle<FrameArray> frame_array, int index) {
3891 : Handle<StackTraceFrame> frame = Handle<StackTraceFrame>::cast(
3892 11020 : NewStruct(STACK_TRACE_FRAME_TYPE, AllocationType::kYoung));
3893 22040 : frame->set_frame_array(*frame_array);
3894 : frame->set_frame_index(index);
3895 22040 : frame->set_frame_info(*undefined_value());
3896 :
3897 11020 : int id = isolate()->last_stack_frame_info_id() + 1;
3898 : isolate()->set_last_stack_frame_info_id(id);
3899 : frame->set_id(id);
3900 11020 : return frame;
3901 : }
3902 :
3903 0 : Handle<StackFrameInfo> Factory::NewStackFrameInfo() {
3904 : Handle<StackFrameInfo> stack_frame_info = Handle<StackFrameInfo>::cast(
3905 0 : NewStruct(STACK_FRAME_INFO_TYPE, AllocationType::kYoung));
3906 : stack_frame_info->set_line_number(0);
3907 : stack_frame_info->set_column_number(0);
3908 : stack_frame_info->set_script_id(0);
3909 0 : stack_frame_info->set_script_name(Smi::kZero);
3910 0 : stack_frame_info->set_script_name_or_source_url(Smi::kZero);
3911 0 : stack_frame_info->set_function_name(Smi::kZero);
3912 : stack_frame_info->set_flag(0);
3913 0 : return stack_frame_info;
3914 : }
3915 :
3916 10770 : Handle<StackFrameInfo> Factory::NewStackFrameInfo(
3917 : Handle<FrameArray> frame_array, int index) {
3918 10770 : FrameArrayIterator it(isolate(), frame_array, index);
3919 : DCHECK(it.HasFrame());
3920 :
3921 : Handle<StackFrameInfo> info = Handle<StackFrameInfo>::cast(
3922 10770 : NewStruct(STACK_FRAME_INFO_TYPE, AllocationType::kYoung));
3923 : info->set_flag(0);
3924 :
3925 10770 : const bool is_wasm = frame_array->IsAnyWasmFrame(index);
3926 21540 : info->set_is_wasm(is_wasm);
3927 :
3928 : // Line numbers are 1-based, for Wasm we need to adjust.
3929 10770 : int line = it.Frame()->GetLineNumber();
3930 10770 : if (is_wasm && line >= 0) line++;
3931 : info->set_line_number(line);
3932 :
3933 : // Column numbers are 1-based. For Wasm we use the position
3934 : // as the iterator does not currently provide a column number.
3935 : const int column =
3936 10770 : is_wasm ? it.Frame()->GetPosition() + 1 : it.Frame()->GetColumnNumber();
3937 : info->set_column_number(column);
3938 :
3939 10770 : info->set_script_id(it.Frame()->GetScriptId());
3940 21540 : info->set_script_name(*it.Frame()->GetFileName());
3941 21540 : info->set_script_name_or_source_url(*it.Frame()->GetScriptNameOrSourceUrl());
3942 :
3943 : // TODO(szuend): Adjust this, once it is decided what name to use in both
3944 : // "simple" and "detailed" stack traces. This code is for
3945 : // backwards compatibility to fullfill test expectations.
3946 10770 : auto function_name = it.Frame()->GetFunctionName();
3947 10770 : if (!is_wasm) {
3948 10322 : Handle<Object> function = it.Frame()->GetFunction();
3949 10322 : if (function->IsJSFunction()) {
3950 : function_name =
3951 10322 : JSFunction::GetDebugName(Handle<JSFunction>::cast(function));
3952 : }
3953 : }
3954 10770 : info->set_function_name(*function_name);
3955 21540 : info->set_is_eval(it.Frame()->IsEval());
3956 21540 : info->set_is_constructor(it.Frame()->IsConstructor());
3957 :
3958 21540 : return info;
3959 : }
3960 :
3961 : Handle<SourcePositionTableWithFrameCache>
3962 8194 : Factory::NewSourcePositionTableWithFrameCache(
3963 : Handle<ByteArray> source_position_table,
3964 : Handle<SimpleNumberDictionary> stack_frame_cache) {
3965 : Handle<SourcePositionTableWithFrameCache>
3966 : source_position_table_with_frame_cache =
3967 : Handle<SourcePositionTableWithFrameCache>::cast(
3968 8194 : NewStruct(TUPLE2_TYPE, AllocationType::kOld));
3969 16388 : source_position_table_with_frame_cache->set_source_position_table(
3970 8194 : *source_position_table);
3971 16388 : source_position_table_with_frame_cache->set_stack_frame_cache(
3972 8194 : *stack_frame_cache);
3973 8194 : return source_position_table_with_frame_cache;
3974 : }
3975 :
3976 64786 : Handle<JSObject> Factory::NewArgumentsObject(Handle<JSFunction> callee,
3977 : int length) {
3978 129059 : bool strict_mode_callee = is_strict(callee->shared()->language_mode()) ||
3979 129059 : !callee->shared()->has_simple_parameters();
3980 : Handle<Map> map = strict_mode_callee ? isolate()->strict_arguments_map()
3981 64786 : : isolate()->sloppy_arguments_map();
3982 : AllocationSiteUsageContext context(isolate(), Handle<AllocationSite>(),
3983 : false);
3984 : DCHECK(!isolate()->has_pending_exception());
3985 64786 : Handle<JSObject> result = NewJSObjectFromMap(map);
3986 : Handle<Smi> value(Smi::FromInt(length), isolate());
3987 64786 : Object::SetProperty(isolate(), result, length_string(), value,
3988 : StoreOrigin::kMaybeKeyed,
3989 64786 : Just(ShouldThrow::kThrowOnError))
3990 : .Assert();
3991 64786 : if (!strict_mode_callee) {
3992 64186 : Object::SetProperty(isolate(), result, callee_string(), callee,
3993 : StoreOrigin::kMaybeKeyed,
3994 64186 : Just(ShouldThrow::kThrowOnError))
3995 : .Assert();
3996 : }
3997 64786 : return result;
3998 : }
3999 :
4000 361861 : Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<NativeContext> context,
4001 : int number_of_properties) {
4002 361861 : if (number_of_properties == 0) {
4003 : // Reuse the initial map of the Object function if the literal has no
4004 : // predeclared properties.
4005 34354 : return handle(context->object_function()->initial_map(), isolate());
4006 : }
4007 :
4008 : // We do not cache maps for too many properties or when running builtin code.
4009 344684 : if (isolate()->bootstrapper()->IsActive()) {
4010 0 : return Map::Create(isolate(), number_of_properties);
4011 : }
4012 :
4013 : // Use initial slow object proto map for too many properties.
4014 : const int kMapCacheSize = 128;
4015 344684 : if (number_of_properties > kMapCacheSize) {
4016 382 : return handle(context->slow_object_with_object_prototype_map(), isolate());
4017 : }
4018 :
4019 344493 : int cache_index = number_of_properties - 1;
4020 688986 : Handle<Object> maybe_cache(context->map_cache(), isolate());
4021 344493 : if (maybe_cache->IsUndefined(isolate())) {
4022 : // Allocate the new map cache for the native context.
4023 47727 : maybe_cache = NewWeakFixedArray(kMapCacheSize, AllocationType::kOld);
4024 47727 : context->set_map_cache(*maybe_cache);
4025 : } else {
4026 : // Check to see whether there is a matching element in the cache.
4027 : Handle<WeakFixedArray> cache = Handle<WeakFixedArray>::cast(maybe_cache);
4028 : MaybeObject result = cache->Get(cache_index);
4029 : HeapObject heap_object;
4030 296766 : if (result->GetHeapObjectIfWeak(&heap_object)) {
4031 : Map map = Map::cast(heap_object);
4032 : DCHECK(!map->is_dictionary_map());
4033 : return handle(map, isolate());
4034 : }
4035 : }
4036 :
4037 : // Create a new map and add it to the cache.
4038 : Handle<WeakFixedArray> cache = Handle<WeakFixedArray>::cast(maybe_cache);
4039 92976 : Handle<Map> map = Map::Create(isolate(), number_of_properties);
4040 : DCHECK(!map->is_dictionary_map());
4041 185952 : cache->Set(cache_index, HeapObjectReference::Weak(*map));
4042 92976 : return map;
4043 : }
4044 :
4045 484655 : Handle<LoadHandler> Factory::NewLoadHandler(int data_count) {
4046 : Handle<Map> map;
4047 484655 : switch (data_count) {
4048 : case 1:
4049 441697 : map = load_handler1_map();
4050 441697 : break;
4051 : case 2:
4052 42953 : map = load_handler2_map();
4053 42953 : break;
4054 : case 3:
4055 5 : map = load_handler3_map();
4056 5 : break;
4057 : default:
4058 0 : UNREACHABLE();
4059 : break;
4060 : }
4061 969294 : return handle(LoadHandler::cast(New(map, AllocationType::kOld)), isolate());
4062 : }
4063 :
4064 238761 : Handle<StoreHandler> Factory::NewStoreHandler(int data_count) {
4065 : Handle<Map> map;
4066 238761 : switch (data_count) {
4067 : case 0:
4068 67122 : map = store_handler0_map();
4069 67122 : break;
4070 : case 1:
4071 169939 : map = store_handler1_map();
4072 169939 : break;
4073 : case 2:
4074 1695 : map = store_handler2_map();
4075 1695 : break;
4076 : case 3:
4077 5 : map = store_handler3_map();
4078 5 : break;
4079 : default:
4080 0 : UNREACHABLE();
4081 : break;
4082 : }
4083 477522 : return handle(StoreHandler::cast(New(map, AllocationType::kOld)), isolate());
4084 : }
4085 :
4086 204782 : void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp, JSRegExp::Type type,
4087 : Handle<String> source, JSRegExp::Flags flags,
4088 : Handle<Object> data) {
4089 : Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
4090 :
4091 204782 : store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
4092 409564 : store->set(JSRegExp::kSourceIndex, *source);
4093 : store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags));
4094 204782 : store->set(JSRegExp::kAtomPatternIndex, *data);
4095 409564 : regexp->set_data(*store);
4096 204782 : }
4097 :
4098 85576 : void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
4099 : JSRegExp::Type type, Handle<String> source,
4100 : JSRegExp::Flags flags, int capture_count) {
4101 : Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
4102 : Smi uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
4103 85576 : store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
4104 171152 : store->set(JSRegExp::kSourceIndex, *source);
4105 : store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags));
4106 : store->set(JSRegExp::kIrregexpLatin1CodeIndex, uninitialized);
4107 : store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
4108 85576 : store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::kZero);
4109 : store->set(JSRegExp::kIrregexpCaptureCountIndex, Smi::FromInt(capture_count));
4110 : store->set(JSRegExp::kIrregexpCaptureNameMapIndex, uninitialized);
4111 171152 : regexp->set_data(*store);
4112 85576 : }
4113 :
4114 136 : Handle<RegExpMatchInfo> Factory::NewRegExpMatchInfo() {
4115 : // Initially, the last match info consists of all fixed fields plus space for
4116 : // the match itself (i.e., 2 capture indices).
4117 : static const int kInitialSize = RegExpMatchInfo::kFirstCaptureIndex +
4118 : RegExpMatchInfo::kInitialCaptureIndices;
4119 :
4120 : Handle<FixedArray> elems = NewFixedArray(kInitialSize);
4121 : Handle<RegExpMatchInfo> result = Handle<RegExpMatchInfo>::cast(elems);
4122 :
4123 : result->SetNumberOfCaptureRegisters(RegExpMatchInfo::kInitialCaptureIndices);
4124 272 : result->SetLastSubject(*empty_string());
4125 272 : result->SetLastInput(*undefined_value());
4126 : result->SetCapture(0, 0);
4127 : result->SetCapture(1, 0);
4128 :
4129 136 : return result;
4130 : }
4131 :
4132 0 : Handle<Object> Factory::GlobalConstantFor(Handle<Name> name) {
4133 0 : if (Name::Equals(isolate(), name, undefined_string())) {
4134 0 : return undefined_value();
4135 : }
4136 0 : if (Name::Equals(isolate(), name, NaN_string())) return nan_value();
4137 0 : if (Name::Equals(isolate(), name, Infinity_string())) return infinity_value();
4138 : return Handle<Object>::null();
4139 : }
4140 :
4141 229688 : Handle<Object> Factory::ToBoolean(bool value) {
4142 477547 : return value ? true_value() : false_value();
4143 : }
4144 :
4145 3622 : Handle<String> Factory::ToPrimitiveHintString(ToPrimitiveHint hint) {
4146 3622 : switch (hint) {
4147 : case ToPrimitiveHint::kDefault:
4148 : return default_string();
4149 : case ToPrimitiveHint::kNumber:
4150 : return number_string();
4151 : case ToPrimitiveHint::kString:
4152 : return string_string();
4153 : }
4154 0 : UNREACHABLE();
4155 : }
4156 :
4157 555 : Handle<Map> Factory::CreateSloppyFunctionMap(
4158 : FunctionMode function_mode, MaybeHandle<JSFunction> maybe_empty_function) {
4159 : bool has_prototype = IsFunctionModeWithPrototype(function_mode);
4160 : int header_size = has_prototype ? JSFunction::kSizeWithPrototype
4161 555 : : JSFunction::kSizeWithoutPrototype;
4162 555 : int descriptors_count = has_prototype ? 5 : 4;
4163 : int inobject_properties_count = 0;
4164 555 : if (IsFunctionModeWithName(function_mode)) ++inobject_properties_count;
4165 :
4166 : Handle<Map> map = NewMap(
4167 555 : JS_FUNCTION_TYPE, header_size + inobject_properties_count * kTaggedSize,
4168 555 : TERMINAL_FAST_ELEMENTS_KIND, inobject_properties_count);
4169 1110 : map->set_has_prototype_slot(has_prototype);
4170 : map->set_is_constructor(has_prototype);
4171 : map->set_is_callable(true);
4172 : Handle<JSFunction> empty_function;
4173 555 : if (maybe_empty_function.ToHandle(&empty_function)) {
4174 444 : Map::SetPrototype(isolate(), map, empty_function);
4175 : }
4176 :
4177 : //
4178 : // Setup descriptors array.
4179 : //
4180 555 : Map::EnsureDescriptorSlack(isolate(), map, descriptors_count);
4181 :
4182 : PropertyAttributes ro_attribs =
4183 : static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
4184 : PropertyAttributes rw_attribs =
4185 : static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
4186 : PropertyAttributes roc_attribs =
4187 : static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
4188 :
4189 : int field_index = 0;
4190 : STATIC_ASSERT(JSFunction::kLengthDescriptorIndex == 0);
4191 : { // Add length accessor.
4192 : Descriptor d = Descriptor::AccessorConstant(
4193 555 : length_string(), function_length_accessor(), roc_attribs);
4194 555 : map->AppendDescriptor(isolate(), &d);
4195 : }
4196 :
4197 : STATIC_ASSERT(JSFunction::kNameDescriptorIndex == 1);
4198 555 : if (IsFunctionModeWithName(function_mode)) {
4199 : // Add name field.
4200 : Handle<Name> name = isolate()->factory()->name_string();
4201 : Descriptor d = Descriptor::DataField(isolate(), name, field_index++,
4202 111 : roc_attribs, Representation::Tagged());
4203 111 : map->AppendDescriptor(isolate(), &d);
4204 :
4205 : } else {
4206 : // Add name accessor.
4207 : Descriptor d = Descriptor::AccessorConstant(
4208 444 : name_string(), function_name_accessor(), roc_attribs);
4209 444 : map->AppendDescriptor(isolate(), &d);
4210 : }
4211 : { // Add arguments accessor.
4212 : Descriptor d = Descriptor::AccessorConstant(
4213 555 : arguments_string(), function_arguments_accessor(), ro_attribs);
4214 555 : map->AppendDescriptor(isolate(), &d);
4215 : }
4216 : { // Add caller accessor.
4217 : Descriptor d = Descriptor::AccessorConstant(
4218 555 : caller_string(), function_caller_accessor(), ro_attribs);
4219 555 : map->AppendDescriptor(isolate(), &d);
4220 : }
4221 555 : if (IsFunctionModeWithPrototype(function_mode)) {
4222 : // Add prototype accessor.
4223 : PropertyAttributes attribs =
4224 : IsFunctionModeWithWritablePrototype(function_mode) ? rw_attribs
4225 333 : : ro_attribs;
4226 : Descriptor d = Descriptor::AccessorConstant(
4227 333 : prototype_string(), function_prototype_accessor(), attribs);
4228 333 : map->AppendDescriptor(isolate(), &d);
4229 : }
4230 : DCHECK_EQ(inobject_properties_count, field_index);
4231 555 : LOG(isolate(), MapDetails(*map));
4232 555 : return map;
4233 : }
4234 :
4235 999 : Handle<Map> Factory::CreateStrictFunctionMap(
4236 : FunctionMode function_mode, Handle<JSFunction> empty_function) {
4237 : bool has_prototype = IsFunctionModeWithPrototype(function_mode);
4238 : int header_size = has_prototype ? JSFunction::kSizeWithPrototype
4239 999 : : JSFunction::kSizeWithoutPrototype;
4240 : int inobject_properties_count = 0;
4241 999 : if (IsFunctionModeWithName(function_mode)) ++inobject_properties_count;
4242 999 : if (IsFunctionModeWithHomeObject(function_mode)) ++inobject_properties_count;
4243 999 : int descriptors_count = (IsFunctionModeWithPrototype(function_mode) ? 3 : 2) +
4244 999 : inobject_properties_count;
4245 :
4246 : Handle<Map> map = NewMap(
4247 999 : JS_FUNCTION_TYPE, header_size + inobject_properties_count * kTaggedSize,
4248 999 : TERMINAL_FAST_ELEMENTS_KIND, inobject_properties_count);
4249 1998 : map->set_has_prototype_slot(has_prototype);
4250 : map->set_is_constructor(has_prototype);
4251 : map->set_is_callable(true);
4252 999 : Map::SetPrototype(isolate(), map, empty_function);
4253 :
4254 : //
4255 : // Setup descriptors array.
4256 : //
4257 999 : Map::EnsureDescriptorSlack(isolate(), map, descriptors_count);
4258 :
4259 : PropertyAttributes rw_attribs =
4260 : static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
4261 : PropertyAttributes ro_attribs =
4262 : static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
4263 : PropertyAttributes roc_attribs =
4264 : static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
4265 :
4266 : int field_index = 0;
4267 : STATIC_ASSERT(JSFunction::kLengthDescriptorIndex == 0);
4268 : { // Add length accessor.
4269 : Descriptor d = Descriptor::AccessorConstant(
4270 999 : length_string(), function_length_accessor(), roc_attribs);
4271 999 : map->AppendDescriptor(isolate(), &d);
4272 : }
4273 :
4274 : STATIC_ASSERT(JSFunction::kNameDescriptorIndex == 1);
4275 999 : if (IsFunctionModeWithName(function_mode)) {
4276 : // Add name field.
4277 : Handle<Name> name = isolate()->factory()->name_string();
4278 : Descriptor d = Descriptor::DataField(isolate(), name, field_index++,
4279 444 : roc_attribs, Representation::Tagged());
4280 444 : map->AppendDescriptor(isolate(), &d);
4281 :
4282 : } else {
4283 : // Add name accessor.
4284 : Descriptor d = Descriptor::AccessorConstant(
4285 555 : name_string(), function_name_accessor(), roc_attribs);
4286 555 : map->AppendDescriptor(isolate(), &d);
4287 : }
4288 :
4289 : STATIC_ASSERT(JSFunction::kMaybeHomeObjectDescriptorIndex == 2);
4290 999 : if (IsFunctionModeWithHomeObject(function_mode)) {
4291 : // Add home object field.
4292 : Handle<Name> name = isolate()->factory()->home_object_symbol();
4293 : Descriptor d = Descriptor::DataField(isolate(), name, field_index++,
4294 444 : DONT_ENUM, Representation::Tagged());
4295 444 : map->AppendDescriptor(isolate(), &d);
4296 : }
4297 :
4298 999 : if (IsFunctionModeWithPrototype(function_mode)) {
4299 : // Add prototype accessor.
4300 : PropertyAttributes attribs =
4301 : IsFunctionModeWithWritablePrototype(function_mode) ? rw_attribs
4302 555 : : ro_attribs;
4303 : Descriptor d = Descriptor::AccessorConstant(
4304 555 : prototype_string(), function_prototype_accessor(), attribs);
4305 555 : map->AppendDescriptor(isolate(), &d);
4306 : }
4307 : DCHECK_EQ(inobject_properties_count, field_index);
4308 999 : LOG(isolate(), MapDetails(*map));
4309 999 : return map;
4310 : }
4311 :
4312 111 : Handle<Map> Factory::CreateClassFunctionMap(Handle<JSFunction> empty_function) {
4313 111 : Handle<Map> map = NewMap(JS_FUNCTION_TYPE, JSFunction::kSizeWithPrototype);
4314 111 : map->set_has_prototype_slot(true);
4315 : map->set_is_constructor(true);
4316 : map->set_is_prototype_map(true);
4317 : map->set_is_callable(true);
4318 111 : Map::SetPrototype(isolate(), map, empty_function);
4319 :
4320 : //
4321 : // Setup descriptors array.
4322 : //
4323 111 : Map::EnsureDescriptorSlack(isolate(), map, 2);
4324 :
4325 : PropertyAttributes ro_attribs =
4326 : static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
4327 : PropertyAttributes roc_attribs =
4328 : static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
4329 :
4330 : STATIC_ASSERT(JSFunction::kLengthDescriptorIndex == 0);
4331 : { // Add length accessor.
4332 : Descriptor d = Descriptor::AccessorConstant(
4333 111 : length_string(), function_length_accessor(), roc_attribs);
4334 111 : map->AppendDescriptor(isolate(), &d);
4335 : }
4336 :
4337 : {
4338 : // Add prototype accessor.
4339 : Descriptor d = Descriptor::AccessorConstant(
4340 111 : prototype_string(), function_prototype_accessor(), ro_attribs);
4341 111 : map->AppendDescriptor(isolate(), &d);
4342 : }
4343 111 : LOG(isolate(), MapDetails(*map));
4344 111 : return map;
4345 : }
4346 :
4347 13832 : Handle<JSPromise> Factory::NewJSPromiseWithoutHook(AllocationType allocation) {
4348 : Handle<JSPromise> promise = Handle<JSPromise>::cast(
4349 13832 : NewJSObject(isolate()->promise_function(), allocation));
4350 13832 : promise->set_reactions_or_result(Smi::kZero);
4351 : promise->set_flags(0);
4352 : for (int i = 0; i < v8::Promise::kEmbedderFieldCount; i++) {
4353 : promise->SetEmbedderField(i, Smi::kZero);
4354 : }
4355 13832 : return promise;
4356 : }
4357 :
4358 9504 : Handle<JSPromise> Factory::NewJSPromise(AllocationType allocation) {
4359 9504 : Handle<JSPromise> promise = NewJSPromiseWithoutHook(allocation);
4360 9504 : isolate()->RunPromiseHook(PromiseHookType::kInit, promise, undefined_value());
4361 9504 : return promise;
4362 : }
4363 :
4364 3581706 : Handle<CallHandlerInfo> Factory::NewCallHandlerInfo(bool has_no_side_effect) {
4365 : Handle<Map> map = has_no_side_effect
4366 : ? side_effect_free_call_handler_info_map()
4367 7163412 : : side_effect_call_handler_info_map();
4368 : Handle<CallHandlerInfo> info(
4369 7163413 : CallHandlerInfo::cast(New(map, AllocationType::kOld)), isolate());
4370 3581707 : Object undefined_value = ReadOnlyRoots(isolate()).undefined_value();
4371 3581707 : info->set_callback(undefined_value);
4372 3581707 : info->set_js_callback(undefined_value);
4373 3581706 : info->set_data(undefined_value);
4374 3581709 : return info;
4375 : }
4376 :
4377 : // static
4378 238372 : NewFunctionArgs NewFunctionArgs::ForWasm(
4379 : Handle<String> name,
4380 : Handle<WasmExportedFunctionData> exported_function_data, Handle<Map> map) {
4381 : NewFunctionArgs args;
4382 238372 : args.name_ = name;
4383 238372 : args.maybe_map_ = map;
4384 238372 : args.maybe_exported_function_data_ = exported_function_data;
4385 238372 : args.language_mode_ = LanguageMode::kSloppy;
4386 238372 : args.prototype_mutability_ = MUTABLE;
4387 :
4388 238372 : return args;
4389 : }
4390 :
4391 : // static
4392 227 : NewFunctionArgs NewFunctionArgs::ForBuiltin(Handle<String> name,
4393 : Handle<Map> map, int builtin_id) {
4394 : DCHECK(Builtins::IsBuiltinId(builtin_id));
4395 :
4396 : NewFunctionArgs args;
4397 227 : args.name_ = name;
4398 227 : args.maybe_map_ = map;
4399 227 : args.maybe_builtin_id_ = builtin_id;
4400 227 : args.language_mode_ = LanguageMode::kStrict;
4401 227 : args.prototype_mutability_ = MUTABLE;
4402 :
4403 : args.SetShouldSetLanguageMode();
4404 :
4405 227 : return args;
4406 : }
4407 :
4408 : // static
4409 84754 : NewFunctionArgs NewFunctionArgs::ForFunctionWithoutCode(
4410 : Handle<String> name, Handle<Map> map, LanguageMode language_mode) {
4411 : NewFunctionArgs args;
4412 84935 : args.name_ = name;
4413 84935 : args.maybe_map_ = map;
4414 84935 : args.maybe_builtin_id_ = Builtins::kIllegal;
4415 84935 : args.language_mode_ = language_mode;
4416 84935 : args.prototype_mutability_ = MUTABLE;
4417 :
4418 : args.SetShouldSetLanguageMode();
4419 :
4420 84754 : return args;
4421 : }
4422 :
4423 : // static
4424 262866 : NewFunctionArgs NewFunctionArgs::ForBuiltinWithPrototype(
4425 : Handle<String> name, Handle<HeapObject> prototype, InstanceType type,
4426 : int instance_size, int inobject_properties, int builtin_id,
4427 : MutableMode prototype_mutability) {
4428 : DCHECK(Builtins::IsBuiltinId(builtin_id));
4429 :
4430 : NewFunctionArgs args;
4431 262866 : args.name_ = name;
4432 262866 : args.type_ = type;
4433 262866 : args.instance_size_ = instance_size;
4434 262866 : args.inobject_properties_ = inobject_properties;
4435 262866 : args.maybe_prototype_ = prototype;
4436 262866 : args.maybe_builtin_id_ = builtin_id;
4437 262866 : args.language_mode_ = LanguageMode::kStrict;
4438 262866 : args.prototype_mutability_ = prototype_mutability;
4439 :
4440 : args.SetShouldCreateAndSetInitialMap();
4441 : args.SetShouldSetPrototype();
4442 : args.SetShouldSetLanguageMode();
4443 :
4444 262866 : return args;
4445 : }
4446 :
4447 : // static
4448 1684174 : NewFunctionArgs NewFunctionArgs::ForBuiltinWithoutPrototype(
4449 : Handle<String> name, int builtin_id, LanguageMode language_mode) {
4450 : DCHECK(Builtins::IsBuiltinId(builtin_id));
4451 :
4452 : NewFunctionArgs args;
4453 1684174 : args.name_ = name;
4454 1684174 : args.maybe_builtin_id_ = builtin_id;
4455 1684174 : args.language_mode_ = language_mode;
4456 1684174 : args.prototype_mutability_ = MUTABLE;
4457 :
4458 : args.SetShouldSetLanguageMode();
4459 :
4460 1684174 : return args;
4461 : }
4462 :
4463 0 : void NewFunctionArgs::SetShouldCreateAndSetInitialMap() {
4464 : // Needed to create the initial map.
4465 : maybe_prototype_.Assert();
4466 : DCHECK_NE(kUninitialized, instance_size_);
4467 : DCHECK_NE(kUninitialized, inobject_properties_);
4468 :
4469 262866 : should_create_and_set_initial_map_ = true;
4470 0 : }
4471 :
4472 0 : void NewFunctionArgs::SetShouldSetPrototype() {
4473 : maybe_prototype_.Assert();
4474 262866 : should_set_prototype_ = true;
4475 0 : }
4476 :
4477 0 : void NewFunctionArgs::SetShouldSetLanguageMode() {
4478 : DCHECK(language_mode_ == LanguageMode::kStrict ||
4479 : language_mode_ == LanguageMode::kSloppy);
4480 2032202 : should_set_language_mode_ = true;
4481 0 : }
4482 :
4483 2270575 : Handle<Map> NewFunctionArgs::GetMap(Isolate* isolate) const {
4484 2270575 : if (!maybe_map_.is_null()) {
4485 : return maybe_map_.ToHandleChecked();
4486 1947043 : } else if (maybe_prototype_.is_null()) {
4487 1684176 : return is_strict(language_mode_)
4488 : ? isolate->strict_function_without_prototype_map()
4489 1684176 : : isolate->sloppy_function_without_prototype_map();
4490 : } else {
4491 : DCHECK(!maybe_prototype_.is_null());
4492 262867 : switch (prototype_mutability_) {
4493 : case MUTABLE:
4494 71488 : return is_strict(language_mode_) ? isolate->strict_function_map()
4495 71488 : : isolate->sloppy_function_map();
4496 : case IMMUTABLE:
4497 191379 : return is_strict(language_mode_)
4498 : ? isolate->strict_function_with_readonly_prototype_map()
4499 191379 : : isolate->sloppy_function_with_readonly_prototype_map();
4500 : }
4501 : }
4502 0 : UNREACHABLE();
4503 : }
4504 :
4505 : } // namespace internal
4506 121996 : } // namespace v8
|