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