Upstream version 8.37.186.0
[platform/framework/web/crosswalk.git] / src / v8 / src / factory.cc
1 // Copyright 2014 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "src/factory.h"
6
7 #include "src/conversions.h"
8 #include "src/isolate-inl.h"
9 #include "src/macro-assembler.h"
10
11 namespace v8 {
12 namespace internal {
13
14
15 template<typename T>
16 Handle<T> Factory::New(Handle<Map> map, AllocationSpace space) {
17   CALL_HEAP_FUNCTION(
18       isolate(),
19       isolate()->heap()->Allocate(*map, space),
20       T);
21 }
22
23
24 template<typename T>
25 Handle<T> Factory::New(Handle<Map> map,
26                        AllocationSpace space,
27                        Handle<AllocationSite> allocation_site) {
28   CALL_HEAP_FUNCTION(
29       isolate(),
30       isolate()->heap()->Allocate(*map, space, *allocation_site),
31       T);
32 }
33
34
35 Handle<HeapObject> Factory::NewFillerObject(int size,
36                                             bool double_align,
37                                             AllocationSpace space) {
38   CALL_HEAP_FUNCTION(
39       isolate(),
40       isolate()->heap()->AllocateFillerObject(size, double_align, space),
41       HeapObject);
42 }
43
44
45 Handle<Box> Factory::NewBox(Handle<Object> value) {
46   Handle<Box> result = Handle<Box>::cast(NewStruct(BOX_TYPE));
47   result->set_value(*value);
48   return result;
49 }
50
51
52 Handle<Oddball> Factory::NewOddball(Handle<Map> map,
53                                     const char* to_string,
54                                     Handle<Object> to_number,
55                                     byte kind) {
56   Handle<Oddball> oddball = New<Oddball>(map, OLD_POINTER_SPACE);
57   Oddball::Initialize(isolate(), oddball, to_string, to_number, kind);
58   return oddball;
59 }
60
61
62 Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
63   ASSERT(0 <= size);
64   CALL_HEAP_FUNCTION(
65       isolate(),
66       isolate()->heap()->AllocateFixedArray(size, pretenure),
67       FixedArray);
68 }
69
70
71 Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
72                                                    PretenureFlag pretenure) {
73   ASSERT(0 <= size);
74   CALL_HEAP_FUNCTION(
75       isolate(),
76       isolate()->heap()->AllocateFixedArrayWithFiller(size,
77                                                       pretenure,
78                                                       *the_hole_value()),
79       FixedArray);
80 }
81
82
83 Handle<FixedArray> Factory::NewUninitializedFixedArray(int size) {
84   CALL_HEAP_FUNCTION(
85       isolate(),
86       isolate()->heap()->AllocateUninitializedFixedArray(size),
87       FixedArray);
88 }
89
90
91 Handle<FixedArrayBase> Factory::NewFixedDoubleArray(int size,
92                                                     PretenureFlag pretenure) {
93   ASSERT(0 <= size);
94   CALL_HEAP_FUNCTION(
95       isolate(),
96       isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
97       FixedArrayBase);
98 }
99
100
101 Handle<FixedArrayBase> Factory::NewFixedDoubleArrayWithHoles(
102     int size,
103     PretenureFlag pretenure) {
104   ASSERT(0 <= size);
105   Handle<FixedArrayBase> array = NewFixedDoubleArray(size, pretenure);
106   if (size > 0) {
107     Handle<FixedDoubleArray> double_array =
108         Handle<FixedDoubleArray>::cast(array);
109     for (int i = 0; i < size; ++i) {
110       double_array->set_the_hole(i);
111     }
112   }
113   return array;
114 }
115
116
117 Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
118     const ConstantPoolArray::NumberOfEntries& small) {
119   ASSERT(small.total_count() > 0);
120   CALL_HEAP_FUNCTION(
121       isolate(),
122       isolate()->heap()->AllocateConstantPoolArray(small),
123       ConstantPoolArray);
124 }
125
126
127 Handle<ConstantPoolArray> Factory::NewExtendedConstantPoolArray(
128     const ConstantPoolArray::NumberOfEntries& small,
129     const ConstantPoolArray::NumberOfEntries& extended) {
130   ASSERT(small.total_count() > 0);
131   ASSERT(extended.total_count() > 0);
132   CALL_HEAP_FUNCTION(
133       isolate(),
134       isolate()->heap()->AllocateExtendedConstantPoolArray(small, extended),
135       ConstantPoolArray);
136 }
137
138
139 Handle<OrderedHashSet> Factory::NewOrderedHashSet() {
140   return OrderedHashSet::Allocate(isolate(), 4);
141 }
142
143
144 Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
145   return OrderedHashMap::Allocate(isolate(), 4);
146 }
147
148
149 Handle<AccessorPair> Factory::NewAccessorPair() {
150   Handle<AccessorPair> accessors =
151       Handle<AccessorPair>::cast(NewStruct(ACCESSOR_PAIR_TYPE));
152   accessors->set_getter(*the_hole_value(), SKIP_WRITE_BARRIER);
153   accessors->set_setter(*the_hole_value(), SKIP_WRITE_BARRIER);
154   accessors->set_access_flags(Smi::FromInt(0), SKIP_WRITE_BARRIER);
155   return accessors;
156 }
157
158
159 Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
160   Handle<TypeFeedbackInfo> info =
161       Handle<TypeFeedbackInfo>::cast(NewStruct(TYPE_FEEDBACK_INFO_TYPE));
162   info->initialize_storage();
163   return info;
164 }
165
166
167 // Internalized strings are created in the old generation (data space).
168 Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
169   Utf8StringKey key(string, isolate()->heap()->HashSeed());
170   return InternalizeStringWithKey(&key);
171 }
172
173
174 // Internalized strings are created in the old generation (data space).
175 Handle<String> Factory::InternalizeString(Handle<String> string) {
176   if (string->IsInternalizedString()) return string;
177   return StringTable::LookupString(isolate(), string);
178 }
179
180
181 Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
182   OneByteStringKey key(string, isolate()->heap()->HashSeed());
183   return InternalizeStringWithKey(&key);
184 }
185
186
187 Handle<String> Factory::InternalizeOneByteString(
188     Handle<SeqOneByteString> string, int from, int length) {
189   SubStringKey<uint8_t> key(string, from, length);
190   return InternalizeStringWithKey(&key);
191 }
192
193
194 Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
195   TwoByteStringKey key(string, isolate()->heap()->HashSeed());
196   return InternalizeStringWithKey(&key);
197 }
198
199
200 template<class StringTableKey>
201 Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
202   return StringTable::LookupKey(isolate(), key);
203 }
204
205
206 template Handle<String> Factory::InternalizeStringWithKey<
207     SubStringKey<uint8_t> > (SubStringKey<uint8_t>* key);
208 template Handle<String> Factory::InternalizeStringWithKey<
209     SubStringKey<uint16_t> > (SubStringKey<uint16_t>* key);
210
211
212 MaybeHandle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
213                                                   PretenureFlag pretenure) {
214   int length = string.length();
215   if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
216   Handle<SeqOneByteString> result;
217   ASSIGN_RETURN_ON_EXCEPTION(
218       isolate(),
219       result,
220       NewRawOneByteString(string.length(), pretenure),
221       String);
222
223   DisallowHeapAllocation no_gc;
224   // Copy the characters into the new object.
225   CopyChars(SeqOneByteString::cast(*result)->GetChars(),
226             string.start(),
227             length);
228   return result;
229 }
230
231 MaybeHandle<String> Factory::NewStringFromUtf8(Vector<const char> string,
232                                                PretenureFlag pretenure) {
233   // Check for ASCII first since this is the common case.
234   const char* start = string.start();
235   int length = string.length();
236   int non_ascii_start = String::NonAsciiStart(start, length);
237   if (non_ascii_start >= length) {
238     // If the string is ASCII, we do not need to convert the characters
239     // since UTF8 is backwards compatible with ASCII.
240     return NewStringFromOneByte(Vector<const uint8_t>::cast(string), pretenure);
241   }
242
243   // Non-ASCII and we need to decode.
244   Access<UnicodeCache::Utf8Decoder>
245       decoder(isolate()->unicode_cache()->utf8_decoder());
246   decoder->Reset(string.start() + non_ascii_start,
247                  length - non_ascii_start);
248   int utf16_length = decoder->Utf16Length();
249   ASSERT(utf16_length > 0);
250   // Allocate string.
251   Handle<SeqTwoByteString> result;
252   ASSIGN_RETURN_ON_EXCEPTION(
253       isolate(), result,
254       NewRawTwoByteString(non_ascii_start + utf16_length, pretenure),
255       String);
256   // Copy ascii portion.
257   uint16_t* data = result->GetChars();
258   const char* ascii_data = string.start();
259   for (int i = 0; i < non_ascii_start; i++) {
260     *data++ = *ascii_data++;
261   }
262   // Now write the remainder.
263   decoder->WriteUtf16(data, utf16_length);
264   return result;
265 }
266
267
268 MaybeHandle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
269                                                   PretenureFlag pretenure) {
270   int length = string.length();
271   const uc16* start = string.start();
272   if (String::IsOneByte(start, length)) {
273     Handle<SeqOneByteString> result;
274     ASSIGN_RETURN_ON_EXCEPTION(
275         isolate(),
276         result,
277         NewRawOneByteString(length, pretenure),
278         String);
279     CopyChars(result->GetChars(), start, length);
280     return result;
281   } else {
282     Handle<SeqTwoByteString> result;
283     ASSIGN_RETURN_ON_EXCEPTION(
284         isolate(),
285         result,
286         NewRawTwoByteString(length, pretenure),
287         String);
288     CopyChars(result->GetChars(), start, length);
289     return result;
290   }
291 }
292
293
294 Handle<String> Factory::NewInternalizedStringFromUtf8(Vector<const char> str,
295                                                       int chars,
296                                                       uint32_t hash_field) {
297   CALL_HEAP_FUNCTION(
298       isolate(),
299       isolate()->heap()->AllocateInternalizedStringFromUtf8(
300           str, chars, hash_field),
301       String);
302 }
303
304
305 MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedString(
306       Vector<const uint8_t> str,
307       uint32_t hash_field) {
308   CALL_HEAP_FUNCTION(
309       isolate(),
310       isolate()->heap()->AllocateOneByteInternalizedString(str, hash_field),
311       String);
312 }
313
314
315 MUST_USE_RESULT Handle<String> Factory::NewTwoByteInternalizedString(
316       Vector<const uc16> str,
317       uint32_t hash_field) {
318   CALL_HEAP_FUNCTION(
319       isolate(),
320       isolate()->heap()->AllocateTwoByteInternalizedString(str, hash_field),
321       String);
322 }
323
324
325 Handle<String> Factory::NewInternalizedStringImpl(
326     Handle<String> string, int chars, uint32_t hash_field) {
327   CALL_HEAP_FUNCTION(
328       isolate(),
329       isolate()->heap()->AllocateInternalizedStringImpl(
330           *string, chars, hash_field),
331       String);
332 }
333
334
335 MaybeHandle<Map> Factory::InternalizedStringMapForString(
336     Handle<String> string) {
337   // If the string is in new space it cannot be used as internalized.
338   if (isolate()->heap()->InNewSpace(*string)) return MaybeHandle<Map>();
339
340   // Find the corresponding internalized string map for strings.
341   switch (string->map()->instance_type()) {
342     case STRING_TYPE: return internalized_string_map();
343     case ASCII_STRING_TYPE: return ascii_internalized_string_map();
344     case EXTERNAL_STRING_TYPE: return external_internalized_string_map();
345     case EXTERNAL_ASCII_STRING_TYPE:
346       return external_ascii_internalized_string_map();
347     case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
348       return external_internalized_string_with_one_byte_data_map();
349     case SHORT_EXTERNAL_STRING_TYPE:
350       return short_external_internalized_string_map();
351     case SHORT_EXTERNAL_ASCII_STRING_TYPE:
352       return short_external_ascii_internalized_string_map();
353     case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
354       return short_external_internalized_string_with_one_byte_data_map();
355     default: return MaybeHandle<Map>();  // No match found.
356   }
357 }
358
359
360 MaybeHandle<SeqOneByteString> Factory::NewRawOneByteString(
361     int length, PretenureFlag pretenure) {
362   if (length > String::kMaxLength || length < 0) {
363     return isolate()->Throw<SeqOneByteString>(NewInvalidStringLengthError());
364   }
365   CALL_HEAP_FUNCTION(
366       isolate(),
367       isolate()->heap()->AllocateRawOneByteString(length, pretenure),
368       SeqOneByteString);
369 }
370
371
372 MaybeHandle<SeqTwoByteString> Factory::NewRawTwoByteString(
373     int length, PretenureFlag pretenure) {
374   if (length > String::kMaxLength || length < 0) {
375     return isolate()->Throw<SeqTwoByteString>(NewInvalidStringLengthError());
376   }
377   CALL_HEAP_FUNCTION(
378       isolate(),
379       isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
380       SeqTwoByteString);
381 }
382
383
384 Handle<String> Factory::LookupSingleCharacterStringFromCode(uint32_t code) {
385   if (code <= String::kMaxOneByteCharCodeU) {
386     {
387       DisallowHeapAllocation no_allocation;
388       Object* value = single_character_string_cache()->get(code);
389       if (value != *undefined_value()) {
390         return handle(String::cast(value), isolate());
391       }
392     }
393     uint8_t buffer[1];
394     buffer[0] = static_cast<uint8_t>(code);
395     Handle<String> result =
396         InternalizeOneByteString(Vector<const uint8_t>(buffer, 1));
397     single_character_string_cache()->set(code, *result);
398     return result;
399   }
400   ASSERT(code <= String::kMaxUtf16CodeUnitU);
401
402   Handle<SeqTwoByteString> result = NewRawTwoByteString(1).ToHandleChecked();
403   result->SeqTwoByteStringSet(0, static_cast<uint16_t>(code));
404   return result;
405 }
406
407
408 // Returns true for a character in a range.  Both limits are inclusive.
409 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
410   // This makes uses of the the unsigned wraparound.
411   return character - from <= to - from;
412 }
413
414
415 static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
416                                                           uint16_t c1,
417                                                           uint16_t c2) {
418   // Numeric strings have a different hash algorithm not known by
419   // LookupTwoCharsStringIfExists, so we skip this step for such strings.
420   if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
421     Handle<String> result;
422     if (StringTable::LookupTwoCharsStringIfExists(isolate, c1, c2).
423         ToHandle(&result)) {
424       return result;
425     }
426   }
427
428   // Now we know the length is 2, we might as well make use of that fact
429   // when building the new string.
430   if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
431     // We can do this.
432     ASSERT(IsPowerOf2(String::kMaxOneByteCharCodeU + 1));  // because of this.
433     Handle<SeqOneByteString> str =
434         isolate->factory()->NewRawOneByteString(2).ToHandleChecked();
435     uint8_t* dest = str->GetChars();
436     dest[0] = static_cast<uint8_t>(c1);
437     dest[1] = static_cast<uint8_t>(c2);
438     return str;
439   } else {
440     Handle<SeqTwoByteString> str =
441         isolate->factory()->NewRawTwoByteString(2).ToHandleChecked();
442     uc16* dest = str->GetChars();
443     dest[0] = c1;
444     dest[1] = c2;
445     return str;
446   }
447 }
448
449
450 template<typename SinkChar, typename StringType>
451 Handle<String> ConcatStringContent(Handle<StringType> result,
452                                    Handle<String> first,
453                                    Handle<String> second) {
454   DisallowHeapAllocation pointer_stays_valid;
455   SinkChar* sink = result->GetChars();
456   String::WriteToFlat(*first, sink, 0, first->length());
457   String::WriteToFlat(*second, sink + first->length(), 0, second->length());
458   return result;
459 }
460
461
462 MaybeHandle<String> Factory::NewConsString(Handle<String> left,
463                                            Handle<String> right) {
464   int left_length = left->length();
465   if (left_length == 0) return right;
466   int right_length = right->length();
467   if (right_length == 0) return left;
468
469   int length = left_length + right_length;
470
471   if (length == 2) {
472     uint16_t c1 = left->Get(0);
473     uint16_t c2 = right->Get(0);
474     return MakeOrFindTwoCharacterString(isolate(), c1, c2);
475   }
476
477   // Make sure that an out of memory exception is thrown if the length
478   // of the new cons string is too large.
479   if (length > String::kMaxLength || length < 0) {
480     return isolate()->Throw<String>(NewInvalidStringLengthError());
481   }
482
483   bool left_is_one_byte = left->IsOneByteRepresentation();
484   bool right_is_one_byte = right->IsOneByteRepresentation();
485   bool is_one_byte = left_is_one_byte && right_is_one_byte;
486   bool is_one_byte_data_in_two_byte_string = false;
487   if (!is_one_byte) {
488     // At least one of the strings uses two-byte representation so we
489     // can't use the fast case code for short ASCII strings below, but
490     // we can try to save memory if all chars actually fit in ASCII.
491     is_one_byte_data_in_two_byte_string =
492         left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
493     if (is_one_byte_data_in_two_byte_string) {
494       isolate()->counters()->string_add_runtime_ext_to_ascii()->Increment();
495     }
496   }
497
498   // If the resulting string is small make a flat string.
499   if (length < ConsString::kMinLength) {
500     // Note that neither of the two inputs can be a slice because:
501     STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
502     ASSERT(left->IsFlat());
503     ASSERT(right->IsFlat());
504
505     STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
506     if (is_one_byte) {
507       Handle<SeqOneByteString> result =
508           NewRawOneByteString(length).ToHandleChecked();
509       DisallowHeapAllocation no_gc;
510       uint8_t* dest = result->GetChars();
511       // Copy left part.
512       const uint8_t* src = left->IsExternalString()
513           ? Handle<ExternalAsciiString>::cast(left)->GetChars()
514           : Handle<SeqOneByteString>::cast(left)->GetChars();
515       for (int i = 0; i < left_length; i++) *dest++ = src[i];
516       // Copy right part.
517       src = right->IsExternalString()
518           ? Handle<ExternalAsciiString>::cast(right)->GetChars()
519           : Handle<SeqOneByteString>::cast(right)->GetChars();
520       for (int i = 0; i < right_length; i++) *dest++ = src[i];
521       return result;
522     }
523
524     return (is_one_byte_data_in_two_byte_string)
525         ? ConcatStringContent<uint8_t>(
526             NewRawOneByteString(length).ToHandleChecked(), left, right)
527         : ConcatStringContent<uc16>(
528             NewRawTwoByteString(length).ToHandleChecked(), left, right);
529   }
530
531   Handle<Map> map = (is_one_byte || is_one_byte_data_in_two_byte_string)
532       ? cons_ascii_string_map()  : cons_string_map();
533   Handle<ConsString> result =  New<ConsString>(map, NEW_SPACE);
534
535   DisallowHeapAllocation no_gc;
536   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
537
538   result->set_hash_field(String::kEmptyHashField);
539   result->set_length(length);
540   result->set_first(*left, mode);
541   result->set_second(*right, mode);
542   return result;
543 }
544
545
546 Handle<String> Factory::NewFlatConcatString(Handle<String> first,
547                                             Handle<String> second) {
548   int total_length = first->length() + second->length();
549   if (first->IsOneByteRepresentation() && second->IsOneByteRepresentation()) {
550     return ConcatStringContent<uint8_t>(
551         NewRawOneByteString(total_length).ToHandleChecked(), first, second);
552   } else {
553     return ConcatStringContent<uc16>(
554         NewRawTwoByteString(total_length).ToHandleChecked(), first, second);
555   }
556 }
557
558
559 Handle<String> Factory::NewProperSubString(Handle<String> str,
560                                            int begin,
561                                            int end) {
562 #if VERIFY_HEAP
563   if (FLAG_verify_heap) str->StringVerify();
564 #endif
565   ASSERT(begin > 0 || end < str->length());
566
567   str = String::Flatten(str);
568
569   int length = end - begin;
570   if (length <= 0) return empty_string();
571   if (length == 1) {
572     return LookupSingleCharacterStringFromCode(str->Get(begin));
573   }
574   if (length == 2) {
575     // Optimization for 2-byte strings often used as keys in a decompression
576     // dictionary.  Check whether we already have the string in the string
577     // table to prevent creation of many unnecessary strings.
578     uint16_t c1 = str->Get(begin);
579     uint16_t c2 = str->Get(begin + 1);
580     return MakeOrFindTwoCharacterString(isolate(), c1, c2);
581   }
582
583   if (!FLAG_string_slices || length < SlicedString::kMinLength) {
584     if (str->IsOneByteRepresentation()) {
585       Handle<SeqOneByteString> result =
586           NewRawOneByteString(length).ToHandleChecked();
587       uint8_t* dest = result->GetChars();
588       DisallowHeapAllocation no_gc;
589       String::WriteToFlat(*str, dest, begin, end);
590       return result;
591     } else {
592       Handle<SeqTwoByteString> result =
593           NewRawTwoByteString(length).ToHandleChecked();
594       uc16* dest = result->GetChars();
595       DisallowHeapAllocation no_gc;
596       String::WriteToFlat(*str, dest, begin, end);
597       return result;
598     }
599   }
600
601   int offset = begin;
602
603   if (str->IsSlicedString()) {
604     Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
605     str = Handle<String>(slice->parent(), isolate());
606     offset += slice->offset();
607   }
608
609   ASSERT(str->IsSeqString() || str->IsExternalString());
610   Handle<Map> map = str->IsOneByteRepresentation() ? sliced_ascii_string_map()
611                                                    : sliced_string_map();
612   Handle<SlicedString> slice = New<SlicedString>(map, NEW_SPACE);
613
614   slice->set_hash_field(String::kEmptyHashField);
615   slice->set_length(length);
616   slice->set_parent(*str);
617   slice->set_offset(offset);
618   return slice;
619 }
620
621
622 MaybeHandle<String> Factory::NewExternalStringFromAscii(
623     const ExternalAsciiString::Resource* resource) {
624   size_t length = resource->length();
625   if (length > static_cast<size_t>(String::kMaxLength)) {
626     return isolate()->Throw<String>(NewInvalidStringLengthError());
627   }
628
629   Handle<Map> map = external_ascii_string_map();
630   Handle<ExternalAsciiString> external_string =
631       New<ExternalAsciiString>(map, NEW_SPACE);
632   external_string->set_length(static_cast<int>(length));
633   external_string->set_hash_field(String::kEmptyHashField);
634   external_string->set_resource(resource);
635
636   return external_string;
637 }
638
639
640 MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
641     const ExternalTwoByteString::Resource* resource) {
642   size_t length = resource->length();
643   if (length > static_cast<size_t>(String::kMaxLength)) {
644     return isolate()->Throw<String>(NewInvalidStringLengthError());
645   }
646
647   // For small strings we check whether the resource contains only
648   // one byte characters.  If yes, we use a different string map.
649   static const size_t kOneByteCheckLengthLimit = 32;
650   bool is_one_byte = length <= kOneByteCheckLengthLimit &&
651       String::IsOneByte(resource->data(), static_cast<int>(length));
652   Handle<Map> map = is_one_byte ?
653       external_string_with_one_byte_data_map() : external_string_map();
654   Handle<ExternalTwoByteString> external_string =
655       New<ExternalTwoByteString>(map, NEW_SPACE);
656   external_string->set_length(static_cast<int>(length));
657   external_string->set_hash_field(String::kEmptyHashField);
658   external_string->set_resource(resource);
659
660   return external_string;
661 }
662
663
664 Handle<Symbol> Factory::NewSymbol() {
665   CALL_HEAP_FUNCTION(
666       isolate(),
667       isolate()->heap()->AllocateSymbol(),
668       Symbol);
669 }
670
671
672 Handle<Symbol> Factory::NewPrivateSymbol() {
673   Handle<Symbol> symbol = NewSymbol();
674   symbol->set_is_private(true);
675   return symbol;
676 }
677
678
679 Handle<Context> Factory::NewNativeContext() {
680   Handle<FixedArray> array = NewFixedArray(Context::NATIVE_CONTEXT_SLOTS);
681   array->set_map_no_write_barrier(*native_context_map());
682   Handle<Context> context = Handle<Context>::cast(array);
683   context->set_js_array_maps(*undefined_value());
684   ASSERT(context->IsNativeContext());
685   return context;
686 }
687
688
689 Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
690                                           Handle<ScopeInfo> scope_info) {
691   Handle<FixedArray> array =
692       NewFixedArray(scope_info->ContextLength(), TENURED);
693   array->set_map_no_write_barrier(*global_context_map());
694   Handle<Context> context = Handle<Context>::cast(array);
695   context->set_closure(*function);
696   context->set_previous(function->context());
697   context->set_extension(*scope_info);
698   context->set_global_object(function->context()->global_object());
699   ASSERT(context->IsGlobalContext());
700   return context;
701 }
702
703
704 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
705   Handle<FixedArray> array =
706       NewFixedArray(scope_info->ContextLength(), TENURED);
707   array->set_map_no_write_barrier(*module_context_map());
708   // Instance link will be set later.
709   Handle<Context> context = Handle<Context>::cast(array);
710   context->set_extension(Smi::FromInt(0));
711   return context;
712 }
713
714
715 Handle<Context> Factory::NewFunctionContext(int length,
716                                             Handle<JSFunction> function) {
717   ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
718   Handle<FixedArray> array = NewFixedArray(length);
719   array->set_map_no_write_barrier(*function_context_map());
720   Handle<Context> context = Handle<Context>::cast(array);
721   context->set_closure(*function);
722   context->set_previous(function->context());
723   context->set_extension(Smi::FromInt(0));
724   context->set_global_object(function->context()->global_object());
725   return context;
726 }
727
728
729 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
730                                          Handle<Context> previous,
731                                          Handle<String> name,
732                                          Handle<Object> thrown_object) {
733   STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
734   Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
735   array->set_map_no_write_barrier(*catch_context_map());
736   Handle<Context> context = Handle<Context>::cast(array);
737   context->set_closure(*function);
738   context->set_previous(*previous);
739   context->set_extension(*name);
740   context->set_global_object(previous->global_object());
741   context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
742   return context;
743 }
744
745
746 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
747                                         Handle<Context> previous,
748                                         Handle<JSReceiver> extension) {
749   Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS);
750   array->set_map_no_write_barrier(*with_context_map());
751   Handle<Context> context = Handle<Context>::cast(array);
752   context->set_closure(*function);
753   context->set_previous(*previous);
754   context->set_extension(*extension);
755   context->set_global_object(previous->global_object());
756   return context;
757 }
758
759
760 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
761                                          Handle<Context> previous,
762                                          Handle<ScopeInfo> scope_info) {
763   Handle<FixedArray> array =
764       NewFixedArrayWithHoles(scope_info->ContextLength());
765   array->set_map_no_write_barrier(*block_context_map());
766   Handle<Context> context = Handle<Context>::cast(array);
767   context->set_closure(*function);
768   context->set_previous(*previous);
769   context->set_extension(*scope_info);
770   context->set_global_object(previous->global_object());
771   return context;
772 }
773
774
775 Handle<Struct> Factory::NewStruct(InstanceType type) {
776   CALL_HEAP_FUNCTION(
777       isolate(),
778       isolate()->heap()->AllocateStruct(type),
779       Struct);
780 }
781
782
783 Handle<CodeCache> Factory::NewCodeCache() {
784   Handle<CodeCache> code_cache =
785       Handle<CodeCache>::cast(NewStruct(CODE_CACHE_TYPE));
786   code_cache->set_default_cache(*empty_fixed_array(), SKIP_WRITE_BARRIER);
787   code_cache->set_normal_type_cache(*undefined_value(), SKIP_WRITE_BARRIER);
788   return code_cache;
789 }
790
791
792 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
793     int aliased_context_slot) {
794   Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
795       NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
796   entry->set_aliased_context_slot(aliased_context_slot);
797   return entry;
798 }
799
800
801 Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
802   return Handle<DeclaredAccessorDescriptor>::cast(
803       NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
804 }
805
806
807 Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
808   Handle<DeclaredAccessorInfo> info =
809       Handle<DeclaredAccessorInfo>::cast(
810           NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
811   info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
812   return info;
813 }
814
815
816 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
817   Handle<ExecutableAccessorInfo> info =
818       Handle<ExecutableAccessorInfo>::cast(
819           NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
820   info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
821   return info;
822 }
823
824
825 Handle<Script> Factory::NewScript(Handle<String> source) {
826   // Generate id for this script.
827   Heap* heap = isolate()->heap();
828   int id = heap->last_script_id()->value() + 1;
829   if (!Smi::IsValid(id) || id < 0) id = 1;
830   heap->set_last_script_id(Smi::FromInt(id));
831
832   // Create and initialize script object.
833   Handle<Foreign> wrapper = NewForeign(0, TENURED);
834   Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
835   script->set_source(*source);
836   script->set_name(heap->undefined_value());
837   script->set_id(Smi::FromInt(id));
838   script->set_line_offset(Smi::FromInt(0));
839   script->set_column_offset(Smi::FromInt(0));
840   script->set_context_data(heap->undefined_value());
841   script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
842   script->set_wrapper(*wrapper);
843   script->set_line_ends(heap->undefined_value());
844   script->set_eval_from_shared(heap->undefined_value());
845   script->set_eval_from_instructions_offset(Smi::FromInt(0));
846   script->set_flags(Smi::FromInt(0));
847
848   return script;
849 }
850
851
852 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
853   CALL_HEAP_FUNCTION(isolate(),
854                      isolate()->heap()->AllocateForeign(addr, pretenure),
855                      Foreign);
856 }
857
858
859 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
860   return NewForeign((Address) desc, TENURED);
861 }
862
863
864 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
865   ASSERT(0 <= length);
866   CALL_HEAP_FUNCTION(
867       isolate(),
868       isolate()->heap()->AllocateByteArray(length, pretenure),
869       ByteArray);
870 }
871
872
873 Handle<ExternalArray> Factory::NewExternalArray(int length,
874                                                 ExternalArrayType array_type,
875                                                 void* external_pointer,
876                                                 PretenureFlag pretenure) {
877   ASSERT(0 <= length && length <= Smi::kMaxValue);
878   CALL_HEAP_FUNCTION(
879       isolate(),
880       isolate()->heap()->AllocateExternalArray(length,
881                                                array_type,
882                                                external_pointer,
883                                                pretenure),
884       ExternalArray);
885 }
886
887
888 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
889     int length,
890     ExternalArrayType array_type,
891     PretenureFlag pretenure) {
892   ASSERT(0 <= length && length <= Smi::kMaxValue);
893   CALL_HEAP_FUNCTION(
894       isolate(),
895       isolate()->heap()->AllocateFixedTypedArray(length,
896                                                  array_type,
897                                                  pretenure),
898       FixedTypedArrayBase);
899 }
900
901
902 Handle<Cell> Factory::NewCell(Handle<Object> value) {
903   AllowDeferredHandleDereference convert_to_cell;
904   CALL_HEAP_FUNCTION(
905       isolate(),
906       isolate()->heap()->AllocateCell(*value),
907       Cell);
908 }
909
910
911 Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
912   CALL_HEAP_FUNCTION(
913       isolate(),
914       isolate()->heap()->AllocatePropertyCell(),
915       PropertyCell);
916 }
917
918
919 Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
920   AllowDeferredHandleDereference convert_to_cell;
921   Handle<PropertyCell> cell = NewPropertyCellWithHole();
922   PropertyCell::SetValueInferType(cell, value);
923   return cell;
924 }
925
926
927 Handle<AllocationSite> Factory::NewAllocationSite() {
928   Handle<Map> map = allocation_site_map();
929   Handle<AllocationSite> site = New<AllocationSite>(map, OLD_POINTER_SPACE);
930   site->Initialize();
931
932   // Link the site
933   site->set_weak_next(isolate()->heap()->allocation_sites_list());
934   isolate()->heap()->set_allocation_sites_list(*site);
935   return site;
936 }
937
938
939 Handle<Map> Factory::NewMap(InstanceType type,
940                             int instance_size,
941                             ElementsKind elements_kind) {
942   CALL_HEAP_FUNCTION(
943       isolate(),
944       isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
945       Map);
946 }
947
948
949 Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> object) {
950   CALL_HEAP_FUNCTION(isolate(),
951                      isolate()->heap()->CopyJSObject(*object, NULL),
952                      JSObject);
953 }
954
955
956 Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
957     Handle<JSObject> object,
958     Handle<AllocationSite> site) {
959   CALL_HEAP_FUNCTION(isolate(),
960                      isolate()->heap()->CopyJSObject(
961                          *object,
962                          site.is_null() ? NULL : *site),
963                      JSObject);
964 }
965
966
967 Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
968                                                   Handle<Map> map) {
969   CALL_HEAP_FUNCTION(isolate(),
970                      isolate()->heap()->CopyFixedArrayWithMap(*array, *map),
971                      FixedArray);
972 }
973
974
975 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
976   CALL_HEAP_FUNCTION(isolate(),
977                      isolate()->heap()->CopyFixedArray(*array),
978                      FixedArray);
979 }
980
981
982 Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
983     Handle<FixedArray> array) {
984   ASSERT(isolate()->heap()->InNewSpace(*array));
985   CALL_HEAP_FUNCTION(isolate(),
986                      isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
987                      FixedArray);
988 }
989
990
991 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
992     Handle<FixedDoubleArray> array) {
993   CALL_HEAP_FUNCTION(isolate(),
994                      isolate()->heap()->CopyFixedDoubleArray(*array),
995                      FixedDoubleArray);
996 }
997
998
999 Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
1000     Handle<ConstantPoolArray> array) {
1001   CALL_HEAP_FUNCTION(isolate(),
1002                      isolate()->heap()->CopyConstantPoolArray(*array),
1003                      ConstantPoolArray);
1004 }
1005
1006
1007 Handle<Object> Factory::NewNumber(double value,
1008                                   PretenureFlag pretenure) {
1009   // We need to distinguish the minus zero value and this cannot be
1010   // done after conversion to int. Doing this by comparing bit
1011   // patterns is faster than using fpclassify() et al.
1012   if (IsMinusZero(value)) return NewHeapNumber(-0.0, pretenure);
1013
1014   int int_value = FastD2I(value);
1015   if (value == int_value && Smi::IsValid(int_value)) {
1016     return handle(Smi::FromInt(int_value), isolate());
1017   }
1018
1019   // Materialize the value in the heap.
1020   return NewHeapNumber(value, pretenure);
1021 }
1022
1023
1024 Handle<Object> Factory::NewNumberFromInt(int32_t value,
1025                                          PretenureFlag pretenure) {
1026   if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
1027   // Bypass NumberFromDouble to avoid various redundant checks.
1028   return NewHeapNumber(FastI2D(value), pretenure);
1029 }
1030
1031
1032 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1033                                           PretenureFlag pretenure) {
1034   int32_t int32v = static_cast<int32_t>(value);
1035   if (int32v >= 0 && Smi::IsValid(int32v)) {
1036     return handle(Smi::FromInt(int32v), isolate());
1037   }
1038   return NewHeapNumber(FastUI2D(value), pretenure);
1039 }
1040
1041
1042 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1043                                           PretenureFlag pretenure) {
1044   CALL_HEAP_FUNCTION(
1045       isolate(),
1046       isolate()->heap()->AllocateHeapNumber(value, pretenure), HeapNumber);
1047 }
1048
1049
1050 Handle<Float32x4> Factory::NewFloat32x4(float32x4_value_t value,
1051                                         PretenureFlag pretenure) {
1052   CALL_HEAP_FUNCTION(
1053       isolate(),
1054       isolate()->heap()->AllocateFloat32x4(value, pretenure), Float32x4);
1055 }
1056
1057
1058 Handle<Float64x2> Factory::NewFloat64x2(float64x2_value_t value,
1059                                         PretenureFlag pretenure) {
1060   CALL_HEAP_FUNCTION(
1061       isolate(),
1062       isolate()->heap()->AllocateFloat64x2(value, pretenure), Float64x2);
1063 }
1064
1065
1066 Handle<Int32x4> Factory::NewInt32x4(int32x4_value_t value,
1067                                     PretenureFlag pretenure) {
1068   CALL_HEAP_FUNCTION(
1069       isolate(),
1070       isolate()->heap()->AllocateInt32x4(value, pretenure), Int32x4);
1071 }
1072
1073
1074 Handle<Object> Factory::NewTypeError(const char* message,
1075                                      Vector< Handle<Object> > args) {
1076   return NewError("MakeTypeError", message, args);
1077 }
1078
1079
1080 Handle<Object> Factory::NewTypeError(Handle<String> message) {
1081   return NewError("$TypeError", message);
1082 }
1083
1084
1085 Handle<Object> Factory::NewRangeError(const char* message,
1086                                       Vector< Handle<Object> > args) {
1087   return NewError("MakeRangeError", message, args);
1088 }
1089
1090
1091 Handle<Object> Factory::NewRangeError(Handle<String> message) {
1092   return NewError("$RangeError", message);
1093 }
1094
1095
1096 Handle<Object> Factory::NewSyntaxError(const char* message,
1097                                        Handle<JSArray> args) {
1098   return NewError("MakeSyntaxError", message, args);
1099 }
1100
1101
1102 Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
1103   return NewError("$SyntaxError", message);
1104 }
1105
1106
1107 Handle<Object> Factory::NewReferenceError(const char* message,
1108                                           Vector< Handle<Object> > args) {
1109   return NewError("MakeReferenceError", message, args);
1110 }
1111
1112
1113 Handle<Object> Factory::NewReferenceError(const char* message,
1114                                           Handle<JSArray> args) {
1115   return NewError("MakeReferenceError", message, args);
1116 }
1117
1118
1119 Handle<Object> Factory::NewReferenceError(Handle<String> message) {
1120   return NewError("$ReferenceError", message);
1121 }
1122
1123
1124 Handle<Object> Factory::NewError(const char* maker,
1125                                  const char* message,
1126                                  Vector< Handle<Object> > args) {
1127   // Instantiate a closeable HandleScope for EscapeFrom.
1128   v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
1129   Handle<FixedArray> array = NewFixedArray(args.length());
1130   for (int i = 0; i < args.length(); i++) {
1131     array->set(i, *args[i]);
1132   }
1133   Handle<JSArray> object = NewJSArrayWithElements(array);
1134   Handle<Object> result = NewError(maker, message, object);
1135   return result.EscapeFrom(&scope);
1136 }
1137
1138
1139 Handle<Object> Factory::NewEvalError(const char* message,
1140                                      Vector< Handle<Object> > args) {
1141   return NewError("MakeEvalError", message, args);
1142 }
1143
1144
1145 Handle<Object> Factory::NewError(const char* message,
1146                                  Vector< Handle<Object> > args) {
1147   return NewError("MakeError", message, args);
1148 }
1149
1150
1151 Handle<String> Factory::EmergencyNewError(const char* message,
1152                                           Handle<JSArray> args) {
1153   const int kBufferSize = 1000;
1154   char buffer[kBufferSize];
1155   size_t space = kBufferSize;
1156   char* p = &buffer[0];
1157
1158   Vector<char> v(buffer, kBufferSize);
1159   StrNCpy(v, message, space);
1160   space -= Min(space, strlen(message));
1161   p = &buffer[kBufferSize] - space;
1162
1163   for (unsigned i = 0; i < ARRAY_SIZE(args); i++) {
1164     if (space > 0) {
1165       *p++ = ' ';
1166       space--;
1167       if (space > 0) {
1168         Handle<String> arg_str = Handle<String>::cast(
1169             Object::GetElement(isolate(), args, i).ToHandleChecked());
1170         SmartArrayPointer<char> arg = arg_str->ToCString();
1171         Vector<char> v2(p, static_cast<int>(space));
1172         StrNCpy(v2, arg.get(), space);
1173         space -= Min(space, strlen(arg.get()));
1174         p = &buffer[kBufferSize] - space;
1175       }
1176     }
1177   }
1178   if (space > 0) {
1179     *p = '\0';
1180   } else {
1181     buffer[kBufferSize - 1] = '\0';
1182   }
1183   return NewStringFromUtf8(CStrVector(buffer), TENURED).ToHandleChecked();
1184 }
1185
1186
1187 Handle<Object> Factory::NewError(const char* maker,
1188                                  const char* message,
1189                                  Handle<JSArray> args) {
1190   Handle<String> make_str = InternalizeUtf8String(maker);
1191   Handle<Object> fun_obj = Object::GetProperty(
1192       isolate()->js_builtins_object(), make_str).ToHandleChecked();
1193   // If the builtins haven't been properly configured yet this error
1194   // constructor may not have been defined.  Bail out.
1195   if (!fun_obj->IsJSFunction()) {
1196     return EmergencyNewError(message, args);
1197   }
1198   Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1199   Handle<Object> message_obj = InternalizeUtf8String(message);
1200   Handle<Object> argv[] = { message_obj, args };
1201
1202   // Invoke the JavaScript factory method. If an exception is thrown while
1203   // running the factory method, use the exception as the result.
1204   Handle<Object> result;
1205   Handle<Object> exception;
1206   if (!Execution::TryCall(fun,
1207                           isolate()->js_builtins_object(),
1208                           ARRAY_SIZE(argv),
1209                           argv,
1210                           &exception).ToHandle(&result)) {
1211     return exception;
1212   }
1213   return result;
1214 }
1215
1216
1217 Handle<Object> Factory::NewError(Handle<String> message) {
1218   return NewError("$Error", message);
1219 }
1220
1221
1222 Handle<Object> Factory::NewError(const char* constructor,
1223                                  Handle<String> message) {
1224   Handle<String> constr = InternalizeUtf8String(constructor);
1225   Handle<JSFunction> fun = Handle<JSFunction>::cast(Object::GetProperty(
1226       isolate()->js_builtins_object(), constr).ToHandleChecked());
1227   Handle<Object> argv[] = { message };
1228
1229   // Invoke the JavaScript factory method. If an exception is thrown while
1230   // running the factory method, use the exception as the result.
1231   Handle<Object> result;
1232   Handle<Object> exception;
1233   if (!Execution::TryCall(fun,
1234                           isolate()->js_builtins_object(),
1235                           ARRAY_SIZE(argv),
1236                           argv,
1237                           &exception).ToHandle(&result)) {
1238     return exception;
1239   }
1240   return result;
1241 }
1242
1243
1244 void Factory::InitializeFunction(Handle<JSFunction> function,
1245                                  Handle<SharedFunctionInfo> info,
1246                                  Handle<Context> context) {
1247   function->initialize_properties();
1248   function->initialize_elements();
1249   function->set_shared(*info);
1250   function->set_code(info->code());
1251   function->set_context(*context);
1252   function->set_prototype_or_initial_map(*the_hole_value());
1253   function->set_literals_or_bindings(*empty_fixed_array());
1254   function->set_next_function_link(*undefined_value());
1255 }
1256
1257
1258 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1259                                         Handle<SharedFunctionInfo> info,
1260                                         Handle<Context> context,
1261                                         PretenureFlag pretenure) {
1262   AllocationSpace space = pretenure == TENURED ? OLD_POINTER_SPACE : NEW_SPACE;
1263   Handle<JSFunction> result = New<JSFunction>(map, space);
1264   InitializeFunction(result, info, context);
1265   return result;
1266 }
1267
1268
1269 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1270                                         Handle<String> name,
1271                                         MaybeHandle<Code> code) {
1272   Handle<Context> context(isolate()->context()->native_context());
1273   Handle<SharedFunctionInfo> info = NewSharedFunctionInfo(name, code);
1274   ASSERT((info->strict_mode() == SLOPPY) &&
1275          (map.is_identical_to(isolate()->sloppy_function_map()) ||
1276           map.is_identical_to(
1277               isolate()->sloppy_function_without_prototype_map()) ||
1278           map.is_identical_to(
1279               isolate()->sloppy_function_with_readonly_prototype_map())));
1280   return NewFunction(map, info, context);
1281 }
1282
1283
1284 Handle<JSFunction> Factory::NewFunction(Handle<String> name) {
1285   return NewFunction(
1286       isolate()->sloppy_function_map(), name, MaybeHandle<Code>());
1287 }
1288
1289
1290 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1291                                                         Handle<Code> code) {
1292   return NewFunction(
1293       isolate()->sloppy_function_without_prototype_map(), name, code);
1294 }
1295
1296
1297 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1298                                         Handle<Code> code,
1299                                         Handle<Object> prototype,
1300                                         bool read_only_prototype) {
1301   Handle<Map> map = read_only_prototype
1302       ? isolate()->sloppy_function_with_readonly_prototype_map()
1303       : isolate()->sloppy_function_map();
1304   Handle<JSFunction> result = NewFunction(map, name, code);
1305   result->set_prototype_or_initial_map(*prototype);
1306   return result;
1307 }
1308
1309
1310 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1311                                         Handle<Code> code,
1312                                         Handle<Object> prototype,
1313                                         InstanceType type,
1314                                         int instance_size,
1315                                         bool read_only_prototype) {
1316   // Allocate the function
1317   Handle<JSFunction> function = NewFunction(
1318       name, code, prototype, read_only_prototype);
1319
1320   Handle<Map> initial_map = NewMap(
1321       type, instance_size, GetInitialFastElementsKind());
1322   if (prototype->IsTheHole() && !function->shared()->is_generator()) {
1323     prototype = NewFunctionPrototype(function);
1324   }
1325   initial_map->set_prototype(*prototype);
1326   function->set_initial_map(*initial_map);
1327   initial_map->set_constructor(*function);
1328
1329   return function;
1330 }
1331
1332
1333 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1334                                         Handle<Code> code,
1335                                         InstanceType type,
1336                                         int instance_size) {
1337   return NewFunction(name, code, the_hole_value(), type, instance_size);
1338 }
1339
1340
1341 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
1342   // Make sure to use globals from the function's context, since the function
1343   // can be from a different context.
1344   Handle<Context> native_context(function->context()->native_context());
1345   Handle<Map> new_map;
1346   if (function->shared()->is_generator()) {
1347     // Generator prototypes can share maps since they don't have "constructor"
1348     // properties.
1349     new_map = handle(native_context->generator_object_prototype_map());
1350   } else {
1351     // Each function prototype gets a fresh map to avoid unwanted sharing of
1352     // maps between prototypes of different constructors.
1353     Handle<JSFunction> object_function(native_context->object_function());
1354     ASSERT(object_function->has_initial_map());
1355     new_map = Map::Copy(handle(object_function->initial_map()));
1356   }
1357
1358   Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
1359
1360   if (!function->shared()->is_generator()) {
1361     JSObject::SetOwnPropertyIgnoreAttributes(prototype,
1362                                              constructor_string(),
1363                                              function,
1364                                              DONT_ENUM).Assert();
1365   }
1366
1367   return prototype;
1368 }
1369
1370
1371 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1372     Handle<SharedFunctionInfo> info,
1373     Handle<Context> context,
1374     PretenureFlag pretenure) {
1375   int map_index = Context::FunctionMapIndex(info->strict_mode(),
1376                                             info->is_generator());
1377   Handle<Map> map(Map::cast(context->native_context()->get(map_index)));
1378   Handle<JSFunction> result = NewFunction(map, info, context, pretenure);
1379
1380   if (info->ic_age() != isolate()->heap()->global_ic_age()) {
1381     info->ResetForNewContext(isolate()->heap()->global_ic_age());
1382   }
1383
1384   int index = info->SearchOptimizedCodeMap(context->native_context(),
1385                                            BailoutId::None());
1386   if (!info->bound() && index < 0) {
1387     int number_of_literals = info->num_literals();
1388     Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
1389     if (number_of_literals > 0) {
1390       // Store the native context in the literals array prefix. This
1391       // context will be used when creating object, regexp and array
1392       // literals in this function.
1393       literals->set(JSFunction::kLiteralNativeContextIndex,
1394                     context->native_context());
1395     }
1396     result->set_literals(*literals);
1397   }
1398
1399   if (index > 0) {
1400     // Caching of optimized code enabled and optimized code found.
1401     FixedArray* literals = info->GetLiteralsFromOptimizedCodeMap(index);
1402     if (literals != NULL) result->set_literals(literals);
1403     Code* code = info->GetCodeFromOptimizedCodeMap(index);
1404     ASSERT(!code->marked_for_deoptimization());
1405     result->ReplaceCode(code);
1406     return result;
1407   }
1408
1409   if (isolate()->use_crankshaft() &&
1410       FLAG_always_opt &&
1411       result->is_compiled() &&
1412       !info->is_toplevel() &&
1413       info->allows_lazy_compilation() &&
1414       !info->optimization_disabled() &&
1415       !isolate()->DebuggerHasBreakPoints()) {
1416     result->MarkForOptimization();
1417   }
1418   return result;
1419 }
1420
1421
1422 Handle<JSObject> Factory::NewIteratorResultObject(Handle<Object> value,
1423                                                      bool done) {
1424   Handle<Map> map(isolate()->native_context()->iterator_result_map());
1425   Handle<JSObject> result = NewJSObjectFromMap(map, NOT_TENURED, false);
1426   result->InObjectPropertyAtPut(
1427       JSGeneratorObject::kResultValuePropertyIndex, *value);
1428   result->InObjectPropertyAtPut(
1429       JSGeneratorObject::kResultDonePropertyIndex, *ToBoolean(done));
1430   return result;
1431 }
1432
1433
1434 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1435   Handle<FixedArray> array = NewFixedArray(length, TENURED);
1436   array->set_map_no_write_barrier(*scope_info_map());
1437   Handle<ScopeInfo> scope_info = Handle<ScopeInfo>::cast(array);
1438   return scope_info;
1439 }
1440
1441
1442 Handle<JSObject> Factory::NewExternal(void* value) {
1443   Handle<Foreign> foreign = NewForeign(static_cast<Address>(value));
1444   Handle<JSObject> external = NewJSObjectFromMap(external_map());
1445   external->SetInternalField(0, *foreign);
1446   return external;
1447 }
1448
1449
1450 Handle<Code> Factory::NewCodeRaw(int object_size, bool immovable) {
1451   CALL_HEAP_FUNCTION(isolate(),
1452                      isolate()->heap()->AllocateCode(object_size, immovable),
1453                      Code);
1454 }
1455
1456
1457 Handle<Code> Factory::NewCode(const CodeDesc& desc,
1458                               Code::Flags flags,
1459                               Handle<Object> self_ref,
1460                               bool immovable,
1461                               bool crankshafted,
1462                               int prologue_offset,
1463                               bool is_debug) {
1464   Handle<ByteArray> reloc_info = NewByteArray(desc.reloc_size, TENURED);
1465   Handle<ConstantPoolArray> constant_pool =
1466       desc.origin->NewConstantPool(isolate());
1467
1468   // Compute size.
1469   int body_size = RoundUp(desc.instr_size, kObjectAlignment);
1470   int obj_size = Code::SizeFor(body_size);
1471
1472   Handle<Code> code = NewCodeRaw(obj_size, immovable);
1473   ASSERT(isolate()->code_range() == NULL ||
1474          !isolate()->code_range()->valid() ||
1475          isolate()->code_range()->contains(code->address()));
1476
1477   // The code object has not been fully initialized yet.  We rely on the
1478   // fact that no allocation will happen from this point on.
1479   DisallowHeapAllocation no_gc;
1480   code->set_gc_metadata(Smi::FromInt(0));
1481   code->set_ic_age(isolate()->heap()->global_ic_age());
1482   code->set_instruction_size(desc.instr_size);
1483   code->set_relocation_info(*reloc_info);
1484   code->set_flags(flags);
1485   code->set_raw_kind_specific_flags1(0);
1486   code->set_raw_kind_specific_flags2(0);
1487   code->set_is_crankshafted(crankshafted);
1488   code->set_deoptimization_data(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1489   code->set_raw_type_feedback_info(*undefined_value());
1490   code->set_next_code_link(*undefined_value());
1491   code->set_handler_table(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1492   code->set_prologue_offset(prologue_offset);
1493   if (code->kind() == Code::OPTIMIZED_FUNCTION) {
1494     code->set_marked_for_deoptimization(false);
1495   }
1496
1497   if (is_debug) {
1498     ASSERT(code->kind() == Code::FUNCTION);
1499     code->set_has_debug_break_slots(true);
1500   }
1501
1502   desc.origin->PopulateConstantPool(*constant_pool);
1503   code->set_constant_pool(*constant_pool);
1504
1505   // Allow self references to created code object by patching the handle to
1506   // point to the newly allocated Code object.
1507   if (!self_ref.is_null()) *(self_ref.location()) = *code;
1508
1509   // Migrate generated code.
1510   // The generated code can contain Object** values (typically from handles)
1511   // that are dereferenced during the copy to point directly to the actual heap
1512   // objects. These pointers can include references to the code object itself,
1513   // through the self_reference parameter.
1514   code->CopyFrom(desc);
1515
1516 #ifdef VERIFY_HEAP
1517   if (FLAG_verify_heap) code->ObjectVerify();
1518 #endif
1519   return code;
1520 }
1521
1522
1523 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1524   CALL_HEAP_FUNCTION(isolate(),
1525                      isolate()->heap()->CopyCode(*code),
1526                      Code);
1527 }
1528
1529
1530 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1531   CALL_HEAP_FUNCTION(isolate(),
1532                      isolate()->heap()->CopyCode(*code, reloc_info),
1533                      Code);
1534 }
1535
1536
1537 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1538                                       PretenureFlag pretenure) {
1539   JSFunction::EnsureHasInitialMap(constructor);
1540   CALL_HEAP_FUNCTION(
1541       isolate(),
1542       isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1543 }
1544
1545
1546 Handle<JSObject> Factory::NewJSObjectWithMemento(
1547     Handle<JSFunction> constructor,
1548     Handle<AllocationSite> site) {
1549   JSFunction::EnsureHasInitialMap(constructor);
1550   CALL_HEAP_FUNCTION(
1551       isolate(),
1552       isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
1553       JSObject);
1554 }
1555
1556
1557 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1558                                       Handle<ScopeInfo> scope_info) {
1559   // Allocate a fresh map. Modules do not have a prototype.
1560   Handle<Map> map = NewMap(JS_MODULE_TYPE, JSModule::kSize);
1561   // Allocate the object based on the map.
1562   Handle<JSModule> module =
1563       Handle<JSModule>::cast(NewJSObjectFromMap(map, TENURED));
1564   module->set_context(*context);
1565   module->set_scope_info(*scope_info);
1566   return module;
1567 }
1568
1569
1570 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1571   ASSERT(constructor->has_initial_map());
1572   Handle<Map> map(constructor->initial_map());
1573   ASSERT(map->is_dictionary_map());
1574
1575   // Make sure no field properties are described in the initial map.
1576   // This guarantees us that normalizing the properties does not
1577   // require us to change property values to PropertyCells.
1578   ASSERT(map->NextFreePropertyIndex() == 0);
1579
1580   // Make sure we don't have a ton of pre-allocated slots in the
1581   // global objects. They will be unused once we normalize the object.
1582   ASSERT(map->unused_property_fields() == 0);
1583   ASSERT(map->inobject_properties() == 0);
1584
1585   // Initial size of the backing store to avoid resize of the storage during
1586   // bootstrapping. The size differs between the JS global object ad the
1587   // builtins object.
1588   int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1589
1590   // Allocate a dictionary object for backing storage.
1591   int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1592   Handle<NameDictionary> dictionary =
1593       NameDictionary::New(isolate(), at_least_space_for);
1594
1595   // The global object might be created from an object template with accessors.
1596   // Fill these accessors into the dictionary.
1597   Handle<DescriptorArray> descs(map->instance_descriptors());
1598   for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1599     PropertyDetails details = descs->GetDetails(i);
1600     ASSERT(details.type() == CALLBACKS);  // Only accessors are expected.
1601     PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
1602     Handle<Name> name(descs->GetKey(i));
1603     Handle<Object> value(descs->GetCallbacksObject(i), isolate());
1604     Handle<PropertyCell> cell = NewPropertyCell(value);
1605     // |dictionary| already contains enough space for all properties.
1606     USE(NameDictionary::Add(dictionary, name, cell, d));
1607   }
1608
1609   // Allocate the global object and initialize it with the backing store.
1610   Handle<GlobalObject> global = New<GlobalObject>(map, OLD_POINTER_SPACE);
1611   isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1612
1613   // Create a new map for the global object.
1614   Handle<Map> new_map = Map::CopyDropDescriptors(map);
1615   new_map->set_dictionary_map(true);
1616
1617   // Set up the global object as a normalized object.
1618   global->set_map(*new_map);
1619   global->set_properties(*dictionary);
1620
1621   // Make sure result is a global object with properties in dictionary.
1622   ASSERT(global->IsGlobalObject() && !global->HasFastProperties());
1623   return global;
1624 }
1625
1626
1627 Handle<JSObject> Factory::NewJSObjectFromMap(
1628     Handle<Map> map,
1629     PretenureFlag pretenure,
1630     bool alloc_props,
1631     Handle<AllocationSite> allocation_site) {
1632   CALL_HEAP_FUNCTION(
1633       isolate(),
1634       isolate()->heap()->AllocateJSObjectFromMap(
1635           *map,
1636           pretenure,
1637           alloc_props,
1638           allocation_site.is_null() ? NULL : *allocation_site),
1639       JSObject);
1640 }
1641
1642
1643 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1644                                     PretenureFlag pretenure) {
1645   Context* native_context = isolate()->context()->native_context();
1646   JSFunction* array_function = native_context->array_function();
1647   Map* map = array_function->initial_map();
1648   Map* transition_map = isolate()->get_initial_js_array_map(elements_kind);
1649   if (transition_map != NULL) map = transition_map;
1650   return Handle<JSArray>::cast(NewJSObjectFromMap(handle(map), pretenure));
1651 }
1652
1653
1654 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1655                                     int length,
1656                                     int capacity,
1657                                     ArrayStorageAllocationMode mode,
1658                                     PretenureFlag pretenure) {
1659   Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1660   NewJSArrayStorage(array, length, capacity, mode);
1661   return array;
1662 }
1663
1664
1665 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1666                                                 ElementsKind elements_kind,
1667                                                 int length,
1668                                                 PretenureFlag pretenure) {
1669   ASSERT(length <= elements->length());
1670   Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1671
1672   array->set_elements(*elements);
1673   array->set_length(Smi::FromInt(length));
1674   JSObject::ValidateElements(array);
1675   return array;
1676 }
1677
1678
1679 void Factory::NewJSArrayStorage(Handle<JSArray> array,
1680                                 int length,
1681                                 int capacity,
1682                                 ArrayStorageAllocationMode mode) {
1683   ASSERT(capacity >= length);
1684
1685   if (capacity == 0) {
1686     array->set_length(Smi::FromInt(0));
1687     array->set_elements(*empty_fixed_array());
1688     return;
1689   }
1690
1691   Handle<FixedArrayBase> elms;
1692   ElementsKind elements_kind = array->GetElementsKind();
1693   if (IsFastDoubleElementsKind(elements_kind)) {
1694     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1695       elms = NewFixedDoubleArray(capacity);
1696     } else {
1697       ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1698       elms = NewFixedDoubleArrayWithHoles(capacity);
1699     }
1700   } else {
1701     ASSERT(IsFastSmiOrObjectElementsKind(elements_kind));
1702     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1703       elms = NewUninitializedFixedArray(capacity);
1704     } else {
1705       ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1706       elms = NewFixedArrayWithHoles(capacity);
1707     }
1708   }
1709
1710   array->set_elements(*elms);
1711   array->set_length(Smi::FromInt(length));
1712 }
1713
1714
1715 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1716     Handle<JSFunction> function) {
1717   ASSERT(function->shared()->is_generator());
1718   JSFunction::EnsureHasInitialMap(function);
1719   Handle<Map> map(function->initial_map());
1720   ASSERT(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1721   CALL_HEAP_FUNCTION(
1722       isolate(),
1723       isolate()->heap()->AllocateJSObjectFromMap(*map),
1724       JSGeneratorObject);
1725 }
1726
1727
1728 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1729   Handle<JSFunction> array_buffer_fun(
1730       isolate()->context()->native_context()->array_buffer_fun());
1731   CALL_HEAP_FUNCTION(
1732       isolate(),
1733       isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1734       JSArrayBuffer);
1735 }
1736
1737
1738 Handle<JSDataView> Factory::NewJSDataView() {
1739   Handle<JSFunction> data_view_fun(
1740       isolate()->context()->native_context()->data_view_fun());
1741   CALL_HEAP_FUNCTION(
1742       isolate(),
1743       isolate()->heap()->AllocateJSObject(*data_view_fun),
1744       JSDataView);
1745 }
1746
1747
1748 static JSFunction* GetTypedArrayFun(ExternalArrayType type,
1749                                     Isolate* isolate) {
1750   Context* native_context = isolate->context()->native_context();
1751   switch (type) {
1752 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size)                        \
1753     case kExternal##Type##Array:                                              \
1754       return native_context->type##_array_fun();
1755
1756     TYPED_ARRAYS(TYPED_ARRAY_FUN)
1757 #undef TYPED_ARRAY_FUN
1758
1759     default:
1760       UNREACHABLE();
1761       return NULL;
1762   }
1763 }
1764
1765
1766 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1767   Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1768
1769   CALL_HEAP_FUNCTION(
1770       isolate(),
1771       isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1772       JSTypedArray);
1773 }
1774
1775
1776 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1777                                     Handle<Object> prototype) {
1778   // Allocate map.
1779   // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1780   // maps. Will probably depend on the identity of the handler object, too.
1781   Handle<Map> map = NewMap(JS_PROXY_TYPE, JSProxy::kSize);
1782   map->set_prototype(*prototype);
1783
1784   // Allocate the proxy object.
1785   Handle<JSProxy> result = New<JSProxy>(map, NEW_SPACE);
1786   result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1787   result->set_handler(*handler);
1788   result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1789   return result;
1790 }
1791
1792
1793 Handle<JSProxy> Factory::NewJSFunctionProxy(Handle<Object> handler,
1794                                             Handle<Object> call_trap,
1795                                             Handle<Object> construct_trap,
1796                                             Handle<Object> prototype) {
1797   // Allocate map.
1798   // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1799   // maps. Will probably depend on the identity of the handler object, too.
1800   Handle<Map> map = NewMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
1801   map->set_prototype(*prototype);
1802
1803   // Allocate the proxy object.
1804   Handle<JSFunctionProxy> result = New<JSFunctionProxy>(map, NEW_SPACE);
1805   result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1806   result->set_handler(*handler);
1807   result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1808   result->set_call_trap(*call_trap);
1809   result->set_construct_trap(*construct_trap);
1810   return result;
1811 }
1812
1813
1814 void Factory::ReinitializeJSReceiver(Handle<JSReceiver> object,
1815                                      InstanceType type,
1816                                      int size) {
1817   ASSERT(type >= FIRST_JS_OBJECT_TYPE);
1818
1819   // Allocate fresh map.
1820   // TODO(rossberg): Once we optimize proxies, cache these maps.
1821   Handle<Map> map = NewMap(type, size);
1822
1823   // Check that the receiver has at least the size of the fresh object.
1824   int size_difference = object->map()->instance_size() - map->instance_size();
1825   ASSERT(size_difference >= 0);
1826
1827   map->set_prototype(object->map()->prototype());
1828
1829   // Allocate the backing storage for the properties.
1830   int prop_size = map->InitialPropertiesLength();
1831   Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1832
1833   Heap* heap = isolate()->heap();
1834   MaybeHandle<SharedFunctionInfo> shared;
1835   if (type == JS_FUNCTION_TYPE) {
1836     OneByteStringKey key(STATIC_ASCII_VECTOR("<freezing call trap>"),
1837                          heap->HashSeed());
1838     Handle<String> name = InternalizeStringWithKey(&key);
1839     shared = NewSharedFunctionInfo(name, MaybeHandle<Code>());
1840   }
1841
1842   // In order to keep heap in consistent state there must be no allocations
1843   // before object re-initialization is finished and filler object is installed.
1844   DisallowHeapAllocation no_allocation;
1845
1846   // Reset the map for the object.
1847   object->set_map(*map);
1848   Handle<JSObject> jsobj = Handle<JSObject>::cast(object);
1849
1850   // Reinitialize the object from the constructor map.
1851   heap->InitializeJSObjectFromMap(*jsobj, *properties, *map);
1852
1853   // Functions require some minimal initialization.
1854   if (type == JS_FUNCTION_TYPE) {
1855     map->set_function_with_prototype(true);
1856     Handle<JSFunction> js_function = Handle<JSFunction>::cast(object);
1857     Handle<Context> context(isolate()->context()->native_context());
1858     InitializeFunction(js_function, shared.ToHandleChecked(), context);
1859   }
1860
1861   // Put in filler if the new object is smaller than the old.
1862   if (size_difference > 0) {
1863     heap->CreateFillerObjectAt(
1864         object->address() + map->instance_size(), size_difference);
1865   }
1866 }
1867
1868
1869 void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
1870                                         Handle<JSFunction> constructor) {
1871   ASSERT(constructor->has_initial_map());
1872   Handle<Map> map(constructor->initial_map(), isolate());
1873
1874   // The proxy's hash should be retained across reinitialization.
1875   Handle<Object> hash(object->hash(), isolate());
1876
1877   // Check that the already allocated object has the same size and type as
1878   // objects allocated using the constructor.
1879   ASSERT(map->instance_size() == object->map()->instance_size());
1880   ASSERT(map->instance_type() == object->map()->instance_type());
1881
1882   // Allocate the backing storage for the properties.
1883   int prop_size = map->InitialPropertiesLength();
1884   Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1885
1886   // In order to keep heap in consistent state there must be no allocations
1887   // before object re-initialization is finished.
1888   DisallowHeapAllocation no_allocation;
1889
1890   // Reset the map for the object.
1891   object->set_map(constructor->initial_map());
1892
1893   Heap* heap = isolate()->heap();
1894   // Reinitialize the object from the constructor map.
1895   heap->InitializeJSObjectFromMap(*object, *properties, *map);
1896
1897   // Restore the saved hash.
1898   object->set_hash(*hash);
1899 }
1900
1901
1902 void Factory::BecomeJSObject(Handle<JSReceiver> object) {
1903   ReinitializeJSReceiver(object, JS_OBJECT_TYPE, JSObject::kHeaderSize);
1904 }
1905
1906
1907 void Factory::BecomeJSFunction(Handle<JSReceiver> object) {
1908   ReinitializeJSReceiver(object, JS_FUNCTION_TYPE, JSFunction::kSize);
1909 }
1910
1911
1912 Handle<FixedArray> Factory::NewTypeFeedbackVector(int slot_count) {
1913   // Ensure we can skip the write barrier
1914   ASSERT_EQ(isolate()->heap()->uninitialized_symbol(),
1915             *TypeFeedbackInfo::UninitializedSentinel(isolate()));
1916
1917   CALL_HEAP_FUNCTION(
1918       isolate(),
1919       isolate()->heap()->AllocateFixedArrayWithFiller(
1920           slot_count,
1921           TENURED,
1922           *TypeFeedbackInfo::UninitializedSentinel(isolate())),
1923       FixedArray);
1924 }
1925
1926
1927 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1928     Handle<String> name,
1929     int number_of_literals,
1930     bool is_generator,
1931     Handle<Code> code,
1932     Handle<ScopeInfo> scope_info,
1933     Handle<FixedArray> feedback_vector) {
1934   Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name, code);
1935   shared->set_scope_info(*scope_info);
1936   shared->set_feedback_vector(*feedback_vector);
1937   int literals_array_size = number_of_literals;
1938   // If the function contains object, regexp or array literals,
1939   // allocate extra space for a literals array prefix containing the
1940   // context.
1941   if (number_of_literals > 0) {
1942     literals_array_size += JSFunction::kLiteralsPrefixSize;
1943   }
1944   shared->set_num_literals(literals_array_size);
1945   if (is_generator) {
1946     shared->set_instance_class_name(isolate()->heap()->Generator_string());
1947     shared->DisableOptimization(kGenerator);
1948   }
1949   return shared;
1950 }
1951
1952
1953 Handle<JSMessageObject> Factory::NewJSMessageObject(
1954     Handle<String> type,
1955     Handle<JSArray> arguments,
1956     int start_position,
1957     int end_position,
1958     Handle<Object> script,
1959     Handle<Object> stack_frames) {
1960   Handle<Map> map = message_object_map();
1961   Handle<JSMessageObject> message = New<JSMessageObject>(map, NEW_SPACE);
1962   message->set_properties(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1963   message->initialize_elements();
1964   message->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1965   message->set_type(*type);
1966   message->set_arguments(*arguments);
1967   message->set_start_position(start_position);
1968   message->set_end_position(end_position);
1969   message->set_script(*script);
1970   message->set_stack_frames(*stack_frames);
1971   return message;
1972 }
1973
1974
1975 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1976     Handle<String> name,
1977     MaybeHandle<Code> maybe_code) {
1978   Handle<Map> map = shared_function_info_map();
1979   Handle<SharedFunctionInfo> share = New<SharedFunctionInfo>(map,
1980                                                              OLD_POINTER_SPACE);
1981
1982   // Set pointer fields.
1983   share->set_name(*name);
1984   Handle<Code> code;
1985   if (!maybe_code.ToHandle(&code)) {
1986     code = handle(isolate()->builtins()->builtin(Builtins::kIllegal));
1987   }
1988   share->set_code(*code);
1989   share->set_optimized_code_map(Smi::FromInt(0));
1990   share->set_scope_info(ScopeInfo::Empty(isolate()));
1991   Code* construct_stub =
1992       isolate()->builtins()->builtin(Builtins::kJSConstructStubGeneric);
1993   share->set_construct_stub(construct_stub);
1994   share->set_instance_class_name(*Object_string());
1995   share->set_function_data(*undefined_value(), SKIP_WRITE_BARRIER);
1996   share->set_script(*undefined_value(), SKIP_WRITE_BARRIER);
1997   share->set_debug_info(*undefined_value(), SKIP_WRITE_BARRIER);
1998   share->set_inferred_name(*empty_string(), SKIP_WRITE_BARRIER);
1999   share->set_feedback_vector(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2000   share->set_profiler_ticks(0);
2001   share->set_ast_node_count(0);
2002   share->set_counters(0);
2003
2004   // Set integer fields (smi or int, depending on the architecture).
2005   share->set_length(0);
2006   share->set_formal_parameter_count(0);
2007   share->set_expected_nof_properties(0);
2008   share->set_num_literals(0);
2009   share->set_start_position_and_type(0);
2010   share->set_end_position(0);
2011   share->set_function_token_position(0);
2012   // All compiler hints default to false or 0.
2013   share->set_compiler_hints(0);
2014   share->set_opt_count_and_bailout_reason(0);
2015
2016   return share;
2017 }
2018
2019
2020 static inline int NumberCacheHash(Handle<FixedArray> cache,
2021                                   Handle<Object> number) {
2022   int mask = (cache->length() >> 1) - 1;
2023   if (number->IsSmi()) {
2024     return Handle<Smi>::cast(number)->value() & mask;
2025   } else {
2026     DoubleRepresentation rep(number->Number());
2027     return
2028         (static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) & mask;
2029   }
2030 }
2031
2032
2033 Handle<Object> Factory::GetNumberStringCache(Handle<Object> number) {
2034   DisallowHeapAllocation no_gc;
2035   int hash = NumberCacheHash(number_string_cache(), number);
2036   Object* key = number_string_cache()->get(hash * 2);
2037   if (key == *number || (key->IsHeapNumber() && number->IsHeapNumber() &&
2038                          key->Number() == number->Number())) {
2039     return Handle<String>(
2040         String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
2041   }
2042   return undefined_value();
2043 }
2044
2045
2046 void Factory::SetNumberStringCache(Handle<Object> number,
2047                                    Handle<String> string) {
2048   int hash = NumberCacheHash(number_string_cache(), number);
2049   if (number_string_cache()->get(hash * 2) != *undefined_value()) {
2050     int full_size = isolate()->heap()->FullSizeNumberStringCacheLength();
2051     if (number_string_cache()->length() != full_size) {
2052       // The first time we have a hash collision, we move to the full sized
2053       // number string cache.  The idea is to have a small number string
2054       // cache in the snapshot to keep  boot-time memory usage down.
2055       // If we expand the number string cache already while creating
2056       // the snapshot then that didn't work out.
2057       ASSERT(!isolate()->serializer_enabled() || FLAG_extra_code != NULL);
2058       Handle<FixedArray> new_cache = NewFixedArray(full_size, TENURED);
2059       isolate()->heap()->set_number_string_cache(*new_cache);
2060       return;
2061     }
2062   }
2063   number_string_cache()->set(hash * 2, *number);
2064   number_string_cache()->set(hash * 2 + 1, *string);
2065 }
2066
2067
2068 Handle<String> Factory::NumberToString(Handle<Object> number,
2069                                        bool check_number_string_cache) {
2070   isolate()->counters()->number_to_string_runtime()->Increment();
2071   if (check_number_string_cache) {
2072     Handle<Object> cached = GetNumberStringCache(number);
2073     if (!cached->IsUndefined()) return Handle<String>::cast(cached);
2074   }
2075
2076   char arr[100];
2077   Vector<char> buffer(arr, ARRAY_SIZE(arr));
2078   const char* str;
2079   if (number->IsSmi()) {
2080     int num = Handle<Smi>::cast(number)->value();
2081     str = IntToCString(num, buffer);
2082   } else {
2083     double num = Handle<HeapNumber>::cast(number)->value();
2084     str = DoubleToCString(num, buffer);
2085   }
2086
2087   // We tenure the allocated string since it is referenced from the
2088   // number-string cache which lives in the old space.
2089   Handle<String> js_string = NewStringFromAsciiChecked(str, TENURED);
2090   SetNumberStringCache(number, js_string);
2091   return js_string;
2092 }
2093
2094
2095 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
2096   // Get the original code of the function.
2097   Handle<Code> code(shared->code());
2098
2099   // Create a copy of the code before allocating the debug info object to avoid
2100   // allocation while setting up the debug info object.
2101   Handle<Code> original_code(*Factory::CopyCode(code));
2102
2103   // Allocate initial fixed array for active break points before allocating the
2104   // debug info object to avoid allocation while setting up the debug info
2105   // object.
2106   Handle<FixedArray> break_points(
2107       NewFixedArray(DebugInfo::kEstimatedNofBreakPointsInFunction));
2108
2109   // Create and set up the debug info object. Debug info contains function, a
2110   // copy of the original code, the executing code and initial fixed array for
2111   // active break points.
2112   Handle<DebugInfo> debug_info =
2113       Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
2114   debug_info->set_shared(*shared);
2115   debug_info->set_original_code(*original_code);
2116   debug_info->set_code(*code);
2117   debug_info->set_break_points(*break_points);
2118
2119   // Link debug info to function.
2120   shared->set_debug_info(*debug_info);
2121
2122   return debug_info;
2123 }
2124
2125
2126 Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
2127                                              int length) {
2128   CALL_HEAP_FUNCTION(
2129       isolate(),
2130       isolate()->heap()->AllocateArgumentsObject(*callee, length), JSObject);
2131 }
2132
2133
2134 Handle<JSFunction> Factory::CreateApiFunction(
2135     Handle<FunctionTemplateInfo> obj,
2136     Handle<Object> prototype,
2137     ApiInstanceType instance_type) {
2138   Handle<Code> code = isolate()->builtins()->HandleApiCall();
2139   Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
2140
2141   Handle<JSFunction> result;
2142   if (obj->remove_prototype()) {
2143     result = NewFunctionWithoutPrototype(empty_string(), code);
2144   } else {
2145     int internal_field_count = 0;
2146     if (!obj->instance_template()->IsUndefined()) {
2147       Handle<ObjectTemplateInfo> instance_template =
2148           Handle<ObjectTemplateInfo>(
2149               ObjectTemplateInfo::cast(obj->instance_template()));
2150       internal_field_count =
2151           Smi::cast(instance_template->internal_field_count())->value();
2152     }
2153
2154     // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
2155     // JSObject::GetHeaderSize.
2156     int instance_size = kPointerSize * internal_field_count;
2157     InstanceType type;
2158     switch (instance_type) {
2159       case JavaScriptObject:
2160         type = JS_OBJECT_TYPE;
2161         instance_size += JSObject::kHeaderSize;
2162         break;
2163       case InnerGlobalObject:
2164         type = JS_GLOBAL_OBJECT_TYPE;
2165         instance_size += JSGlobalObject::kSize;
2166         break;
2167       case OuterGlobalObject:
2168         type = JS_GLOBAL_PROXY_TYPE;
2169         instance_size += JSGlobalProxy::kSize;
2170         break;
2171       default:
2172         UNREACHABLE();
2173         type = JS_OBJECT_TYPE;  // Keep the compiler happy.
2174         break;
2175     }
2176
2177     result = NewFunction(empty_string(), code, prototype, type,
2178                          instance_size, obj->read_only_prototype());
2179   }
2180
2181   result->shared()->set_length(obj->length());
2182   Handle<Object> class_name(obj->class_name(), isolate());
2183   if (class_name->IsString()) {
2184     result->shared()->set_instance_class_name(*class_name);
2185     result->shared()->set_name(*class_name);
2186   }
2187   result->shared()->set_function_data(*obj);
2188   result->shared()->set_construct_stub(*construct_stub);
2189   result->shared()->DontAdaptArguments();
2190
2191   if (obj->remove_prototype()) {
2192     ASSERT(result->shared()->IsApiFunction());
2193     ASSERT(!result->has_initial_map());
2194     ASSERT(!result->has_prototype());
2195     return result;
2196   }
2197
2198   JSObject::SetOwnPropertyIgnoreAttributes(
2199       handle(JSObject::cast(result->prototype())),
2200       constructor_string(),
2201       result,
2202       DONT_ENUM).Assert();
2203
2204   // Down from here is only valid for API functions that can be used as a
2205   // constructor (don't set the "remove prototype" flag).
2206
2207   Handle<Map> map(result->initial_map());
2208
2209   // Mark as undetectable if needed.
2210   if (obj->undetectable()) {
2211     map->set_is_undetectable();
2212   }
2213
2214   // Mark as hidden for the __proto__ accessor if needed.
2215   if (obj->hidden_prototype()) {
2216     map->set_is_hidden_prototype();
2217   }
2218
2219   // Mark as needs_access_check if needed.
2220   if (obj->needs_access_check()) {
2221     map->set_is_access_check_needed(true);
2222   }
2223
2224   // Set interceptor information in the map.
2225   if (!obj->named_property_handler()->IsUndefined()) {
2226     map->set_has_named_interceptor();
2227   }
2228   if (!obj->indexed_property_handler()->IsUndefined()) {
2229     map->set_has_indexed_interceptor();
2230   }
2231
2232   // Set instance call-as-function information in the map.
2233   if (!obj->instance_call_handler()->IsUndefined()) {
2234     map->set_has_instance_call_handler();
2235   }
2236
2237   // Recursively copy parent instance templates' accessors,
2238   // 'data' may be modified.
2239   int max_number_of_additional_properties = 0;
2240   int max_number_of_static_properties = 0;
2241   FunctionTemplateInfo* info = *obj;
2242   while (true) {
2243     if (!info->instance_template()->IsUndefined()) {
2244       Object* props =
2245           ObjectTemplateInfo::cast(
2246               info->instance_template())->property_accessors();
2247       if (!props->IsUndefined()) {
2248         Handle<Object> props_handle(props, isolate());
2249         NeanderArray props_array(props_handle);
2250         max_number_of_additional_properties += props_array.length();
2251       }
2252     }
2253     if (!info->property_accessors()->IsUndefined()) {
2254       Object* props = info->property_accessors();
2255       if (!props->IsUndefined()) {
2256         Handle<Object> props_handle(props, isolate());
2257         NeanderArray props_array(props_handle);
2258         max_number_of_static_properties += props_array.length();
2259       }
2260     }
2261     Object* parent = info->parent_template();
2262     if (parent->IsUndefined()) break;
2263     info = FunctionTemplateInfo::cast(parent);
2264   }
2265
2266   Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);
2267
2268   // Use a temporary FixedArray to acculumate static accessors
2269   int valid_descriptors = 0;
2270   Handle<FixedArray> array;
2271   if (max_number_of_static_properties > 0) {
2272     array = NewFixedArray(max_number_of_static_properties);
2273   }
2274
2275   while (true) {
2276     // Install instance descriptors
2277     if (!obj->instance_template()->IsUndefined()) {
2278       Handle<ObjectTemplateInfo> instance =
2279           Handle<ObjectTemplateInfo>(
2280               ObjectTemplateInfo::cast(obj->instance_template()), isolate());
2281       Handle<Object> props = Handle<Object>(instance->property_accessors(),
2282                                             isolate());
2283       if (!props->IsUndefined()) {
2284         Map::AppendCallbackDescriptors(map, props);
2285       }
2286     }
2287     // Accumulate static accessors
2288     if (!obj->property_accessors()->IsUndefined()) {
2289       Handle<Object> props = Handle<Object>(obj->property_accessors(),
2290                                             isolate());
2291       valid_descriptors =
2292           AccessorInfo::AppendUnique(props, array, valid_descriptors);
2293     }
2294     // Climb parent chain
2295     Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
2296     if (parent->IsUndefined()) break;
2297     obj = Handle<FunctionTemplateInfo>::cast(parent);
2298   }
2299
2300   // Install accumulated static accessors
2301   for (int i = 0; i < valid_descriptors; i++) {
2302     Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
2303     JSObject::SetAccessor(result, accessor).Assert();
2304   }
2305
2306   ASSERT(result->shared()->IsApiFunction());
2307   return result;
2308 }
2309
2310
2311 Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
2312                                         Handle<FixedArray> keys,
2313                                         Handle<Map> map) {
2314   Handle<MapCache> map_cache = handle(MapCache::cast(context->map_cache()));
2315   Handle<MapCache> result = MapCache::Put(map_cache, keys, map);
2316   context->set_map_cache(*result);
2317   return result;
2318 }
2319
2320
2321 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
2322                                                Handle<FixedArray> keys) {
2323   if (context->map_cache()->IsUndefined()) {
2324     // Allocate the new map cache for the native context.
2325     Handle<MapCache> new_cache = MapCache::New(isolate(), 24);
2326     context->set_map_cache(*new_cache);
2327   }
2328   // Check to see whether there is a matching element in the cache.
2329   Handle<MapCache> cache =
2330       Handle<MapCache>(MapCache::cast(context->map_cache()));
2331   Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
2332   if (result->IsMap()) return Handle<Map>::cast(result);
2333   // Create a new map and add it to the cache.
2334   Handle<Map> map = Map::Create(
2335       handle(context->object_function()), keys->length());
2336   AddToMapCache(context, keys, map);
2337   return map;
2338 }
2339
2340
2341 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
2342                                 JSRegExp::Type type,
2343                                 Handle<String> source,
2344                                 JSRegExp::Flags flags,
2345                                 Handle<Object> data) {
2346   Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
2347
2348   store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2349   store->set(JSRegExp::kSourceIndex, *source);
2350   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2351   store->set(JSRegExp::kAtomPatternIndex, *data);
2352   regexp->set_data(*store);
2353 }
2354
2355 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
2356                                     JSRegExp::Type type,
2357                                     Handle<String> source,
2358                                     JSRegExp::Flags flags,
2359                                     int capture_count) {
2360   Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
2361   Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
2362   store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2363   store->set(JSRegExp::kSourceIndex, *source);
2364   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2365   store->set(JSRegExp::kIrregexpASCIICodeIndex, uninitialized);
2366   store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
2367   store->set(JSRegExp::kIrregexpASCIICodeSavedIndex, uninitialized);
2368   store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
2369   store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
2370   store->set(JSRegExp::kIrregexpCaptureCountIndex,
2371              Smi::FromInt(capture_count));
2372   regexp->set_data(*store);
2373 }
2374
2375
2376
2377 MaybeHandle<FunctionTemplateInfo> Factory::ConfigureInstance(
2378     Handle<FunctionTemplateInfo> desc, Handle<JSObject> instance) {
2379   // Configure the instance by adding the properties specified by the
2380   // instance template.
2381   Handle<Object> instance_template(desc->instance_template(), isolate());
2382   if (!instance_template->IsUndefined()) {
2383       RETURN_ON_EXCEPTION(
2384           isolate(),
2385           Execution::ConfigureInstance(isolate(), instance, instance_template),
2386           FunctionTemplateInfo);
2387   }
2388   return desc;
2389 }
2390
2391
2392 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
2393   if (String::Equals(name, undefined_string())) return undefined_value();
2394   if (String::Equals(name, nan_string())) return nan_value();
2395   if (String::Equals(name, infinity_string())) return infinity_value();
2396   return Handle<Object>::null();
2397 }
2398
2399
2400 Handle<Object> Factory::ToBoolean(bool value) {
2401   return value ? true_value() : false_value();
2402 }
2403
2404
2405 } }  // namespace v8::internal