blob: 45a79c1b3cc4477be0bdc3cfdc4825ba35cd1e1a [file] [log] [blame]
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001// 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.
Steve Blocka7e24c12009-10-30 11:49:00 +00004
Ben Murdochb8a8cc12014-11-26 15:28:44 +00005#include "src/factory.h"
Steve Blocka7e24c12009-10-30 11:49:00 +00006
Ben Murdochb8a8cc12014-11-26 15:28:44 +00007#include "src/allocation-site-scopes.h"
8#include "src/base/bits.h"
9#include "src/conversions.h"
10#include "src/isolate-inl.h"
11#include "src/macro-assembler.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000012
13namespace v8 {
14namespace internal {
15
16
Ben Murdochb8a8cc12014-11-26 15:28:44 +000017template<typename T>
18Handle<T> Factory::New(Handle<Map> map, AllocationSpace space) {
19 CALL_HEAP_FUNCTION(
20 isolate(),
21 isolate()->heap()->Allocate(*map, space),
22 T);
23}
24
25
26template<typename T>
27Handle<T> Factory::New(Handle<Map> map,
28 AllocationSpace space,
29 Handle<AllocationSite> allocation_site) {
30 CALL_HEAP_FUNCTION(
31 isolate(),
32 isolate()->heap()->Allocate(*map, space, *allocation_site),
33 T);
34}
35
36
37Handle<HeapObject> Factory::NewFillerObject(int size,
38 bool double_align,
39 AllocationSpace space) {
40 CALL_HEAP_FUNCTION(
41 isolate(),
42 isolate()->heap()->AllocateFillerObject(size, double_align, space),
43 HeapObject);
44}
45
46
47Handle<Box> Factory::NewBox(Handle<Object> value) {
48 Handle<Box> result = Handle<Box>::cast(NewStruct(BOX_TYPE));
49 result->set_value(*value);
50 return result;
51}
52
53
54Handle<Oddball> Factory::NewOddball(Handle<Map> map,
55 const char* to_string,
56 Handle<Object> to_number,
57 byte kind) {
58 Handle<Oddball> oddball = New<Oddball>(map, OLD_POINTER_SPACE);
59 Oddball::Initialize(isolate(), oddball, to_string, to_number, kind);
60 return oddball;
61}
62
63
Steve Blocka7e24c12009-10-30 11:49:00 +000064Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +000065 DCHECK(0 <= size);
Steve Block44f0eee2011-05-26 01:26:41 +010066 CALL_HEAP_FUNCTION(
67 isolate(),
68 isolate()->heap()->AllocateFixedArray(size, pretenure),
69 FixedArray);
Steve Blocka7e24c12009-10-30 11:49:00 +000070}
71
72
Steve Block6ded16b2010-05-10 14:33:55 +010073Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
74 PretenureFlag pretenure) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +000075 DCHECK(0 <= size);
Steve Block44f0eee2011-05-26 01:26:41 +010076 CALL_HEAP_FUNCTION(
77 isolate(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +000078 isolate()->heap()->AllocateFixedArrayWithFiller(size,
79 pretenure,
80 *the_hole_value()),
Steve Block44f0eee2011-05-26 01:26:41 +010081 FixedArray);
Steve Blocka7e24c12009-10-30 11:49:00 +000082}
83
84
Ben Murdochb8a8cc12014-11-26 15:28:44 +000085Handle<FixedArray> Factory::NewUninitializedFixedArray(int size) {
86 CALL_HEAP_FUNCTION(
87 isolate(),
88 isolate()->heap()->AllocateUninitializedFixedArray(size),
89 FixedArray);
90}
91
92
93Handle<FixedArrayBase> Factory::NewFixedDoubleArray(int size,
94 PretenureFlag pretenure) {
95 DCHECK(0 <= size);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000096 CALL_HEAP_FUNCTION(
97 isolate(),
98 isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
Ben Murdochb8a8cc12014-11-26 15:28:44 +000099 FixedArrayBase);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000100}
101
102
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000103Handle<FixedArrayBase> Factory::NewFixedDoubleArrayWithHoles(
104 int size,
Ben Murdochb0fe1622011-05-05 13:52:32 +0100105 PretenureFlag pretenure) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000106 DCHECK(0 <= size);
107 Handle<FixedArrayBase> array = NewFixedDoubleArray(size, pretenure);
108 if (size > 0) {
109 Handle<FixedDoubleArray> double_array =
110 Handle<FixedDoubleArray>::cast(array);
111 for (int i = 0; i < size; ++i) {
112 double_array->set_the_hole(i);
113 }
114 }
115 return array;
Ben Murdochb0fe1622011-05-05 13:52:32 +0100116}
117
118
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000119Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
120 const ConstantPoolArray::NumberOfEntries& small) {
121 DCHECK(small.total_count() > 0);
122 CALL_HEAP_FUNCTION(
123 isolate(),
124 isolate()->heap()->AllocateConstantPoolArray(small),
125 ConstantPoolArray);
126}
127
128
129Handle<ConstantPoolArray> Factory::NewExtendedConstantPoolArray(
130 const ConstantPoolArray::NumberOfEntries& small,
131 const ConstantPoolArray::NumberOfEntries& extended) {
132 DCHECK(small.total_count() > 0);
133 DCHECK(extended.total_count() > 0);
134 CALL_HEAP_FUNCTION(
135 isolate(),
136 isolate()->heap()->AllocateExtendedConstantPoolArray(small, extended),
137 ConstantPoolArray);
138}
139
140
141Handle<OrderedHashSet> Factory::NewOrderedHashSet() {
142 return OrderedHashSet::Allocate(isolate(), 4);
143}
144
145
146Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
147 return OrderedHashMap::Allocate(isolate(), 4);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100148}
149
150
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100151Handle<AccessorPair> Factory::NewAccessorPair() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000152 Handle<AccessorPair> accessors =
153 Handle<AccessorPair>::cast(NewStruct(ACCESSOR_PAIR_TYPE));
154 accessors->set_getter(*the_hole_value(), SKIP_WRITE_BARRIER);
155 accessors->set_setter(*the_hole_value(), SKIP_WRITE_BARRIER);
156 return accessors;
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100157}
158
159
160Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000161 Handle<TypeFeedbackInfo> info =
162 Handle<TypeFeedbackInfo>::cast(NewStruct(TYPE_FEEDBACK_INFO_TYPE));
163 info->initialize_storage();
164 return info;
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100165}
166
167
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000168// Internalized strings are created in the old generation (data space).
169Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
170 Utf8StringKey key(string, isolate()->heap()->HashSeed());
171 return InternalizeStringWithKey(&key);
Steve Block9fac8402011-05-12 15:51:54 +0100172}
173
Ben Murdoch257744e2011-11-30 15:57:28 +0000174
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000175// Internalized strings are created in the old generation (data space).
176Handle<String> Factory::InternalizeString(Handle<String> string) {
177 if (string->IsInternalizedString()) return string;
178 return StringTable::LookupString(isolate(), string);
Ben Murdoch257744e2011-11-30 15:57:28 +0000179}
180
181
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000182Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
183 OneByteStringKey key(string, isolate()->heap()->HashSeed());
184 return InternalizeStringWithKey(&key);
Steve Block9fac8402011-05-12 15:51:54 +0100185}
186
Steve Blocka7e24c12009-10-30 11:49:00 +0000187
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000188Handle<String> Factory::InternalizeOneByteString(
189 Handle<SeqOneByteString> string, int from, int length) {
190 SeqOneByteSubStringKey key(string, from, length);
191 return InternalizeStringWithKey(&key);
Steve Blocka7e24c12009-10-30 11:49:00 +0000192}
193
194
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000195Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
196 TwoByteStringKey key(string, isolate()->heap()->HashSeed());
197 return InternalizeStringWithKey(&key);
Steve Blocka7e24c12009-10-30 11:49:00 +0000198}
199
200
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000201template<class StringTableKey>
202Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
203 return StringTable::LookupKey(isolate(), key);
204}
205
206
207MaybeHandle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000208 PretenureFlag pretenure) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000209 int length = string.length();
210 if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
211 Handle<SeqOneByteString> result;
212 ASSIGN_RETURN_ON_EXCEPTION(
Steve Block44f0eee2011-05-26 01:26:41 +0100213 isolate(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000214 result,
215 NewRawOneByteString(string.length(), pretenure),
216 String);
217
218 DisallowHeapAllocation no_gc;
219 // Copy the characters into the new object.
220 CopyChars(SeqOneByteString::cast(*result)->GetChars(),
221 string.start(),
222 length);
223 return result;
224}
225
226MaybeHandle<String> Factory::NewStringFromUtf8(Vector<const char> string,
227 PretenureFlag pretenure) {
228 // Check for ASCII first since this is the common case.
229 const char* start = string.start();
230 int length = string.length();
231 int non_ascii_start = String::NonAsciiStart(start, length);
232 if (non_ascii_start >= length) {
233 // If the string is ASCII, we do not need to convert the characters
234 // since UTF8 is backwards compatible with ASCII.
235 return NewStringFromOneByte(Vector<const uint8_t>::cast(string), pretenure);
236 }
237
238 // Non-ASCII and we need to decode.
239 Access<UnicodeCache::Utf8Decoder>
240 decoder(isolate()->unicode_cache()->utf8_decoder());
241 decoder->Reset(string.start() + non_ascii_start,
242 length - non_ascii_start);
243 int utf16_length = decoder->Utf16Length();
244 DCHECK(utf16_length > 0);
245 // Allocate string.
246 Handle<SeqTwoByteString> result;
247 ASSIGN_RETURN_ON_EXCEPTION(
248 isolate(), result,
249 NewRawTwoByteString(non_ascii_start + utf16_length, pretenure),
250 String);
251 // Copy ASCII portion.
252 uint16_t* data = result->GetChars();
253 const char* ascii_data = string.start();
254 for (int i = 0; i < non_ascii_start; i++) {
255 *data++ = *ascii_data++;
256 }
257 // Now write the remainder.
258 decoder->WriteUtf16(data, utf16_length);
259 return result;
Leon Clarkeac952652010-07-15 11:15:24 +0100260}
261
262
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000263MaybeHandle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
264 PretenureFlag pretenure) {
265 int length = string.length();
266 const uc16* start = string.start();
267 if (String::IsOneByte(start, length)) {
268 if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
269 Handle<SeqOneByteString> result;
270 ASSIGN_RETURN_ON_EXCEPTION(
271 isolate(),
272 result,
273 NewRawOneByteString(length, pretenure),
274 String);
275 CopyChars(result->GetChars(), start, length);
276 return result;
277 } else {
278 Handle<SeqTwoByteString> result;
279 ASSIGN_RETURN_ON_EXCEPTION(
280 isolate(),
281 result,
282 NewRawTwoByteString(length, pretenure),
283 String);
284 CopyChars(result->GetChars(), start, length);
285 return result;
286 }
287}
288
289
290Handle<String> Factory::NewInternalizedStringFromUtf8(Vector<const char> str,
291 int chars,
292 uint32_t hash_field) {
293 CALL_HEAP_FUNCTION(
294 isolate(),
295 isolate()->heap()->AllocateInternalizedStringFromUtf8(
296 str, chars, hash_field),
297 String);
298}
299
300
301MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedString(
302 Vector<const uint8_t> str,
303 uint32_t hash_field) {
304 CALL_HEAP_FUNCTION(
305 isolate(),
306 isolate()->heap()->AllocateOneByteInternalizedString(str, hash_field),
307 String);
308}
309
310
311MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedSubString(
312 Handle<SeqOneByteString> string, int offset, int length,
313 uint32_t hash_field) {
314 CALL_HEAP_FUNCTION(
315 isolate(), isolate()->heap()->AllocateOneByteInternalizedString(
316 Vector<const uint8_t>(string->GetChars() + offset, length),
317 hash_field),
318 String);
319}
320
321
322MUST_USE_RESULT Handle<String> Factory::NewTwoByteInternalizedString(
323 Vector<const uc16> str,
324 uint32_t hash_field) {
325 CALL_HEAP_FUNCTION(
326 isolate(),
327 isolate()->heap()->AllocateTwoByteInternalizedString(str, hash_field),
328 String);
329}
330
331
332Handle<String> Factory::NewInternalizedStringImpl(
333 Handle<String> string, int chars, uint32_t hash_field) {
334 CALL_HEAP_FUNCTION(
335 isolate(),
336 isolate()->heap()->AllocateInternalizedStringImpl(
337 *string, chars, hash_field),
338 String);
339}
340
341
342MaybeHandle<Map> Factory::InternalizedStringMapForString(
343 Handle<String> string) {
344 // If the string is in new space it cannot be used as internalized.
345 if (isolate()->heap()->InNewSpace(*string)) return MaybeHandle<Map>();
346
347 // Find the corresponding internalized string map for strings.
348 switch (string->map()->instance_type()) {
349 case STRING_TYPE: return internalized_string_map();
350 case ONE_BYTE_STRING_TYPE:
351 return one_byte_internalized_string_map();
352 case EXTERNAL_STRING_TYPE: return external_internalized_string_map();
353 case EXTERNAL_ONE_BYTE_STRING_TYPE:
354 return external_one_byte_internalized_string_map();
355 case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
356 return external_internalized_string_with_one_byte_data_map();
357 case SHORT_EXTERNAL_STRING_TYPE:
358 return short_external_internalized_string_map();
359 case SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE:
360 return short_external_one_byte_internalized_string_map();
361 case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
362 return short_external_internalized_string_with_one_byte_data_map();
363 default: return MaybeHandle<Map>(); // No match found.
364 }
365}
366
367
368MaybeHandle<SeqOneByteString> Factory::NewRawOneByteString(
369 int length, PretenureFlag pretenure) {
370 if (length > String::kMaxLength || length < 0) {
371 THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqOneByteString);
372 }
373 CALL_HEAP_FUNCTION(
374 isolate(),
375 isolate()->heap()->AllocateRawOneByteString(length, pretenure),
376 SeqOneByteString);
377}
378
379
380MaybeHandle<SeqTwoByteString> Factory::NewRawTwoByteString(
381 int length, PretenureFlag pretenure) {
382 if (length > String::kMaxLength || length < 0) {
383 THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqTwoByteString);
384 }
Steve Block44f0eee2011-05-26 01:26:41 +0100385 CALL_HEAP_FUNCTION(
386 isolate(),
387 isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000388 SeqTwoByteString);
Steve Blocka7e24c12009-10-30 11:49:00 +0000389}
390
391
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000392Handle<String> Factory::LookupSingleCharacterStringFromCode(uint32_t code) {
393 if (code <= String::kMaxOneByteCharCodeU) {
394 {
395 DisallowHeapAllocation no_allocation;
396 Object* value = single_character_string_cache()->get(code);
397 if (value != *undefined_value()) {
398 return handle(String::cast(value), isolate());
399 }
400 }
401 uint8_t buffer[1];
402 buffer[0] = static_cast<uint8_t>(code);
403 Handle<String> result =
404 InternalizeOneByteString(Vector<const uint8_t>(buffer, 1));
405 single_character_string_cache()->set(code, *result);
406 return result;
407 }
408 DCHECK(code <= String::kMaxUtf16CodeUnitU);
409
410 Handle<SeqTwoByteString> result = NewRawTwoByteString(1).ToHandleChecked();
411 result->SeqTwoByteStringSet(0, static_cast<uint16_t>(code));
412 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000413}
414
415
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000416// Returns true for a character in a range. Both limits are inclusive.
417static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
418 // This makes uses of the the unsigned wraparound.
419 return character - from <= to - from;
420}
421
422
423static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
424 uint16_t c1,
425 uint16_t c2) {
426 // Numeric strings have a different hash algorithm not known by
427 // LookupTwoCharsStringIfExists, so we skip this step for such strings.
428 if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
429 Handle<String> result;
430 if (StringTable::LookupTwoCharsStringIfExists(isolate, c1, c2).
431 ToHandle(&result)) {
432 return result;
433 }
434 }
435
436 // Now we know the length is 2, we might as well make use of that fact
437 // when building the new string.
438 if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
439 // We can do this.
440 DCHECK(base::bits::IsPowerOfTwo32(String::kMaxOneByteCharCodeU +
441 1)); // because of this.
442 Handle<SeqOneByteString> str =
443 isolate->factory()->NewRawOneByteString(2).ToHandleChecked();
444 uint8_t* dest = str->GetChars();
445 dest[0] = static_cast<uint8_t>(c1);
446 dest[1] = static_cast<uint8_t>(c2);
447 return str;
448 } else {
449 Handle<SeqTwoByteString> str =
450 isolate->factory()->NewRawTwoByteString(2).ToHandleChecked();
451 uc16* dest = str->GetChars();
452 dest[0] = c1;
453 dest[1] = c2;
454 return str;
455 }
456}
457
458
459template<typename SinkChar, typename StringType>
460Handle<String> ConcatStringContent(Handle<StringType> result,
461 Handle<String> first,
462 Handle<String> second) {
463 DisallowHeapAllocation pointer_stays_valid;
464 SinkChar* sink = result->GetChars();
465 String::WriteToFlat(*first, sink, 0, first->length());
466 String::WriteToFlat(*second, sink + first->length(), 0, second->length());
467 return result;
468}
469
470
471MaybeHandle<String> Factory::NewConsString(Handle<String> left,
472 Handle<String> right) {
473 int left_length = left->length();
474 if (left_length == 0) return right;
475 int right_length = right->length();
476 if (right_length == 0) return left;
477
478 int length = left_length + right_length;
479
480 if (length == 2) {
481 uint16_t c1 = left->Get(0);
482 uint16_t c2 = right->Get(0);
483 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
484 }
485
486 // Make sure that an out of memory exception is thrown if the length
487 // of the new cons string is too large.
488 if (length > String::kMaxLength || length < 0) {
489 THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
490 }
491
492 bool left_is_one_byte = left->IsOneByteRepresentation();
493 bool right_is_one_byte = right->IsOneByteRepresentation();
494 bool is_one_byte = left_is_one_byte && right_is_one_byte;
495 bool is_one_byte_data_in_two_byte_string = false;
496 if (!is_one_byte) {
497 // At least one of the strings uses two-byte representation so we
498 // can't use the fast case code for short one-byte strings below, but
499 // we can try to save memory if all chars actually fit in one-byte.
500 is_one_byte_data_in_two_byte_string =
501 left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
502 if (is_one_byte_data_in_two_byte_string) {
503 isolate()->counters()->string_add_runtime_ext_to_one_byte()->Increment();
504 }
505 }
506
507 // If the resulting string is small make a flat string.
508 if (length < ConsString::kMinLength) {
509 // Note that neither of the two inputs can be a slice because:
510 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
511 DCHECK(left->IsFlat());
512 DCHECK(right->IsFlat());
513
514 STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
515 if (is_one_byte) {
516 Handle<SeqOneByteString> result =
517 NewRawOneByteString(length).ToHandleChecked();
518 DisallowHeapAllocation no_gc;
519 uint8_t* dest = result->GetChars();
520 // Copy left part.
521 const uint8_t* src =
522 left->IsExternalString()
523 ? Handle<ExternalOneByteString>::cast(left)->GetChars()
524 : Handle<SeqOneByteString>::cast(left)->GetChars();
525 for (int i = 0; i < left_length; i++) *dest++ = src[i];
526 // Copy right part.
527 src = right->IsExternalString()
528 ? Handle<ExternalOneByteString>::cast(right)->GetChars()
529 : Handle<SeqOneByteString>::cast(right)->GetChars();
530 for (int i = 0; i < right_length; i++) *dest++ = src[i];
531 return result;
532 }
533
534 return (is_one_byte_data_in_two_byte_string)
535 ? ConcatStringContent<uint8_t>(
536 NewRawOneByteString(length).ToHandleChecked(), left, right)
537 : ConcatStringContent<uc16>(
538 NewRawTwoByteString(length).ToHandleChecked(), left, right);
539 }
540
541 Handle<Map> map = (is_one_byte || is_one_byte_data_in_two_byte_string)
542 ? cons_one_byte_string_map()
543 : cons_string_map();
544 Handle<ConsString> result = New<ConsString>(map, NEW_SPACE);
545
546 DisallowHeapAllocation no_gc;
547 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
548
549 result->set_hash_field(String::kEmptyHashField);
550 result->set_length(length);
551 result->set_first(*left, mode);
552 result->set_second(*right, mode);
553 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000554}
555
556
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000557Handle<String> Factory::NewProperSubString(Handle<String> str,
558 int begin,
559 int end) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000560#if VERIFY_HEAP
561 if (FLAG_verify_heap) str->StringVerify();
562#endif
563 DCHECK(begin > 0 || end < str->length());
564
565 str = String::Flatten(str);
566
567 int length = end - begin;
568 if (length <= 0) return empty_string();
569 if (length == 1) {
570 return LookupSingleCharacterStringFromCode(str->Get(begin));
571 }
572 if (length == 2) {
573 // Optimization for 2-byte strings often used as keys in a decompression
574 // dictionary. Check whether we already have the string in the string
575 // table to prevent creation of many unnecessary strings.
576 uint16_t c1 = str->Get(begin);
577 uint16_t c2 = str->Get(begin + 1);
578 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
579 }
580
581 if (!FLAG_string_slices || length < SlicedString::kMinLength) {
582 if (str->IsOneByteRepresentation()) {
583 Handle<SeqOneByteString> result =
584 NewRawOneByteString(length).ToHandleChecked();
585 uint8_t* dest = result->GetChars();
586 DisallowHeapAllocation no_gc;
587 String::WriteToFlat(*str, dest, begin, end);
588 return result;
589 } else {
590 Handle<SeqTwoByteString> result =
591 NewRawTwoByteString(length).ToHandleChecked();
592 uc16* dest = result->GetChars();
593 DisallowHeapAllocation no_gc;
594 String::WriteToFlat(*str, dest, begin, end);
595 return result;
596 }
597 }
598
599 int offset = begin;
600
601 if (str->IsSlicedString()) {
602 Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
603 str = Handle<String>(slice->parent(), isolate());
604 offset += slice->offset();
605 }
606
607 DCHECK(str->IsSeqString() || str->IsExternalString());
608 Handle<Map> map = str->IsOneByteRepresentation()
609 ? sliced_one_byte_string_map()
610 : sliced_string_map();
611 Handle<SlicedString> slice = New<SlicedString>(map, NEW_SPACE);
612
613 slice->set_hash_field(String::kEmptyHashField);
614 slice->set_length(length);
615 slice->set_parent(*str);
616 slice->set_offset(offset);
617 return slice;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000618}
619
620
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000621MaybeHandle<String> Factory::NewExternalStringFromOneByte(
622 const ExternalOneByteString::Resource* resource) {
623 size_t length = resource->length();
624 if (length > static_cast<size_t>(String::kMaxLength)) {
625 THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
626 }
627
628 Handle<Map> map = external_one_byte_string_map();
629 Handle<ExternalOneByteString> external_string =
630 New<ExternalOneByteString>(map, NEW_SPACE);
631 external_string->set_length(static_cast<int>(length));
632 external_string->set_hash_field(String::kEmptyHashField);
633 external_string->set_resource(resource);
634
635 return external_string;
Steve Blocka7e24c12009-10-30 11:49:00 +0000636}
637
638
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000639MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100640 const ExternalTwoByteString::Resource* resource) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000641 size_t length = resource->length();
642 if (length > static_cast<size_t>(String::kMaxLength)) {
643 THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
644 }
645
646 // For small strings we check whether the resource contains only
647 // one byte characters. If yes, we use a different string map.
648 static const size_t kOneByteCheckLengthLimit = 32;
649 bool is_one_byte = length <= kOneByteCheckLengthLimit &&
650 String::IsOneByte(resource->data(), static_cast<int>(length));
651 Handle<Map> map = is_one_byte ?
652 external_string_with_one_byte_data_map() : external_string_map();
653 Handle<ExternalTwoByteString> external_string =
654 New<ExternalTwoByteString>(map, NEW_SPACE);
655 external_string->set_length(static_cast<int>(length));
656 external_string->set_hash_field(String::kEmptyHashField);
657 external_string->set_resource(resource);
658
659 return external_string;
Steve Blocka7e24c12009-10-30 11:49:00 +0000660}
661
662
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000663Handle<Symbol> Factory::NewSymbol() {
Steve Block44f0eee2011-05-26 01:26:41 +0100664 CALL_HEAP_FUNCTION(
665 isolate(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000666 isolate()->heap()->AllocateSymbol(),
667 Symbol);
668}
669
670
671Handle<Symbol> Factory::NewPrivateSymbol() {
672 Handle<Symbol> symbol = NewSymbol();
673 symbol->set_is_private(true);
674 return symbol;
675}
676
677
678Handle<Symbol> Factory::NewPrivateOwnSymbol() {
679 Handle<Symbol> symbol = NewSymbol();
680 symbol->set_is_private(true);
681 symbol->set_is_own(true);
682 return symbol;
683}
684
685
686Handle<Context> Factory::NewNativeContext() {
687 Handle<FixedArray> array = NewFixedArray(Context::NATIVE_CONTEXT_SLOTS);
688 array->set_map_no_write_barrier(*native_context_map());
689 Handle<Context> context = Handle<Context>::cast(array);
690 context->set_js_array_maps(*undefined_value());
691 DCHECK(context->IsNativeContext());
692 return context;
693}
694
695
696Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
697 Handle<ScopeInfo> scope_info) {
698 Handle<FixedArray> array =
699 NewFixedArray(scope_info->ContextLength(), TENURED);
700 array->set_map_no_write_barrier(*global_context_map());
701 Handle<Context> context = Handle<Context>::cast(array);
702 context->set_closure(*function);
703 context->set_previous(function->context());
704 context->set_extension(*scope_info);
705 context->set_global_object(function->context()->global_object());
706 DCHECK(context->IsGlobalContext());
707 return context;
708}
709
710
711Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
712 Handle<FixedArray> array =
713 NewFixedArray(scope_info->ContextLength(), TENURED);
714 array->set_map_no_write_barrier(*module_context_map());
715 // Instance link will be set later.
716 Handle<Context> context = Handle<Context>::cast(array);
717 context->set_extension(Smi::FromInt(0));
718 return context;
Steve Blocka7e24c12009-10-30 11:49:00 +0000719}
720
721
722Handle<Context> Factory::NewFunctionContext(int length,
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000723 Handle<JSFunction> function) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000724 DCHECK(length >= Context::MIN_CONTEXT_SLOTS);
725 Handle<FixedArray> array = NewFixedArray(length);
726 array->set_map_no_write_barrier(*function_context_map());
727 Handle<Context> context = Handle<Context>::cast(array);
728 context->set_closure(*function);
729 context->set_previous(function->context());
730 context->set_extension(Smi::FromInt(0));
731 context->set_global_object(function->context()->global_object());
732 return context;
Steve Blocka7e24c12009-10-30 11:49:00 +0000733}
734
735
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000736Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
737 Handle<Context> previous,
738 Handle<String> name,
739 Handle<Object> thrown_object) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000740 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
741 Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
742 array->set_map_no_write_barrier(*catch_context_map());
743 Handle<Context> context = Handle<Context>::cast(array);
744 context->set_closure(*function);
745 context->set_previous(*previous);
746 context->set_extension(*name);
747 context->set_global_object(previous->global_object());
748 context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
749 return context;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000750}
751
752
753Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
754 Handle<Context> previous,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000755 Handle<JSReceiver> extension) {
756 Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS);
757 array->set_map_no_write_barrier(*with_context_map());
758 Handle<Context> context = Handle<Context>::cast(array);
759 context->set_closure(*function);
760 context->set_previous(*previous);
761 context->set_extension(*extension);
762 context->set_global_object(previous->global_object());
763 return context;
Steve Blocka7e24c12009-10-30 11:49:00 +0000764}
765
766
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000767Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
768 Handle<Context> previous,
769 Handle<ScopeInfo> scope_info) {
770 Handle<FixedArray> array =
771 NewFixedArrayWithHoles(scope_info->ContextLength());
772 array->set_map_no_write_barrier(*block_context_map());
773 Handle<Context> context = Handle<Context>::cast(array);
774 context->set_closure(*function);
775 context->set_previous(*previous);
776 context->set_extension(*scope_info);
777 context->set_global_object(previous->global_object());
778 return context;
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000779}
780
781
Steve Blocka7e24c12009-10-30 11:49:00 +0000782Handle<Struct> Factory::NewStruct(InstanceType type) {
Steve Block44f0eee2011-05-26 01:26:41 +0100783 CALL_HEAP_FUNCTION(
784 isolate(),
785 isolate()->heap()->AllocateStruct(type),
786 Struct);
Steve Blocka7e24c12009-10-30 11:49:00 +0000787}
788
789
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000790Handle<CodeCache> Factory::NewCodeCache() {
791 Handle<CodeCache> code_cache =
792 Handle<CodeCache>::cast(NewStruct(CODE_CACHE_TYPE));
793 code_cache->set_default_cache(*empty_fixed_array(), SKIP_WRITE_BARRIER);
794 code_cache->set_normal_type_cache(*undefined_value(), SKIP_WRITE_BARRIER);
795 return code_cache;
796}
797
798
799Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
800 int aliased_context_slot) {
801 Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
802 NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
803 entry->set_aliased_context_slot(aliased_context_slot);
804 return entry;
805}
806
807
808Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
809 return Handle<DeclaredAccessorDescriptor>::cast(
810 NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
811}
812
813
814Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
815 Handle<DeclaredAccessorInfo> info =
816 Handle<DeclaredAccessorInfo>::cast(
817 NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
818 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
819 return info;
820}
821
822
823Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
824 Handle<ExecutableAccessorInfo> info =
825 Handle<ExecutableAccessorInfo>::cast(
826 NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
Steve Blocka7e24c12009-10-30 11:49:00 +0000827 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
828 return info;
829}
830
831
832Handle<Script> Factory::NewScript(Handle<String> source) {
833 // Generate id for this script.
Steve Block44f0eee2011-05-26 01:26:41 +0100834 Heap* heap = isolate()->heap();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000835 int id = heap->last_script_id()->value() + 1;
836 if (!Smi::IsValid(id) || id < 0) id = 1;
837 heap->set_last_script_id(Smi::FromInt(id));
Steve Blocka7e24c12009-10-30 11:49:00 +0000838
839 // Create and initialize script object.
Ben Murdoch257744e2011-11-30 15:57:28 +0000840 Handle<Foreign> wrapper = NewForeign(0, TENURED);
Steve Blocka7e24c12009-10-30 11:49:00 +0000841 Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
842 script->set_source(*source);
Steve Block44f0eee2011-05-26 01:26:41 +0100843 script->set_name(heap->undefined_value());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000844 script->set_id(Smi::FromInt(id));
Steve Blocka7e24c12009-10-30 11:49:00 +0000845 script->set_line_offset(Smi::FromInt(0));
846 script->set_column_offset(Smi::FromInt(0));
Steve Block44f0eee2011-05-26 01:26:41 +0100847 script->set_context_data(heap->undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +0000848 script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
Steve Blocka7e24c12009-10-30 11:49:00 +0000849 script->set_wrapper(*wrapper);
Steve Block44f0eee2011-05-26 01:26:41 +0100850 script->set_line_ends(heap->undefined_value());
851 script->set_eval_from_shared(heap->undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +0000852 script->set_eval_from_instructions_offset(Smi::FromInt(0));
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000853 script->set_flags(Smi::FromInt(0));
Steve Blocka7e24c12009-10-30 11:49:00 +0000854
855 return script;
856}
857
858
Ben Murdoch257744e2011-11-30 15:57:28 +0000859Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
Steve Block44f0eee2011-05-26 01:26:41 +0100860 CALL_HEAP_FUNCTION(isolate(),
Ben Murdoch257744e2011-11-30 15:57:28 +0000861 isolate()->heap()->AllocateForeign(addr, pretenure),
862 Foreign);
Steve Blocka7e24c12009-10-30 11:49:00 +0000863}
864
865
Ben Murdoch257744e2011-11-30 15:57:28 +0000866Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
867 return NewForeign((Address) desc, TENURED);
Steve Blocka7e24c12009-10-30 11:49:00 +0000868}
869
870
871Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000872 DCHECK(0 <= length);
Steve Block44f0eee2011-05-26 01:26:41 +0100873 CALL_HEAP_FUNCTION(
874 isolate(),
875 isolate()->heap()->AllocateByteArray(length, pretenure),
876 ByteArray);
Steve Blocka7e24c12009-10-30 11:49:00 +0000877}
878
879
Steve Block3ce2e202009-11-05 08:53:23 +0000880Handle<ExternalArray> Factory::NewExternalArray(int length,
881 ExternalArrayType array_type,
882 void* external_pointer,
883 PretenureFlag pretenure) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000884 DCHECK(0 <= length && length <= Smi::kMaxValue);
Steve Block44f0eee2011-05-26 01:26:41 +0100885 CALL_HEAP_FUNCTION(
886 isolate(),
887 isolate()->heap()->AllocateExternalArray(length,
888 array_type,
889 external_pointer,
890 pretenure),
891 ExternalArray);
Steve Block3ce2e202009-11-05 08:53:23 +0000892}
893
894
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000895Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
896 int length,
897 ExternalArrayType array_type,
898 PretenureFlag pretenure) {
899 DCHECK(0 <= length && length <= Smi::kMaxValue);
Steve Block44f0eee2011-05-26 01:26:41 +0100900 CALL_HEAP_FUNCTION(
901 isolate(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000902 isolate()->heap()->AllocateFixedTypedArray(length,
903 array_type,
904 pretenure),
905 FixedTypedArrayBase);
906}
907
908
909Handle<Cell> Factory::NewCell(Handle<Object> value) {
910 AllowDeferredHandleDereference convert_to_cell;
911 CALL_HEAP_FUNCTION(
912 isolate(),
913 isolate()->heap()->AllocateCell(*value),
914 Cell);
915}
916
917
918Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
919 CALL_HEAP_FUNCTION(
920 isolate(),
921 isolate()->heap()->AllocatePropertyCell(),
922 PropertyCell);
923}
924
925
926Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
927 AllowDeferredHandleDereference convert_to_cell;
928 Handle<PropertyCell> cell = NewPropertyCellWithHole();
929 PropertyCell::SetValueInferType(cell, value);
930 return cell;
931}
932
933
934Handle<AllocationSite> Factory::NewAllocationSite() {
935 Handle<Map> map = allocation_site_map();
936 Handle<AllocationSite> site = New<AllocationSite>(map, OLD_POINTER_SPACE);
937 site->Initialize();
938
939 // Link the site
940 site->set_weak_next(isolate()->heap()->allocation_sites_list());
941 isolate()->heap()->set_allocation_sites_list(*site);
942 return site;
Ben Murdochb0fe1622011-05-05 13:52:32 +0100943}
944
945
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100946Handle<Map> Factory::NewMap(InstanceType type,
947 int instance_size,
948 ElementsKind elements_kind) {
Steve Block44f0eee2011-05-26 01:26:41 +0100949 CALL_HEAP_FUNCTION(
950 isolate(),
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100951 isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
Steve Block44f0eee2011-05-26 01:26:41 +0100952 Map);
Steve Blocka7e24c12009-10-30 11:49:00 +0000953}
954
955
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000956Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> object) {
957 CALL_HEAP_FUNCTION(isolate(),
958 isolate()->heap()->CopyJSObject(*object, NULL),
959 JSObject);
Steve Blocka7e24c12009-10-30 11:49:00 +0000960}
961
962
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000963Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
964 Handle<JSObject> object,
965 Handle<AllocationSite> site) {
966 CALL_HEAP_FUNCTION(isolate(),
967 isolate()->heap()->CopyJSObject(
968 *object,
969 site.is_null() ? NULL : *site),
970 JSObject);
Steve Blocka7e24c12009-10-30 11:49:00 +0000971}
972
973
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000974Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
975 Handle<Map> map) {
976 CALL_HEAP_FUNCTION(isolate(),
977 isolate()->heap()->CopyFixedArrayWithMap(*array, *map),
978 FixedArray);
Steve Block1e0659c2011-05-24 12:43:12 +0100979}
980
981
Steve Blocka7e24c12009-10-30 11:49:00 +0000982Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000983 CALL_HEAP_FUNCTION(isolate(),
984 isolate()->heap()->CopyFixedArray(*array),
985 FixedArray);
986}
987
988
989Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
990 Handle<FixedArray> array) {
991 DCHECK(isolate()->heap()->InNewSpace(*array));
992 CALL_HEAP_FUNCTION(isolate(),
993 isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
994 FixedArray);
Steve Blocka7e24c12009-10-30 11:49:00 +0000995}
996
997
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100998Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
999 Handle<FixedDoubleArray> array) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001000 CALL_HEAP_FUNCTION(isolate(),
1001 isolate()->heap()->CopyFixedDoubleArray(*array),
1002 FixedDoubleArray);
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001003}
1004
1005
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001006Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
1007 Handle<ConstantPoolArray> array) {
1008 CALL_HEAP_FUNCTION(isolate(),
1009 isolate()->heap()->CopyConstantPoolArray(*array),
1010 ConstantPoolArray);
Steve Blocka7e24c12009-10-30 11:49:00 +00001011}
1012
1013
1014Handle<Object> Factory::NewNumber(double value,
1015 PretenureFlag pretenure) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001016 // We need to distinguish the minus zero value and this cannot be
1017 // done after conversion to int. Doing this by comparing bit
1018 // patterns is faster than using fpclassify() et al.
1019 if (IsMinusZero(value)) return NewHeapNumber(-0.0, IMMUTABLE, pretenure);
1020
1021 int int_value = FastD2I(value);
1022 if (value == int_value && Smi::IsValid(int_value)) {
1023 return handle(Smi::FromInt(int_value), isolate());
1024 }
1025
1026 // Materialize the value in the heap.
1027 return NewHeapNumber(value, IMMUTABLE, pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00001028}
1029
1030
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001031Handle<Object> Factory::NewNumberFromInt(int32_t value,
1032 PretenureFlag pretenure) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001033 if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
1034 // Bypass NewNumber to avoid various redundant checks.
1035 return NewHeapNumber(FastI2D(value), IMMUTABLE, pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00001036}
1037
1038
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001039Handle<Object> Factory::NewNumberFromUint(uint32_t value,
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001040 PretenureFlag pretenure) {
1041 int32_t int32v = static_cast<int32_t>(value);
1042 if (int32v >= 0 && Smi::IsValid(int32v)) {
1043 return handle(Smi::FromInt(int32v), isolate());
1044 }
1045 return NewHeapNumber(FastUI2D(value), IMMUTABLE, pretenure);
1046}
1047
1048
1049Handle<HeapNumber> Factory::NewHeapNumber(double value,
1050 MutableMode mode,
1051 PretenureFlag pretenure) {
Steve Block44f0eee2011-05-26 01:26:41 +01001052 CALL_HEAP_FUNCTION(
1053 isolate(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001054 isolate()->heap()->AllocateHeapNumber(value, mode, pretenure),
1055 HeapNumber);
Steve Blocka7e24c12009-10-30 11:49:00 +00001056}
1057
1058
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001059MaybeHandle<Object> Factory::NewTypeError(const char* message,
1060 Vector<Handle<Object> > args) {
1061 return NewError("MakeTypeError", message, args);
Steve Blocka7e24c12009-10-30 11:49:00 +00001062}
1063
1064
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001065MaybeHandle<Object> Factory::NewTypeError(Handle<String> message) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001066 return NewError("$TypeError", message);
1067}
1068
1069
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001070MaybeHandle<Object> Factory::NewRangeError(const char* message,
1071 Vector<Handle<Object> > args) {
1072 return NewError("MakeRangeError", message, args);
Steve Blocka7e24c12009-10-30 11:49:00 +00001073}
1074
1075
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001076MaybeHandle<Object> Factory::NewRangeError(Handle<String> message) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001077 return NewError("$RangeError", message);
1078}
1079
1080
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001081MaybeHandle<Object> Factory::NewSyntaxError(const char* message,
1082 Handle<JSArray> args) {
1083 return NewError("MakeSyntaxError", message, args);
Steve Blocka7e24c12009-10-30 11:49:00 +00001084}
1085
1086
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001087MaybeHandle<Object> Factory::NewSyntaxError(Handle<String> message) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001088 return NewError("$SyntaxError", message);
1089}
1090
1091
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001092MaybeHandle<Object> Factory::NewReferenceError(const char* message,
1093 Vector<Handle<Object> > args) {
1094 return NewError("MakeReferenceError", message, args);
Steve Blocka7e24c12009-10-30 11:49:00 +00001095}
1096
1097
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001098MaybeHandle<Object> Factory::NewReferenceError(const char* message,
1099 Handle<JSArray> args) {
1100 return NewError("MakeReferenceError", message, args);
1101}
1102
1103
1104MaybeHandle<Object> Factory::NewReferenceError(Handle<String> message) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001105 return NewError("$ReferenceError", message);
1106}
1107
1108
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001109MaybeHandle<Object> Factory::NewError(const char* maker, const char* message,
1110 Vector<Handle<Object> > args) {
1111 // Instantiate a closeable HandleScope for EscapeFrom.
1112 v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
Steve Block44f0eee2011-05-26 01:26:41 +01001113 Handle<FixedArray> array = NewFixedArray(args.length());
Steve Blocka7e24c12009-10-30 11:49:00 +00001114 for (int i = 0; i < args.length(); i++) {
1115 array->set(i, *args[i]);
1116 }
Steve Block44f0eee2011-05-26 01:26:41 +01001117 Handle<JSArray> object = NewJSArrayWithElements(array);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001118 Handle<Object> result;
1119 ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
1120 NewError(maker, message, object), Object);
Steve Blocka7e24c12009-10-30 11:49:00 +00001121 return result.EscapeFrom(&scope);
1122}
1123
1124
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001125MaybeHandle<Object> Factory::NewEvalError(const char* message,
1126 Vector<Handle<Object> > args) {
1127 return NewError("MakeEvalError", message, args);
Steve Blocka7e24c12009-10-30 11:49:00 +00001128}
1129
1130
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001131MaybeHandle<Object> Factory::NewError(const char* message,
1132 Vector<Handle<Object> > args) {
1133 return NewError("MakeError", message, args);
Steve Blocka7e24c12009-10-30 11:49:00 +00001134}
1135
1136
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001137Handle<String> Factory::EmergencyNewError(const char* message,
1138 Handle<JSArray> args) {
1139 const int kBufferSize = 1000;
1140 char buffer[kBufferSize];
1141 size_t space = kBufferSize;
1142 char* p = &buffer[0];
1143
1144 Vector<char> v(buffer, kBufferSize);
1145 StrNCpy(v, message, space);
1146 space -= Min(space, strlen(message));
1147 p = &buffer[kBufferSize] - space;
1148
1149 for (int i = 0; i < Smi::cast(args->length())->value(); i++) {
1150 if (space > 0) {
1151 *p++ = ' ';
1152 space--;
1153 if (space > 0) {
1154 Handle<String> arg_str = Handle<String>::cast(
1155 Object::GetElement(isolate(), args, i).ToHandleChecked());
1156 SmartArrayPointer<char> arg = arg_str->ToCString();
1157 Vector<char> v2(p, static_cast<int>(space));
1158 StrNCpy(v2, arg.get(), space);
1159 space -= Min(space, strlen(arg.get()));
1160 p = &buffer[kBufferSize] - space;
1161 }
1162 }
1163 }
1164 if (space > 0) {
1165 *p = '\0';
1166 } else {
1167 buffer[kBufferSize - 1] = '\0';
1168 }
1169 return NewStringFromUtf8(CStrVector(buffer), TENURED).ToHandleChecked();
1170}
1171
1172
1173MaybeHandle<Object> Factory::NewError(const char* maker, const char* message,
1174 Handle<JSArray> args) {
1175 Handle<String> make_str = InternalizeUtf8String(maker);
1176 Handle<Object> fun_obj = Object::GetProperty(
1177 isolate()->js_builtins_object(), make_str).ToHandleChecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00001178 // If the builtins haven't been properly configured yet this error
1179 // constructor may not have been defined. Bail out.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001180 if (!fun_obj->IsJSFunction()) {
1181 return EmergencyNewError(message, args);
1182 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001183 Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001184 Handle<Object> message_obj = InternalizeUtf8String(message);
1185 Handle<Object> argv[] = { message_obj, args };
Steve Blocka7e24c12009-10-30 11:49:00 +00001186
1187 // Invoke the JavaScript factory method. If an exception is thrown while
1188 // running the factory method, use the exception as the result.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001189 Handle<Object> result;
1190 MaybeHandle<Object> exception;
1191 if (!Execution::TryCall(fun,
1192 isolate()->js_builtins_object(),
1193 arraysize(argv),
1194 argv,
1195 &exception).ToHandle(&result)) {
1196 return exception;
1197 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001198 return result;
1199}
1200
1201
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001202MaybeHandle<Object> Factory::NewError(Handle<String> message) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001203 return NewError("$Error", message);
1204}
1205
1206
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001207MaybeHandle<Object> Factory::NewError(const char* constructor,
1208 Handle<String> message) {
1209 Handle<String> constr = InternalizeUtf8String(constructor);
1210 Handle<JSFunction> fun = Handle<JSFunction>::cast(Object::GetProperty(
1211 isolate()->js_builtins_object(), constr).ToHandleChecked());
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001212 Handle<Object> argv[] = { message };
Steve Blocka7e24c12009-10-30 11:49:00 +00001213
1214 // Invoke the JavaScript factory method. If an exception is thrown while
1215 // running the factory method, use the exception as the result.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001216 Handle<Object> result;
1217 MaybeHandle<Object> exception;
1218 if (!Execution::TryCall(fun,
1219 isolate()->js_builtins_object(),
1220 arraysize(argv),
1221 argv,
1222 &exception).ToHandle(&result)) {
1223 return exception;
1224 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001225 return result;
1226}
1227
1228
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001229void Factory::InitializeFunction(Handle<JSFunction> function,
1230 Handle<SharedFunctionInfo> info,
1231 Handle<Context> context) {
1232 function->initialize_properties();
1233 function->initialize_elements();
1234 function->set_shared(*info);
1235 function->set_code(info->code());
1236 function->set_context(*context);
1237 function->set_prototype_or_initial_map(*the_hole_value());
1238 function->set_literals_or_bindings(*empty_fixed_array());
1239 function->set_next_function_link(*undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +00001240}
1241
1242
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001243Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1244 Handle<SharedFunctionInfo> info,
1245 Handle<Context> context,
1246 PretenureFlag pretenure) {
1247 AllocationSpace space = pretenure == TENURED ? OLD_POINTER_SPACE : NEW_SPACE;
1248 Handle<JSFunction> result = New<JSFunction>(map, space);
1249 InitializeFunction(result, info, context);
1250 return result;
1251}
Steve Blocka7e24c12009-10-30 11:49:00 +00001252
Steve Blocka7e24c12009-10-30 11:49:00 +00001253
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001254Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1255 Handle<String> name,
1256 MaybeHandle<Code> code) {
1257 Handle<Context> context(isolate()->native_context());
1258 Handle<SharedFunctionInfo> info = NewSharedFunctionInfo(name, code);
1259 DCHECK((info->strict_mode() == SLOPPY) &&
1260 (map.is_identical_to(isolate()->sloppy_function_map()) ||
1261 map.is_identical_to(
1262 isolate()->sloppy_function_without_prototype_map()) ||
1263 map.is_identical_to(
1264 isolate()->sloppy_function_with_readonly_prototype_map())));
1265 return NewFunction(map, info, context);
1266}
Steve Blocka7e24c12009-10-30 11:49:00 +00001267
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001268
1269Handle<JSFunction> Factory::NewFunction(Handle<String> name) {
1270 return NewFunction(
1271 isolate()->sloppy_function_map(), name, MaybeHandle<Code>());
Steve Blocka7e24c12009-10-30 11:49:00 +00001272}
1273
1274
Steve Block6ded16b2010-05-10 14:33:55 +01001275Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1276 Handle<Code> code) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001277 return NewFunction(
1278 isolate()->sloppy_function_without_prototype_map(), name, code);
1279}
1280
1281
1282Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1283 Handle<Code> code,
1284 Handle<Object> prototype,
1285 bool read_only_prototype) {
1286 Handle<Map> map = read_only_prototype
1287 ? isolate()->sloppy_function_with_readonly_prototype_map()
1288 : isolate()->sloppy_function_map();
1289 Handle<JSFunction> result = NewFunction(map, name, code);
1290 result->set_prototype_or_initial_map(*prototype);
1291 return result;
1292}
1293
1294
1295Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1296 Handle<Code> code,
1297 Handle<Object> prototype,
1298 InstanceType type,
1299 int instance_size,
1300 bool read_only_prototype) {
1301 // Allocate the function
1302 Handle<JSFunction> function = NewFunction(
1303 name, code, prototype, read_only_prototype);
1304
1305 Handle<Map> initial_map = NewMap(
1306 type, instance_size, GetInitialFastElementsKind());
1307 if (prototype->IsTheHole() && !function->shared()->is_generator()) {
1308 prototype = NewFunctionPrototype(function);
1309 }
1310
1311 JSFunction::SetInitialMap(function, initial_map,
1312 Handle<JSReceiver>::cast(prototype));
1313
Steve Block6ded16b2010-05-10 14:33:55 +01001314 return function;
1315}
1316
1317
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001318Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1319 Handle<Code> code,
1320 InstanceType type,
1321 int instance_size) {
1322 return NewFunction(name, code, the_hole_value(), type, instance_size);
1323}
1324
1325
1326Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
1327 // Make sure to use globals from the function's context, since the function
1328 // can be from a different context.
1329 Handle<Context> native_context(function->context()->native_context());
1330 Handle<Map> new_map;
1331 if (function->shared()->is_generator()) {
1332 // Generator prototypes can share maps since they don't have "constructor"
1333 // properties.
1334 new_map = handle(native_context->generator_object_prototype_map());
1335 } else {
1336 // Each function prototype gets a fresh map to avoid unwanted sharing of
1337 // maps between prototypes of different constructors.
1338 Handle<JSFunction> object_function(native_context->object_function());
1339 DCHECK(object_function->has_initial_map());
1340 new_map = handle(object_function->initial_map());
1341 }
1342
1343 DCHECK(!new_map->is_prototype_map());
1344 Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
1345
1346 if (!function->shared()->is_generator()) {
1347 JSObject::AddProperty(prototype, constructor_string(), function, DONT_ENUM);
1348 }
1349
1350 return prototype;
1351}
1352
1353
1354Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1355 Handle<SharedFunctionInfo> info,
1356 Handle<Context> context,
1357 PretenureFlag pretenure) {
1358 int map_index = Context::FunctionMapIndex(info->strict_mode(), info->kind());
1359 Handle<Map> map(Map::cast(context->native_context()->get(map_index)));
1360 Handle<JSFunction> result = NewFunction(map, info, context, pretenure);
1361
1362 if (info->ic_age() != isolate()->heap()->global_ic_age()) {
1363 info->ResetForNewContext(isolate()->heap()->global_ic_age());
1364 }
1365
1366 int index = info->SearchOptimizedCodeMap(context->native_context(),
1367 BailoutId::None());
1368 if (!info->bound() && index < 0) {
1369 int number_of_literals = info->num_literals();
1370 Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
1371 if (number_of_literals > 0) {
1372 // Store the native context in the literals array prefix. This
1373 // context will be used when creating object, regexp and array
1374 // literals in this function.
1375 literals->set(JSFunction::kLiteralNativeContextIndex,
1376 context->native_context());
1377 }
1378 result->set_literals(*literals);
1379 }
1380
1381 if (index > 0) {
1382 // Caching of optimized code enabled and optimized code found.
1383 FixedArray* literals = info->GetLiteralsFromOptimizedCodeMap(index);
1384 if (literals != NULL) result->set_literals(literals);
1385 Code* code = info->GetCodeFromOptimizedCodeMap(index);
1386 DCHECK(!code->marked_for_deoptimization());
1387 result->ReplaceCode(code);
1388 return result;
1389 }
1390
1391 if (isolate()->use_crankshaft() &&
1392 FLAG_always_opt &&
1393 result->is_compiled() &&
1394 !info->is_toplevel() &&
1395 info->allows_lazy_compilation() &&
1396 !info->optimization_disabled() &&
1397 !isolate()->DebuggerHasBreakPoints()) {
1398 result->MarkForOptimization();
1399 }
1400 return result;
1401}
1402
1403
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001404Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001405 Handle<FixedArray> array = NewFixedArray(length, TENURED);
1406 array->set_map_no_write_barrier(*scope_info_map());
1407 Handle<ScopeInfo> scope_info = Handle<ScopeInfo>::cast(array);
1408 return scope_info;
1409}
1410
1411
1412Handle<JSObject> Factory::NewExternal(void* value) {
1413 Handle<Foreign> foreign = NewForeign(static_cast<Address>(value));
1414 Handle<JSObject> external = NewJSObjectFromMap(external_map());
1415 external->SetInternalField(0, *foreign);
1416 return external;
1417}
1418
1419
1420Handle<Code> Factory::NewCodeRaw(int object_size, bool immovable) {
1421 CALL_HEAP_FUNCTION(isolate(),
1422 isolate()->heap()->AllocateCode(object_size, immovable),
1423 Code);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001424}
1425
1426
Steve Blocka7e24c12009-10-30 11:49:00 +00001427Handle<Code> Factory::NewCode(const CodeDesc& desc,
Steve Blocka7e24c12009-10-30 11:49:00 +00001428 Code::Flags flags,
Steve Block44f0eee2011-05-26 01:26:41 +01001429 Handle<Object> self_ref,
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001430 bool immovable,
1431 bool crankshafted,
1432 int prologue_offset,
1433 bool is_debug) {
1434 Handle<ByteArray> reloc_info = NewByteArray(desc.reloc_size, TENURED);
1435 Handle<ConstantPoolArray> constant_pool =
1436 desc.origin->NewConstantPool(isolate());
1437
1438 // Compute size.
1439 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
1440 int obj_size = Code::SizeFor(body_size);
1441
1442 Handle<Code> code = NewCodeRaw(obj_size, immovable);
1443 DCHECK(isolate()->code_range() == NULL ||
1444 !isolate()->code_range()->valid() ||
1445 isolate()->code_range()->contains(code->address()));
1446
1447 // The code object has not been fully initialized yet. We rely on the
1448 // fact that no allocation will happen from this point on.
1449 DisallowHeapAllocation no_gc;
1450 code->set_gc_metadata(Smi::FromInt(0));
1451 code->set_ic_age(isolate()->heap()->global_ic_age());
1452 code->set_instruction_size(desc.instr_size);
1453 code->set_relocation_info(*reloc_info);
1454 code->set_flags(flags);
1455 code->set_raw_kind_specific_flags1(0);
1456 code->set_raw_kind_specific_flags2(0);
1457 code->set_is_crankshafted(crankshafted);
1458 code->set_deoptimization_data(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1459 code->set_raw_type_feedback_info(Smi::FromInt(0));
1460 code->set_next_code_link(*undefined_value());
1461 code->set_handler_table(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1462 code->set_prologue_offset(prologue_offset);
1463 if (code->kind() == Code::OPTIMIZED_FUNCTION) {
1464 code->set_marked_for_deoptimization(false);
1465 }
1466
1467 if (is_debug) {
1468 DCHECK(code->kind() == Code::FUNCTION);
1469 code->set_has_debug_break_slots(true);
1470 }
1471
1472 desc.origin->PopulateConstantPool(*constant_pool);
1473 code->set_constant_pool(*constant_pool);
1474
1475 // Allow self references to created code object by patching the handle to
1476 // point to the newly allocated Code object.
1477 if (!self_ref.is_null()) *(self_ref.location()) = *code;
1478
1479 // Migrate generated code.
1480 // The generated code can contain Object** values (typically from handles)
1481 // that are dereferenced during the copy to point directly to the actual heap
1482 // objects. These pointers can include references to the code object itself,
1483 // through the self_reference parameter.
1484 code->CopyFrom(desc);
1485
1486#ifdef VERIFY_HEAP
1487 if (FLAG_verify_heap) code->ObjectVerify();
1488#endif
1489 return code;
Steve Blocka7e24c12009-10-30 11:49:00 +00001490}
1491
1492
1493Handle<Code> Factory::CopyCode(Handle<Code> code) {
Steve Block44f0eee2011-05-26 01:26:41 +01001494 CALL_HEAP_FUNCTION(isolate(),
1495 isolate()->heap()->CopyCode(*code),
1496 Code);
Steve Blocka7e24c12009-10-30 11:49:00 +00001497}
1498
1499
Steve Block6ded16b2010-05-10 14:33:55 +01001500Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
Steve Block44f0eee2011-05-26 01:26:41 +01001501 CALL_HEAP_FUNCTION(isolate(),
1502 isolate()->heap()->CopyCode(*code, reloc_info),
1503 Code);
Steve Block6ded16b2010-05-10 14:33:55 +01001504}
1505
1506
Steve Blocka7e24c12009-10-30 11:49:00 +00001507Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1508 PretenureFlag pretenure) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001509 JSFunction::EnsureHasInitialMap(constructor);
Steve Block44f0eee2011-05-26 01:26:41 +01001510 CALL_HEAP_FUNCTION(
1511 isolate(),
1512 isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
Steve Blocka7e24c12009-10-30 11:49:00 +00001513}
1514
1515
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001516Handle<JSObject> Factory::NewJSObjectWithMemento(
1517 Handle<JSFunction> constructor,
1518 Handle<AllocationSite> site) {
1519 JSFunction::EnsureHasInitialMap(constructor);
Steve Block44f0eee2011-05-26 01:26:41 +01001520 CALL_HEAP_FUNCTION(
1521 isolate(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001522 isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
Steve Block44f0eee2011-05-26 01:26:41 +01001523 JSObject);
Steve Blocka7e24c12009-10-30 11:49:00 +00001524}
1525
1526
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001527Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1528 Handle<ScopeInfo> scope_info) {
1529 // Allocate a fresh map. Modules do not have a prototype.
1530 Handle<Map> map = NewMap(JS_MODULE_TYPE, JSModule::kSize);
1531 // Allocate the object based on the map.
1532 Handle<JSModule> module =
1533 Handle<JSModule>::cast(NewJSObjectFromMap(map, TENURED));
1534 module->set_context(*context);
1535 module->set_scope_info(*scope_info);
1536 return module;
1537}
1538
1539
1540Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1541 DCHECK(constructor->has_initial_map());
1542 Handle<Map> map(constructor->initial_map());
1543 DCHECK(map->is_dictionary_map());
1544
1545 // Make sure no field properties are described in the initial map.
1546 // This guarantees us that normalizing the properties does not
1547 // require us to change property values to PropertyCells.
1548 DCHECK(map->NextFreePropertyIndex() == 0);
1549
1550 // Make sure we don't have a ton of pre-allocated slots in the
1551 // global objects. They will be unused once we normalize the object.
1552 DCHECK(map->unused_property_fields() == 0);
1553 DCHECK(map->inobject_properties() == 0);
1554
1555 // Initial size of the backing store to avoid resize of the storage during
1556 // bootstrapping. The size differs between the JS global object ad the
1557 // builtins object.
1558 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1559
1560 // Allocate a dictionary object for backing storage.
1561 int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1562 Handle<NameDictionary> dictionary =
1563 NameDictionary::New(isolate(), at_least_space_for);
1564
1565 // The global object might be created from an object template with accessors.
1566 // Fill these accessors into the dictionary.
1567 Handle<DescriptorArray> descs(map->instance_descriptors());
1568 for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1569 PropertyDetails details = descs->GetDetails(i);
1570 DCHECK(details.type() == CALLBACKS); // Only accessors are expected.
1571 PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
1572 Handle<Name> name(descs->GetKey(i));
1573 Handle<Object> value(descs->GetCallbacksObject(i), isolate());
1574 Handle<PropertyCell> cell = NewPropertyCell(value);
1575 // |dictionary| already contains enough space for all properties.
1576 USE(NameDictionary::Add(dictionary, name, cell, d));
1577 }
1578
1579 // Allocate the global object and initialize it with the backing store.
1580 Handle<GlobalObject> global = New<GlobalObject>(map, OLD_POINTER_SPACE);
1581 isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1582
1583 // Create a new map for the global object.
1584 Handle<Map> new_map = Map::CopyDropDescriptors(map);
1585 new_map->set_dictionary_map(true);
1586
1587 // Set up the global object as a normalized object.
1588 global->set_map(*new_map);
1589 global->set_properties(*dictionary);
1590
1591 // Make sure result is a global object with properties in dictionary.
1592 DCHECK(global->IsGlobalObject() && !global->HasFastProperties());
1593 return global;
1594}
1595
1596
1597Handle<JSObject> Factory::NewJSObjectFromMap(
1598 Handle<Map> map,
1599 PretenureFlag pretenure,
1600 bool alloc_props,
1601 Handle<AllocationSite> allocation_site) {
1602 CALL_HEAP_FUNCTION(
1603 isolate(),
1604 isolate()->heap()->AllocateJSObjectFromMap(
1605 *map,
1606 pretenure,
1607 alloc_props,
1608 allocation_site.is_null() ? NULL : *allocation_site),
1609 JSObject);
1610}
1611
1612
1613Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
Steve Blocka7e24c12009-10-30 11:49:00 +00001614 PretenureFlag pretenure) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001615 Context* native_context = isolate()->context()->native_context();
1616 JSFunction* array_function = native_context->array_function();
1617 Map* map = array_function->initial_map();
1618 Map* transition_map = isolate()->get_initial_js_array_map(elements_kind);
1619 if (transition_map != NULL) map = transition_map;
1620 return Handle<JSArray>::cast(NewJSObjectFromMap(handle(map), pretenure));
1621}
1622
1623
1624Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1625 int length,
1626 int capacity,
1627 ArrayStorageAllocationMode mode,
1628 PretenureFlag pretenure) {
1629 Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1630 NewJSArrayStorage(array, length, capacity, mode);
1631 return array;
Steve Blocka7e24c12009-10-30 11:49:00 +00001632}
1633
1634
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001635Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1636 ElementsKind elements_kind,
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001637 int length,
Steve Blocka7e24c12009-10-30 11:49:00 +00001638 PretenureFlag pretenure) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001639 DCHECK(length <= elements->length());
1640 Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1641
1642 array->set_elements(*elements);
1643 array->set_length(Smi::FromInt(length));
1644 JSObject::ValidateElements(array);
1645 return array;
1646}
1647
1648
1649void Factory::NewJSArrayStorage(Handle<JSArray> array,
1650 int length,
1651 int capacity,
1652 ArrayStorageAllocationMode mode) {
1653 DCHECK(capacity >= length);
1654
1655 if (capacity == 0) {
1656 array->set_length(Smi::FromInt(0));
1657 array->set_elements(*empty_fixed_array());
1658 return;
1659 }
1660
1661 Handle<FixedArrayBase> elms;
1662 ElementsKind elements_kind = array->GetElementsKind();
1663 if (IsFastDoubleElementsKind(elements_kind)) {
1664 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1665 elms = NewFixedDoubleArray(capacity);
1666 } else {
1667 DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1668 elms = NewFixedDoubleArrayWithHoles(capacity);
1669 }
1670 } else {
1671 DCHECK(IsFastSmiOrObjectElementsKind(elements_kind));
1672 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1673 elms = NewUninitializedFixedArray(capacity);
1674 } else {
1675 DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1676 elms = NewFixedArrayWithHoles(capacity);
1677 }
1678 }
1679
1680 array->set_elements(*elms);
1681 array->set_length(Smi::FromInt(length));
1682}
1683
1684
1685Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1686 Handle<JSFunction> function) {
1687 DCHECK(function->shared()->is_generator());
1688 JSFunction::EnsureHasInitialMap(function);
1689 Handle<Map> map(function->initial_map());
1690 DCHECK(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001691 CALL_HEAP_FUNCTION(
1692 isolate(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001693 isolate()->heap()->AllocateJSObjectFromMap(*map),
1694 JSGeneratorObject);
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001695}
1696
1697
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001698Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1699 Handle<JSFunction> array_buffer_fun(
1700 isolate()->native_context()->array_buffer_fun());
1701 CALL_HEAP_FUNCTION(
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001702 isolate(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001703 isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1704 JSArrayBuffer);
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001705}
1706
1707
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001708Handle<JSDataView> Factory::NewJSDataView() {
1709 Handle<JSFunction> data_view_fun(
1710 isolate()->native_context()->data_view_fun());
1711 CALL_HEAP_FUNCTION(
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001712 isolate(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001713 isolate()->heap()->AllocateJSObject(*data_view_fun),
1714 JSDataView);
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001715}
1716
1717
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001718static JSFunction* GetTypedArrayFun(ExternalArrayType type,
1719 Isolate* isolate) {
1720 Context* native_context = isolate->context()->native_context();
1721 switch (type) {
1722#define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
1723 case kExternal##Type##Array: \
1724 return native_context->type##_array_fun();
1725
1726 TYPED_ARRAYS(TYPED_ARRAY_FUN)
1727#undef TYPED_ARRAY_FUN
1728
1729 default:
1730 UNREACHABLE();
1731 return NULL;
1732 }
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001733}
1734
1735
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001736Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1737 Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1738
1739 CALL_HEAP_FUNCTION(
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001740 isolate(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001741 isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1742 JSTypedArray);
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001743}
1744
1745
Ben Murdoch257744e2011-11-30 15:57:28 +00001746Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1747 Handle<Object> prototype) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001748 // Allocate map.
1749 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1750 // maps. Will probably depend on the identity of the handler object, too.
1751 Handle<Map> map = NewMap(JS_PROXY_TYPE, JSProxy::kSize);
1752 map->set_prototype(*prototype);
1753
1754 // Allocate the proxy object.
1755 Handle<JSProxy> result = New<JSProxy>(map, NEW_SPACE);
1756 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1757 result->set_handler(*handler);
1758 result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1759 return result;
Ben Murdoch257744e2011-11-30 15:57:28 +00001760}
1761
1762
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001763Handle<JSProxy> Factory::NewJSFunctionProxy(Handle<Object> handler,
1764 Handle<Object> call_trap,
1765 Handle<Object> construct_trap,
1766 Handle<Object> prototype) {
1767 // Allocate map.
1768 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1769 // maps. Will probably depend on the identity of the handler object, too.
1770 Handle<Map> map = NewMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
1771 map->set_prototype(*prototype);
1772
1773 // Allocate the proxy object.
1774 Handle<JSFunctionProxy> result = New<JSFunctionProxy>(map, NEW_SPACE);
1775 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1776 result->set_handler(*handler);
1777 result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1778 result->set_call_trap(*call_trap);
1779 result->set_construct_trap(*construct_trap);
1780 return result;
Ben Murdoch589d6972011-11-30 16:04:58 +00001781}
1782
1783
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001784void Factory::ReinitializeJSProxy(Handle<JSProxy> proxy, InstanceType type,
1785 int size) {
1786 DCHECK(type == JS_OBJECT_TYPE || type == JS_FUNCTION_TYPE);
1787
1788 // Allocate fresh map.
1789 // TODO(rossberg): Once we optimize proxies, cache these maps.
1790 Handle<Map> map = NewMap(type, size);
1791
1792 // Check that the receiver has at least the size of the fresh object.
1793 int size_difference = proxy->map()->instance_size() - map->instance_size();
1794 DCHECK(size_difference >= 0);
1795
1796 map->set_prototype(proxy->map()->prototype());
1797
1798 // Allocate the backing storage for the properties.
1799 int prop_size = map->InitialPropertiesLength();
1800 Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1801
1802 Heap* heap = isolate()->heap();
1803 MaybeHandle<SharedFunctionInfo> shared;
1804 if (type == JS_FUNCTION_TYPE) {
1805 OneByteStringKey key(STATIC_CHAR_VECTOR("<freezing call trap>"),
1806 heap->HashSeed());
1807 Handle<String> name = InternalizeStringWithKey(&key);
1808 shared = NewSharedFunctionInfo(name, MaybeHandle<Code>());
1809 }
1810
1811 // In order to keep heap in consistent state there must be no allocations
1812 // before object re-initialization is finished and filler object is installed.
1813 DisallowHeapAllocation no_allocation;
1814
1815 // Put in filler if the new object is smaller than the old.
1816 if (size_difference > 0) {
1817 Address address = proxy->address();
1818 heap->CreateFillerObjectAt(address + map->instance_size(), size_difference);
1819 heap->AdjustLiveBytes(address, -size_difference, Heap::FROM_MUTATOR);
1820 }
1821
1822 // Reset the map for the object.
1823 proxy->synchronized_set_map(*map);
1824 Handle<JSObject> jsobj = Handle<JSObject>::cast(proxy);
1825
1826 // Reinitialize the object from the constructor map.
1827 heap->InitializeJSObjectFromMap(*jsobj, *properties, *map);
1828
1829 // The current native context is used to set up certain bits.
1830 // TODO(adamk): Using the current context seems wrong, it should be whatever
1831 // context the JSProxy originated in. But that context isn't stored anywhere.
1832 Handle<Context> context(isolate()->native_context());
1833
1834 // Functions require some minimal initialization.
1835 if (type == JS_FUNCTION_TYPE) {
1836 map->set_function_with_prototype(true);
1837 Handle<JSFunction> js_function = Handle<JSFunction>::cast(proxy);
1838 InitializeFunction(js_function, shared.ToHandleChecked(), context);
1839 } else {
1840 // Provide JSObjects with a constructor.
1841 map->set_constructor(context->object_function());
1842 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001843}
1844
1845
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001846void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
1847 Handle<JSFunction> constructor) {
1848 DCHECK(constructor->has_initial_map());
1849 Handle<Map> map(constructor->initial_map(), isolate());
1850
1851 // The proxy's hash should be retained across reinitialization.
1852 Handle<Object> hash(object->hash(), isolate());
1853
1854 // Check that the already allocated object has the same size and type as
1855 // objects allocated using the constructor.
1856 DCHECK(map->instance_size() == object->map()->instance_size());
1857 DCHECK(map->instance_type() == object->map()->instance_type());
1858
1859 // Allocate the backing storage for the properties.
1860 int prop_size = map->InitialPropertiesLength();
1861 Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1862
1863 // In order to keep heap in consistent state there must be no allocations
1864 // before object re-initialization is finished.
1865 DisallowHeapAllocation no_allocation;
1866
1867 // Reset the map for the object.
1868 object->synchronized_set_map(*map);
1869
1870 Heap* heap = isolate()->heap();
1871 // Reinitialize the object from the constructor map.
1872 heap->InitializeJSObjectFromMap(*object, *properties, *map);
1873
1874 // Restore the saved hash.
1875 object->set_hash(*hash);
1876}
1877
1878
1879void Factory::BecomeJSObject(Handle<JSProxy> proxy) {
1880 ReinitializeJSProxy(proxy, JS_OBJECT_TYPE, JSObject::kHeaderSize);
1881}
1882
1883
1884void Factory::BecomeJSFunction(Handle<JSProxy> proxy) {
1885 ReinitializeJSProxy(proxy, JS_FUNCTION_TYPE, JSFunction::kSize);
1886}
1887
1888
1889Handle<TypeFeedbackVector> Factory::NewTypeFeedbackVector(int slot_count) {
1890 // Ensure we can skip the write barrier
1891 DCHECK_EQ(isolate()->heap()->uninitialized_symbol(),
1892 *TypeFeedbackVector::UninitializedSentinel(isolate()));
1893
1894 if (slot_count == 0) {
1895 return Handle<TypeFeedbackVector>::cast(empty_fixed_array());
1896 }
1897
1898 CALL_HEAP_FUNCTION(isolate(),
1899 isolate()->heap()->AllocateFixedArrayWithFiller(
1900 slot_count, TENURED,
1901 *TypeFeedbackVector::UninitializedSentinel(isolate())),
1902 TypeFeedbackVector);
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001903}
1904
1905
Steve Block6ded16b2010-05-10 14:33:55 +01001906Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001907 Handle<String> name, int number_of_literals, FunctionKind kind,
1908 Handle<Code> code, Handle<ScopeInfo> scope_info,
1909 Handle<TypeFeedbackVector> feedback_vector) {
1910 DCHECK(IsValidFunctionKind(kind));
1911 Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name, code);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001912 shared->set_scope_info(*scope_info);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001913 shared->set_feedback_vector(*feedback_vector);
1914 shared->set_kind(kind);
Steve Block6ded16b2010-05-10 14:33:55 +01001915 int literals_array_size = number_of_literals;
1916 // If the function contains object, regexp or array literals,
1917 // allocate extra space for a literals array prefix containing the
1918 // context.
1919 if (number_of_literals > 0) {
1920 literals_array_size += JSFunction::kLiteralsPrefixSize;
1921 }
1922 shared->set_num_literals(literals_array_size);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001923 if (IsGeneratorFunction(kind)) {
1924 shared->set_instance_class_name(isolate()->heap()->Generator_string());
1925 shared->DisableOptimization(kGenerator);
1926 }
Steve Block6ded16b2010-05-10 14:33:55 +01001927 return shared;
1928}
1929
1930
Steve Block1e0659c2011-05-24 12:43:12 +01001931Handle<JSMessageObject> Factory::NewJSMessageObject(
1932 Handle<String> type,
1933 Handle<JSArray> arguments,
1934 int start_position,
1935 int end_position,
1936 Handle<Object> script,
Steve Block1e0659c2011-05-24 12:43:12 +01001937 Handle<Object> stack_frames) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001938 Handle<Map> map = message_object_map();
1939 Handle<JSMessageObject> message = New<JSMessageObject>(map, NEW_SPACE);
1940 message->set_properties(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1941 message->initialize_elements();
1942 message->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1943 message->set_type(*type);
1944 message->set_arguments(*arguments);
1945 message->set_start_position(start_position);
1946 message->set_end_position(end_position);
1947 message->set_script(*script);
1948 message->set_stack_frames(*stack_frames);
1949 return message;
Steve Blocka7e24c12009-10-30 11:49:00 +00001950}
1951
1952
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001953Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
Steve Block44f0eee2011-05-26 01:26:41 +01001954 Handle<String> name,
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001955 MaybeHandle<Code> maybe_code) {
1956 Handle<Map> map = shared_function_info_map();
1957 Handle<SharedFunctionInfo> share = New<SharedFunctionInfo>(map,
1958 OLD_POINTER_SPACE);
1959
1960 // Set pointer fields.
1961 share->set_name(*name);
1962 Handle<Code> code;
1963 if (!maybe_code.ToHandle(&code)) {
1964 code = handle(isolate()->builtins()->builtin(Builtins::kIllegal));
1965 }
1966 share->set_code(*code);
1967 share->set_optimized_code_map(Smi::FromInt(0));
1968 share->set_scope_info(ScopeInfo::Empty(isolate()));
1969 Code* construct_stub =
1970 isolate()->builtins()->builtin(Builtins::kJSConstructStubGeneric);
1971 share->set_construct_stub(construct_stub);
1972 share->set_instance_class_name(*Object_string());
1973 share->set_function_data(*undefined_value(), SKIP_WRITE_BARRIER);
1974 share->set_script(*undefined_value(), SKIP_WRITE_BARRIER);
1975 share->set_debug_info(*undefined_value(), SKIP_WRITE_BARRIER);
1976 share->set_inferred_name(*empty_string(), SKIP_WRITE_BARRIER);
1977 Handle<TypeFeedbackVector> feedback_vector = NewTypeFeedbackVector(0);
1978 share->set_feedback_vector(*feedback_vector, SKIP_WRITE_BARRIER);
1979 share->set_profiler_ticks(0);
1980 share->set_ast_node_count(0);
1981 share->set_counters(0);
1982
1983 // Set integer fields (smi or int, depending on the architecture).
1984 share->set_length(0);
1985 share->set_formal_parameter_count(0);
1986 share->set_expected_nof_properties(0);
1987 share->set_num_literals(0);
1988 share->set_start_position_and_type(0);
1989 share->set_end_position(0);
1990 share->set_function_token_position(0);
1991 // All compiler hints default to false or 0.
1992 share->set_compiler_hints(0);
1993 share->set_opt_count_and_bailout_reason(0);
1994
1995 return share;
Steve Block6ded16b2010-05-10 14:33:55 +01001996}
1997
1998
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001999static inline int NumberCacheHash(Handle<FixedArray> cache,
2000 Handle<Object> number) {
2001 int mask = (cache->length() >> 1) - 1;
2002 if (number->IsSmi()) {
2003 return Handle<Smi>::cast(number)->value() & mask;
2004 } else {
2005 DoubleRepresentation rep(number->Number());
2006 return
2007 (static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) & mask;
2008 }
Steve Block6ded16b2010-05-10 14:33:55 +01002009}
2010
2011
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002012Handle<Object> Factory::GetNumberStringCache(Handle<Object> number) {
2013 DisallowHeapAllocation no_gc;
2014 int hash = NumberCacheHash(number_string_cache(), number);
2015 Object* key = number_string_cache()->get(hash * 2);
2016 if (key == *number || (key->IsHeapNumber() && number->IsHeapNumber() &&
2017 key->Number() == number->Number())) {
2018 return Handle<String>(
2019 String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
2020 }
2021 return undefined_value();
Leon Clarkee46be812010-01-19 14:06:41 +00002022}
2023
2024
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002025void Factory::SetNumberStringCache(Handle<Object> number,
2026 Handle<String> string) {
2027 int hash = NumberCacheHash(number_string_cache(), number);
2028 if (number_string_cache()->get(hash * 2) != *undefined_value()) {
2029 int full_size = isolate()->heap()->FullSizeNumberStringCacheLength();
2030 if (number_string_cache()->length() != full_size) {
2031 // The first time we have a hash collision, we move to the full sized
2032 // number string cache. The idea is to have a small number string
2033 // cache in the snapshot to keep boot-time memory usage down.
2034 // If we expand the number string cache already while creating
2035 // the snapshot then that didn't work out.
2036 DCHECK(!isolate()->serializer_enabled() || FLAG_extra_code != NULL);
2037 Handle<FixedArray> new_cache = NewFixedArray(full_size, TENURED);
2038 isolate()->heap()->set_number_string_cache(*new_cache);
2039 return;
2040 }
2041 }
2042 number_string_cache()->set(hash * 2, *number);
2043 number_string_cache()->set(hash * 2 + 1, *string);
Steve Blocka7e24c12009-10-30 11:49:00 +00002044}
2045
2046
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002047Handle<String> Factory::NumberToString(Handle<Object> number,
2048 bool check_number_string_cache) {
2049 isolate()->counters()->number_to_string_runtime()->Increment();
2050 if (check_number_string_cache) {
2051 Handle<Object> cached = GetNumberStringCache(number);
2052 if (!cached->IsUndefined()) return Handle<String>::cast(cached);
2053 }
2054
2055 char arr[100];
2056 Vector<char> buffer(arr, arraysize(arr));
2057 const char* str;
2058 if (number->IsSmi()) {
2059 int num = Handle<Smi>::cast(number)->value();
2060 str = IntToCString(num, buffer);
2061 } else {
2062 double num = Handle<HeapNumber>::cast(number)->value();
2063 str = DoubleToCString(num, buffer);
2064 }
2065
2066 // We tenure the allocated string since it is referenced from the
2067 // number-string cache which lives in the old space.
2068 Handle<String> js_string = NewStringFromAsciiChecked(str, TENURED);
2069 SetNumberStringCache(number, js_string);
2070 return js_string;
2071}
2072
2073
Steve Blocka7e24c12009-10-30 11:49:00 +00002074Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
2075 // Get the original code of the function.
2076 Handle<Code> code(shared->code());
2077
2078 // Create a copy of the code before allocating the debug info object to avoid
2079 // allocation while setting up the debug info object.
2080 Handle<Code> original_code(*Factory::CopyCode(code));
2081
2082 // Allocate initial fixed array for active break points before allocating the
2083 // debug info object to avoid allocation while setting up the debug info
2084 // object.
2085 Handle<FixedArray> break_points(
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002086 NewFixedArray(DebugInfo::kEstimatedNofBreakPointsInFunction));
Steve Blocka7e24c12009-10-30 11:49:00 +00002087
2088 // Create and set up the debug info object. Debug info contains function, a
2089 // copy of the original code, the executing code and initial fixed array for
2090 // active break points.
2091 Handle<DebugInfo> debug_info =
Steve Block44f0eee2011-05-26 01:26:41 +01002092 Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
Steve Blocka7e24c12009-10-30 11:49:00 +00002093 debug_info->set_shared(*shared);
2094 debug_info->set_original_code(*original_code);
2095 debug_info->set_code(*code);
2096 debug_info->set_break_points(*break_points);
2097
2098 // Link debug info to function.
2099 shared->set_debug_info(*debug_info);
2100
2101 return debug_info;
2102}
Steve Blocka7e24c12009-10-30 11:49:00 +00002103
2104
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002105Handle<JSObject> Factory::NewArgumentsObject(Handle<JSFunction> callee,
Steve Blocka7e24c12009-10-30 11:49:00 +00002106 int length) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002107 bool strict_mode_callee = callee->shared()->strict_mode() == STRICT;
2108 Handle<Map> map = strict_mode_callee ? isolate()->strict_arguments_map()
2109 : isolate()->sloppy_arguments_map();
2110
2111 AllocationSiteUsageContext context(isolate(), Handle<AllocationSite>(),
2112 false);
2113 DCHECK(!isolate()->has_pending_exception());
2114 Handle<JSObject> result = NewJSObjectFromMap(map);
2115 Handle<Smi> value(Smi::FromInt(length), isolate());
2116 Object::SetProperty(result, length_string(), value, STRICT).Assert();
2117 if (!strict_mode_callee) {
2118 Object::SetProperty(result, callee_string(), callee, STRICT).Assert();
2119 }
2120 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00002121}
2122
2123
2124Handle<JSFunction> Factory::CreateApiFunction(
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002125 Handle<FunctionTemplateInfo> obj,
2126 Handle<Object> prototype,
2127 ApiInstanceType instance_type) {
Steve Block44f0eee2011-05-26 01:26:41 +01002128 Handle<Code> code = isolate()->builtins()->HandleApiCall();
2129 Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
Steve Blocka7e24c12009-10-30 11:49:00 +00002130
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002131 Handle<JSFunction> result;
2132 if (obj->remove_prototype()) {
2133 result = NewFunctionWithoutPrototype(empty_string(), code);
2134 } else {
2135 int internal_field_count = 0;
2136 if (!obj->instance_template()->IsUndefined()) {
2137 Handle<ObjectTemplateInfo> instance_template =
2138 Handle<ObjectTemplateInfo>(
2139 ObjectTemplateInfo::cast(obj->instance_template()));
2140 internal_field_count =
2141 Smi::cast(instance_template->internal_field_count())->value();
2142 }
2143
2144 // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
2145 // JSObject::GetHeaderSize.
2146 int instance_size = kPointerSize * internal_field_count;
2147 InstanceType type;
2148 switch (instance_type) {
2149 case JavaScriptObjectType:
2150 type = JS_OBJECT_TYPE;
2151 instance_size += JSObject::kHeaderSize;
2152 break;
2153 case GlobalObjectType:
2154 type = JS_GLOBAL_OBJECT_TYPE;
2155 instance_size += JSGlobalObject::kSize;
2156 break;
2157 case GlobalProxyType:
2158 type = JS_GLOBAL_PROXY_TYPE;
2159 instance_size += JSGlobalProxy::kSize;
2160 break;
2161 default:
2162 UNREACHABLE();
2163 type = JS_OBJECT_TYPE; // Keep the compiler happy.
2164 break;
2165 }
2166
2167 result = NewFunction(empty_string(), code, prototype, type,
2168 instance_size, obj->read_only_prototype());
Steve Blocka7e24c12009-10-30 11:49:00 +00002169 }
2170
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002171 result->shared()->set_length(obj->length());
2172 Handle<Object> class_name(obj->class_name(), isolate());
Steve Blocka7e24c12009-10-30 11:49:00 +00002173 if (class_name->IsString()) {
2174 result->shared()->set_instance_class_name(*class_name);
2175 result->shared()->set_name(*class_name);
2176 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002177 result->shared()->set_function_data(*obj);
2178 result->shared()->set_construct_stub(*construct_stub);
2179 result->shared()->DontAdaptArguments();
Steve Blocka7e24c12009-10-30 11:49:00 +00002180
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002181 if (obj->remove_prototype()) {
2182 DCHECK(result->shared()->IsApiFunction());
2183 DCHECK(!result->has_initial_map());
2184 DCHECK(!result->has_prototype());
2185 return result;
2186 }
2187
2188 if (prototype->IsTheHole()) {
2189#ifdef DEBUG
2190 LookupIterator it(handle(JSObject::cast(result->prototype())),
2191 constructor_string(),
2192 LookupIterator::OWN_SKIP_INTERCEPTOR);
2193 MaybeHandle<Object> maybe_prop = Object::GetProperty(&it);
2194 DCHECK(it.IsFound());
2195 DCHECK(maybe_prop.ToHandleChecked().is_identical_to(result));
2196#endif
2197 } else {
2198 JSObject::AddProperty(handle(JSObject::cast(result->prototype())),
2199 constructor_string(), result, DONT_ENUM);
2200 }
2201
2202 // Down from here is only valid for API functions that can be used as a
2203 // constructor (don't set the "remove prototype" flag).
2204
2205 Handle<Map> map(result->initial_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002206
2207 // Mark as undetectable if needed.
2208 if (obj->undetectable()) {
2209 map->set_is_undetectable();
2210 }
2211
2212 // Mark as hidden for the __proto__ accessor if needed.
2213 if (obj->hidden_prototype()) {
2214 map->set_is_hidden_prototype();
2215 }
2216
2217 // Mark as needs_access_check if needed.
2218 if (obj->needs_access_check()) {
2219 map->set_is_access_check_needed(true);
2220 }
2221
2222 // Set interceptor information in the map.
2223 if (!obj->named_property_handler()->IsUndefined()) {
2224 map->set_has_named_interceptor();
2225 }
2226 if (!obj->indexed_property_handler()->IsUndefined()) {
2227 map->set_has_indexed_interceptor();
2228 }
2229
2230 // Set instance call-as-function information in the map.
2231 if (!obj->instance_call_handler()->IsUndefined()) {
2232 map->set_has_instance_call_handler();
2233 }
2234
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002235 // Recursively copy parent instance templates' accessors,
2236 // 'data' may be modified.
2237 int max_number_of_additional_properties = 0;
2238 int max_number_of_static_properties = 0;
2239 FunctionTemplateInfo* info = *obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00002240 while (true) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002241 if (!info->instance_template()->IsUndefined()) {
2242 Object* props =
2243 ObjectTemplateInfo::cast(
2244 info->instance_template())->property_accessors();
2245 if (!props->IsUndefined()) {
2246 Handle<Object> props_handle(props, isolate());
2247 NeanderArray props_array(props_handle);
2248 max_number_of_additional_properties += props_array.length();
2249 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002250 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002251 if (!info->property_accessors()->IsUndefined()) {
2252 Object* props = info->property_accessors();
2253 if (!props->IsUndefined()) {
2254 Handle<Object> props_handle(props, isolate());
2255 NeanderArray props_array(props_handle);
2256 max_number_of_static_properties += props_array.length();
2257 }
2258 }
2259 Object* parent = info->parent_template();
2260 if (parent->IsUndefined()) break;
2261 info = FunctionTemplateInfo::cast(parent);
2262 }
2263
2264 Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);
2265
2266 // Use a temporary FixedArray to acculumate static accessors
2267 int valid_descriptors = 0;
2268 Handle<FixedArray> array;
2269 if (max_number_of_static_properties > 0) {
2270 array = NewFixedArray(max_number_of_static_properties);
2271 }
2272
2273 while (true) {
2274 // Install instance descriptors
2275 if (!obj->instance_template()->IsUndefined()) {
2276 Handle<ObjectTemplateInfo> instance =
2277 Handle<ObjectTemplateInfo>(
2278 ObjectTemplateInfo::cast(obj->instance_template()), isolate());
2279 Handle<Object> props = Handle<Object>(instance->property_accessors(),
2280 isolate());
2281 if (!props->IsUndefined()) {
2282 Map::AppendCallbackDescriptors(map, props);
2283 }
2284 }
2285 // Accumulate static accessors
2286 if (!obj->property_accessors()->IsUndefined()) {
2287 Handle<Object> props = Handle<Object>(obj->property_accessors(),
2288 isolate());
2289 valid_descriptors =
2290 AccessorInfo::AppendUnique(props, array, valid_descriptors);
2291 }
2292 // Climb parent chain
2293 Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
Steve Blocka7e24c12009-10-30 11:49:00 +00002294 if (parent->IsUndefined()) break;
2295 obj = Handle<FunctionTemplateInfo>::cast(parent);
2296 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002297
2298 // Install accumulated static accessors
2299 for (int i = 0; i < valid_descriptors; i++) {
2300 Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
2301 JSObject::SetAccessor(result, accessor).Assert();
Steve Blocka7e24c12009-10-30 11:49:00 +00002302 }
2303
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002304 DCHECK(result->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00002305 return result;
2306}
2307
2308
2309Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
2310 Handle<FixedArray> keys,
2311 Handle<Map> map) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002312 Handle<MapCache> map_cache = handle(MapCache::cast(context->map_cache()));
2313 Handle<MapCache> result = MapCache::Put(map_cache, keys, map);
2314 context->set_map_cache(*result);
2315 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00002316}
2317
2318
2319Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
2320 Handle<FixedArray> keys) {
2321 if (context->map_cache()->IsUndefined()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002322 // Allocate the new map cache for the native context.
2323 Handle<MapCache> new_cache = MapCache::New(isolate(), 24);
Steve Blocka7e24c12009-10-30 11:49:00 +00002324 context->set_map_cache(*new_cache);
2325 }
2326 // Check to see whether there is a matching element in the cache.
2327 Handle<MapCache> cache =
2328 Handle<MapCache>(MapCache::cast(context->map_cache()));
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002329 Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
Steve Blocka7e24c12009-10-30 11:49:00 +00002330 if (result->IsMap()) return Handle<Map>::cast(result);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002331 int length = keys->length();
2332 // Create a new map and add it to the cache. Reuse the initial map of the
2333 // Object function if the literal has no predeclared properties.
2334 Handle<Map> map = length == 0
2335 ? handle(context->object_function()->initial_map())
2336 : Map::Create(isolate(), length);
Steve Blocka7e24c12009-10-30 11:49:00 +00002337 AddToMapCache(context, keys, map);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002338 return map;
Steve Blocka7e24c12009-10-30 11:49:00 +00002339}
2340
2341
2342void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
2343 JSRegExp::Type type,
2344 Handle<String> source,
2345 JSRegExp::Flags flags,
2346 Handle<Object> data) {
2347 Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
2348
2349 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2350 store->set(JSRegExp::kSourceIndex, *source);
2351 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2352 store->set(JSRegExp::kAtomPatternIndex, *data);
2353 regexp->set_data(*store);
2354}
2355
2356void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
2357 JSRegExp::Type type,
2358 Handle<String> source,
2359 JSRegExp::Flags flags,
2360 int capture_count) {
2361 Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
Ben Murdoch257744e2011-11-30 15:57:28 +00002362 Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
Steve Blocka7e24c12009-10-30 11:49:00 +00002363 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2364 store->set(JSRegExp::kSourceIndex, *source);
2365 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002366 store->set(JSRegExp::kIrregexpLatin1CodeIndex, uninitialized);
Ben Murdoch257744e2011-11-30 15:57:28 +00002367 store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002368 store->set(JSRegExp::kIrregexpLatin1CodeSavedIndex, uninitialized);
Ben Murdoch257744e2011-11-30 15:57:28 +00002369 store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
Steve Blocka7e24c12009-10-30 11:49:00 +00002370 store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
2371 store->set(JSRegExp::kIrregexpCaptureCountIndex,
2372 Smi::FromInt(capture_count));
2373 regexp->set_data(*store);
2374}
2375
2376
2377
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002378MaybeHandle<FunctionTemplateInfo> Factory::ConfigureInstance(
2379 Handle<FunctionTemplateInfo> desc, Handle<JSObject> instance) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002380 // Configure the instance by adding the properties specified by the
2381 // instance template.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002382 Handle<Object> instance_template(desc->instance_template(), isolate());
Steve Blocka7e24c12009-10-30 11:49:00 +00002383 if (!instance_template->IsUndefined()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002384 RETURN_ON_EXCEPTION(
2385 isolate(),
2386 Execution::ConfigureInstance(isolate(), instance, instance_template),
2387 FunctionTemplateInfo);
Steve Blocka7e24c12009-10-30 11:49:00 +00002388 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002389 return desc;
Steve Blocka7e24c12009-10-30 11:49:00 +00002390}
2391
2392
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002393Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002394 if (String::Equals(name, undefined_string())) return undefined_value();
2395 if (String::Equals(name, nan_string())) return nan_value();
2396 if (String::Equals(name, infinity_string())) return infinity_value();
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002397 return Handle<Object>::null();
2398}
2399
2400
2401Handle<Object> Factory::ToBoolean(bool value) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002402 return value ? true_value() : false_value();
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002403}
2404
2405
Steve Blocka7e24c12009-10-30 11:49:00 +00002406} } // namespace v8::internal