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