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