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