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/factory.h"
6 :
7 : #include "src/accessors.h"
8 : #include "src/allocation-site-scopes.h"
9 : #include "src/ast/ast.h"
10 : #include "src/base/bits.h"
11 : #include "src/bootstrapper.h"
12 : #include "src/compiler.h"
13 : #include "src/conversions.h"
14 : #include "src/isolate-inl.h"
15 : #include "src/macro-assembler.h"
16 : #include "src/objects/frame-array-inl.h"
17 : #include "src/objects/module-info.h"
18 : #include "src/objects/scope-info.h"
19 :
20 : namespace v8 {
21 : namespace internal {
22 :
23 :
24 : // Calls the FUNCTION_CALL function and retries it up to three times
25 : // to guarantee that any allocations performed during the call will
26 : // succeed if there's enough memory.
27 : //
28 : // Warning: Do not use the identifiers __object__, __maybe_object__,
29 : // __allocation__ or __scope__ in a call to this macro.
30 :
31 : #define RETURN_OBJECT_UNLESS_RETRY(ISOLATE, TYPE) \
32 : if (__allocation__.To(&__object__)) { \
33 : DCHECK(__object__ != (ISOLATE)->heap()->exception()); \
34 : return Handle<TYPE>(TYPE::cast(__object__), ISOLATE); \
35 : }
36 :
37 : #define CALL_HEAP_FUNCTION(ISOLATE, FUNCTION_CALL, TYPE) \
38 : do { \
39 : AllocationResult __allocation__ = FUNCTION_CALL; \
40 : Object* __object__ = NULL; \
41 : RETURN_OBJECT_UNLESS_RETRY(ISOLATE, TYPE) \
42 : /* Two GCs before panicking. In newspace will almost always succeed. */ \
43 : for (int __i__ = 0; __i__ < 2; __i__++) { \
44 : (ISOLATE)->heap()->CollectGarbage( \
45 : __allocation__.RetrySpace(), \
46 : GarbageCollectionReason::kAllocationFailure); \
47 : __allocation__ = FUNCTION_CALL; \
48 : RETURN_OBJECT_UNLESS_RETRY(ISOLATE, TYPE) \
49 : } \
50 : (ISOLATE)->counters()->gc_last_resort_from_handles()->Increment(); \
51 : (ISOLATE)->heap()->CollectAllAvailableGarbage( \
52 : GarbageCollectionReason::kLastResort); \
53 : { \
54 : AlwaysAllocateScope __scope__(ISOLATE); \
55 : __allocation__ = FUNCTION_CALL; \
56 : } \
57 : RETURN_OBJECT_UNLESS_RETRY(ISOLATE, TYPE) \
58 : /* TODO(1181417): Fix this. */ \
59 : v8::internal::Heap::FatalProcessOutOfMemory("CALL_AND_RETRY_LAST", true); \
60 : return Handle<TYPE>(); \
61 : } while (false)
62 :
63 : template<typename T>
64 68091697 : Handle<T> Factory::New(Handle<Map> map, AllocationSpace space) {
65 204278627 : CALL_HEAP_FUNCTION(
66 : isolate(),
67 : isolate()->heap()->Allocate(*map, space),
68 : T);
69 : }
70 :
71 :
72 : template<typename T>
73 : Handle<T> Factory::New(Handle<Map> map,
74 : AllocationSpace space,
75 : Handle<AllocationSite> allocation_site) {
76 : CALL_HEAP_FUNCTION(
77 : isolate(),
78 : isolate()->heap()->Allocate(*map, space, *allocation_site),
79 : T);
80 : }
81 :
82 :
83 204486 : Handle<HeapObject> Factory::NewFillerObject(int size,
84 : bool double_align,
85 : AllocationSpace space) {
86 683980 : CALL_HEAP_FUNCTION(
87 : isolate(),
88 : isolate()->heap()->AllocateFillerObject(size, double_align, space),
89 : HeapObject);
90 : }
91 :
92 :
93 500740 : Handle<PrototypeInfo> Factory::NewPrototypeInfo() {
94 : Handle<PrototypeInfo> result =
95 500740 : Handle<PrototypeInfo>::cast(NewStruct(PROTOTYPE_INFO_TYPE));
96 500740 : result->set_prototype_users(WeakFixedArray::Empty());
97 : result->set_registry_slot(PrototypeInfo::UNREGISTERED);
98 500740 : result->set_validity_cell(Smi::kZero);
99 : result->set_bit_field(0);
100 500740 : return result;
101 : }
102 :
103 249808 : Handle<Tuple2> Factory::NewTuple2(Handle<Object> value1,
104 : Handle<Object> value2) {
105 249808 : Handle<Tuple2> result = Handle<Tuple2>::cast(NewStruct(TUPLE2_TYPE));
106 249808 : result->set_value1(*value1);
107 249808 : result->set_value2(*value2);
108 249808 : return result;
109 : }
110 :
111 2581551 : Handle<Tuple3> Factory::NewTuple3(Handle<Object> value1, Handle<Object> value2,
112 : Handle<Object> value3) {
113 2581551 : Handle<Tuple3> result = Handle<Tuple3>::cast(NewStruct(TUPLE3_TYPE));
114 2581550 : result->set_value1(*value1);
115 2581550 : result->set_value2(*value2);
116 2581550 : result->set_value3(*value3);
117 2581550 : return result;
118 : }
119 :
120 1219288 : Handle<ContextExtension> Factory::NewContextExtension(
121 : Handle<ScopeInfo> scope_info, Handle<Object> extension) {
122 : Handle<ContextExtension> result =
123 1219288 : Handle<ContextExtension>::cast(NewStruct(CONTEXT_EXTENSION_TYPE));
124 1219288 : result->set_scope_info(*scope_info);
125 1219288 : result->set_extension(*extension);
126 1219288 : return result;
127 : }
128 :
129 293194 : Handle<ConstantElementsPair> Factory::NewConstantElementsPair(
130 : ElementsKind elements_kind, Handle<FixedArrayBase> constant_values) {
131 : Handle<ConstantElementsPair> result =
132 293194 : Handle<ConstantElementsPair>::cast(NewStruct(TUPLE2_TYPE));
133 293194 : result->set_elements_kind(elements_kind);
134 293194 : result->set_constant_values(*constant_values);
135 293194 : return result;
136 : }
137 :
138 258 : Handle<Oddball> Factory::NewOddball(Handle<Map> map, const char* to_string,
139 : Handle<Object> to_number,
140 : const char* type_of, byte kind) {
141 258 : Handle<Oddball> oddball = New<Oddball>(map, OLD_SPACE);
142 258 : Oddball::Initialize(isolate(), oddball, to_string, to_number, type_of, kind);
143 258 : return oddball;
144 : }
145 :
146 :
147 86576418 : Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
148 : DCHECK(0 <= size);
149 259740900 : CALL_HEAP_FUNCTION(
150 : isolate(),
151 : isolate()->heap()->AllocateFixedArray(size, pretenure),
152 : FixedArray);
153 : }
154 :
155 1488371 : MaybeHandle<FixedArray> Factory::TryNewFixedArray(int size,
156 : PretenureFlag pretenure) {
157 : DCHECK(0 <= size);
158 : AllocationResult allocation =
159 1488371 : isolate()->heap()->AllocateFixedArray(size, pretenure);
160 : Object* array = NULL;
161 1488371 : if (!allocation.To(&array)) return MaybeHandle<FixedArray>();
162 : return Handle<FixedArray>(FixedArray::cast(array), isolate());
163 : }
164 :
165 6281923 : Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
166 : PretenureFlag pretenure) {
167 : DCHECK(0 <= size);
168 18847221 : CALL_HEAP_FUNCTION(
169 : isolate(),
170 : isolate()->heap()->AllocateFixedArrayWithFiller(size,
171 : pretenure,
172 : *the_hole_value()),
173 : FixedArray);
174 : }
175 :
176 2904690 : Handle<FixedArray> Factory::NewUninitializedFixedArray(int size) {
177 8715322 : CALL_HEAP_FUNCTION(
178 : isolate(),
179 : isolate()->heap()->AllocateUninitializedFixedArray(size),
180 : FixedArray);
181 : }
182 :
183 669535 : Handle<BoilerplateDescription> Factory::NewBoilerplateDescription(
184 : int boilerplate, int all_properties, int index_keys, bool has_seen_proto) {
185 : DCHECK_GE(boilerplate, 0);
186 : DCHECK_GE(all_properties, index_keys);
187 : DCHECK_GE(index_keys, 0);
188 :
189 : int backing_store_size =
190 669535 : all_properties - index_keys - (has_seen_proto ? 1 : 0);
191 : DCHECK_GE(backing_store_size, 0);
192 669535 : bool has_different_size_backing_store = boilerplate != backing_store_size;
193 :
194 : // Space for name and value for every boilerplate property.
195 669535 : int size = 2 * boilerplate;
196 :
197 669535 : if (has_different_size_backing_store) {
198 : // An extra entry for the backing store size.
199 3343 : size++;
200 : }
201 :
202 : Handle<BoilerplateDescription> description =
203 669535 : Handle<BoilerplateDescription>::cast(NewFixedArray(size, TENURED));
204 :
205 669534 : if (has_different_size_backing_store) {
206 : DCHECK((boilerplate != (all_properties - index_keys)) || has_seen_proto);
207 3343 : description->set_backing_store_size(isolate(), backing_store_size);
208 : }
209 669534 : return description;
210 : }
211 :
212 902965 : Handle<FixedArrayBase> Factory::NewFixedDoubleArray(int size,
213 : PretenureFlag pretenure) {
214 : DCHECK(0 <= size);
215 2708981 : CALL_HEAP_FUNCTION(
216 : isolate(),
217 : isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
218 : FixedArrayBase);
219 : }
220 :
221 :
222 21 : Handle<FixedArrayBase> Factory::NewFixedDoubleArrayWithHoles(
223 : int size,
224 : PretenureFlag pretenure) {
225 : DCHECK(0 <= size);
226 21 : Handle<FixedArrayBase> array = NewFixedDoubleArray(size, pretenure);
227 21 : if (size > 0) {
228 : Handle<FixedDoubleArray>::cast(array)->FillWithHoles(0, size);
229 : }
230 21 : return array;
231 : }
232 :
233 1210075 : Handle<FrameArray> Factory::NewFrameArray(int number_of_frames,
234 : PretenureFlag pretenure) {
235 : DCHECK_LE(0, number_of_frames);
236 : Handle<FixedArray> result =
237 1210075 : NewFixedArrayWithHoles(FrameArray::LengthFor(number_of_frames));
238 : result->set(FrameArray::kFrameCountIndex, Smi::kZero);
239 1210075 : return Handle<FrameArray>::cast(result);
240 : }
241 :
242 79423 : Handle<OrderedHashSet> Factory::NewOrderedHashSet() {
243 79423 : return OrderedHashSet::Allocate(isolate(), OrderedHashSet::kMinCapacity);
244 : }
245 :
246 :
247 80032 : Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
248 80032 : return OrderedHashMap::Allocate(isolate(), OrderedHashMap::kMinCapacity);
249 : }
250 :
251 :
252 507487 : Handle<AccessorPair> Factory::NewAccessorPair() {
253 : Handle<AccessorPair> accessors =
254 507487 : Handle<AccessorPair>::cast(NewStruct(ACCESSOR_PAIR_TYPE));
255 507488 : accessors->set_getter(*null_value(), SKIP_WRITE_BARRIER);
256 507488 : accessors->set_setter(*null_value(), SKIP_WRITE_BARRIER);
257 507488 : return accessors;
258 : }
259 :
260 :
261 1080603 : Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
262 : Handle<TypeFeedbackInfo> info =
263 1080603 : Handle<TypeFeedbackInfo>::cast(NewStruct(TUPLE3_TYPE));
264 : info->initialize_storage();
265 1080614 : return info;
266 : }
267 :
268 :
269 : // Internalized strings are created in the old generation (data space).
270 24522791 : Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
271 : Utf8StringKey key(string, isolate()->heap()->HashSeed());
272 24522789 : return InternalizeStringWithKey(&key);
273 : }
274 :
275 :
276 206164 : Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
277 : OneByteStringKey key(string, isolate()->heap()->HashSeed());
278 206164 : return InternalizeStringWithKey(&key);
279 : }
280 :
281 :
282 115049 : Handle<String> Factory::InternalizeOneByteString(
283 : Handle<SeqOneByteString> string, int from, int length) {
284 : SeqOneByteSubStringKey key(string, from, length);
285 115049 : return InternalizeStringWithKey(&key);
286 : }
287 :
288 :
289 0 : Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
290 : TwoByteStringKey key(string, isolate()->heap()->HashSeed());
291 0 : return InternalizeStringWithKey(&key);
292 : }
293 :
294 :
295 : template<class StringTableKey>
296 : Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
297 24844004 : return StringTable::LookupKey(isolate(), key);
298 : }
299 :
300 :
301 65590303 : MaybeHandle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
302 : PretenureFlag pretenure) {
303 : int length = string.length();
304 65590303 : if (length == 0) return empty_string();
305 65548506 : if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
306 : Handle<SeqOneByteString> result;
307 129687954 : ASSIGN_RETURN_ON_EXCEPTION(
308 : isolate(),
309 : result,
310 : NewRawOneByteString(string.length(), pretenure),
311 : String);
312 :
313 : DisallowHeapAllocation no_gc;
314 : // Copy the characters into the new object.
315 : CopyChars(SeqOneByteString::cast(*result)->GetChars(),
316 : string.start(),
317 129687946 : length);
318 : return result;
319 : }
320 :
321 11050822 : MaybeHandle<String> Factory::NewStringFromUtf8(Vector<const char> string,
322 : PretenureFlag pretenure) {
323 : // Check for ASCII first since this is the common case.
324 : const char* start = string.start();
325 : int length = string.length();
326 11050822 : int non_ascii_start = String::NonAsciiStart(start, length);
327 11050826 : if (non_ascii_start >= length) {
328 : // If the string is ASCII, we do not need to convert the characters
329 : // since UTF8 is backwards compatible with ASCII.
330 11049296 : return NewStringFromOneByte(Vector<const uint8_t>::cast(string), pretenure);
331 : }
332 :
333 : // Non-ASCII and we need to decode.
334 : Access<UnicodeCache::Utf8Decoder>
335 1530 : decoder(isolate()->unicode_cache()->utf8_decoder());
336 : decoder->Reset(string.start() + non_ascii_start,
337 1530 : length - non_ascii_start);
338 1530 : int utf16_length = static_cast<int>(decoder->Utf16Length());
339 : DCHECK(utf16_length > 0);
340 : // Allocate string.
341 : Handle<SeqTwoByteString> result;
342 3060 : ASSIGN_RETURN_ON_EXCEPTION(
343 : isolate(), result,
344 : NewRawTwoByteString(non_ascii_start + utf16_length, pretenure),
345 : String);
346 : // Copy ASCII portion.
347 1530 : uint16_t* data = result->GetChars();
348 : const char* ascii_data = string.start();
349 2044513 : for (int i = 0; i < non_ascii_start; i++) {
350 2042983 : *data++ = *ascii_data++;
351 : }
352 : // Now write the remainder.
353 1530 : decoder->WriteUtf16(data, utf16_length);
354 : return result;
355 : }
356 :
357 182051 : MaybeHandle<String> Factory::NewStringFromUtf8SubString(
358 : Handle<SeqOneByteString> str, int begin, int length,
359 : PretenureFlag pretenure) {
360 : // Check for ASCII first since this is the common case.
361 182051 : const char* start = reinterpret_cast<const char*>(str->GetChars() + begin);
362 182051 : int non_ascii_start = String::NonAsciiStart(start, length);
363 182051 : if (non_ascii_start >= length) {
364 : // If the string is ASCII, we can just make a substring.
365 : // TODO(v8): the pretenure flag is ignored in this case.
366 545295 : return NewSubString(str, begin, begin + length);
367 : }
368 :
369 : // Non-ASCII and we need to decode.
370 : Access<UnicodeCache::Utf8Decoder> decoder(
371 286 : isolate()->unicode_cache()->utf8_decoder());
372 286 : decoder->Reset(start + non_ascii_start, length - non_ascii_start);
373 286 : int utf16_length = static_cast<int>(decoder->Utf16Length());
374 : DCHECK(utf16_length > 0);
375 : // Allocate string.
376 : Handle<SeqTwoByteString> result;
377 572 : ASSIGN_RETURN_ON_EXCEPTION(
378 : isolate(), result,
379 : NewRawTwoByteString(non_ascii_start + utf16_length, pretenure), String);
380 :
381 : // Reset the decoder, because the original {str} may have moved.
382 : const char* ascii_data =
383 286 : reinterpret_cast<const char*>(str->GetChars() + begin);
384 286 : decoder->Reset(ascii_data + non_ascii_start, length - non_ascii_start);
385 : // Copy ASCII portion.
386 286 : uint16_t* data = result->GetChars();
387 1066 : for (int i = 0; i < non_ascii_start; i++) {
388 780 : *data++ = *ascii_data++;
389 : }
390 : // Now write the remainder.
391 286 : decoder->WriteUtf16(data, utf16_length);
392 : return result;
393 : }
394 :
395 1725678 : MaybeHandle<String> Factory::NewStringFromTwoByte(const uc16* string,
396 : int length,
397 : PretenureFlag pretenure) {
398 1725678 : if (length == 0) return empty_string();
399 1725665 : if (String::IsOneByte(string, length)) {
400 1722911 : if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
401 : Handle<SeqOneByteString> result;
402 3424100 : ASSIGN_RETURN_ON_EXCEPTION(
403 : isolate(),
404 : result,
405 : NewRawOneByteString(length, pretenure),
406 : String);
407 1712054 : CopyChars(result->GetChars(), string, length);
408 : return result;
409 : } else {
410 : Handle<SeqTwoByteString> result;
411 5508 : ASSIGN_RETURN_ON_EXCEPTION(
412 : isolate(),
413 : result,
414 : NewRawTwoByteString(length, pretenure),
415 : String);
416 2754 : CopyChars(result->GetChars(), string, length);
417 : return result;
418 : }
419 : }
420 :
421 1724304 : MaybeHandle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
422 : PretenureFlag pretenure) {
423 1724304 : return NewStringFromTwoByte(string.start(), string.length(), pretenure);
424 : }
425 :
426 1378 : MaybeHandle<String> Factory::NewStringFromTwoByte(
427 : const ZoneVector<uc16>* string, PretenureFlag pretenure) {
428 1378 : return NewStringFromTwoByte(string->data(), static_cast<int>(string->size()),
429 1378 : pretenure);
430 : }
431 :
432 168851 : Handle<String> Factory::NewInternalizedStringFromUtf8(Vector<const char> str,
433 : int chars,
434 : uint32_t hash_field) {
435 506555 : CALL_HEAP_FUNCTION(
436 : isolate(),
437 : isolate()->heap()->AllocateInternalizedStringFromUtf8(
438 : str, chars, hash_field),
439 : String);
440 : }
441 :
442 :
443 10888457 : MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedString(
444 : Vector<const uint8_t> str,
445 : uint32_t hash_field) {
446 32665373 : CALL_HEAP_FUNCTION(
447 : isolate(),
448 : isolate()->heap()->AllocateOneByteInternalizedString(str, hash_field),
449 : String);
450 : }
451 :
452 :
453 115049 : MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedSubString(
454 : Handle<SeqOneByteString> string, int offset, int length,
455 : uint32_t hash_field) {
456 460196 : CALL_HEAP_FUNCTION(
457 : isolate(), isolate()->heap()->AllocateOneByteInternalizedString(
458 : Vector<const uint8_t>(string->GetChars() + offset, length),
459 : hash_field),
460 : String);
461 : }
462 :
463 :
464 30439 : MUST_USE_RESULT Handle<String> Factory::NewTwoByteInternalizedString(
465 : Vector<const uc16> str,
466 : uint32_t hash_field) {
467 91317 : CALL_HEAP_FUNCTION(
468 : isolate(),
469 : isolate()->heap()->AllocateTwoByteInternalizedString(str, hash_field),
470 : String);
471 : }
472 :
473 :
474 1893437 : Handle<String> Factory::NewInternalizedStringImpl(
475 : Handle<String> string, int chars, uint32_t hash_field) {
476 5680313 : CALL_HEAP_FUNCTION(
477 : isolate(),
478 : isolate()->heap()->AllocateInternalizedStringImpl(
479 : *string, chars, hash_field),
480 : String);
481 : }
482 :
483 : namespace {
484 :
485 10922 : MaybeHandle<Map> GetInternalizedStringMap(Factory* f, Handle<String> string) {
486 10922 : switch (string->map()->instance_type()) {
487 : case STRING_TYPE:
488 : return f->internalized_string_map();
489 : case ONE_BYTE_STRING_TYPE:
490 : return f->one_byte_internalized_string_map();
491 : case EXTERNAL_STRING_TYPE:
492 : return f->external_internalized_string_map();
493 : case EXTERNAL_ONE_BYTE_STRING_TYPE:
494 : return f->external_one_byte_internalized_string_map();
495 : case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
496 : return f->external_internalized_string_with_one_byte_data_map();
497 : case SHORT_EXTERNAL_STRING_TYPE:
498 : return f->short_external_internalized_string_map();
499 : case SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE:
500 : return f->short_external_one_byte_internalized_string_map();
501 : case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
502 : return f->short_external_internalized_string_with_one_byte_data_map();
503 : default: return MaybeHandle<Map>(); // No match found.
504 : }
505 : }
506 :
507 : } // namespace
508 :
509 1904346 : MaybeHandle<Map> Factory::InternalizedStringMapForString(
510 : Handle<String> string) {
511 : // If the string is in new space it cannot be used as internalized.
512 1904346 : if (isolate()->heap()->InNewSpace(*string)) return MaybeHandle<Map>();
513 :
514 10916 : return GetInternalizedStringMap(this, string);
515 : }
516 :
517 : template <class StringClass>
518 6 : Handle<StringClass> Factory::InternalizeExternalString(Handle<String> string) {
519 : Handle<StringClass> cast_string = Handle<StringClass>::cast(string);
520 12 : Handle<Map> map = GetInternalizedStringMap(this, string).ToHandleChecked();
521 6 : Handle<StringClass> external_string = New<StringClass>(map, OLD_SPACE);
522 : external_string->set_length(cast_string->length());
523 : external_string->set_hash_field(cast_string->hash_field());
524 : external_string->set_resource(nullptr);
525 : isolate()->heap()->RegisterExternalString(*external_string);
526 6 : return external_string;
527 : }
528 :
529 : template Handle<ExternalOneByteString>
530 : Factory::InternalizeExternalString<ExternalOneByteString>(Handle<String>);
531 : template Handle<ExternalTwoByteString>
532 : Factory::InternalizeExternalString<ExternalTwoByteString>(Handle<String>);
533 :
534 144509030 : MaybeHandle<SeqOneByteString> Factory::NewRawOneByteString(
535 : int length, PretenureFlag pretenure) {
536 144509030 : if (length > String::kMaxLength || length < 0) {
537 71 : THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqOneByteString);
538 : }
539 : DCHECK(length > 0); // Use Factory::empty_string() instead.
540 289027115 : CALL_HEAP_FUNCTION(
541 : isolate(),
542 : isolate()->heap()->AllocateRawOneByteString(length, pretenure),
543 : SeqOneByteString);
544 : }
545 :
546 :
547 40501389 : MaybeHandle<SeqTwoByteString> Factory::NewRawTwoByteString(
548 : int length, PretenureFlag pretenure) {
549 40501389 : if (length > String::kMaxLength || length < 0) {
550 21 : THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqTwoByteString);
551 : }
552 : DCHECK(length > 0); // Use Factory::empty_string() instead.
553 81004898 : CALL_HEAP_FUNCTION(
554 : isolate(),
555 : isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
556 : SeqTwoByteString);
557 : }
558 :
559 :
560 14055106 : Handle<String> Factory::LookupSingleCharacterStringFromCode(uint32_t code) {
561 14055106 : if (code <= String::kMaxOneByteCharCodeU) {
562 : {
563 : DisallowHeapAllocation no_allocation;
564 1600196 : Object* value = single_character_string_cache()->get(code);
565 1600196 : if (value != *undefined_value()) {
566 : return handle(String::cast(value), isolate());
567 : }
568 : }
569 : uint8_t buffer[1];
570 64121 : buffer[0] = static_cast<uint8_t>(code);
571 : Handle<String> result =
572 64121 : InternalizeOneByteString(Vector<const uint8_t>(buffer, 1));
573 64121 : single_character_string_cache()->set(code, *result);
574 64121 : return result;
575 : }
576 : DCHECK(code <= String::kMaxUtf16CodeUnitU);
577 :
578 24909820 : Handle<SeqTwoByteString> result = NewRawTwoByteString(1).ToHandleChecked();
579 : result->SeqTwoByteStringSet(0, static_cast<uint16_t>(code));
580 12454910 : return result;
581 : }
582 :
583 :
584 : // Returns true for a character in a range. Both limits are inclusive.
585 : static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
586 : // This makes uses of the the unsigned wraparound.
587 7326215 : return character - from <= to - from;
588 : }
589 :
590 :
591 7324208 : static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
592 : uint16_t c1,
593 : uint16_t c2) {
594 : // Numeric strings have a different hash algorithm not known by
595 : // LookupTwoCharsStringIfExists, so we skip this step for such strings.
596 14650423 : if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
597 : Handle<String> result;
598 7323341 : if (StringTable::LookupTwoCharsStringIfExists(isolate, c1, c2).
599 14646682 : ToHandle(&result)) {
600 21532 : return result;
601 : }
602 : }
603 :
604 : // Now we know the length is 2, we might as well make use of that fact
605 : // when building the new string.
606 7302676 : if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
607 : // We can do this.
608 : DCHECK(base::bits::IsPowerOfTwo32(String::kMaxOneByteCharCodeU +
609 : 1)); // because of this.
610 : Handle<SeqOneByteString> str =
611 10649224 : isolate->factory()->NewRawOneByteString(2).ToHandleChecked();
612 : uint8_t* dest = str->GetChars();
613 5324612 : dest[0] = static_cast<uint8_t>(c1);
614 5324612 : dest[1] = static_cast<uint8_t>(c2);
615 5324612 : return str;
616 : } else {
617 : Handle<SeqTwoByteString> str =
618 3956128 : isolate->factory()->NewRawTwoByteString(2).ToHandleChecked();
619 : uc16* dest = str->GetChars();
620 1978064 : dest[0] = c1;
621 1978064 : dest[1] = c2;
622 1978064 : return str;
623 : }
624 : }
625 :
626 :
627 : template<typename SinkChar, typename StringType>
628 8843143 : Handle<String> ConcatStringContent(Handle<StringType> result,
629 : Handle<String> first,
630 : Handle<String> second) {
631 : DisallowHeapAllocation pointer_stays_valid;
632 8843143 : SinkChar* sink = result->GetChars();
633 8843143 : String::WriteToFlat(*first, sink, 0, first->length());
634 8843143 : String::WriteToFlat(*second, sink + first->length(), 0, second->length());
635 8843143 : return result;
636 : }
637 :
638 :
639 73961045 : MaybeHandle<String> Factory::NewConsString(Handle<String> left,
640 : Handle<String> right) {
641 73961044 : if (left->IsThinString()) {
642 : left = handle(Handle<ThinString>::cast(left)->actual(), isolate());
643 : }
644 73961045 : if (right->IsThinString()) {
645 : right = handle(Handle<ThinString>::cast(right)->actual(), isolate());
646 : }
647 : int left_length = left->length();
648 73961045 : if (left_length == 0) return right;
649 : int right_length = right->length();
650 59001789 : if (right_length == 0) return left;
651 :
652 47130941 : int length = left_length + right_length;
653 :
654 47130941 : if (length == 2) {
655 : uint16_t c1 = left->Get(0);
656 : uint16_t c2 = right->Get(0);
657 6487531 : return MakeOrFindTwoCharacterString(isolate(), c1, c2);
658 : }
659 :
660 : // Make sure that an out of memory exception is thrown if the length
661 : // of the new cons string is too large.
662 40643410 : if (length > String::kMaxLength || length < 0) {
663 82 : THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
664 : }
665 :
666 : bool left_is_one_byte = left->IsOneByteRepresentation();
667 : bool right_is_one_byte = right->IsOneByteRepresentation();
668 40643328 : bool is_one_byte = left_is_one_byte && right_is_one_byte;
669 : bool is_one_byte_data_in_two_byte_string = false;
670 40643328 : if (!is_one_byte) {
671 : // At least one of the strings uses two-byte representation so we
672 : // can't use the fast case code for short one-byte strings below, but
673 : // we can try to save memory if all chars actually fit in one-byte.
674 : is_one_byte_data_in_two_byte_string =
675 13418717 : left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
676 12024506 : if (is_one_byte_data_in_two_byte_string) {
677 18 : isolate()->counters()->string_add_runtime_ext_to_one_byte()->Increment();
678 : }
679 : }
680 :
681 : // If the resulting string is small make a flat string.
682 40643328 : if (length < ConsString::kMinLength) {
683 : // Note that neither of the two inputs can be a slice because:
684 : STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
685 : DCHECK(left->IsFlat());
686 : DCHECK(right->IsFlat());
687 :
688 : STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
689 16197603 : if (is_one_byte) {
690 : Handle<SeqOneByteString> result =
691 14708920 : NewRawOneByteString(length).ToHandleChecked();
692 : DisallowHeapAllocation no_gc;
693 7354460 : uint8_t* dest = result->GetChars();
694 : // Copy left part.
695 : const uint8_t* src =
696 : left->IsExternalString()
697 : ? Handle<ExternalOneByteString>::cast(left)->GetChars()
698 14706844 : : Handle<SeqOneByteString>::cast(left)->GetChars();
699 7354460 : for (int i = 0; i < left_length; i++) *dest++ = src[i];
700 : // Copy right part.
701 : src = right->IsExternalString()
702 : ? Handle<ExternalOneByteString>::cast(right)->GetChars()
703 14707612 : : Handle<SeqOneByteString>::cast(right)->GetChars();
704 7354460 : for (int i = 0; i < right_length; i++) *dest++ = src[i];
705 : return result;
706 : }
707 :
708 : return (is_one_byte_data_in_two_byte_string)
709 : ? ConcatStringContent<uint8_t>(
710 8843143 : NewRawOneByteString(length).ToHandleChecked(), left, right)
711 : : ConcatStringContent<uc16>(
712 35372572 : NewRawTwoByteString(length).ToHandleChecked(), left, right);
713 : }
714 :
715 24445725 : bool one_byte = (is_one_byte || is_one_byte_data_in_two_byte_string);
716 24445725 : return NewConsString(left, right, length, one_byte);
717 : }
718 :
719 24445739 : Handle<String> Factory::NewConsString(Handle<String> left, Handle<String> right,
720 : int length, bool one_byte) {
721 : DCHECK(!left->IsThinString());
722 : DCHECK(!right->IsThinString());
723 : DCHECK_GE(length, ConsString::kMinLength);
724 : DCHECK_LE(length, String::kMaxLength);
725 :
726 : Handle<ConsString> result =
727 : one_byte ? New<ConsString>(cons_one_byte_string_map(), NEW_SPACE)
728 48891478 : : New<ConsString>(cons_string_map(), NEW_SPACE);
729 :
730 : DisallowHeapAllocation no_gc;
731 24445740 : WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
732 :
733 : result->set_hash_field(String::kEmptyHashField);
734 : result->set_length(length);
735 24445740 : result->set_first(*left, mode);
736 24445740 : result->set_second(*right, mode);
737 24445740 : return result;
738 : }
739 :
740 0 : Handle<String> Factory::NewSurrogatePairString(uint16_t lead, uint16_t trail) {
741 : DCHECK_GE(lead, 0xD800);
742 : DCHECK_LE(lead, 0xDBFF);
743 : DCHECK_GE(trail, 0xDC00);
744 : DCHECK_LE(trail, 0xDFFF);
745 :
746 : Handle<SeqTwoByteString> str =
747 0 : isolate()->factory()->NewRawTwoByteString(2).ToHandleChecked();
748 : uc16* dest = str->GetChars();
749 0 : dest[0] = lead;
750 0 : dest[1] = trail;
751 0 : return str;
752 : }
753 :
754 5809101 : Handle<String> Factory::NewProperSubString(Handle<String> str,
755 : int begin,
756 : int end) {
757 : #if VERIFY_HEAP
758 : if (FLAG_verify_heap) str->StringVerify();
759 : #endif
760 : DCHECK(begin > 0 || end < str->length());
761 :
762 5809101 : str = String::Flatten(str);
763 :
764 5809101 : int length = end - begin;
765 5809101 : if (length <= 0) return empty_string();
766 5702470 : if (length == 1) {
767 805213 : return LookupSingleCharacterStringFromCode(str->Get(begin));
768 : }
769 4897257 : if (length == 2) {
770 : // Optimization for 2-byte strings often used as keys in a decompression
771 : // dictionary. Check whether we already have the string in the string
772 : // table to prevent creation of many unnecessary strings.
773 : uint16_t c1 = str->Get(begin);
774 836677 : uint16_t c2 = str->Get(begin + 1);
775 836677 : return MakeOrFindTwoCharacterString(isolate(), c1, c2);
776 : }
777 :
778 4060580 : if (!FLAG_string_slices || length < SlicedString::kMinLength) {
779 467170 : if (str->IsOneByteRepresentation()) {
780 : Handle<SeqOneByteString> result =
781 904662 : NewRawOneByteString(length).ToHandleChecked();
782 452331 : uint8_t* dest = result->GetChars();
783 : DisallowHeapAllocation no_gc;
784 452331 : String::WriteToFlat(*str, dest, begin, end);
785 452331 : return result;
786 : } else {
787 : Handle<SeqTwoByteString> result =
788 29678 : NewRawTwoByteString(length).ToHandleChecked();
789 14839 : uc16* dest = result->GetChars();
790 : DisallowHeapAllocation no_gc;
791 14839 : String::WriteToFlat(*str, dest, begin, end);
792 14839 : return result;
793 : }
794 : }
795 :
796 : int offset = begin;
797 :
798 3593410 : if (str->IsSlicedString()) {
799 : Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
800 : str = Handle<String>(slice->parent(), isolate());
801 2865 : offset += slice->offset();
802 : }
803 3593410 : if (str->IsThinString()) {
804 : Handle<ThinString> thin = Handle<ThinString>::cast(str);
805 : str = handle(thin->actual(), isolate());
806 : }
807 :
808 : DCHECK(str->IsSeqString() || str->IsExternalString());
809 : Handle<Map> map = str->IsOneByteRepresentation()
810 : ? sliced_one_byte_string_map()
811 7186820 : : sliced_string_map();
812 3593410 : Handle<SlicedString> slice = New<SlicedString>(map, NEW_SPACE);
813 :
814 : slice->set_hash_field(String::kEmptyHashField);
815 : slice->set_length(length);
816 3593410 : slice->set_parent(*str);
817 : slice->set_offset(offset);
818 3593410 : return slice;
819 : }
820 :
821 :
822 8020 : MaybeHandle<String> Factory::NewExternalStringFromOneByte(
823 : const ExternalOneByteString::Resource* resource) {
824 8020 : size_t length = resource->length();
825 8020 : if (length > static_cast<size_t>(String::kMaxLength)) {
826 6 : THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
827 : }
828 8014 : if (length == 0) return empty_string();
829 :
830 : Handle<Map> map;
831 8001 : if (resource->IsCompressible()) {
832 : // TODO(hajimehoshi): Rename this to 'uncached_external_one_byte_string_map'
833 7 : map = short_external_one_byte_string_map();
834 : } else {
835 7998 : map = external_one_byte_string_map();
836 : }
837 : Handle<ExternalOneByteString> external_string =
838 8005 : New<ExternalOneByteString>(map, NEW_SPACE);
839 8006 : external_string->set_length(static_cast<int>(length));
840 : external_string->set_hash_field(String::kEmptyHashField);
841 : external_string->set_resource(resource);
842 :
843 : return external_string;
844 : }
845 :
846 :
847 22715 : MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
848 : const ExternalTwoByteString::Resource* resource) {
849 22715 : size_t length = resource->length();
850 22715 : if (length > static_cast<size_t>(String::kMaxLength)) {
851 6 : THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
852 : }
853 22709 : if (length == 0) return empty_string();
854 :
855 : // For small strings we check whether the resource contains only
856 : // one byte characters. If yes, we use a different string map.
857 : static const size_t kOneByteCheckLengthLimit = 32;
858 26220 : bool is_one_byte = length <= kOneByteCheckLengthLimit &&
859 3518 : String::IsOneByte(resource->data(), static_cast<int>(length));
860 : Handle<Map> map;
861 22702 : if (resource->IsCompressible()) {
862 : // TODO(hajimehoshi): Rename these to 'uncached_external_string_...'.
863 : map = is_one_byte ? short_external_string_with_one_byte_data_map()
864 0 : : short_external_string_map();
865 : } else {
866 : map = is_one_byte ? external_string_with_one_byte_data_map()
867 45404 : : external_string_map();
868 : }
869 : Handle<ExternalTwoByteString> external_string =
870 22702 : New<ExternalTwoByteString>(map, NEW_SPACE);
871 22702 : external_string->set_length(static_cast<int>(length));
872 : external_string->set_hash_field(String::kEmptyHashField);
873 : external_string->set_resource(resource);
874 :
875 : return external_string;
876 : }
877 :
878 18689 : Handle<ExternalOneByteString> Factory::NewNativeSourceString(
879 : const ExternalOneByteString::Resource* resource) {
880 18689 : size_t length = resource->length();
881 : DCHECK_LE(length, static_cast<size_t>(String::kMaxLength));
882 :
883 18689 : Handle<Map> map = native_source_string_map();
884 : Handle<ExternalOneByteString> external_string =
885 18689 : New<ExternalOneByteString>(map, OLD_SPACE);
886 18689 : external_string->set_length(static_cast<int>(length));
887 : external_string->set_hash_field(String::kEmptyHashField);
888 : external_string->set_resource(resource);
889 :
890 18689 : return external_string;
891 : }
892 :
893 0 : Handle<JSStringIterator> Factory::NewJSStringIterator(Handle<String> string) {
894 : Handle<Map> map(isolate()->native_context()->string_iterator_map(),
895 0 : isolate());
896 0 : Handle<String> flat_string = String::Flatten(string);
897 : Handle<JSStringIterator> iterator =
898 0 : Handle<JSStringIterator>::cast(NewJSObjectFromMap(map));
899 0 : iterator->set_string(*flat_string);
900 : iterator->set_index(0);
901 :
902 0 : return iterator;
903 : }
904 :
905 437306 : Handle<Symbol> Factory::NewSymbol() {
906 1311918 : CALL_HEAP_FUNCTION(
907 : isolate(),
908 : isolate()->heap()->AllocateSymbol(),
909 : Symbol);
910 : }
911 :
912 :
913 428494 : Handle<Symbol> Factory::NewPrivateSymbol() {
914 428494 : Handle<Symbol> symbol = NewSymbol();
915 : symbol->set_is_private(true);
916 428494 : return symbol;
917 : }
918 :
919 406 : Handle<JSPromise> Factory::NewJSPromise() {
920 : Handle<JSFunction> constructor(
921 812 : isolate()->native_context()->promise_function(), isolate());
922 : DCHECK(constructor->has_initial_map());
923 : Handle<Map> map(constructor->initial_map(), isolate());
924 :
925 : DCHECK(!map->is_prototype_map());
926 406 : Handle<JSObject> promise_obj = NewJSObjectFromMap(map);
927 : Handle<JSPromise> promise = Handle<JSPromise>::cast(promise_obj);
928 : promise->set_status(v8::Promise::kPending);
929 : promise->set_flags(0);
930 :
931 406 : isolate()->RunPromiseHook(PromiseHookType::kInit, promise, undefined_value());
932 406 : return promise;
933 : }
934 :
935 177 : Handle<Context> Factory::NewNativeContext() {
936 : Handle<FixedArray> array =
937 177 : NewFixedArray(Context::NATIVE_CONTEXT_SLOTS, TENURED);
938 : array->set_map_no_write_barrier(*native_context_map());
939 : Handle<Context> context = Handle<Context>::cast(array);
940 : context->set_native_context(*context);
941 : context->set_errors_thrown(Smi::kZero);
942 : context->set_math_random_index(Smi::kZero);
943 177 : Handle<WeakCell> weak_cell = NewWeakCell(context);
944 : context->set_self_weak_cell(*weak_cell);
945 : DCHECK(context->IsNativeContext());
946 177 : return context;
947 : }
948 :
949 :
950 11615 : Handle<Context> Factory::NewScriptContext(Handle<JSFunction> function,
951 : Handle<ScopeInfo> scope_info) {
952 : DCHECK_EQ(scope_info->scope_type(), SCRIPT_SCOPE);
953 : Handle<FixedArray> array =
954 11615 : NewFixedArray(scope_info->ContextLength(), TENURED);
955 : array->set_map_no_write_barrier(*script_context_map());
956 : Handle<Context> context = Handle<Context>::cast(array);
957 : context->set_closure(*function);
958 : context->set_previous(function->context());
959 : context->set_extension(*scope_info);
960 : context->set_native_context(function->native_context());
961 : DCHECK(context->IsScriptContext());
962 11615 : return context;
963 : }
964 :
965 :
966 79 : Handle<ScriptContextTable> Factory::NewScriptContextTable() {
967 79 : Handle<FixedArray> array = NewFixedArray(1);
968 : array->set_map_no_write_barrier(*script_context_table_map());
969 : Handle<ScriptContextTable> context_table =
970 : Handle<ScriptContextTable>::cast(array);
971 : context_table->set_used(0);
972 79 : return context_table;
973 : }
974 :
975 1875 : Handle<Context> Factory::NewModuleContext(Handle<Module> module,
976 : Handle<JSFunction> function,
977 : Handle<ScopeInfo> scope_info) {
978 : DCHECK_EQ(scope_info->scope_type(), MODULE_SCOPE);
979 : Handle<FixedArray> array =
980 1875 : NewFixedArray(scope_info->ContextLength(), TENURED);
981 : array->set_map_no_write_barrier(*module_context_map());
982 : Handle<Context> context = Handle<Context>::cast(array);
983 : context->set_closure(*function);
984 : context->set_previous(function->context());
985 : context->set_extension(*module);
986 : context->set_native_context(function->native_context());
987 : DCHECK(context->IsModuleContext());
988 1875 : return context;
989 : }
990 :
991 15 : Handle<Context> Factory::NewFunctionContext(int length,
992 : Handle<JSFunction> function,
993 : ScopeType scope_type) {
994 : DCHECK(function->shared()->scope_info()->scope_type() == scope_type);
995 : DCHECK(length >= Context::MIN_CONTEXT_SLOTS);
996 15 : Handle<FixedArray> array = NewFixedArray(length);
997 : Handle<Map> map;
998 15 : switch (scope_type) {
999 : case EVAL_SCOPE:
1000 : map = eval_context_map();
1001 0 : break;
1002 : case FUNCTION_SCOPE:
1003 : map = function_context_map();
1004 15 : break;
1005 : default:
1006 0 : UNREACHABLE();
1007 : }
1008 : array->set_map_no_write_barrier(*map);
1009 : Handle<Context> context = Handle<Context>::cast(array);
1010 : context->set_closure(*function);
1011 : context->set_previous(function->context());
1012 : context->set_extension(*the_hole_value());
1013 : context->set_native_context(function->native_context());
1014 15 : return context;
1015 : }
1016 :
1017 907440 : Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
1018 : Handle<Context> previous,
1019 : Handle<ScopeInfo> scope_info,
1020 : Handle<String> name,
1021 : Handle<Object> thrown_object) {
1022 : STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
1023 907440 : Handle<ContextExtension> extension = NewContextExtension(scope_info, name);
1024 907440 : Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
1025 : array->set_map_no_write_barrier(*catch_context_map());
1026 : Handle<Context> context = Handle<Context>::cast(array);
1027 : context->set_closure(*function);
1028 : context->set_previous(*previous);
1029 : context->set_extension(*extension);
1030 : context->set_native_context(previous->native_context());
1031 907440 : context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
1032 907440 : return context;
1033 : }
1034 :
1035 16414 : Handle<Context> Factory::NewDebugEvaluateContext(Handle<Context> previous,
1036 : Handle<ScopeInfo> scope_info,
1037 : Handle<JSReceiver> extension,
1038 : Handle<Context> wrapped,
1039 : Handle<StringSet> whitelist) {
1040 : STATIC_ASSERT(Context::WHITE_LIST_INDEX == Context::MIN_CONTEXT_SLOTS + 1);
1041 : DCHECK(scope_info->IsDebugEvaluateScope());
1042 : Handle<ContextExtension> context_extension = NewContextExtension(
1043 : scope_info, extension.is_null() ? Handle<Object>::cast(undefined_value())
1044 32828 : : Handle<Object>::cast(extension));
1045 16414 : Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS + 2);
1046 : array->set_map_no_write_barrier(*debug_evaluate_context_map());
1047 : Handle<Context> c = Handle<Context>::cast(array);
1048 16414 : c->set_closure(wrapped.is_null() ? previous->closure() : wrapped->closure());
1049 : c->set_previous(*previous);
1050 : c->set_native_context(previous->native_context());
1051 : c->set_extension(*context_extension);
1052 18252 : if (!wrapped.is_null()) c->set(Context::WRAPPED_CONTEXT_INDEX, *wrapped);
1053 31680 : if (!whitelist.is_null()) c->set(Context::WHITE_LIST_INDEX, *whitelist);
1054 16414 : return c;
1055 : }
1056 :
1057 294048 : Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
1058 : Handle<Context> previous,
1059 : Handle<ScopeInfo> scope_info,
1060 : Handle<JSReceiver> extension) {
1061 : Handle<ContextExtension> context_extension =
1062 294048 : NewContextExtension(scope_info, extension);
1063 294048 : Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS);
1064 : array->set_map_no_write_barrier(*with_context_map());
1065 : Handle<Context> context = Handle<Context>::cast(array);
1066 : context->set_closure(*function);
1067 : context->set_previous(*previous);
1068 : context->set_extension(*context_extension);
1069 : context->set_native_context(previous->native_context());
1070 294048 : return context;
1071 : }
1072 :
1073 :
1074 84072 : Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
1075 : Handle<Context> previous,
1076 : Handle<ScopeInfo> scope_info) {
1077 : DCHECK_EQ(scope_info->scope_type(), BLOCK_SCOPE);
1078 84072 : Handle<FixedArray> array = NewFixedArray(scope_info->ContextLength());
1079 : array->set_map_no_write_barrier(*block_context_map());
1080 : Handle<Context> context = Handle<Context>::cast(array);
1081 : context->set_closure(*function);
1082 : context->set_previous(*previous);
1083 : context->set_extension(*scope_info);
1084 : context->set_native_context(previous->native_context());
1085 84072 : return context;
1086 : }
1087 :
1088 16537239 : Handle<Struct> Factory::NewStruct(InstanceType type) {
1089 49611722 : CALL_HEAP_FUNCTION(
1090 : isolate(),
1091 : isolate()->heap()->AllocateStruct(type),
1092 : Struct);
1093 : }
1094 :
1095 88 : Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
1096 : int aliased_context_slot) {
1097 : Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
1098 88 : NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
1099 : entry->set_aliased_context_slot(aliased_context_slot);
1100 88 : return entry;
1101 : }
1102 :
1103 :
1104 124405 : Handle<AccessorInfo> Factory::NewAccessorInfo() {
1105 : Handle<AccessorInfo> info =
1106 124405 : Handle<AccessorInfo>::cast(NewStruct(ACCESSOR_INFO_TYPE));
1107 : info->set_flag(0); // Must clear the flag, it was initialized as undefined.
1108 : info->set_is_sloppy(true);
1109 124405 : return info;
1110 : }
1111 :
1112 :
1113 2094740 : Handle<Script> Factory::NewScript(Handle<String> source) {
1114 : // Create and initialize script object.
1115 12568451 : Heap* heap = isolate()->heap();
1116 2094740 : Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
1117 2094743 : script->set_source(*source);
1118 2094743 : script->set_name(heap->undefined_value());
1119 : script->set_id(isolate()->heap()->NextScriptId());
1120 : script->set_line_offset(0);
1121 : script->set_column_offset(0);
1122 2094742 : script->set_context_data(heap->undefined_value());
1123 : script->set_type(Script::TYPE_NORMAL);
1124 2094741 : script->set_wrapper(heap->undefined_value());
1125 2094743 : script->set_line_ends(heap->undefined_value());
1126 2094741 : script->set_eval_from_shared(heap->undefined_value());
1127 : script->set_eval_from_position(0);
1128 2094742 : script->set_shared_function_infos(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1129 : script->set_flags(0);
1130 : script->set_preparsed_scope_data(
1131 2094741 : PodArray<uint32_t>::cast(heap->empty_byte_array()));
1132 :
1133 4189483 : heap->set_script_list(*WeakFixedArray::Add(script_list(), script));
1134 2094743 : return script;
1135 : }
1136 :
1137 :
1138 4373607 : Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
1139 13120844 : CALL_HEAP_FUNCTION(isolate(),
1140 : isolate()->heap()->AllocateForeign(addr, pretenure),
1141 : Foreign);
1142 : }
1143 :
1144 :
1145 0 : Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
1146 0 : return NewForeign((Address) desc, TENURED);
1147 : }
1148 :
1149 :
1150 6532086 : Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
1151 : DCHECK(0 <= length);
1152 19596311 : CALL_HEAP_FUNCTION(
1153 : isolate(),
1154 : isolate()->heap()->AllocateByteArray(length, pretenure),
1155 : ByteArray);
1156 : }
1157 :
1158 :
1159 2103821 : Handle<BytecodeArray> Factory::NewBytecodeArray(
1160 : int length, const byte* raw_bytecodes, int frame_size, int parameter_count,
1161 : Handle<FixedArray> constant_pool) {
1162 : DCHECK(0 <= length);
1163 6311481 : CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateBytecodeArray(
1164 : length, raw_bytecodes, frame_size,
1165 : parameter_count, *constant_pool),
1166 : BytecodeArray);
1167 : }
1168 :
1169 :
1170 15830 : Handle<FixedTypedArrayBase> Factory::NewFixedTypedArrayWithExternalPointer(
1171 : int length, ExternalArrayType array_type, void* external_pointer,
1172 : PretenureFlag pretenure) {
1173 : DCHECK(0 <= length && length <= Smi::kMaxValue);
1174 47490 : CALL_HEAP_FUNCTION(
1175 : isolate(), isolate()->heap()->AllocateFixedTypedArrayWithExternalPointer(
1176 : length, array_type, external_pointer, pretenure),
1177 : FixedTypedArrayBase);
1178 : }
1179 :
1180 :
1181 714 : Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
1182 : int length, ExternalArrayType array_type, bool initialize,
1183 : PretenureFlag pretenure) {
1184 : DCHECK(0 <= length && length <= Smi::kMaxValue);
1185 2142 : CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateFixedTypedArray(
1186 : length, array_type, initialize, pretenure),
1187 : FixedTypedArrayBase);
1188 : }
1189 :
1190 15209244 : Handle<Cell> Factory::NewCell(Handle<Object> value) {
1191 : AllowDeferredHandleDereference convert_to_cell;
1192 45627766 : CALL_HEAP_FUNCTION(
1193 : isolate(),
1194 : isolate()->heap()->AllocateCell(*value),
1195 : Cell);
1196 : }
1197 :
1198 7472430 : Handle<Cell> Factory::NewNoClosuresCell(Handle<Object> value) {
1199 7472430 : Handle<Cell> cell = NewCell(value);
1200 : cell->set_map_no_write_barrier(*no_closures_cell_map());
1201 7472441 : return cell;
1202 : }
1203 :
1204 6123934 : Handle<Cell> Factory::NewOneClosureCell(Handle<Object> value) {
1205 6123934 : Handle<Cell> cell = NewCell(value);
1206 : cell->set_map_no_write_barrier(*one_closure_cell_map());
1207 6123931 : return cell;
1208 : }
1209 :
1210 2238 : Handle<Cell> Factory::NewManyClosuresCell(Handle<Object> value) {
1211 2238 : Handle<Cell> cell = NewCell(value);
1212 : cell->set_map_no_write_barrier(*many_closures_cell_map());
1213 2238 : return cell;
1214 : }
1215 :
1216 8854434 : Handle<PropertyCell> Factory::NewPropertyCell() {
1217 26563301 : CALL_HEAP_FUNCTION(
1218 : isolate(),
1219 : isolate()->heap()->AllocatePropertyCell(),
1220 : PropertyCell);
1221 : }
1222 :
1223 :
1224 39367614 : Handle<WeakCell> Factory::NewWeakCell(Handle<HeapObject> value) {
1225 : // It is safe to dereference the value because we are embedding it
1226 : // in cell and not inspecting its fields.
1227 : AllowDeferredHandleDereference convert_to_cell;
1228 118102864 : CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateWeakCell(*value),
1229 : WeakCell);
1230 : }
1231 :
1232 :
1233 634745 : Handle<TransitionArray> Factory::NewTransitionArray(int capacity) {
1234 1904235 : CALL_HEAP_FUNCTION(isolate(),
1235 : isolate()->heap()->AllocateTransitionArray(capacity),
1236 : TransitionArray);
1237 : }
1238 :
1239 :
1240 1272261 : Handle<AllocationSite> Factory::NewAllocationSite() {
1241 1272261 : Handle<Map> map = allocation_site_map();
1242 1272261 : Handle<AllocationSite> site = New<AllocationSite>(map, OLD_SPACE);
1243 1272262 : site->Initialize();
1244 :
1245 : // Link the site
1246 2544524 : site->set_weak_next(isolate()->heap()->allocation_sites_list());
1247 : isolate()->heap()->set_allocation_sites_list(*site);
1248 1272262 : return site;
1249 : }
1250 :
1251 :
1252 30946021 : Handle<Map> Factory::NewMap(InstanceType type,
1253 : int instance_size,
1254 : ElementsKind elements_kind) {
1255 92838064 : CALL_HEAP_FUNCTION(
1256 : isolate(),
1257 : isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
1258 : Map);
1259 : }
1260 :
1261 :
1262 624805 : Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> object) {
1263 1874424 : CALL_HEAP_FUNCTION(isolate(),
1264 : isolate()->heap()->CopyJSObject(*object, NULL),
1265 : JSObject);
1266 : }
1267 :
1268 :
1269 8940784 : Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
1270 : Handle<JSObject> object,
1271 : Handle<AllocationSite> site) {
1272 35763815 : CALL_HEAP_FUNCTION(isolate(),
1273 : isolate()->heap()->CopyJSObject(
1274 : *object,
1275 : site.is_null() ? NULL : *site),
1276 : JSObject);
1277 : }
1278 :
1279 :
1280 25846 : Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
1281 : Handle<Map> map) {
1282 77541 : CALL_HEAP_FUNCTION(isolate(),
1283 : isolate()->heap()->CopyFixedArrayWithMap(*array, *map),
1284 : FixedArray);
1285 : }
1286 :
1287 :
1288 5714280 : Handle<FixedArray> Factory::CopyFixedArrayAndGrow(Handle<FixedArray> array,
1289 : int grow_by,
1290 : PretenureFlag pretenure) {
1291 17143393 : CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->CopyFixedArrayAndGrow(
1292 : *array, grow_by, pretenure),
1293 : FixedArray);
1294 : }
1295 :
1296 3539637 : Handle<FixedArray> Factory::CopyFixedArrayUpTo(Handle<FixedArray> array,
1297 : int new_len,
1298 : PretenureFlag pretenure) {
1299 10619037 : CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->CopyFixedArrayUpTo(
1300 : *array, new_len, pretenure),
1301 : FixedArray);
1302 : }
1303 :
1304 980922 : Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
1305 2942862 : CALL_HEAP_FUNCTION(isolate(),
1306 : isolate()->heap()->CopyFixedArray(*array),
1307 : FixedArray);
1308 : }
1309 :
1310 :
1311 0 : Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
1312 : Handle<FixedArray> array) {
1313 : DCHECK(isolate()->heap()->InNewSpace(*array));
1314 0 : CALL_HEAP_FUNCTION(isolate(),
1315 : isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
1316 : FixedArray);
1317 : }
1318 :
1319 :
1320 4798 : Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
1321 : Handle<FixedDoubleArray> array) {
1322 14394 : CALL_HEAP_FUNCTION(isolate(),
1323 : isolate()->heap()->CopyFixedDoubleArray(*array),
1324 : FixedDoubleArray);
1325 : }
1326 :
1327 :
1328 55580313 : Handle<Object> Factory::NewNumber(double value,
1329 : PretenureFlag pretenure) {
1330 : // Materialize as a SMI if possible
1331 : int32_t int_value;
1332 55580313 : if (DoubleToSmiInteger(value, &int_value)) {
1333 19240564 : return handle(Smi::FromInt(int_value), isolate());
1334 : }
1335 :
1336 : // Materialize the value in the heap.
1337 36339745 : return NewHeapNumber(value, IMMUTABLE, pretenure);
1338 : }
1339 :
1340 :
1341 587101 : Handle<Object> Factory::NewNumberFromInt(int32_t value,
1342 : PretenureFlag pretenure) {
1343 587101 : if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
1344 : // Bypass NewNumber to avoid various redundant checks.
1345 : return NewHeapNumber(FastI2D(value), IMMUTABLE, pretenure);
1346 : }
1347 :
1348 :
1349 18527408 : Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1350 : PretenureFlag pretenure) {
1351 18527408 : int32_t int32v = static_cast<int32_t>(value);
1352 18527408 : if (int32v >= 0 && Smi::IsValid(int32v)) {
1353 18499967 : return handle(Smi::FromInt(int32v), isolate());
1354 : }
1355 27441 : return NewHeapNumber(FastUI2D(value), IMMUTABLE, pretenure);
1356 : }
1357 :
1358 36560980 : Handle<HeapNumber> Factory::NewHeapNumber(MutableMode mode,
1359 : PretenureFlag pretenure) {
1360 109713766 : CALL_HEAP_FUNCTION(isolate(),
1361 : isolate()->heap()->AllocateHeapNumber(mode, pretenure),
1362 : HeapNumber);
1363 : }
1364 :
1365 1137541 : Handle<Object> Factory::NewError(Handle<JSFunction> constructor,
1366 : MessageTemplate::Template template_index,
1367 : Handle<Object> arg0, Handle<Object> arg1,
1368 : Handle<Object> arg2) {
1369 : HandleScope scope(isolate());
1370 1137541 : if (isolate()->bootstrapper()->IsActive()) {
1371 : // During bootstrapping we cannot construct error objects.
1372 : return scope.CloseAndEscape(NewStringFromAsciiChecked(
1373 36 : MessageTemplate::TemplateString(template_index)));
1374 : }
1375 :
1376 1137505 : if (arg0.is_null()) arg0 = undefined_value();
1377 1137505 : if (arg1.is_null()) arg1 = undefined_value();
1378 1137505 : if (arg2.is_null()) arg2 = undefined_value();
1379 :
1380 : Handle<Object> result;
1381 1137505 : if (!ErrorUtils::MakeGenericError(isolate(), constructor, template_index,
1382 : arg0, arg1, arg2, SKIP_NONE)
1383 2275010 : .ToHandle(&result)) {
1384 : // If an exception is thrown while
1385 : // running the factory method, use the exception as the result.
1386 : DCHECK(isolate()->has_pending_exception());
1387 0 : result = handle(isolate()->pending_exception(), isolate());
1388 : isolate()->clear_pending_exception();
1389 : }
1390 :
1391 1137505 : return scope.CloseAndEscape(result);
1392 : }
1393 :
1394 :
1395 16929 : Handle<Object> Factory::NewError(Handle<JSFunction> constructor,
1396 : Handle<String> message) {
1397 : // Construct a new error object. If an exception is thrown, use the exception
1398 : // as the result.
1399 :
1400 : Handle<Object> no_caller;
1401 : MaybeHandle<Object> maybe_error =
1402 : ErrorUtils::Construct(isolate(), constructor, constructor, message,
1403 16929 : SKIP_NONE, no_caller, false);
1404 16929 : if (maybe_error.is_null()) {
1405 : DCHECK(isolate()->has_pending_exception());
1406 0 : maybe_error = handle(isolate()->pending_exception(), isolate());
1407 : isolate()->clear_pending_exception();
1408 : }
1409 :
1410 16929 : return maybe_error.ToHandleChecked();
1411 : }
1412 :
1413 328 : Handle<Object> Factory::NewInvalidStringLengthError() {
1414 : // Invalidate the "string length" protector.
1415 328 : if (isolate()->IsStringLengthOverflowIntact()) {
1416 135 : isolate()->InvalidateStringLengthOverflowProtector();
1417 : }
1418 328 : return NewRangeError(MessageTemplate::kInvalidStringLength);
1419 : }
1420 :
1421 : #define DEFINE_ERROR(NAME, name) \
1422 : Handle<Object> Factory::New##NAME(MessageTemplate::Template template_index, \
1423 : Handle<Object> arg0, Handle<Object> arg1, \
1424 : Handle<Object> arg2) { \
1425 : return NewError(isolate()->name##_function(), template_index, arg0, arg1, \
1426 : arg2); \
1427 : }
1428 84 : DEFINE_ERROR(Error, error)
1429 4340 : DEFINE_ERROR(EvalError, eval_error)
1430 21180 : DEFINE_ERROR(RangeError, range_error)
1431 187010 : DEFINE_ERROR(ReferenceError, reference_error)
1432 375005 : DEFINE_ERROR(SyntaxError, syntax_error)
1433 505464 : DEFINE_ERROR(TypeError, type_error)
1434 0 : DEFINE_ERROR(WasmCompileError, wasm_compile_error)
1435 0 : DEFINE_ERROR(WasmLinkError, wasm_link_error)
1436 36243 : DEFINE_ERROR(WasmRuntimeError, wasm_runtime_error)
1437 : #undef DEFINE_ERROR
1438 :
1439 26519071 : Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1440 : Handle<SharedFunctionInfo> info,
1441 : Handle<Object> context_or_undefined,
1442 : PretenureFlag pretenure) {
1443 26519071 : AllocationSpace space = pretenure == TENURED ? OLD_SPACE : NEW_SPACE;
1444 26519071 : Handle<JSFunction> function = New<JSFunction>(map, space);
1445 : DCHECK(context_or_undefined->IsContext() ||
1446 : context_or_undefined->IsUndefined(isolate()));
1447 :
1448 26519080 : function->initialize_properties();
1449 26519080 : function->initialize_elements();
1450 26519076 : function->set_shared(*info);
1451 26519078 : function->set_code(info->code());
1452 26519071 : function->set_context(*context_or_undefined);
1453 26519076 : function->set_prototype_or_initial_map(*the_hole_value());
1454 26519080 : function->set_feedback_vector_cell(*undefined_cell());
1455 26519081 : function->set_next_function_link(*undefined_value(), SKIP_WRITE_BARRIER);
1456 26519079 : isolate()->heap()->InitializeJSObjectBody(*function, *map, JSFunction::kSize);
1457 26519079 : return function;
1458 : }
1459 :
1460 :
1461 563002 : Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1462 : Handle<String> name,
1463 : MaybeHandle<Code> code) {
1464 563002 : Handle<Context> context(isolate()->native_context());
1465 : Handle<SharedFunctionInfo> info =
1466 563002 : NewSharedFunctionInfo(name, code, map->is_constructor());
1467 : DCHECK(is_sloppy(info->language_mode()));
1468 : DCHECK(!map->IsUndefined(isolate()));
1469 : DCHECK(
1470 : map.is_identical_to(isolate()->sloppy_function_map()) ||
1471 : map.is_identical_to(isolate()->sloppy_function_without_prototype_map()) ||
1472 : map.is_identical_to(
1473 : isolate()->sloppy_function_with_readonly_prototype_map()) ||
1474 : map.is_identical_to(isolate()->strict_function_map()) ||
1475 : map.is_identical_to(isolate()->strict_function_without_prototype_map()) ||
1476 : // TODO(titzer): wasm_function_map() could be undefined here. ugly.
1477 : (*map == context->get(Context::WASM_FUNCTION_MAP_INDEX)) ||
1478 : (*map == context->get(Context::NATIVE_FUNCTION_MAP_INDEX)) ||
1479 : map.is_identical_to(isolate()->proxy_function_map()));
1480 563003 : return NewFunction(map, info, context);
1481 : }
1482 :
1483 :
1484 106744 : Handle<JSFunction> Factory::NewFunction(Handle<String> name) {
1485 : return NewFunction(
1486 106744 : isolate()->sloppy_function_map(), name, MaybeHandle<Code>());
1487 : }
1488 :
1489 :
1490 276090 : Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1491 : Handle<Code> code,
1492 : bool is_strict) {
1493 : Handle<Map> map = is_strict
1494 : ? isolate()->strict_function_without_prototype_map()
1495 276090 : : isolate()->sloppy_function_without_prototype_map();
1496 276090 : return NewFunction(map, name, code);
1497 : }
1498 :
1499 :
1500 89819 : Handle<JSFunction> Factory::NewFunction(Handle<String> name, Handle<Code> code,
1501 : Handle<Object> prototype,
1502 : bool is_strict) {
1503 : Handle<Map> map = is_strict ? isolate()->strict_function_map()
1504 89819 : : isolate()->sloppy_function_map();
1505 89819 : Handle<JSFunction> result = NewFunction(map, name, code);
1506 89819 : result->set_prototype_or_initial_map(*prototype);
1507 89819 : return result;
1508 : }
1509 :
1510 :
1511 89819 : Handle<JSFunction> Factory::NewFunction(Handle<String> name, Handle<Code> code,
1512 : Handle<Object> prototype,
1513 : InstanceType type, int instance_size,
1514 : bool is_strict) {
1515 : // Allocate the function
1516 89819 : Handle<JSFunction> function = NewFunction(name, code, prototype, is_strict);
1517 :
1518 : ElementsKind elements_kind =
1519 89819 : type == JS_ARRAY_TYPE ? FAST_SMI_ELEMENTS : FAST_HOLEY_SMI_ELEMENTS;
1520 89819 : Handle<Map> initial_map = NewMap(type, instance_size, elements_kind);
1521 : // TODO(littledan): Why do we have this is_generator test when
1522 : // NewFunctionPrototype already handles finding an appropriately
1523 : // shared prototype?
1524 89819 : if (!IsResumableFunction(function->shared()->kind())) {
1525 89819 : if (prototype->IsTheHole(isolate())) {
1526 42863 : prototype = NewFunctionPrototype(function);
1527 : }
1528 : }
1529 :
1530 : JSFunction::SetInitialMap(function, initial_map,
1531 89819 : Handle<JSReceiver>::cast(prototype));
1532 :
1533 89819 : return function;
1534 : }
1535 :
1536 :
1537 42863 : Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1538 : Handle<Code> code,
1539 : InstanceType type,
1540 : int instance_size) {
1541 42863 : return NewFunction(name, code, the_hole_value(), type, instance_size);
1542 : }
1543 :
1544 :
1545 432823 : Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
1546 : // Make sure to use globals from the function's context, since the function
1547 : // can be from a different context.
1548 : Handle<Context> native_context(function->context()->native_context());
1549 : Handle<Map> new_map;
1550 432823 : if (V8_UNLIKELY(IsAsyncGeneratorFunction(function->shared()->kind()))) {
1551 1806 : new_map = handle(native_context->async_generator_object_prototype_map());
1552 431017 : } else if (IsResumableFunction(function->shared()->kind())) {
1553 : // Generator and async function prototypes can share maps since they
1554 : // don't have "constructor" properties.
1555 18110 : new_map = handle(native_context->generator_object_prototype_map());
1556 : } else {
1557 : // Each function prototype gets a fresh map to avoid unwanted sharing of
1558 : // maps between prototypes of different constructors.
1559 : Handle<JSFunction> object_function(native_context->object_function());
1560 : DCHECK(object_function->has_initial_map());
1561 412907 : new_map = handle(object_function->initial_map());
1562 : }
1563 :
1564 : DCHECK(!new_map->is_prototype_map());
1565 432823 : Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
1566 :
1567 432823 : if (!IsResumableFunction(function->shared()->kind())) {
1568 412907 : JSObject::AddProperty(prototype, constructor_string(), function, DONT_ENUM);
1569 : }
1570 :
1571 432823 : return prototype;
1572 : }
1573 :
1574 :
1575 6098674 : Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1576 : Handle<SharedFunctionInfo> info,
1577 : Handle<Context> context,
1578 : PretenureFlag pretenure) {
1579 : int map_index =
1580 12197348 : Context::FunctionMapIndex(info->language_mode(), info->kind());
1581 : Handle<Map> initial_map(Map::cast(context->native_context()->get(map_index)));
1582 :
1583 : return NewFunctionFromSharedFunctionInfo(initial_map, info, context,
1584 6098695 : pretenure);
1585 : }
1586 :
1587 19856626 : Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1588 : Handle<SharedFunctionInfo> info, Handle<Context> context,
1589 : Handle<Cell> vector, PretenureFlag pretenure) {
1590 : int map_index =
1591 39713252 : Context::FunctionMapIndex(info->language_mode(), info->kind());
1592 : Handle<Map> initial_map(Map::cast(context->native_context()->get(map_index)));
1593 :
1594 : return NewFunctionFromSharedFunctionInfo(initial_map, info, context, vector,
1595 19856631 : pretenure);
1596 : }
1597 :
1598 6099425 : Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1599 : Handle<Map> initial_map, Handle<SharedFunctionInfo> info,
1600 : Handle<Object> context_or_undefined, PretenureFlag pretenure) {
1601 : DCHECK_EQ(JS_FUNCTION_TYPE, initial_map->instance_type());
1602 : Handle<JSFunction> result =
1603 6099425 : NewFunction(initial_map, info, context_or_undefined, pretenure);
1604 :
1605 6099423 : if (info->ic_age() != isolate()->heap()->global_ic_age()) {
1606 35963 : info->ResetForNewContext(isolate()->heap()->global_ic_age());
1607 : }
1608 :
1609 6099422 : if (context_or_undefined->IsContext()) {
1610 : // Give compiler a chance to pre-initialize.
1611 6099422 : Compiler::PostInstantiation(result, pretenure);
1612 : }
1613 :
1614 6099424 : return result;
1615 : }
1616 :
1617 19856628 : Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1618 : Handle<Map> initial_map, Handle<SharedFunctionInfo> info,
1619 : Handle<Object> context_or_undefined, Handle<Cell> vector,
1620 : PretenureFlag pretenure) {
1621 : DCHECK_EQ(JS_FUNCTION_TYPE, initial_map->instance_type());
1622 : Handle<JSFunction> result =
1623 19856628 : NewFunction(initial_map, info, context_or_undefined, pretenure);
1624 :
1625 : // Bump the closure count that is encoded in the vector cell's map.
1626 19856632 : if (vector->map() == *no_closures_cell_map()) {
1627 5392900 : vector->set_map(*one_closure_cell_map());
1628 14463732 : } else if (vector->map() == *one_closure_cell_map()) {
1629 292281 : vector->set_map(*many_closures_cell_map());
1630 : } else {
1631 : DCHECK_EQ(vector->map(), *many_closures_cell_map());
1632 : }
1633 :
1634 19856628 : result->set_feedback_vector_cell(*vector);
1635 19856630 : if (info->ic_age() != isolate()->heap()->global_ic_age()) {
1636 12892 : info->ResetForNewContext(isolate()->heap()->global_ic_age());
1637 : }
1638 :
1639 19856630 : if (context_or_undefined->IsContext()) {
1640 : // Give compiler a chance to pre-initialize.
1641 19856630 : Compiler::PostInstantiation(result, pretenure);
1642 : }
1643 :
1644 19856632 : return result;
1645 : }
1646 :
1647 4049342 : Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1648 4049342 : Handle<FixedArray> array = NewFixedArray(length, TENURED);
1649 : array->set_map_no_write_barrier(*scope_info_map());
1650 : Handle<ScopeInfo> scope_info = Handle<ScopeInfo>::cast(array);
1651 4049349 : return scope_info;
1652 : }
1653 :
1654 6456 : Handle<ModuleInfo> Factory::NewModuleInfo() {
1655 6456 : Handle<FixedArray> array = NewFixedArray(ModuleInfo::kLength, TENURED);
1656 : array->set_map_no_write_barrier(*module_info_map());
1657 6456 : return Handle<ModuleInfo>::cast(array);
1658 : }
1659 :
1660 11483 : Handle<JSObject> Factory::NewExternal(void* value) {
1661 11483 : Handle<Foreign> foreign = NewForeign(static_cast<Address>(value));
1662 11483 : Handle<JSObject> external = NewJSObjectFromMap(external_map());
1663 11483 : external->SetEmbedderField(0, *foreign);
1664 11483 : return external;
1665 : }
1666 :
1667 :
1668 2555743 : Handle<Code> Factory::NewCodeRaw(int object_size, bool immovable) {
1669 7667195 : CALL_HEAP_FUNCTION(isolate(),
1670 : isolate()->heap()->AllocateCode(object_size, immovable),
1671 : Code);
1672 : }
1673 :
1674 :
1675 2555734 : Handle<Code> Factory::NewCode(const CodeDesc& desc,
1676 : Code::Flags flags,
1677 : Handle<Object> self_ref,
1678 : bool immovable,
1679 : bool crankshafted,
1680 : int prologue_offset,
1681 : bool is_debug) {
1682 2555734 : Handle<ByteArray> reloc_info = NewByteArray(desc.reloc_size, TENURED);
1683 :
1684 2555744 : bool has_unwinding_info = desc.unwinding_info != nullptr;
1685 : DCHECK((has_unwinding_info && desc.unwinding_info_size > 0) ||
1686 : (!has_unwinding_info && desc.unwinding_info_size == 0));
1687 :
1688 : // Compute size.
1689 2555744 : int body_size = desc.instr_size;
1690 : int unwinding_info_size_field_size = kInt64Size;
1691 2555744 : if (has_unwinding_info) {
1692 25 : body_size = RoundUp(body_size, kInt64Size) + desc.unwinding_info_size +
1693 25 : unwinding_info_size_field_size;
1694 : }
1695 : int obj_size = Code::SizeFor(RoundUp(body_size, kObjectAlignment));
1696 :
1697 2555744 : Handle<Code> code = NewCodeRaw(obj_size, immovable);
1698 : DCHECK(!isolate()->heap()->memory_allocator()->code_range()->valid() ||
1699 : isolate()->heap()->memory_allocator()->code_range()->contains(
1700 : code->address()) ||
1701 : obj_size <= isolate()->heap()->code_space()->AreaSize());
1702 :
1703 : // The code object has not been fully initialized yet. We rely on the
1704 : // fact that no allocation will happen from this point on.
1705 : DisallowHeapAllocation no_gc;
1706 2555722 : code->set_gc_metadata(Smi::kZero);
1707 2555725 : code->set_ic_age(isolate()->heap()->global_ic_age());
1708 2555725 : code->set_instruction_size(desc.instr_size);
1709 2555725 : code->set_relocation_info(*reloc_info);
1710 : code->set_flags(flags);
1711 : code->set_has_unwinding_info(has_unwinding_info);
1712 : code->set_raw_kind_specific_flags1(0);
1713 : code->set_raw_kind_specific_flags2(0);
1714 : code->set_is_crankshafted(crankshafted);
1715 : code->set_has_tagged_params(true);
1716 2555744 : code->set_deoptimization_data(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1717 2555744 : code->set_raw_type_feedback_info(Smi::kZero);
1718 2555745 : code->set_next_code_link(*undefined_value(), SKIP_WRITE_BARRIER);
1719 2555744 : code->set_handler_table(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1720 2555744 : code->set_source_position_table(*empty_byte_array(), SKIP_WRITE_BARRIER);
1721 : code->set_prologue_offset(prologue_offset);
1722 2555745 : code->set_constant_pool_offset(desc.instr_size - desc.constant_pool_size);
1723 : code->set_builtin_index(-1);
1724 2555745 : code->set_trap_handler_index(Smi::FromInt(-1));
1725 :
1726 2555739 : switch (code->kind()) {
1727 : case Code::OPTIMIZED_FUNCTION:
1728 : code->set_marked_for_deoptimization(false);
1729 : break;
1730 : case Code::JS_TO_WASM_FUNCTION:
1731 : case Code::WASM_FUNCTION:
1732 : code->set_has_tagged_params(false);
1733 : break;
1734 : default:
1735 : break;
1736 : }
1737 :
1738 2555739 : if (is_debug) {
1739 : DCHECK(code->kind() == Code::FUNCTION);
1740 : code->set_has_debug_break_slots(true);
1741 : }
1742 :
1743 : // Allow self references to created code object by patching the handle to
1744 : // point to the newly allocated Code object.
1745 2555739 : if (!self_ref.is_null()) *(self_ref.location()) = *code;
1746 :
1747 : // Migrate generated code.
1748 : // The generated code can contain Object** values (typically from handles)
1749 : // that are dereferenced during the copy to point directly to the actual heap
1750 : // objects. These pointers can include references to the code object itself,
1751 : // through the self_reference parameter.
1752 2555739 : code->CopyFrom(desc);
1753 :
1754 : #ifdef VERIFY_HEAP
1755 : if (FLAG_verify_heap) code->ObjectVerify();
1756 : #endif
1757 2555742 : return code;
1758 : }
1759 :
1760 :
1761 166641 : Handle<Code> Factory::CopyCode(Handle<Code> code) {
1762 499983 : CALL_HEAP_FUNCTION(isolate(),
1763 : isolate()->heap()->CopyCode(*code),
1764 : Code);
1765 : }
1766 :
1767 :
1768 9490 : Handle<BytecodeArray> Factory::CopyBytecodeArray(
1769 : Handle<BytecodeArray> bytecode_array) {
1770 28470 : CALL_HEAP_FUNCTION(isolate(),
1771 : isolate()->heap()->CopyBytecodeArray(*bytecode_array),
1772 : BytecodeArray);
1773 : }
1774 :
1775 16796750 : Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1776 : PretenureFlag pretenure) {
1777 16796750 : JSFunction::EnsureHasInitialMap(constructor);
1778 50390779 : CALL_HEAP_FUNCTION(
1779 : isolate(),
1780 : isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1781 : }
1782 :
1783 381628 : Handle<JSObject> Factory::NewJSObjectWithNullProto(PretenureFlag pretenure) {
1784 : Handle<JSObject> result =
1785 381628 : NewJSObject(isolate()->object_function(), pretenure);
1786 : Handle<Map> new_map =
1787 381628 : Map::Copy(Handle<Map>(result->map()), "ObjectWithNullProto");
1788 381628 : Map::SetPrototype(new_map, null_value());
1789 381628 : JSObject::MigrateToMap(result, new_map);
1790 381628 : return result;
1791 : }
1792 :
1793 106904 : Handle<JSGlobalObject> Factory::NewJSGlobalObject(
1794 : Handle<JSFunction> constructor) {
1795 : DCHECK(constructor->has_initial_map());
1796 : Handle<Map> map(constructor->initial_map());
1797 : DCHECK(map->is_dictionary_map());
1798 :
1799 : // Make sure no field properties are described in the initial map.
1800 : // This guarantees us that normalizing the properties does not
1801 : // require us to change property values to PropertyCells.
1802 : DCHECK(map->NextFreePropertyIndex() == 0);
1803 :
1804 : // Make sure we don't have a ton of pre-allocated slots in the
1805 : // global objects. They will be unused once we normalize the object.
1806 : DCHECK(map->unused_property_fields() == 0);
1807 : DCHECK(map->GetInObjectProperties() == 0);
1808 :
1809 : // Initial size of the backing store to avoid resize of the storage during
1810 : // bootstrapping. The size differs between the JS global object ad the
1811 : // builtins object.
1812 : int initial_size = 64;
1813 :
1814 : // Allocate a dictionary object for backing storage.
1815 106904 : int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1816 : Handle<GlobalDictionary> dictionary =
1817 106904 : GlobalDictionary::New(isolate(), at_least_space_for);
1818 :
1819 : // The global object might be created from an object template with accessors.
1820 : // Fill these accessors into the dictionary.
1821 : Handle<DescriptorArray> descs(map->instance_descriptors());
1822 213808 : for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1823 0 : PropertyDetails details = descs->GetDetails(i);
1824 : // Only accessors are expected.
1825 : DCHECK_EQ(kAccessor, details.kind());
1826 : PropertyDetails d(kAccessor, details.attributes(), i + 1,
1827 0 : PropertyCellType::kMutable);
1828 : Handle<Name> name(descs->GetKey(i));
1829 0 : Handle<PropertyCell> cell = NewPropertyCell();
1830 0 : cell->set_value(descs->GetValue(i));
1831 : // |dictionary| already contains enough space for all properties.
1832 0 : USE(GlobalDictionary::Add(dictionary, name, cell, d));
1833 : }
1834 :
1835 : // Allocate the global object and initialize it with the backing store.
1836 106904 : Handle<JSGlobalObject> global = New<JSGlobalObject>(map, OLD_SPACE);
1837 106904 : isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1838 :
1839 : // Create a new map for the global object.
1840 106904 : Handle<Map> new_map = Map::CopyDropDescriptors(map);
1841 : new_map->set_dictionary_map(true);
1842 :
1843 : // Set up the global object as a normalized object.
1844 106904 : global->set_map(*new_map);
1845 106904 : global->set_properties(*dictionary);
1846 :
1847 : // Make sure result is a global object with properties in dictionary.
1848 : DCHECK(global->IsJSGlobalObject() && !global->HasFastProperties());
1849 106904 : return global;
1850 : }
1851 :
1852 :
1853 30602740 : Handle<JSObject> Factory::NewJSObjectFromMap(
1854 : Handle<Map> map,
1855 : PretenureFlag pretenure,
1856 : Handle<AllocationSite> allocation_site) {
1857 122411762 : CALL_HEAP_FUNCTION(
1858 : isolate(),
1859 : isolate()->heap()->AllocateJSObjectFromMap(
1860 : *map,
1861 : pretenure,
1862 : allocation_site.is_null() ? NULL : *allocation_site),
1863 : JSObject);
1864 : }
1865 :
1866 :
1867 21500812 : Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1868 : PretenureFlag pretenure) {
1869 21500812 : Map* map = isolate()->get_initial_js_array_map(elements_kind);
1870 21500812 : if (map == nullptr) {
1871 0 : Context* native_context = isolate()->context()->native_context();
1872 : JSFunction* array_function = native_context->array_function();
1873 : map = array_function->initial_map();
1874 : }
1875 21500812 : return Handle<JSArray>::cast(NewJSObjectFromMap(handle(map), pretenure));
1876 : }
1877 :
1878 3244975 : Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind, int length,
1879 : int capacity,
1880 : ArrayStorageAllocationMode mode,
1881 : PretenureFlag pretenure) {
1882 3244975 : Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1883 3244975 : NewJSArrayStorage(array, length, capacity, mode);
1884 3244975 : return array;
1885 : }
1886 :
1887 18255837 : Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1888 : ElementsKind elements_kind,
1889 : int length,
1890 : PretenureFlag pretenure) {
1891 : DCHECK(length <= elements->length());
1892 18255837 : Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1893 :
1894 18255837 : array->set_elements(*elements);
1895 : array->set_length(Smi::FromInt(length));
1896 18255837 : JSObject::ValidateElements(array);
1897 18255837 : return array;
1898 : }
1899 :
1900 :
1901 5113631 : void Factory::NewJSArrayStorage(Handle<JSArray> array,
1902 : int length,
1903 : int capacity,
1904 : ArrayStorageAllocationMode mode) {
1905 : DCHECK(capacity >= length);
1906 :
1907 5113631 : if (capacity == 0) {
1908 : array->set_length(Smi::kZero);
1909 2019335 : array->set_elements(*empty_fixed_array());
1910 5113631 : return;
1911 : }
1912 :
1913 : HandleScope inner_scope(isolate());
1914 : Handle<FixedArrayBase> elms;
1915 : ElementsKind elements_kind = array->GetElementsKind();
1916 3094296 : if (IsFastDoubleElementsKind(elements_kind)) {
1917 703 : if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1918 682 : elms = NewFixedDoubleArray(capacity);
1919 : } else {
1920 : DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1921 21 : elms = NewFixedDoubleArrayWithHoles(capacity);
1922 : }
1923 : } else {
1924 : DCHECK(IsFastSmiOrObjectElementsKind(elements_kind));
1925 3093593 : if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1926 917248 : elms = NewUninitializedFixedArray(capacity);
1927 : } else {
1928 : DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1929 2176345 : elms = NewFixedArrayWithHoles(capacity);
1930 : }
1931 : }
1932 :
1933 3094296 : array->set_elements(*elms);
1934 : array->set_length(Smi::FromInt(length));
1935 : }
1936 :
1937 300 : Handle<JSModuleNamespace> Factory::NewJSModuleNamespace() {
1938 300 : Handle<Map> map = isolate()->js_module_namespace_map();
1939 : Handle<JSModuleNamespace> module_namespace(
1940 300 : Handle<JSModuleNamespace>::cast(NewJSObjectFromMap(map)));
1941 : FieldIndex index = FieldIndex::ForDescriptor(
1942 300 : *map, JSModuleNamespace::kToStringTagFieldIndex);
1943 : module_namespace->FastPropertyAtPut(index,
1944 600 : isolate()->heap()->Module_string());
1945 300 : return module_namespace;
1946 : }
1947 :
1948 37547 : Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1949 : Handle<JSFunction> function) {
1950 : DCHECK(IsResumableFunction(function->shared()->kind()));
1951 37547 : JSFunction::EnsureHasInitialMap(function);
1952 : Handle<Map> map(function->initial_map());
1953 :
1954 : DCHECK(map->instance_type() == JS_GENERATOR_OBJECT_TYPE ||
1955 : map->instance_type() == JS_ASYNC_GENERATOR_OBJECT_TYPE);
1956 :
1957 112641 : CALL_HEAP_FUNCTION(
1958 : isolate(),
1959 : isolate()->heap()->AllocateJSObjectFromMap(*map),
1960 : JSGeneratorObject);
1961 : }
1962 :
1963 2001 : Handle<Module> Factory::NewModule(Handle<SharedFunctionInfo> code) {
1964 : Handle<ModuleInfo> module_info(code->scope_info()->ModuleDescriptorInfo(),
1965 2001 : isolate());
1966 : Handle<ObjectHashTable> exports =
1967 2001 : ObjectHashTable::New(isolate(), module_info->RegularExportCount());
1968 : Handle<FixedArray> regular_exports =
1969 2001 : NewFixedArray(module_info->RegularExportCount());
1970 : Handle<FixedArray> regular_imports =
1971 2001 : NewFixedArray(module_info->regular_imports()->length());
1972 : int requested_modules_length = module_info->module_requests()->length();
1973 : Handle<FixedArray> requested_modules =
1974 : requested_modules_length > 0 ? NewFixedArray(requested_modules_length)
1975 2001 : : empty_fixed_array();
1976 :
1977 2001 : Handle<Module> module = Handle<Module>::cast(NewStruct(MODULE_TYPE));
1978 2001 : module->set_code(*code);
1979 2001 : module->set_exports(*exports);
1980 2001 : module->set_regular_exports(*regular_exports);
1981 2001 : module->set_regular_imports(*regular_imports);
1982 2001 : module->set_hash(isolate()->GenerateIdentityHash(Smi::kMaxValue));
1983 4002 : module->set_module_namespace(isolate()->heap()->undefined_value());
1984 2001 : module->set_requested_modules(*requested_modules);
1985 : module->set_status(Module::kUnprepared);
1986 : DCHECK(!module->instantiated());
1987 : DCHECK(!module->evaluated());
1988 2001 : return module;
1989 : }
1990 :
1991 12615 : Handle<JSArrayBuffer> Factory::NewJSArrayBuffer(SharedFlag shared,
1992 : PretenureFlag pretenure) {
1993 : Handle<JSFunction> array_buffer_fun(
1994 : shared == SharedFlag::kShared
1995 13301 : ? isolate()->native_context()->shared_array_buffer_fun()
1996 49774 : : isolate()->native_context()->array_buffer_fun());
1997 37848 : CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateJSObject(
1998 : *array_buffer_fun, pretenure),
1999 : JSArrayBuffer);
2000 : }
2001 :
2002 :
2003 29 : Handle<JSDataView> Factory::NewJSDataView() {
2004 : Handle<JSFunction> data_view_fun(
2005 58 : isolate()->native_context()->data_view_fun());
2006 87 : CALL_HEAP_FUNCTION(
2007 : isolate(),
2008 : isolate()->heap()->AllocateJSObject(*data_view_fun),
2009 : JSDataView);
2010 : }
2011 :
2012 0 : Handle<JSIteratorResult> Factory::NewJSIteratorResult(Handle<Object> value,
2013 : bool done) {
2014 0 : Handle<Map> map(isolate()->native_context()->iterator_result_map());
2015 : Handle<JSIteratorResult> js_iter_result =
2016 0 : Handle<JSIteratorResult>::cast(NewJSObjectFromMap(map));
2017 0 : js_iter_result->set_value(*value);
2018 0 : js_iter_result->set_done(*ToBoolean(done));
2019 0 : return js_iter_result;
2020 : }
2021 :
2022 332 : Handle<JSAsyncFromSyncIterator> Factory::NewJSAsyncFromSyncIterator(
2023 : Handle<JSReceiver> sync_iterator) {
2024 664 : Handle<Map> map(isolate()->native_context()->async_from_sync_iterator_map());
2025 : Handle<JSAsyncFromSyncIterator> iterator =
2026 332 : Handle<JSAsyncFromSyncIterator>::cast(NewJSObjectFromMap(map));
2027 :
2028 332 : iterator->set_sync_iterator(*sync_iterator);
2029 332 : return iterator;
2030 : }
2031 :
2032 22 : Handle<JSMap> Factory::NewJSMap() {
2033 44 : Handle<Map> map(isolate()->native_context()->js_map_map());
2034 22 : Handle<JSMap> js_map = Handle<JSMap>::cast(NewJSObjectFromMap(map));
2035 22 : JSMap::Initialize(js_map, isolate());
2036 22 : return js_map;
2037 : }
2038 :
2039 :
2040 422 : Handle<JSSet> Factory::NewJSSet() {
2041 844 : Handle<Map> map(isolate()->native_context()->js_set_map());
2042 422 : Handle<JSSet> js_set = Handle<JSSet>::cast(NewJSObjectFromMap(map));
2043 422 : JSSet::Initialize(js_set, isolate());
2044 422 : return js_set;
2045 : }
2046 :
2047 :
2048 0 : Handle<JSMapIterator> Factory::NewJSMapIterator() {
2049 0 : Handle<Map> map(isolate()->native_context()->map_iterator_map());
2050 0 : CALL_HEAP_FUNCTION(isolate(),
2051 : isolate()->heap()->AllocateJSObjectFromMap(*map),
2052 : JSMapIterator);
2053 : }
2054 :
2055 :
2056 0 : Handle<JSSetIterator> Factory::NewJSSetIterator() {
2057 0 : Handle<Map> map(isolate()->native_context()->set_iterator_map());
2058 0 : CALL_HEAP_FUNCTION(isolate(),
2059 : isolate()->heap()->AllocateJSObjectFromMap(*map),
2060 : JSSetIterator);
2061 : }
2062 :
2063 1679 : ExternalArrayType Factory::GetArrayTypeFromElementsKind(ElementsKind kind) {
2064 1679 : switch (kind) {
2065 : #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
2066 : case TYPE##_ELEMENTS: \
2067 : return kExternal##Type##Array;
2068 93 : TYPED_ARRAYS(TYPED_ARRAY_CASE)
2069 : default:
2070 0 : UNREACHABLE();
2071 : return kExternalInt8Array;
2072 : }
2073 : #undef TYPED_ARRAY_CASE
2074 : }
2075 :
2076 1137 : size_t Factory::GetExternalArrayElementSize(ExternalArrayType type) {
2077 1137 : switch (type) {
2078 : #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
2079 : case kExternal##Type##Array: \
2080 : return size;
2081 157 : TYPED_ARRAYS(TYPED_ARRAY_CASE)
2082 : default:
2083 0 : UNREACHABLE();
2084 : return 0;
2085 : }
2086 : #undef TYPED_ARRAY_CASE
2087 : }
2088 :
2089 : namespace {
2090 :
2091 302 : ElementsKind GetExternalArrayElementsKind(ExternalArrayType type) {
2092 302 : switch (type) {
2093 : #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
2094 : case kExternal##Type##Array: \
2095 : return TYPE##_ELEMENTS;
2096 31 : TYPED_ARRAYS(TYPED_ARRAY_CASE)
2097 : }
2098 0 : UNREACHABLE();
2099 : return FIRST_FIXED_TYPED_ARRAY_ELEMENTS_KIND;
2100 : #undef TYPED_ARRAY_CASE
2101 : }
2102 :
2103 70 : size_t GetFixedTypedArraysElementSize(ElementsKind kind) {
2104 70 : switch (kind) {
2105 : #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
2106 : case TYPE##_ELEMENTS: \
2107 : return size;
2108 7 : TYPED_ARRAYS(TYPED_ARRAY_CASE)
2109 : default:
2110 0 : UNREACHABLE();
2111 : return 0;
2112 : }
2113 : #undef TYPED_ARRAY_CASE
2114 : }
2115 :
2116 :
2117 302 : JSFunction* GetTypedArrayFun(ExternalArrayType type, Isolate* isolate) {
2118 : Context* native_context = isolate->context()->native_context();
2119 302 : switch (type) {
2120 : #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
2121 : case kExternal##Type##Array: \
2122 : return native_context->type##_array_fun();
2123 :
2124 302 : TYPED_ARRAYS(TYPED_ARRAY_FUN)
2125 : #undef TYPED_ARRAY_FUN
2126 :
2127 : default:
2128 0 : UNREACHABLE();
2129 : return NULL;
2130 : }
2131 : }
2132 :
2133 :
2134 70 : JSFunction* GetTypedArrayFun(ElementsKind elements_kind, Isolate* isolate) {
2135 : Context* native_context = isolate->context()->native_context();
2136 70 : switch (elements_kind) {
2137 : #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
2138 : case TYPE##_ELEMENTS: \
2139 : return native_context->type##_array_fun();
2140 :
2141 70 : TYPED_ARRAYS(TYPED_ARRAY_FUN)
2142 : #undef TYPED_ARRAY_FUN
2143 :
2144 : default:
2145 0 : UNREACHABLE();
2146 : return NULL;
2147 : }
2148 : }
2149 :
2150 :
2151 331 : void SetupArrayBufferView(i::Isolate* isolate,
2152 : i::Handle<i::JSArrayBufferView> obj,
2153 : i::Handle<i::JSArrayBuffer> buffer,
2154 : size_t byte_offset, size_t byte_length,
2155 : PretenureFlag pretenure = NOT_TENURED) {
2156 : DCHECK(byte_offset + byte_length <=
2157 : static_cast<size_t>(buffer->byte_length()->Number()));
2158 :
2159 : DCHECK_EQ(obj->GetEmbedderFieldCount(),
2160 : v8::ArrayBufferView::kEmbedderFieldCount);
2161 993 : for (int i = 0; i < v8::ArrayBufferView::kEmbedderFieldCount; i++) {
2162 : obj->SetEmbedderField(i, Smi::kZero);
2163 : }
2164 :
2165 331 : obj->set_buffer(*buffer);
2166 :
2167 : i::Handle<i::Object> byte_offset_object =
2168 331 : isolate->factory()->NewNumberFromSize(byte_offset, pretenure);
2169 331 : obj->set_byte_offset(*byte_offset_object);
2170 :
2171 : i::Handle<i::Object> byte_length_object =
2172 331 : isolate->factory()->NewNumberFromSize(byte_length, pretenure);
2173 331 : obj->set_byte_length(*byte_length_object);
2174 331 : }
2175 :
2176 :
2177 : } // namespace
2178 :
2179 :
2180 302 : Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
2181 : PretenureFlag pretenure) {
2182 302 : Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
2183 :
2184 906 : CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateJSObject(
2185 : *typed_array_fun_handle, pretenure),
2186 : JSTypedArray);
2187 : }
2188 :
2189 :
2190 70 : Handle<JSTypedArray> Factory::NewJSTypedArray(ElementsKind elements_kind,
2191 : PretenureFlag pretenure) {
2192 : Handle<JSFunction> typed_array_fun_handle(
2193 70 : GetTypedArrayFun(elements_kind, isolate()));
2194 :
2195 210 : CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateJSObject(
2196 : *typed_array_fun_handle, pretenure),
2197 : JSTypedArray);
2198 : }
2199 :
2200 :
2201 302 : Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
2202 : Handle<JSArrayBuffer> buffer,
2203 : size_t byte_offset, size_t length,
2204 : PretenureFlag pretenure) {
2205 302 : Handle<JSTypedArray> obj = NewJSTypedArray(type, pretenure);
2206 :
2207 302 : size_t element_size = GetExternalArrayElementSize(type);
2208 302 : ElementsKind elements_kind = GetExternalArrayElementsKind(type);
2209 :
2210 302 : CHECK(byte_offset % element_size == 0);
2211 :
2212 302 : CHECK(length <= (std::numeric_limits<size_t>::max() / element_size));
2213 302 : CHECK(length <= static_cast<size_t>(Smi::kMaxValue));
2214 302 : size_t byte_length = length * element_size;
2215 : SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length,
2216 302 : pretenure);
2217 :
2218 302 : Handle<Object> length_object = NewNumberFromSize(length, pretenure);
2219 302 : obj->set_length(*length_object);
2220 :
2221 : Handle<FixedTypedArrayBase> elements = NewFixedTypedArrayWithExternalPointer(
2222 : static_cast<int>(length), type,
2223 302 : static_cast<uint8_t*>(buffer->backing_store()) + byte_offset, pretenure);
2224 302 : Handle<Map> map = JSObject::GetElementsTransitionMap(obj, elements_kind);
2225 302 : JSObject::SetMapAndElements(obj, map, elements);
2226 302 : return obj;
2227 : }
2228 :
2229 :
2230 70 : Handle<JSTypedArray> Factory::NewJSTypedArray(ElementsKind elements_kind,
2231 : size_t number_of_elements,
2232 : PretenureFlag pretenure) {
2233 70 : Handle<JSTypedArray> obj = NewJSTypedArray(elements_kind, pretenure);
2234 : DCHECK_EQ(obj->GetEmbedderFieldCount(),
2235 : v8::ArrayBufferView::kEmbedderFieldCount);
2236 210 : for (int i = 0; i < v8::ArrayBufferView::kEmbedderFieldCount; i++) {
2237 : obj->SetEmbedderField(i, Smi::kZero);
2238 : }
2239 :
2240 70 : size_t element_size = GetFixedTypedArraysElementSize(elements_kind);
2241 70 : ExternalArrayType array_type = GetArrayTypeFromElementsKind(elements_kind);
2242 :
2243 70 : CHECK(number_of_elements <=
2244 : (std::numeric_limits<size_t>::max() / element_size));
2245 70 : CHECK(number_of_elements <= static_cast<size_t>(Smi::kMaxValue));
2246 70 : size_t byte_length = number_of_elements * element_size;
2247 :
2248 70 : obj->set_byte_offset(Smi::kZero);
2249 : i::Handle<i::Object> byte_length_object =
2250 70 : NewNumberFromSize(byte_length, pretenure);
2251 70 : obj->set_byte_length(*byte_length_object);
2252 : Handle<Object> length_object =
2253 70 : NewNumberFromSize(number_of_elements, pretenure);
2254 70 : obj->set_length(*length_object);
2255 :
2256 : Handle<JSArrayBuffer> buffer =
2257 70 : NewJSArrayBuffer(SharedFlag::kNotShared, pretenure);
2258 : JSArrayBuffer::Setup(buffer, isolate(), true, NULL, byte_length,
2259 70 : SharedFlag::kNotShared);
2260 70 : obj->set_buffer(*buffer);
2261 : Handle<FixedTypedArrayBase> elements = NewFixedTypedArray(
2262 70 : static_cast<int>(number_of_elements), array_type, true, pretenure);
2263 70 : obj->set_elements(*elements);
2264 70 : return obj;
2265 : }
2266 :
2267 :
2268 29 : Handle<JSDataView> Factory::NewJSDataView(Handle<JSArrayBuffer> buffer,
2269 : size_t byte_offset,
2270 : size_t byte_length) {
2271 29 : Handle<JSDataView> obj = NewJSDataView();
2272 29 : SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
2273 29 : return obj;
2274 : }
2275 :
2276 :
2277 1085 : MaybeHandle<JSBoundFunction> Factory::NewJSBoundFunction(
2278 : Handle<JSReceiver> target_function, Handle<Object> bound_this,
2279 : Vector<Handle<Object>> bound_args) {
2280 : DCHECK(target_function->IsCallable());
2281 : STATIC_ASSERT(Code::kMaxArguments <= FixedArray::kMaxLength);
2282 1085 : if (bound_args.length() >= Code::kMaxArguments) {
2283 0 : THROW_NEW_ERROR(isolate(),
2284 : NewRangeError(MessageTemplate::kTooManyArguments),
2285 : JSBoundFunction);
2286 : }
2287 :
2288 : // Determine the prototype of the {target_function}.
2289 : Handle<Object> prototype;
2290 2170 : ASSIGN_RETURN_ON_EXCEPTION(
2291 : isolate(), prototype,
2292 : JSReceiver::GetPrototype(isolate(), target_function), JSBoundFunction);
2293 :
2294 : // Create the [[BoundArguments]] for the result.
2295 : Handle<FixedArray> bound_arguments;
2296 1085 : if (bound_args.length() == 0) {
2297 : bound_arguments = empty_fixed_array();
2298 : } else {
2299 534 : bound_arguments = NewFixedArray(bound_args.length());
2300 1142 : for (int i = 0; i < bound_args.length(); ++i) {
2301 1216 : bound_arguments->set(i, *bound_args[i]);
2302 : }
2303 : }
2304 :
2305 : // Setup the map for the JSBoundFunction instance.
2306 : Handle<Map> map = target_function->IsConstructor()
2307 : ? isolate()->bound_function_with_constructor_map()
2308 1085 : : isolate()->bound_function_without_constructor_map();
2309 1085 : if (map->prototype() != *prototype) {
2310 192 : map = Map::TransitionToPrototype(map, prototype, REGULAR_PROTOTYPE);
2311 : }
2312 : DCHECK_EQ(target_function->IsConstructor(), map->is_constructor());
2313 :
2314 : // Setup the JSBoundFunction instance.
2315 : Handle<JSBoundFunction> result =
2316 1085 : Handle<JSBoundFunction>::cast(NewJSObjectFromMap(map));
2317 1085 : result->set_bound_target_function(*target_function);
2318 1085 : result->set_bound_this(*bound_this);
2319 1085 : result->set_bound_arguments(*bound_arguments);
2320 : return result;
2321 : }
2322 :
2323 :
2324 : // ES6 section 9.5.15 ProxyCreate (target, handler)
2325 45340 : Handle<JSProxy> Factory::NewJSProxy(Handle<JSReceiver> target,
2326 : Handle<JSReceiver> handler) {
2327 : // Allocate the proxy object.
2328 : Handle<Map> map;
2329 45340 : if (target->IsCallable()) {
2330 4398 : if (target->IsConstructor()) {
2331 2352 : map = Handle<Map>(isolate()->proxy_constructor_map());
2332 : } else {
2333 2046 : map = Handle<Map>(isolate()->proxy_callable_map());
2334 : }
2335 : } else {
2336 40942 : map = Handle<Map>(isolate()->proxy_map());
2337 : }
2338 : DCHECK(map->prototype()->IsNull(isolate()));
2339 45340 : Handle<JSProxy> result = New<JSProxy>(map, NEW_SPACE);
2340 45340 : result->initialize_properties();
2341 45340 : result->set_target(*target);
2342 45340 : result->set_handler(*handler);
2343 45340 : result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
2344 45340 : return result;
2345 : }
2346 :
2347 106868 : Handle<JSGlobalProxy> Factory::NewUninitializedJSGlobalProxy(int size) {
2348 : // Create an empty shell of a JSGlobalProxy that needs to be reinitialized
2349 : // via ReinitializeJSGlobalProxy later.
2350 106868 : Handle<Map> map = NewMap(JS_GLOBAL_PROXY_TYPE, size);
2351 : // Maintain invariant expected from any JSGlobalProxy.
2352 : map->set_is_access_check_needed(true);
2353 320604 : CALL_HEAP_FUNCTION(
2354 : isolate(), isolate()->heap()->AllocateJSObjectFromMap(*map, NOT_TENURED),
2355 : JSGlobalProxy);
2356 : }
2357 :
2358 :
2359 106927 : void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
2360 : Handle<JSFunction> constructor) {
2361 : DCHECK(constructor->has_initial_map());
2362 : Handle<Map> map(constructor->initial_map(), isolate());
2363 : Handle<Map> old_map(object->map(), isolate());
2364 :
2365 : // The proxy's hash should be retained across reinitialization.
2366 : Handle<Object> hash(object->hash(), isolate());
2367 :
2368 106927 : if (old_map->is_prototype_map()) {
2369 0 : map = Map::Copy(map, "CopyAsPrototypeForJSGlobalProxy");
2370 : map->set_is_prototype_map(true);
2371 : }
2372 106927 : JSObject::NotifyMapChange(old_map, map, isolate());
2373 106927 : old_map->NotifyLeafMapLayoutChange();
2374 :
2375 : // Check that the already allocated object has the same size and type as
2376 : // objects allocated using the constructor.
2377 : DCHECK(map->instance_size() == old_map->instance_size());
2378 : DCHECK(map->instance_type() == old_map->instance_type());
2379 :
2380 : // Allocate the backing storage for the properties.
2381 : Handle<FixedArray> properties = empty_fixed_array();
2382 :
2383 : // In order to keep heap in consistent state there must be no allocations
2384 : // before object re-initialization is finished.
2385 : DisallowHeapAllocation no_allocation;
2386 :
2387 : // Reset the map for the object.
2388 106927 : object->synchronized_set_map(*map);
2389 :
2390 106927 : Heap* heap = isolate()->heap();
2391 : // Reinitialize the object from the constructor map.
2392 106927 : heap->InitializeJSObjectFromMap(*object, *properties, *map);
2393 :
2394 : // Restore the saved hash.
2395 106927 : object->set_hash(*hash);
2396 106927 : }
2397 :
2398 6238379 : Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2399 : Handle<String> name, FunctionKind kind, Handle<Code> code,
2400 : Handle<ScopeInfo> scope_info) {
2401 : DCHECK(IsValidFunctionKind(kind));
2402 : Handle<SharedFunctionInfo> shared =
2403 12476758 : NewSharedFunctionInfo(name, code, IsConstructable(kind));
2404 6238379 : shared->set_scope_info(*scope_info);
2405 6238378 : shared->set_outer_scope_info(*the_hole_value());
2406 : shared->set_kind(kind);
2407 6238380 : if (IsGeneratorFunction(kind)) {
2408 5363 : shared->set_instance_class_name(isolate()->heap()->Generator_string());
2409 : }
2410 6238380 : return shared;
2411 : }
2412 :
2413 6235386 : Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfoForLiteral(
2414 6235391 : FunctionLiteral* literal, Handle<Script> script) {
2415 6235386 : Handle<Code> code = isolate()->builtins()->CompileLazy();
2416 6235386 : Handle<ScopeInfo> scope_info(ScopeInfo::Empty(isolate()));
2417 : Handle<SharedFunctionInfo> result =
2418 12470782 : NewSharedFunctionInfo(literal->name(), literal->kind(), code, scope_info);
2419 6235392 : SharedFunctionInfo::InitFromFunctionLiteral(result, literal);
2420 6235394 : SharedFunctionInfo::SetScript(result, script);
2421 6235391 : return result;
2422 : }
2423 :
2424 1404907 : Handle<JSMessageObject> Factory::NewJSMessageObject(
2425 : MessageTemplate::Template message, Handle<Object> argument,
2426 : int start_position, int end_position, Handle<Object> script,
2427 : Handle<Object> stack_frames) {
2428 1404907 : Handle<Map> map = message_object_map();
2429 1404907 : Handle<JSMessageObject> message_obj = New<JSMessageObject>(map, NEW_SPACE);
2430 1404907 : message_obj->set_properties(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2431 1404907 : message_obj->initialize_elements();
2432 1404907 : message_obj->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2433 1404907 : message_obj->set_type(message);
2434 1404907 : message_obj->set_argument(*argument);
2435 : message_obj->set_start_position(start_position);
2436 : message_obj->set_end_position(end_position);
2437 1404907 : message_obj->set_script(*script);
2438 1404907 : message_obj->set_stack_frames(*stack_frames);
2439 : message_obj->set_error_level(v8::Isolate::kMessageError);
2440 1404907 : return message_obj;
2441 : }
2442 :
2443 :
2444 10654399 : Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2445 : Handle<String> name, MaybeHandle<Code> maybe_code, bool is_constructor) {
2446 : // Function names are assumed to be flat elsewhere. Must flatten before
2447 : // allocating SharedFunctionInfo to avoid GC seeing the uninitialized SFI.
2448 10654399 : name = String::Flatten(name, TENURED);
2449 :
2450 10654410 : Handle<Map> map = shared_function_info_map();
2451 10654410 : Handle<SharedFunctionInfo> share = New<SharedFunctionInfo>(map, OLD_SPACE);
2452 :
2453 : // Set pointer fields.
2454 10654403 : share->set_name(*name);
2455 10654403 : share->set_function_data(*undefined_value(), SKIP_WRITE_BARRIER);
2456 : Handle<Code> code;
2457 10654390 : if (!maybe_code.ToHandle(&code)) {
2458 106799 : code = isolate()->builtins()->Illegal();
2459 : }
2460 10654389 : share->set_code(*code);
2461 10654409 : share->set_optimized_code_map(*empty_fixed_array());
2462 21308818 : share->set_scope_info(ScopeInfo::Empty(isolate()));
2463 10654406 : share->set_outer_scope_info(*the_hole_value());
2464 : Handle<Code> construct_stub =
2465 9778979 : is_constructor ? isolate()->builtins()->JSConstructStubGeneric()
2466 20433386 : : isolate()->builtins()->ConstructedNonConstructable();
2467 10654403 : share->SetConstructStub(*construct_stub);
2468 10654406 : share->set_instance_class_name(*Object_string());
2469 10654407 : share->set_script(*undefined_value(), SKIP_WRITE_BARRIER);
2470 10654408 : share->set_debug_info(Smi::kZero, SKIP_WRITE_BARRIER);
2471 10654407 : share->set_function_identifier(*undefined_value(), SKIP_WRITE_BARRIER);
2472 : StaticFeedbackVectorSpec empty_spec;
2473 : Handle<FeedbackMetadata> feedback_metadata =
2474 10654406 : FeedbackMetadata::New(isolate(), &empty_spec);
2475 10654402 : share->set_feedback_metadata(*feedback_metadata, SKIP_WRITE_BARRIER);
2476 : share->set_function_literal_id(FunctionLiteral::kIdTypeInvalid);
2477 : #if TRACE_MAPS
2478 : share->set_unique_id(isolate()->GetNextUniqueSharedFunctionInfoId());
2479 : #endif
2480 : share->set_profiler_ticks(0);
2481 : share->set_ast_node_count(0);
2482 : share->set_counters(0);
2483 :
2484 : // Set integer fields (smi or int, depending on the architecture).
2485 : share->set_length(0);
2486 : share->set_internal_formal_parameter_count(0);
2487 : share->set_expected_nof_properties(0);
2488 : share->set_start_position_and_type(0);
2489 : share->set_end_position(0);
2490 : share->set_function_token_position(0);
2491 : // All compiler hints default to false or 0.
2492 : share->set_compiler_hints(0);
2493 : share->set_opt_count_and_bailout_reason(0);
2494 :
2495 : // Link into the list.
2496 : Handle<Object> new_noscript_list =
2497 10654404 : WeakFixedArray::Add(noscript_shared_function_infos(), share);
2498 : isolate()->heap()->set_noscript_shared_function_infos(*new_noscript_list);
2499 :
2500 10654405 : return share;
2501 : }
2502 :
2503 :
2504 102974495 : static inline int NumberCacheHash(Handle<FixedArray> cache,
2505 : Handle<Object> number) {
2506 102974495 : int mask = (cache->length() >> 1) - 1;
2507 102974495 : if (number->IsSmi()) {
2508 99158992 : return Handle<Smi>::cast(number)->value() & mask;
2509 : } else {
2510 : int64_t bits = bit_cast<int64_t>(number->Number());
2511 3815503 : return (static_cast<int>(bits) ^ static_cast<int>(bits >> 32)) & mask;
2512 : }
2513 : }
2514 :
2515 :
2516 52077513 : Handle<Object> Factory::GetNumberStringCache(Handle<Object> number) {
2517 : DisallowHeapAllocation no_gc;
2518 52077513 : int hash = NumberCacheHash(number_string_cache(), number);
2519 52077513 : Object* key = number_string_cache()->get(hash * 2);
2520 102514164 : if (key == *number || (key->IsHeapNumber() && number->IsHeapNumber() &&
2521 : key->Number() == number->Number())) {
2522 : return Handle<String>(
2523 9154168 : String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
2524 : }
2525 47500429 : return undefined_value();
2526 : }
2527 :
2528 :
2529 50896982 : void Factory::SetNumberStringCache(Handle<Object> number,
2530 : Handle<String> string) {
2531 50896982 : int hash = NumberCacheHash(number_string_cache(), number);
2532 101793964 : if (number_string_cache()->get(hash * 2) != *undefined_value()) {
2533 42897637 : int full_size = isolate()->heap()->FullSizeNumberStringCacheLength();
2534 42897637 : if (number_string_cache()->length() != full_size) {
2535 2007 : Handle<FixedArray> new_cache = NewFixedArray(full_size, TENURED);
2536 : isolate()->heap()->set_number_string_cache(*new_cache);
2537 50896982 : return;
2538 : }
2539 : }
2540 50894975 : number_string_cache()->set(hash * 2, *number);
2541 101789950 : number_string_cache()->set(hash * 2 + 1, *string);
2542 : }
2543 :
2544 :
2545 55474066 : Handle<String> Factory::NumberToString(Handle<Object> number,
2546 : bool check_number_string_cache) {
2547 55474066 : isolate()->counters()->number_to_string_runtime()->Increment();
2548 55474066 : if (check_number_string_cache) {
2549 52077513 : Handle<Object> cached = GetNumberStringCache(number);
2550 52077513 : if (!cached->IsUndefined(isolate())) return Handle<String>::cast(cached);
2551 : }
2552 :
2553 : char arr[100];
2554 : Vector<char> buffer(arr, arraysize(arr));
2555 : const char* str;
2556 50896982 : if (number->IsSmi()) {
2557 : int num = Handle<Smi>::cast(number)->value();
2558 48839225 : str = IntToCString(num, buffer);
2559 : } else {
2560 : double num = Handle<HeapNumber>::cast(number)->value();
2561 2057757 : str = DoubleToCString(num, buffer);
2562 : }
2563 :
2564 : // We tenure the allocated string since it is referenced from the
2565 : // number-string cache which lives in the old space.
2566 50896982 : Handle<String> js_string = NewStringFromAsciiChecked(str, TENURED);
2567 50896982 : SetNumberStringCache(number, js_string);
2568 50896982 : return js_string;
2569 : }
2570 :
2571 :
2572 11715 : Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
2573 : DCHECK(!shared->HasDebugInfo());
2574 : // Allocate initial fixed array for active break points before allocating the
2575 : // debug info object to avoid allocation while setting up the debug info
2576 : // object.
2577 : Handle<FixedArray> break_points(
2578 11715 : NewFixedArray(DebugInfo::kEstimatedNofBreakPointsInFunction));
2579 :
2580 : // Make a copy of the bytecode array if available.
2581 : Handle<Object> maybe_debug_bytecode_array = undefined_value();
2582 11715 : if (shared->HasBytecodeArray()) {
2583 : Handle<BytecodeArray> original(shared->bytecode_array());
2584 9490 : maybe_debug_bytecode_array = CopyBytecodeArray(original);
2585 : }
2586 :
2587 : // Create and set up the debug info object. Debug info contains function, a
2588 : // copy of the original code, the executing code and initial fixed array for
2589 : // active break points.
2590 : Handle<DebugInfo> debug_info =
2591 11715 : Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
2592 11715 : debug_info->set_shared(*shared);
2593 : debug_info->set_debugger_hints(shared->debugger_hints());
2594 11715 : debug_info->set_debug_bytecode_array(*maybe_debug_bytecode_array);
2595 11715 : debug_info->set_break_points(*break_points);
2596 :
2597 : // Link debug info to function.
2598 11715 : shared->set_debug_info(*debug_info);
2599 :
2600 11715 : return debug_info;
2601 : }
2602 :
2603 2934 : Handle<BreakPointInfo> Factory::NewBreakPointInfo(int source_position) {
2604 : Handle<BreakPointInfo> new_break_point_info =
2605 2934 : Handle<BreakPointInfo>::cast(NewStruct(TUPLE2_TYPE));
2606 : new_break_point_info->set_source_position(source_position);
2607 2934 : new_break_point_info->set_break_point_objects(*undefined_value());
2608 2934 : return new_break_point_info;
2609 : }
2610 :
2611 12890 : Handle<StackFrameInfo> Factory::NewStackFrameInfo() {
2612 : Handle<StackFrameInfo> stack_frame_info =
2613 12890 : Handle<StackFrameInfo>::cast(NewStruct(STACK_FRAME_INFO_TYPE));
2614 : stack_frame_info->set_line_number(0);
2615 : stack_frame_info->set_column_number(0);
2616 : stack_frame_info->set_script_id(0);
2617 12890 : stack_frame_info->set_script_name(Smi::kZero);
2618 12890 : stack_frame_info->set_script_name_or_source_url(Smi::kZero);
2619 12890 : stack_frame_info->set_function_name(Smi::kZero);
2620 : stack_frame_info->set_flag(0);
2621 12890 : return stack_frame_info;
2622 : }
2623 :
2624 : Handle<SourcePositionTableWithFrameCache>
2625 8941 : Factory::NewSourcePositionTableWithFrameCache(
2626 : Handle<ByteArray> source_position_table,
2627 : Handle<UnseededNumberDictionary> stack_frame_cache) {
2628 : Handle<SourcePositionTableWithFrameCache>
2629 : source_position_table_with_frame_cache =
2630 : Handle<SourcePositionTableWithFrameCache>::cast(
2631 8941 : NewStruct(TUPLE2_TYPE));
2632 : source_position_table_with_frame_cache->set_source_position_table(
2633 8941 : *source_position_table);
2634 : source_position_table_with_frame_cache->set_stack_frame_cache(
2635 8941 : *stack_frame_cache);
2636 8941 : return source_position_table_with_frame_cache;
2637 : }
2638 :
2639 98055 : Handle<JSObject> Factory::NewArgumentsObject(Handle<JSFunction> callee,
2640 : int length) {
2641 195635 : bool strict_mode_callee = is_strict(callee->shared()->language_mode()) ||
2642 : !callee->shared()->has_simple_parameters();
2643 : Handle<Map> map = strict_mode_callee ? isolate()->strict_arguments_map()
2644 98055 : : isolate()->sloppy_arguments_map();
2645 : AllocationSiteUsageContext context(isolate(), Handle<AllocationSite>(),
2646 : false);
2647 : DCHECK(!isolate()->has_pending_exception());
2648 98055 : Handle<JSObject> result = NewJSObjectFromMap(map);
2649 : Handle<Smi> value(Smi::FromInt(length), isolate());
2650 98055 : Object::SetProperty(result, length_string(), value, STRICT).Assert();
2651 98055 : if (!strict_mode_callee) {
2652 97467 : Object::SetProperty(result, callee_string(), callee, STRICT).Assert();
2653 : }
2654 98055 : return result;
2655 : }
2656 :
2657 :
2658 34 : Handle<JSWeakMap> Factory::NewJSWeakMap() {
2659 : // TODO(adamk): Currently the map is only created three times per
2660 : // isolate. If it's created more often, the map should be moved into the
2661 : // strong root list.
2662 34 : Handle<Map> map = NewMap(JS_WEAK_MAP_TYPE, JSWeakMap::kSize);
2663 34 : return Handle<JSWeakMap>::cast(NewJSObjectFromMap(map));
2664 : }
2665 :
2666 :
2667 831886 : Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
2668 : int number_of_properties,
2669 : bool* is_result_from_cache) {
2670 : const int kMapCacheSize = 128;
2671 :
2672 : // We do not cache maps for too many properties or when running builtin code.
2673 1663454 : if (number_of_properties > kMapCacheSize ||
2674 831568 : isolate()->bootstrapper()->IsActive()) {
2675 108362 : *is_result_from_cache = false;
2676 108362 : Handle<Map> map = Map::Create(isolate(), number_of_properties);
2677 108362 : return map;
2678 : }
2679 723524 : *is_result_from_cache = true;
2680 723524 : if (number_of_properties == 0) {
2681 : // Reuse the initial map of the Object function if the literal has no
2682 : // predeclared properties.
2683 : return handle(context->object_function()->initial_map(), isolate());
2684 : }
2685 :
2686 631906 : int cache_index = number_of_properties - 1;
2687 : Handle<Object> maybe_cache(context->map_cache(), isolate());
2688 631906 : if (maybe_cache->IsUndefined(isolate())) {
2689 : // Allocate the new map cache for the native context.
2690 60588 : maybe_cache = NewFixedArray(kMapCacheSize, TENURED);
2691 : context->set_map_cache(*maybe_cache);
2692 : } else {
2693 : // Check to see whether there is a matching element in the cache.
2694 : Handle<FixedArray> cache = Handle<FixedArray>::cast(maybe_cache);
2695 : Object* result = cache->get(cache_index);
2696 571318 : if (result->IsWeakCell()) {
2697 : WeakCell* cell = WeakCell::cast(result);
2698 492938 : if (!cell->cleared()) {
2699 : return handle(Map::cast(cell->value()), isolate());
2700 : }
2701 : }
2702 : }
2703 : // Create a new map and add it to the cache.
2704 : Handle<FixedArray> cache = Handle<FixedArray>::cast(maybe_cache);
2705 139232 : Handle<Map> map = Map::Create(isolate(), number_of_properties);
2706 139232 : Handle<WeakCell> cell = NewWeakCell(map);
2707 139232 : cache->set(cache_index, *cell);
2708 139232 : return map;
2709 : }
2710 :
2711 :
2712 262450 : void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
2713 : JSRegExp::Type type,
2714 : Handle<String> source,
2715 : JSRegExp::Flags flags,
2716 : Handle<Object> data) {
2717 262450 : Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
2718 :
2719 262450 : store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2720 262450 : store->set(JSRegExp::kSourceIndex, *source);
2721 : store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags));
2722 262450 : store->set(JSRegExp::kAtomPatternIndex, *data);
2723 262450 : regexp->set_data(*store);
2724 262450 : }
2725 :
2726 :
2727 97561 : void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
2728 : JSRegExp::Type type,
2729 : Handle<String> source,
2730 : JSRegExp::Flags flags,
2731 : int capture_count) {
2732 97561 : Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
2733 : Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
2734 97561 : store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2735 97561 : store->set(JSRegExp::kSourceIndex, *source);
2736 : store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags));
2737 : store->set(JSRegExp::kIrregexpLatin1CodeIndex, uninitialized);
2738 : store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
2739 : store->set(JSRegExp::kIrregexpLatin1CodeSavedIndex, uninitialized);
2740 : store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
2741 : store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::kZero);
2742 : store->set(JSRegExp::kIrregexpCaptureCountIndex,
2743 : Smi::FromInt(capture_count));
2744 : store->set(JSRegExp::kIrregexpCaptureNameMapIndex, uninitialized);
2745 97561 : regexp->set_data(*store);
2746 97561 : }
2747 :
2748 183 : Handle<RegExpMatchInfo> Factory::NewRegExpMatchInfo() {
2749 : // Initially, the last match info consists of all fixed fields plus space for
2750 : // the match itself (i.e., 2 capture indices).
2751 : static const int kInitialSize = RegExpMatchInfo::kFirstCaptureIndex +
2752 : RegExpMatchInfo::kInitialCaptureIndices;
2753 :
2754 183 : Handle<FixedArray> elems = NewFixedArray(kInitialSize);
2755 : Handle<RegExpMatchInfo> result = Handle<RegExpMatchInfo>::cast(elems);
2756 :
2757 : result->SetNumberOfCaptureRegisters(RegExpMatchInfo::kInitialCaptureIndices);
2758 : result->SetLastSubject(*empty_string());
2759 : result->SetLastInput(*undefined_value());
2760 : result->SetCapture(0, 0);
2761 : result->SetCapture(1, 0);
2762 :
2763 183 : return result;
2764 : }
2765 :
2766 361625 : Handle<Object> Factory::GlobalConstantFor(Handle<Name> name) {
2767 367772 : if (Name::Equals(name, undefined_string())) return undefined_value();
2768 357700 : if (Name::Equals(name, nan_string())) return nan_value();
2769 356288 : if (Name::Equals(name, infinity_string())) return infinity_value();
2770 : return Handle<Object>::null();
2771 : }
2772 :
2773 :
2774 254717 : Handle<Object> Factory::ToBoolean(bool value) {
2775 509434 : return value ? true_value() : false_value();
2776 : }
2777 :
2778 6668 : Handle<String> Factory::ToPrimitiveHintString(ToPrimitiveHint hint) {
2779 6668 : switch (hint) {
2780 : case ToPrimitiveHint::kDefault:
2781 : return default_string();
2782 : case ToPrimitiveHint::kNumber:
2783 : return number_string();
2784 : case ToPrimitiveHint::kString:
2785 : return string_string();
2786 : }
2787 0 : UNREACHABLE();
2788 : return Handle<String>::null();
2789 : }
2790 :
2791 328 : Handle<Map> Factory::CreateSloppyFunctionMap(FunctionMode function_mode) {
2792 328 : Handle<Map> map = NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
2793 328 : SetFunctionInstanceDescriptor(map, function_mode);
2794 : map->set_is_constructor(IsFunctionModeWithPrototype(function_mode));
2795 : map->set_is_callable();
2796 328 : return map;
2797 : }
2798 :
2799 328 : void Factory::SetFunctionInstanceDescriptor(Handle<Map> map,
2800 : FunctionMode function_mode) {
2801 328 : int size = IsFunctionModeWithPrototype(function_mode) ? 5 : 4;
2802 328 : Map::EnsureDescriptorSlack(map, size);
2803 :
2804 : PropertyAttributes ro_attribs =
2805 : static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
2806 : PropertyAttributes roc_attribs =
2807 : static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
2808 :
2809 : STATIC_ASSERT(JSFunction::kLengthDescriptorIndex == 0);
2810 : Handle<AccessorInfo> length =
2811 328 : Accessors::FunctionLengthInfo(isolate(), roc_attribs);
2812 : { // Add length.
2813 : Descriptor d = Descriptor::AccessorConstant(
2814 : Handle<Name>(Name::cast(length->name())), length, roc_attribs);
2815 328 : map->AppendDescriptor(&d);
2816 : }
2817 :
2818 : STATIC_ASSERT(JSFunction::kNameDescriptorIndex == 1);
2819 : Handle<AccessorInfo> name =
2820 328 : Accessors::FunctionNameInfo(isolate(), roc_attribs);
2821 : { // Add name.
2822 : Descriptor d = Descriptor::AccessorConstant(
2823 : Handle<Name>(Name::cast(name->name())), name, roc_attribs);
2824 328 : map->AppendDescriptor(&d);
2825 : }
2826 : Handle<AccessorInfo> args =
2827 328 : Accessors::FunctionArgumentsInfo(isolate(), ro_attribs);
2828 : { // Add arguments.
2829 : Descriptor d = Descriptor::AccessorConstant(
2830 : Handle<Name>(Name::cast(args->name())), args, ro_attribs);
2831 328 : map->AppendDescriptor(&d);
2832 : }
2833 : Handle<AccessorInfo> caller =
2834 328 : Accessors::FunctionCallerInfo(isolate(), ro_attribs);
2835 : { // Add caller.
2836 : Descriptor d = Descriptor::AccessorConstant(
2837 : Handle<Name>(Name::cast(caller->name())), caller, ro_attribs);
2838 328 : map->AppendDescriptor(&d);
2839 : }
2840 328 : if (IsFunctionModeWithPrototype(function_mode)) {
2841 170 : if (function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE) {
2842 : ro_attribs = static_cast<PropertyAttributes>(ro_attribs & ~READ_ONLY);
2843 : }
2844 : Handle<AccessorInfo> prototype =
2845 170 : Accessors::FunctionPrototypeInfo(isolate(), ro_attribs);
2846 : Descriptor d = Descriptor::AccessorConstant(
2847 : Handle<Name>(Name::cast(prototype->name())), prototype, ro_attribs);
2848 170 : map->AppendDescriptor(&d);
2849 : }
2850 328 : }
2851 :
2852 237 : Handle<Map> Factory::CreateStrictFunctionMap(
2853 : FunctionMode function_mode, Handle<JSFunction> empty_function) {
2854 237 : Handle<Map> map = NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
2855 237 : SetStrictFunctionInstanceDescriptor(map, function_mode);
2856 : map->set_is_constructor(IsFunctionModeWithPrototype(function_mode));
2857 : map->set_is_callable();
2858 237 : Map::SetPrototype(map, empty_function);
2859 237 : return map;
2860 : }
2861 :
2862 237 : void Factory::SetStrictFunctionInstanceDescriptor(Handle<Map> map,
2863 : FunctionMode function_mode) {
2864 237 : int size = IsFunctionModeWithPrototype(function_mode) ? 3 : 2;
2865 237 : Map::EnsureDescriptorSlack(map, size);
2866 :
2867 : PropertyAttributes rw_attribs =
2868 : static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
2869 : PropertyAttributes ro_attribs =
2870 : static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE | READ_ONLY);
2871 : PropertyAttributes roc_attribs =
2872 : static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
2873 :
2874 : DCHECK(function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE ||
2875 : function_mode == FUNCTION_WITH_READONLY_PROTOTYPE ||
2876 : function_mode == FUNCTION_WITHOUT_PROTOTYPE);
2877 : STATIC_ASSERT(JSFunction::kLengthDescriptorIndex == 0);
2878 : { // Add length.
2879 : Handle<AccessorInfo> length =
2880 237 : Accessors::FunctionLengthInfo(isolate(), roc_attribs);
2881 : Descriptor d = Descriptor::AccessorConstant(
2882 : handle(Name::cast(length->name())), length, roc_attribs);
2883 237 : map->AppendDescriptor(&d);
2884 : }
2885 :
2886 : STATIC_ASSERT(JSFunction::kNameDescriptorIndex == 1);
2887 : { // Add name.
2888 : Handle<AccessorInfo> name =
2889 237 : Accessors::FunctionNameInfo(isolate(), roc_attribs);
2890 : Descriptor d = Descriptor::AccessorConstant(
2891 : handle(Name::cast(name->name())), name, roc_attribs);
2892 237 : map->AppendDescriptor(&d);
2893 : }
2894 237 : if (IsFunctionModeWithPrototype(function_mode)) {
2895 : // Add prototype.
2896 : PropertyAttributes attribs =
2897 : function_mode == FUNCTION_WITH_WRITEABLE_PROTOTYPE ? rw_attribs
2898 158 : : ro_attribs;
2899 : Handle<AccessorInfo> prototype =
2900 158 : Accessors::FunctionPrototypeInfo(isolate(), attribs);
2901 : Descriptor d = Descriptor::AccessorConstant(
2902 : Handle<Name>(Name::cast(prototype->name())), prototype, attribs);
2903 158 : map->AppendDescriptor(&d);
2904 : }
2905 237 : }
2906 :
2907 79 : Handle<Map> Factory::CreateClassFunctionMap(Handle<JSFunction> empty_function) {
2908 79 : Handle<Map> map = NewMap(JS_FUNCTION_TYPE, JSFunction::kSize);
2909 79 : SetClassFunctionInstanceDescriptor(map);
2910 : map->set_is_constructor(true);
2911 : map->set_is_callable();
2912 79 : Map::SetPrototype(map, empty_function);
2913 79 : return map;
2914 : }
2915 :
2916 79 : void Factory::SetClassFunctionInstanceDescriptor(Handle<Map> map) {
2917 79 : Map::EnsureDescriptorSlack(map, 2);
2918 :
2919 : PropertyAttributes rw_attribs =
2920 : static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
2921 : PropertyAttributes roc_attribs =
2922 : static_cast<PropertyAttributes>(DONT_ENUM | READ_ONLY);
2923 :
2924 : STATIC_ASSERT(JSFunction::kLengthDescriptorIndex == 0);
2925 : { // Add length.
2926 : Handle<AccessorInfo> length =
2927 79 : Accessors::FunctionLengthInfo(isolate(), roc_attribs);
2928 : Descriptor d = Descriptor::AccessorConstant(
2929 : handle(Name::cast(length->name())), length, roc_attribs);
2930 79 : map->AppendDescriptor(&d);
2931 : }
2932 :
2933 : {
2934 : // Add prototype.
2935 : Handle<AccessorInfo> prototype =
2936 79 : Accessors::FunctionPrototypeInfo(isolate(), rw_attribs);
2937 : Descriptor d = Descriptor::AccessorConstant(
2938 : Handle<Name>(Name::cast(prototype->name())), prototype, rw_attribs);
2939 79 : map->AppendDescriptor(&d);
2940 : }
2941 79 : }
2942 :
2943 : } // namespace internal
2944 : } // namespace v8
|