1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "execution.h"
34 #include "isolate-inl.h"
35 #include "macro-assembler.h"
37 #include "objects-visiting.h"
39 #include "scopeinfo.h"
45 Handle<Box> Factory::NewBox(Handle<Object> value, PretenureFlag pretenure) {
48 isolate()->heap()->AllocateBox(*value, pretenure),
53 Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
57 isolate()->heap()->AllocateFixedArray(size, pretenure),
62 Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
63 PretenureFlag pretenure) {
67 isolate()->heap()->AllocateFixedArrayWithHoles(size, pretenure),
72 Handle<FixedArray> Factory::NewUninitializedFixedArray(int size) {
75 isolate()->heap()->AllocateUninitializedFixedArray(size),
80 Handle<FixedDoubleArray> Factory::NewFixedDoubleArray(int size,
81 PretenureFlag pretenure) {
85 isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
90 Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
91 int number_of_int64_entries,
92 int number_of_code_ptr_entries,
93 int number_of_heap_ptr_entries,
94 int number_of_int32_entries) {
95 ASSERT(number_of_int64_entries > 0 || number_of_code_ptr_entries > 0 ||
96 number_of_heap_ptr_entries > 0 || number_of_int32_entries > 0);
99 isolate()->heap()->AllocateConstantPoolArray(number_of_int64_entries,
100 number_of_code_ptr_entries,
101 number_of_heap_ptr_entries,
102 number_of_int32_entries),
107 Handle<NameDictionary> Factory::NewNameDictionary(int at_least_space_for) {
108 ASSERT(0 <= at_least_space_for);
109 CALL_HEAP_FUNCTION(isolate(),
110 NameDictionary::Allocate(isolate()->heap(),
116 Handle<SeededNumberDictionary> Factory::NewSeededNumberDictionary(
117 int at_least_space_for) {
118 ASSERT(0 <= at_least_space_for);
119 CALL_HEAP_FUNCTION(isolate(),
120 SeededNumberDictionary::Allocate(isolate()->heap(),
122 SeededNumberDictionary);
126 Handle<UnseededNumberDictionary> Factory::NewUnseededNumberDictionary(
127 int at_least_space_for) {
128 ASSERT(0 <= at_least_space_for);
129 CALL_HEAP_FUNCTION(isolate(),
130 UnseededNumberDictionary::Allocate(isolate()->heap(),
132 UnseededNumberDictionary);
136 Handle<ObjectHashSet> Factory::NewObjectHashSet(int at_least_space_for) {
137 ASSERT(0 <= at_least_space_for);
138 CALL_HEAP_FUNCTION(isolate(),
139 ObjectHashSet::Allocate(isolate()->heap(),
145 Handle<ObjectHashTable> Factory::NewObjectHashTable(
146 int at_least_space_for,
147 MinimumCapacity capacity_option) {
148 ASSERT(0 <= at_least_space_for);
149 CALL_HEAP_FUNCTION(isolate(),
150 ObjectHashTable::Allocate(isolate()->heap(),
157 Handle<WeakHashTable> Factory::NewWeakHashTable(int at_least_space_for) {
158 ASSERT(0 <= at_least_space_for);
161 WeakHashTable::Allocate(isolate()->heap(),
163 USE_DEFAULT_MINIMUM_CAPACITY,
169 Handle<DescriptorArray> Factory::NewDescriptorArray(int number_of_descriptors,
171 ASSERT(0 <= number_of_descriptors);
172 CALL_HEAP_FUNCTION(isolate(),
173 DescriptorArray::Allocate(
174 isolate(), number_of_descriptors, slack),
179 Handle<DeoptimizationInputData> Factory::NewDeoptimizationInputData(
180 int deopt_entry_count,
181 PretenureFlag pretenure) {
182 ASSERT(deopt_entry_count > 0);
183 CALL_HEAP_FUNCTION(isolate(),
184 DeoptimizationInputData::Allocate(isolate(),
187 DeoptimizationInputData);
191 Handle<DeoptimizationOutputData> Factory::NewDeoptimizationOutputData(
192 int deopt_entry_count,
193 PretenureFlag pretenure) {
194 ASSERT(deopt_entry_count > 0);
195 CALL_HEAP_FUNCTION(isolate(),
196 DeoptimizationOutputData::Allocate(isolate(),
199 DeoptimizationOutputData);
203 Handle<AccessorPair> Factory::NewAccessorPair() {
204 CALL_HEAP_FUNCTION(isolate(),
205 isolate()->heap()->AllocateAccessorPair(),
210 Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
211 CALL_HEAP_FUNCTION(isolate(),
212 isolate()->heap()->AllocateTypeFeedbackInfo(),
217 // Internalized strings are created in the old generation (data space).
218 Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
219 Utf8StringKey key(string, isolate()->heap()->HashSeed());
220 return InternalizeStringWithKey(&key);
224 // Internalized strings are created in the old generation (data space).
225 Handle<String> Factory::InternalizeString(Handle<String> string) {
226 CALL_HEAP_FUNCTION(isolate(),
227 isolate()->heap()->InternalizeString(*string),
232 Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
233 OneByteStringKey key(string, isolate()->heap()->HashSeed());
234 return InternalizeStringWithKey(&key);
238 Handle<String> Factory::InternalizeOneByteString(
239 Handle<SeqOneByteString> string, int from, int length) {
240 SubStringKey<uint8_t> key(string, from, length);
241 return InternalizeStringWithKey(&key);
245 Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
246 TwoByteStringKey key(string, isolate()->heap()->HashSeed());
247 return InternalizeStringWithKey(&key);
251 template<class StringTableKey>
252 Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
253 CALL_HEAP_FUNCTION(isolate(),
254 isolate()->heap()->InternalizeStringWithKey(key),
259 template Handle<String> Factory::InternalizeStringWithKey<
260 SubStringKey<uint8_t> > (SubStringKey<uint8_t>* key);
261 template Handle<String> Factory::InternalizeStringWithKey<
262 SubStringKey<uint16_t> > (SubStringKey<uint16_t>* key);
265 Handle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
266 PretenureFlag pretenure) {
269 isolate()->heap()->AllocateStringFromOneByte(string, pretenure),
273 Handle<String> Factory::NewStringFromUtf8(Vector<const char> string,
274 PretenureFlag pretenure) {
277 isolate()->heap()->AllocateStringFromUtf8(string, pretenure),
282 Handle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
283 PretenureFlag pretenure) {
286 isolate()->heap()->AllocateStringFromTwoByte(string, pretenure),
291 Handle<SeqOneByteString> Factory::NewRawOneByteString(int length,
292 PretenureFlag pretenure) {
295 isolate()->heap()->AllocateRawOneByteString(length, pretenure),
300 Handle<SeqTwoByteString> Factory::NewRawTwoByteString(int length,
301 PretenureFlag pretenure) {
304 isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
309 // Returns true for a character in a range. Both limits are inclusive.
310 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
311 // This makes uses of the the unsigned wraparound.
312 return character - from <= to - from;
316 static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
319 // Numeric strings have a different hash algorithm not known by
320 // LookupTwoCharsStringIfExists, so we skip this step for such strings.
321 if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
323 StringTable* table = isolate->heap()->string_table();
324 if (table->LookupTwoCharsStringIfExists(c1, c2, &result)) {
325 return handle(result);
329 // Now we know the length is 2, we might as well make use of that fact
330 // when building the new string.
331 if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
333 ASSERT(IsPowerOf2(String::kMaxOneByteCharCodeU + 1)); // because of this.
334 Handle<SeqOneByteString> str = isolate->factory()->NewRawOneByteString(2);
335 uint8_t* dest = str->GetChars();
336 dest[0] = static_cast<uint8_t>(c1);
337 dest[1] = static_cast<uint8_t>(c2);
340 Handle<SeqTwoByteString> str = isolate->factory()->NewRawTwoByteString(2);
341 uc16* dest = str->GetChars();
349 template<typename SinkChar, typename StringType>
350 Handle<String> ConcatStringContent(Handle<StringType> result,
351 Handle<String> first,
352 Handle<String> second) {
353 DisallowHeapAllocation pointer_stays_valid;
354 SinkChar* sink = result->GetChars();
355 String::WriteToFlat(*first, sink, 0, first->length());
356 String::WriteToFlat(*second, sink + first->length(), 0, second->length());
361 Handle<ConsString> Factory::NewRawConsString(String::Encoding encoding) {
362 Handle<Map> map = (encoding == String::ONE_BYTE_ENCODING)
363 ? cons_ascii_string_map() : cons_string_map();
364 CALL_HEAP_FUNCTION(isolate(),
365 isolate()->heap()->Allocate(*map, NEW_SPACE),
370 Handle<String> Factory::NewConsString(Handle<String> left,
371 Handle<String> right) {
372 int left_length = left->length();
373 if (left_length == 0) return right;
374 int right_length = right->length();
375 if (right_length == 0) return left;
377 int length = left_length + right_length;
380 uint16_t c1 = left->Get(0);
381 uint16_t c2 = right->Get(0);
382 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
385 // Make sure that an out of memory exception is thrown if the length
386 // of the new cons string is too large.
387 if (length > String::kMaxLength || length < 0) {
388 isolate()->ThrowInvalidStringLength();
389 return Handle<String>::null();
392 bool left_is_one_byte = left->IsOneByteRepresentation();
393 bool right_is_one_byte = right->IsOneByteRepresentation();
394 bool is_one_byte = left_is_one_byte && right_is_one_byte;
395 bool is_one_byte_data_in_two_byte_string = false;
397 // At least one of the strings uses two-byte representation so we
398 // can't use the fast case code for short ASCII strings below, but
399 // we can try to save memory if all chars actually fit in ASCII.
400 is_one_byte_data_in_two_byte_string =
401 left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
402 if (is_one_byte_data_in_two_byte_string) {
403 isolate()->counters()->string_add_runtime_ext_to_ascii()->Increment();
407 // If the resulting string is small make a flat string.
408 if (length < ConsString::kMinLength) {
409 // Note that neither of the two inputs can be a slice because:
410 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
411 ASSERT(left->IsFlat());
412 ASSERT(right->IsFlat());
414 STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
416 Handle<SeqOneByteString> result = NewRawOneByteString(length);
417 DisallowHeapAllocation no_gc;
418 uint8_t* dest = result->GetChars();
420 const uint8_t* src = left->IsExternalString()
421 ? Handle<ExternalAsciiString>::cast(left)->GetChars()
422 : Handle<SeqOneByteString>::cast(left)->GetChars();
423 for (int i = 0; i < left_length; i++) *dest++ = src[i];
425 src = right->IsExternalString()
426 ? Handle<ExternalAsciiString>::cast(right)->GetChars()
427 : Handle<SeqOneByteString>::cast(right)->GetChars();
428 for (int i = 0; i < right_length; i++) *dest++ = src[i];
432 return (is_one_byte_data_in_two_byte_string)
433 ? ConcatStringContent<uint8_t>(NewRawOneByteString(length), left, right)
434 : ConcatStringContent<uc16>(NewRawTwoByteString(length), left, right);
437 Handle<ConsString> result = NewRawConsString(
438 (is_one_byte || is_one_byte_data_in_two_byte_string)
439 ? String::ONE_BYTE_ENCODING
440 : String::TWO_BYTE_ENCODING);
442 DisallowHeapAllocation no_gc;
443 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
445 result->set_hash_field(String::kEmptyHashField);
446 result->set_length(length);
447 result->set_first(*left, mode);
448 result->set_second(*right, mode);
453 Handle<String> Factory::NewFlatConcatString(Handle<String> first,
454 Handle<String> second) {
455 int total_length = first->length() + second->length();
456 if (first->IsOneByteRepresentation() && second->IsOneByteRepresentation()) {
457 return ConcatStringContent<uint8_t>(
458 NewRawOneByteString(total_length), first, second);
460 return ConcatStringContent<uc16>(
461 NewRawTwoByteString(total_length), first, second);
466 Handle<SlicedString> Factory::NewRawSlicedString(String::Encoding encoding) {
467 Handle<Map> map = (encoding == String::ONE_BYTE_ENCODING)
468 ? sliced_ascii_string_map() : sliced_string_map();
469 CALL_HEAP_FUNCTION(isolate(),
470 isolate()->heap()->Allocate(*map, NEW_SPACE),
475 Handle<String> Factory::NewProperSubString(Handle<String> str,
479 if (FLAG_verify_heap) str->StringVerify();
481 ASSERT(begin > 0 || end < str->length());
483 str = FlattenGetString(str);
485 int length = end - begin;
486 if (length <= 0) return empty_string();
488 return LookupSingleCharacterStringFromCode(isolate(), str->Get(begin));
491 // Optimization for 2-byte strings often used as keys in a decompression
492 // dictionary. Check whether we already have the string in the string
493 // table to prevent creation of many unnecessary strings.
494 uint16_t c1 = str->Get(begin);
495 uint16_t c2 = str->Get(begin + 1);
496 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
499 if (!FLAG_string_slices || length < SlicedString::kMinLength) {
500 if (str->IsOneByteRepresentation()) {
501 Handle<SeqOneByteString> result = NewRawOneByteString(length);
502 ASSERT(!result.is_null());
503 uint8_t* dest = result->GetChars();
504 DisallowHeapAllocation no_gc;
505 String::WriteToFlat(*str, dest, begin, end);
508 Handle<SeqTwoByteString> result = NewRawTwoByteString(length);
509 ASSERT(!result.is_null());
510 uc16* dest = result->GetChars();
511 DisallowHeapAllocation no_gc;
512 String::WriteToFlat(*str, dest, begin, end);
519 if (str->IsSlicedString()) {
520 Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
521 str = Handle<String>(slice->parent(), isolate());
522 offset += slice->offset();
525 ASSERT(str->IsSeqString() || str->IsExternalString());
526 Handle<SlicedString> slice = NewRawSlicedString(
527 str->IsOneByteRepresentation() ? String::ONE_BYTE_ENCODING
528 : String::TWO_BYTE_ENCODING);
530 slice->set_hash_field(String::kEmptyHashField);
531 slice->set_length(length);
532 slice->set_parent(*str);
533 slice->set_offset(offset);
538 Handle<String> Factory::NewExternalStringFromAscii(
539 const ExternalAsciiString::Resource* resource) {
542 isolate()->heap()->AllocateExternalStringFromAscii(resource),
547 Handle<String> Factory::NewExternalStringFromTwoByte(
548 const ExternalTwoByteString::Resource* resource) {
551 isolate()->heap()->AllocateExternalStringFromTwoByte(resource),
556 Handle<Symbol> Factory::NewSymbol() {
559 isolate()->heap()->AllocateSymbol(),
564 Handle<Symbol> Factory::NewPrivateSymbol() {
567 isolate()->heap()->AllocatePrivateSymbol(),
572 Handle<Context> Factory::NewNativeContext() {
575 isolate()->heap()->AllocateNativeContext(),
580 Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
581 Handle<ScopeInfo> scope_info) {
584 isolate()->heap()->AllocateGlobalContext(*function, *scope_info),
589 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
592 isolate()->heap()->AllocateModuleContext(*scope_info),
597 Handle<Context> Factory::NewFunctionContext(int length,
598 Handle<JSFunction> function) {
601 isolate()->heap()->AllocateFunctionContext(length, *function),
606 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
607 Handle<Context> previous,
609 Handle<Object> thrown_object) {
612 isolate()->heap()->AllocateCatchContext(*function,
620 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
621 Handle<Context> previous,
622 Handle<JSObject> extension) {
625 isolate()->heap()->AllocateWithContext(*function, *previous, *extension),
630 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
631 Handle<Context> previous,
632 Handle<ScopeInfo> scope_info) {
635 isolate()->heap()->AllocateBlockContext(*function,
642 Handle<Struct> Factory::NewStruct(InstanceType type) {
645 isolate()->heap()->AllocateStruct(type),
650 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
651 int aliased_context_slot) {
652 Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
653 NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
654 entry->set_aliased_context_slot(aliased_context_slot);
659 Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
660 return Handle<DeclaredAccessorDescriptor>::cast(
661 NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
665 Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
666 Handle<DeclaredAccessorInfo> info =
667 Handle<DeclaredAccessorInfo>::cast(
668 NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
669 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
674 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
675 Handle<ExecutableAccessorInfo> info =
676 Handle<ExecutableAccessorInfo>::cast(
677 NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
678 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
683 Handle<Script> Factory::NewScript(Handle<String> source) {
684 // Generate id for this script.
685 Heap* heap = isolate()->heap();
686 int id = heap->last_script_id()->value() + 1;
687 if (!Smi::IsValid(id) || id < 0) id = 1;
688 heap->set_last_script_id(Smi::FromInt(id));
690 // Create and initialize script object.
691 Handle<Foreign> wrapper = NewForeign(0, TENURED);
692 Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
693 script->set_source(*source);
694 script->set_name(heap->undefined_value());
695 script->set_id(Smi::FromInt(id));
696 script->set_line_offset(Smi::FromInt(0));
697 script->set_column_offset(Smi::FromInt(0));
698 script->set_context_data(heap->undefined_value());
699 script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
700 script->set_wrapper(*wrapper);
701 script->set_line_ends(heap->undefined_value());
702 script->set_eval_from_shared(heap->undefined_value());
703 script->set_eval_from_instructions_offset(Smi::FromInt(0));
704 script->set_flags(Smi::FromInt(0));
710 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
711 CALL_HEAP_FUNCTION(isolate(),
712 isolate()->heap()->AllocateForeign(addr, pretenure),
717 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
718 return NewForeign((Address) desc, TENURED);
722 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
726 isolate()->heap()->AllocateByteArray(length, pretenure),
731 Handle<ExternalArray> Factory::NewExternalArray(int length,
732 ExternalArrayType array_type,
733 void* external_pointer,
734 PretenureFlag pretenure) {
735 ASSERT(0 <= length && length <= Smi::kMaxValue);
738 isolate()->heap()->AllocateExternalArray(length,
746 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
748 ExternalArrayType array_type,
749 PretenureFlag pretenure) {
750 ASSERT(0 <= length && length <= Smi::kMaxValue);
753 isolate()->heap()->AllocateFixedTypedArray(length,
756 FixedTypedArrayBase);
760 Handle<Cell> Factory::NewCell(Handle<Object> value) {
761 AllowDeferredHandleDereference convert_to_cell;
764 isolate()->heap()->AllocateCell(*value),
769 Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
772 isolate()->heap()->AllocatePropertyCell(),
777 Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
778 AllowDeferredHandleDereference convert_to_cell;
779 Handle<PropertyCell> cell = NewPropertyCellWithHole();
780 PropertyCell::SetValueInferType(cell, value);
785 Handle<AllocationSite> Factory::NewAllocationSite() {
788 isolate()->heap()->AllocateAllocationSite(),
793 Handle<Map> Factory::NewMap(InstanceType type,
795 ElementsKind elements_kind) {
798 isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
803 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
804 // Make sure to use globals from the function's context, since the function
805 // can be from a different context.
806 Handle<Context> native_context(function->context()->native_context());
808 if (function->shared()->is_generator()) {
809 // Generator prototypes can share maps since they don't have "constructor"
811 new_map = handle(native_context->generator_object_prototype_map());
813 // Each function prototype gets a fresh map to avoid unwanted sharing of
814 // maps between prototypes of different constructors.
815 Handle<JSFunction> object_function(native_context->object_function());
816 ASSERT(object_function->has_initial_map());
817 new_map = Map::Copy(handle(object_function->initial_map()));
820 Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
822 if (!function->shared()->is_generator()) {
823 JSObject::SetLocalPropertyIgnoreAttributes(prototype,
824 constructor_string(),
833 Handle<Map> Factory::CopyWithPreallocatedFieldDescriptors(Handle<Map> src) {
835 isolate(), src->CopyWithPreallocatedFieldDescriptors(), Map);
839 Handle<Map> Factory::CopyMap(Handle<Map> src,
840 int extra_inobject_properties) {
841 Handle<Map> copy = CopyWithPreallocatedFieldDescriptors(src);
842 // Check that we do not overflow the instance size when adding the
843 // extra inobject properties.
844 int instance_size_delta = extra_inobject_properties * kPointerSize;
845 int max_instance_size_delta =
846 JSObject::kMaxInstanceSize - copy->instance_size();
847 int max_extra_properties = max_instance_size_delta >> kPointerSizeLog2;
848 if (extra_inobject_properties > max_extra_properties) {
849 // If the instance size overflows, we allocate as many properties
850 // as we can as inobject properties.
851 instance_size_delta = max_instance_size_delta;
852 extra_inobject_properties = max_extra_properties;
854 // Adjust the map with the extra inobject properties.
855 int inobject_properties =
856 copy->inobject_properties() + extra_inobject_properties;
857 copy->set_inobject_properties(inobject_properties);
858 copy->set_unused_property_fields(inobject_properties);
859 copy->set_instance_size(copy->instance_size() + instance_size_delta);
860 copy->set_visitor_id(StaticVisitorBase::GetVisitorId(*copy));
865 Handle<Map> Factory::CopyMap(Handle<Map> src) {
866 CALL_HEAP_FUNCTION(isolate(), src->Copy(), Map);
870 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
871 CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedArray);
875 Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
876 Handle<FixedArray> array) {
877 ASSERT(isolate()->heap()->InNewSpace(*array));
878 CALL_HEAP_FUNCTION(isolate(),
879 isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
884 Handle<FixedArray> Factory::CopySizeFixedArray(Handle<FixedArray> array,
886 PretenureFlag pretenure) {
887 CALL_HEAP_FUNCTION(isolate(),
888 array->CopySize(new_length, pretenure),
893 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
894 Handle<FixedDoubleArray> array) {
895 CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedDoubleArray);
899 Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
900 Handle<ConstantPoolArray> array) {
901 CALL_HEAP_FUNCTION(isolate(), array->Copy(), ConstantPoolArray);
905 Handle<JSFunction> Factory::BaseNewFunctionFromSharedFunctionInfo(
906 Handle<SharedFunctionInfo> function_info,
907 Handle<Map> function_map,
908 PretenureFlag pretenure) {
911 isolate()->heap()->AllocateFunction(*function_map,
913 isolate()->heap()->the_hole_value(),
919 static Handle<Map> MapForNewFunction(Isolate *isolate,
920 Handle<SharedFunctionInfo> function_info) {
921 Context *context = isolate->context()->native_context();
922 int map_index = Context::FunctionMapIndex(function_info->strict_mode(),
923 function_info->is_generator());
924 return Handle<Map>(Map::cast(context->get(map_index)));
928 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
929 Handle<SharedFunctionInfo> function_info,
930 Handle<Context> context,
931 PretenureFlag pretenure) {
932 Handle<JSFunction> result = BaseNewFunctionFromSharedFunctionInfo(
934 MapForNewFunction(isolate(), function_info),
937 if (function_info->ic_age() != isolate()->heap()->global_ic_age()) {
938 function_info->ResetForNewContext(isolate()->heap()->global_ic_age());
941 result->set_context(*context);
943 int index = function_info->SearchOptimizedCodeMap(context->native_context(),
945 if (!function_info->bound() && index < 0) {
946 int number_of_literals = function_info->num_literals();
947 Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
948 if (number_of_literals > 0) {
949 // Store the native context in the literals array prefix. This
950 // context will be used when creating object, regexp and array
951 // literals in this function.
952 literals->set(JSFunction::kLiteralNativeContextIndex,
953 context->native_context());
955 result->set_literals(*literals);
959 // Caching of optimized code enabled and optimized code found.
960 FixedArray* literals =
961 function_info->GetLiteralsFromOptimizedCodeMap(index);
962 if (literals != NULL) result->set_literals(literals);
963 Code* code = function_info->GetCodeFromOptimizedCodeMap(index);
964 ASSERT(!code->marked_for_deoptimization());
965 result->ReplaceCode(code);
969 if (isolate()->use_crankshaft() &&
971 result->is_compiled() &&
972 !function_info->is_toplevel() &&
973 function_info->allows_lazy_compilation() &&
974 !function_info->optimization_disabled() &&
975 !isolate()->DebuggerHasBreakPoints()) {
976 result->MarkForOptimization();
982 Handle<Object> Factory::NewNumber(double value,
983 PretenureFlag pretenure) {
986 isolate()->heap()->NumberFromDouble(value, pretenure), Object);
990 Handle<Object> Factory::NewNumberFromInt(int32_t value,
991 PretenureFlag pretenure) {
994 isolate()->heap()->NumberFromInt32(value, pretenure), Object);
998 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
999 PretenureFlag pretenure) {
1002 isolate()->heap()->NumberFromUint32(value, pretenure), Object);
1006 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1007 PretenureFlag pretenure) {
1010 isolate()->heap()->AllocateHeapNumber(value, pretenure), HeapNumber);
1014 Handle<Float32x4> Factory::NewFloat32x4(float32x4_value_t value,
1015 PretenureFlag pretenure) {
1018 isolate()->heap()->AllocateFloat32x4(value, pretenure), Float32x4);
1022 Handle<Int32x4> Factory::NewInt32x4(int32x4_value_t value,
1023 PretenureFlag pretenure) {
1026 isolate()->heap()->AllocateInt32x4(value, pretenure), Int32x4);
1030 Handle<JSObject> Factory::NewNeanderObject() {
1033 isolate()->heap()->AllocateJSObjectFromMap(
1034 isolate()->heap()->neander_map()),
1039 Handle<Object> Factory::NewTypeError(const char* message,
1040 Vector< Handle<Object> > args) {
1041 return NewError("MakeTypeError", message, args);
1045 Handle<Object> Factory::NewTypeError(Handle<String> message) {
1046 return NewError("$TypeError", message);
1050 Handle<Object> Factory::NewRangeError(const char* message,
1051 Vector< Handle<Object> > args) {
1052 return NewError("MakeRangeError", message, args);
1056 Handle<Object> Factory::NewRangeError(Handle<String> message) {
1057 return NewError("$RangeError", message);
1061 Handle<Object> Factory::NewSyntaxError(const char* message,
1062 Handle<JSArray> args) {
1063 return NewError("MakeSyntaxError", message, args);
1067 Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
1068 return NewError("$SyntaxError", message);
1072 Handle<Object> Factory::NewReferenceError(const char* message,
1073 Vector< Handle<Object> > args) {
1074 return NewError("MakeReferenceError", message, args);
1078 Handle<Object> Factory::NewReferenceError(const char* message,
1079 Handle<JSArray> args) {
1080 return NewError("MakeReferenceError", message, args);
1084 Handle<Object> Factory::NewReferenceError(Handle<String> message) {
1085 return NewError("$ReferenceError", message);
1089 Handle<Object> Factory::NewError(const char* maker,
1090 const char* message,
1091 Vector< Handle<Object> > args) {
1092 // Instantiate a closeable HandleScope for EscapeFrom.
1093 v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
1094 Handle<FixedArray> array = NewFixedArray(args.length());
1095 for (int i = 0; i < args.length(); i++) {
1096 array->set(i, *args[i]);
1098 Handle<JSArray> object = NewJSArrayWithElements(array);
1099 Handle<Object> result = NewError(maker, message, object);
1100 return result.EscapeFrom(&scope);
1104 Handle<Object> Factory::NewEvalError(const char* message,
1105 Vector< Handle<Object> > args) {
1106 return NewError("MakeEvalError", message, args);
1110 Handle<Object> Factory::NewError(const char* message,
1111 Vector< Handle<Object> > args) {
1112 return NewError("MakeError", message, args);
1116 Handle<String> Factory::EmergencyNewError(const char* message,
1117 Handle<JSArray> args) {
1118 const int kBufferSize = 1000;
1119 char buffer[kBufferSize];
1120 size_t space = kBufferSize;
1121 char* p = &buffer[0];
1123 Vector<char> v(buffer, kBufferSize);
1124 OS::StrNCpy(v, message, space);
1125 space -= Min(space, strlen(message));
1126 p = &buffer[kBufferSize] - space;
1128 for (unsigned i = 0; i < ARRAY_SIZE(args); i++) {
1133 Handle<String> arg_str = Handle<String>::cast(
1134 Object::GetElementNoExceptionThrown(isolate(), args, i));
1135 SmartArrayPointer<char> arg = arg_str->ToCString();
1136 Vector<char> v2(p, static_cast<int>(space));
1137 OS::StrNCpy(v2, arg.get(), space);
1138 space -= Min(space, strlen(arg.get()));
1139 p = &buffer[kBufferSize] - space;
1146 buffer[kBufferSize - 1] = '\0';
1148 Handle<String> error_string = NewStringFromUtf8(CStrVector(buffer), TENURED);
1149 return error_string;
1153 Handle<Object> Factory::NewError(const char* maker,
1154 const char* message,
1155 Handle<JSArray> args) {
1156 Handle<String> make_str = InternalizeUtf8String(maker);
1157 Handle<Object> fun_obj(
1158 isolate()->js_builtins_object()->GetPropertyNoExceptionThrown(*make_str),
1160 // If the builtins haven't been properly configured yet this error
1161 // constructor may not have been defined. Bail out.
1162 if (!fun_obj->IsJSFunction()) {
1163 return EmergencyNewError(message, args);
1165 Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1166 Handle<Object> message_obj = InternalizeUtf8String(message);
1167 Handle<Object> argv[] = { message_obj, args };
1169 // Invoke the JavaScript factory method. If an exception is thrown while
1170 // running the factory method, use the exception as the result.
1171 bool caught_exception;
1172 Handle<Object> result = Execution::TryCall(fun,
1173 isolate()->js_builtins_object(),
1181 Handle<Object> Factory::NewError(Handle<String> message) {
1182 return NewError("$Error", message);
1186 Handle<Object> Factory::NewError(const char* constructor,
1187 Handle<String> message) {
1188 Handle<String> constr = InternalizeUtf8String(constructor);
1189 Handle<JSFunction> fun = Handle<JSFunction>(
1190 JSFunction::cast(isolate()->js_builtins_object()->
1191 GetPropertyNoExceptionThrown(*constr)));
1192 Handle<Object> argv[] = { message };
1194 // Invoke the JavaScript factory method. If an exception is thrown while
1195 // running the factory method, use the exception as the result.
1196 bool caught_exception;
1197 Handle<Object> result = Execution::TryCall(fun,
1198 isolate()->js_builtins_object(),
1206 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1210 bool force_initial_map) {
1211 // Allocate the function
1212 Handle<JSFunction> function = NewFunction(name, the_hole_value());
1214 // Set up the code pointer in both the shared function info and in
1215 // the function itself.
1216 function->shared()->set_code(*code);
1217 function->set_code(*code);
1219 if (force_initial_map ||
1220 type != JS_OBJECT_TYPE ||
1221 instance_size != JSObject::kHeaderSize) {
1222 Handle<Map> initial_map = NewMap(type, instance_size);
1223 Handle<JSObject> prototype = NewFunctionPrototype(function);
1224 initial_map->set_prototype(*prototype);
1225 function->set_initial_map(*initial_map);
1226 initial_map->set_constructor(*function);
1228 ASSERT(!function->has_initial_map());
1229 ASSERT(!function->has_prototype());
1236 Handle<JSFunction> Factory::NewFunctionWithPrototype(Handle<String> name,
1239 Handle<JSObject> prototype,
1241 bool force_initial_map) {
1242 // Allocate the function.
1243 Handle<JSFunction> function = NewFunction(name, prototype);
1245 // Set up the code pointer in both the shared function info and in
1246 // the function itself.
1247 function->shared()->set_code(*code);
1248 function->set_code(*code);
1250 if (force_initial_map ||
1251 type != JS_OBJECT_TYPE ||
1252 instance_size != JSObject::kHeaderSize) {
1253 Handle<Map> initial_map = NewMap(type,
1255 GetInitialFastElementsKind());
1256 function->set_initial_map(*initial_map);
1257 initial_map->set_constructor(*function);
1260 JSFunction::SetPrototype(function, prototype);
1265 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1266 Handle<Code> code) {
1267 Handle<JSFunction> function = NewFunctionWithoutPrototype(name, SLOPPY);
1268 function->shared()->set_code(*code);
1269 function->set_code(*code);
1270 ASSERT(!function->has_initial_map());
1271 ASSERT(!function->has_prototype());
1276 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1279 isolate()->heap()->AllocateScopeInfo(length),
1284 Handle<JSObject> Factory::NewExternal(void* value) {
1285 CALL_HEAP_FUNCTION(isolate(),
1286 isolate()->heap()->AllocateExternal(value),
1291 Handle<Code> Factory::NewCode(const CodeDesc& desc,
1293 Handle<Object> self_ref,
1296 int prologue_offset) {
1297 CALL_HEAP_FUNCTION(isolate(),
1298 isolate()->heap()->CreateCode(
1299 desc, flags, self_ref, immovable, crankshafted,
1305 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1306 CALL_HEAP_FUNCTION(isolate(),
1307 isolate()->heap()->CopyCode(*code),
1312 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1313 CALL_HEAP_FUNCTION(isolate(),
1314 isolate()->heap()->CopyCode(*code, reloc_info),
1319 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1320 PretenureFlag pretenure) {
1321 JSFunction::EnsureHasInitialMap(constructor);
1324 isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1328 Handle<JSObject> Factory::NewJSObjectWithMemento(
1329 Handle<JSFunction> constructor,
1330 Handle<AllocationSite> site) {
1331 JSFunction::EnsureHasInitialMap(constructor);
1334 isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
1339 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1340 Handle<ScopeInfo> scope_info) {
1343 isolate()->heap()->AllocateJSModule(*context, *scope_info), JSModule);
1347 // TODO(mstarzinger): Temporary wrapper until handlified.
1348 static Handle<NameDictionary> NameDictionaryAdd(Handle<NameDictionary> dict,
1350 Handle<Object> value,
1351 PropertyDetails details) {
1352 CALL_HEAP_FUNCTION(dict->GetIsolate(),
1353 dict->Add(*name, *value, details),
1358 static Handle<GlobalObject> NewGlobalObjectFromMap(Isolate* isolate,
1360 CALL_HEAP_FUNCTION(isolate,
1361 isolate->heap()->Allocate(*map, OLD_POINTER_SPACE),
1366 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1367 ASSERT(constructor->has_initial_map());
1368 Handle<Map> map(constructor->initial_map());
1369 ASSERT(map->is_dictionary_map());
1371 // Make sure no field properties are described in the initial map.
1372 // This guarantees us that normalizing the properties does not
1373 // require us to change property values to PropertyCells.
1374 ASSERT(map->NextFreePropertyIndex() == 0);
1376 // Make sure we don't have a ton of pre-allocated slots in the
1377 // global objects. They will be unused once we normalize the object.
1378 ASSERT(map->unused_property_fields() == 0);
1379 ASSERT(map->inobject_properties() == 0);
1381 // Initial size of the backing store to avoid resize of the storage during
1382 // bootstrapping. The size differs between the JS global object ad the
1384 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1386 // Allocate a dictionary object for backing storage.
1387 int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1388 Handle<NameDictionary> dictionary = NewNameDictionary(at_least_space_for);
1390 // The global object might be created from an object template with accessors.
1391 // Fill these accessors into the dictionary.
1392 Handle<DescriptorArray> descs(map->instance_descriptors());
1393 for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1394 PropertyDetails details = descs->GetDetails(i);
1395 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
1396 PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
1397 Handle<Name> name(descs->GetKey(i));
1398 Handle<Object> value(descs->GetCallbacksObject(i), isolate());
1399 Handle<PropertyCell> cell = NewPropertyCell(value);
1400 NameDictionaryAdd(dictionary, name, cell, d);
1403 // Allocate the global object and initialize it with the backing store.
1404 Handle<GlobalObject> global = NewGlobalObjectFromMap(isolate(), map);
1405 isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1407 // Create a new map for the global object.
1408 Handle<Map> new_map = Map::CopyDropDescriptors(map);
1409 new_map->set_dictionary_map(true);
1411 // Set up the global object as a normalized object.
1412 global->set_map(*new_map);
1413 global->set_properties(*dictionary);
1415 // Make sure result is a global object with properties in dictionary.
1416 ASSERT(global->IsGlobalObject() && !global->HasFastProperties());
1421 Handle<JSObject> Factory::NewJSObjectFromMap(
1423 PretenureFlag pretenure,
1425 Handle<AllocationSite> allocation_site) {
1428 isolate()->heap()->AllocateJSObjectFromMap(
1432 allocation_site.is_null() ? NULL : *allocation_site),
1437 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1440 PretenureFlag pretenure) {
1441 if (capacity != 0) {
1442 elements_kind = GetHoleyElementsKind(elements_kind);
1444 CALL_HEAP_FUNCTION(isolate(),
1445 isolate()->heap()->AllocateJSArrayAndStorage(
1449 INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE,
1455 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1456 ElementsKind elements_kind,
1458 PretenureFlag pretenure) {
1459 ASSERT(length <= elements->length());
1462 isolate()->heap()->AllocateJSArrayWithElements(*elements,
1470 void Factory::NewJSArrayStorage(Handle<JSArray> array,
1473 ArrayStorageAllocationMode mode) {
1474 CALL_HEAP_FUNCTION_VOID(isolate(),
1475 isolate()->heap()->AllocateJSArrayStorage(*array,
1482 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1483 Handle<JSFunction> function) {
1484 ASSERT(function->shared()->is_generator());
1485 JSFunction::EnsureHasInitialMap(function);
1486 Handle<Map> map(function->initial_map());
1487 ASSERT(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1490 isolate()->heap()->AllocateJSObjectFromMap(*map),
1495 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1496 Handle<JSFunction> array_buffer_fun(
1497 isolate()->context()->native_context()->array_buffer_fun());
1500 isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1505 Handle<JSDataView> Factory::NewJSDataView() {
1506 Handle<JSFunction> data_view_fun(
1507 isolate()->context()->native_context()->data_view_fun());
1510 isolate()->heap()->AllocateJSObject(*data_view_fun),
1515 static JSFunction* GetTypedArrayFun(ExternalArrayType type,
1517 Context* native_context = isolate->context()->native_context();
1519 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
1520 case kExternal##Type##Array: \
1521 return native_context->type##_array_fun();
1523 TYPED_ARRAYS(TYPED_ARRAY_FUN)
1524 #undef TYPED_ARRAY_FUN
1533 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1534 Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1538 isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1543 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1544 Handle<Object> prototype) {
1547 isolate()->heap()->AllocateJSProxy(*handler, *prototype),
1552 void Factory::BecomeJSObject(Handle<JSReceiver> object) {
1553 CALL_HEAP_FUNCTION_VOID(
1555 isolate()->heap()->ReinitializeJSReceiver(
1556 *object, JS_OBJECT_TYPE, JSObject::kHeaderSize));
1560 void Factory::BecomeJSFunction(Handle<JSReceiver> object) {
1561 CALL_HEAP_FUNCTION_VOID(
1563 isolate()->heap()->ReinitializeJSReceiver(
1564 *object, JS_FUNCTION_TYPE, JSFunction::kSize));
1568 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1569 Handle<String> name,
1570 int number_of_literals,
1573 Handle<ScopeInfo> scope_info) {
1574 Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name);
1575 shared->set_code(*code);
1576 shared->set_scope_info(*scope_info);
1577 int literals_array_size = number_of_literals;
1578 // If the function contains object, regexp or array literals,
1579 // allocate extra space for a literals array prefix containing the
1581 if (number_of_literals > 0) {
1582 literals_array_size += JSFunction::kLiteralsPrefixSize;
1584 shared->set_num_literals(literals_array_size);
1586 shared->set_instance_class_name(isolate()->heap()->Generator_string());
1587 shared->DisableOptimization(kGenerator);
1593 Handle<JSMessageObject> Factory::NewJSMessageObject(
1594 Handle<String> type,
1595 Handle<JSArray> arguments,
1598 Handle<Object> script,
1599 Handle<Object> stack_frames) {
1600 CALL_HEAP_FUNCTION(isolate(),
1601 isolate()->heap()->AllocateJSMessageObject(*type,
1611 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(Handle<String> name) {
1612 CALL_HEAP_FUNCTION(isolate(),
1613 isolate()->heap()->AllocateSharedFunctionInfo(*name),
1614 SharedFunctionInfo);
1618 Handle<String> Factory::NumberToString(Handle<Object> number) {
1619 CALL_HEAP_FUNCTION(isolate(),
1620 isolate()->heap()->NumberToString(*number), String);
1624 Handle<String> Factory::Uint32ToString(uint32_t value) {
1625 CALL_HEAP_FUNCTION(isolate(),
1626 isolate()->heap()->Uint32ToString(value), String);
1630 Handle<SeededNumberDictionary> Factory::DictionaryAtNumberPut(
1631 Handle<SeededNumberDictionary> dictionary,
1633 Handle<Object> value) {
1634 CALL_HEAP_FUNCTION(isolate(),
1635 dictionary->AtNumberPut(key, *value),
1636 SeededNumberDictionary);
1640 Handle<UnseededNumberDictionary> Factory::DictionaryAtNumberPut(
1641 Handle<UnseededNumberDictionary> dictionary,
1643 Handle<Object> value) {
1644 CALL_HEAP_FUNCTION(isolate(),
1645 dictionary->AtNumberPut(key, *value),
1646 UnseededNumberDictionary);
1650 Handle<JSFunction> Factory::NewFunctionHelper(Handle<String> name,
1651 Handle<Object> prototype) {
1652 Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1655 isolate()->heap()->AllocateFunction(*isolate()->sloppy_function_map(),
1662 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1663 Handle<Object> prototype) {
1664 Handle<JSFunction> fun = NewFunctionHelper(name, prototype);
1665 fun->set_context(isolate()->context()->native_context());
1670 Handle<JSFunction> Factory::NewFunctionWithoutPrototypeHelper(
1671 Handle<String> name,
1672 StrictMode strict_mode) {
1673 Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1674 Handle<Map> map = strict_mode == SLOPPY
1675 ? isolate()->sloppy_function_without_prototype_map()
1676 : isolate()->strict_function_without_prototype_map();
1677 CALL_HEAP_FUNCTION(isolate(),
1678 isolate()->heap()->AllocateFunction(
1686 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(
1687 Handle<String> name,
1688 StrictMode strict_mode) {
1689 Handle<JSFunction> fun = NewFunctionWithoutPrototypeHelper(name, strict_mode);
1690 fun->set_context(isolate()->context()->native_context());
1695 Handle<Object> Factory::ToObject(Handle<Object> object) {
1696 CALL_HEAP_FUNCTION(isolate(), object->ToObject(isolate()), Object);
1700 Handle<Object> Factory::ToObject(Handle<Object> object,
1701 Handle<Context> native_context) {
1702 CALL_HEAP_FUNCTION(isolate(), object->ToObject(*native_context), Object);
1706 #ifdef ENABLE_DEBUGGER_SUPPORT
1707 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
1708 // Get the original code of the function.
1709 Handle<Code> code(shared->code());
1711 // Create a copy of the code before allocating the debug info object to avoid
1712 // allocation while setting up the debug info object.
1713 Handle<Code> original_code(*Factory::CopyCode(code));
1715 // Allocate initial fixed array for active break points before allocating the
1716 // debug info object to avoid allocation while setting up the debug info
1718 Handle<FixedArray> break_points(
1719 NewFixedArray(Debug::kEstimatedNofBreakPointsInFunction));
1721 // Create and set up the debug info object. Debug info contains function, a
1722 // copy of the original code, the executing code and initial fixed array for
1723 // active break points.
1724 Handle<DebugInfo> debug_info =
1725 Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
1726 debug_info->set_shared(*shared);
1727 debug_info->set_original_code(*original_code);
1728 debug_info->set_code(*code);
1729 debug_info->set_break_points(*break_points);
1731 // Link debug info to function.
1732 shared->set_debug_info(*debug_info);
1739 Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
1743 isolate()->heap()->AllocateArgumentsObject(*callee, length), JSObject);
1747 Handle<JSFunction> Factory::CreateApiFunction(
1748 Handle<FunctionTemplateInfo> obj, ApiInstanceType instance_type) {
1749 Handle<Code> code = isolate()->builtins()->HandleApiCall();
1750 Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
1752 int internal_field_count = 0;
1753 if (!obj->instance_template()->IsUndefined()) {
1754 Handle<ObjectTemplateInfo> instance_template =
1755 Handle<ObjectTemplateInfo>(
1756 ObjectTemplateInfo::cast(obj->instance_template()));
1757 internal_field_count =
1758 Smi::cast(instance_template->internal_field_count())->value();
1761 // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
1762 // JSObject::GetHeaderSize.
1763 int instance_size = kPointerSize * internal_field_count;
1765 switch (instance_type) {
1766 case JavaScriptObject:
1767 type = JS_OBJECT_TYPE;
1768 instance_size += JSObject::kHeaderSize;
1770 case InnerGlobalObject:
1771 type = JS_GLOBAL_OBJECT_TYPE;
1772 instance_size += JSGlobalObject::kSize;
1774 case OuterGlobalObject:
1775 type = JS_GLOBAL_PROXY_TYPE;
1776 instance_size += JSGlobalProxy::kSize;
1780 type = JS_OBJECT_TYPE; // Keep the compiler happy.
1784 Handle<JSFunction> result =
1785 NewFunction(Factory::empty_string(),
1792 result->shared()->set_length(obj->length());
1795 Handle<Object> class_name = Handle<Object>(obj->class_name(), isolate());
1796 if (class_name->IsString()) {
1797 result->shared()->set_instance_class_name(*class_name);
1798 result->shared()->set_name(*class_name);
1801 Handle<Map> map = Handle<Map>(result->initial_map());
1803 // Mark as undetectable if needed.
1804 if (obj->undetectable()) {
1805 map->set_is_undetectable();
1808 // Mark as hidden for the __proto__ accessor if needed.
1809 if (obj->hidden_prototype()) {
1810 map->set_is_hidden_prototype();
1813 // Mark as needs_access_check if needed.
1814 if (obj->needs_access_check()) {
1815 map->set_is_access_check_needed(true);
1818 // Set interceptor information in the map.
1819 if (!obj->named_property_handler()->IsUndefined()) {
1820 map->set_has_named_interceptor();
1822 if (!obj->indexed_property_handler()->IsUndefined()) {
1823 map->set_has_indexed_interceptor();
1826 // Set instance call-as-function information in the map.
1827 if (!obj->instance_call_handler()->IsUndefined()) {
1828 map->set_has_instance_call_handler();
1831 result->shared()->set_function_data(*obj);
1832 result->shared()->set_construct_stub(*construct_stub);
1833 result->shared()->DontAdaptArguments();
1835 // Recursively copy parent instance templates' accessors,
1836 // 'data' may be modified.
1837 int max_number_of_additional_properties = 0;
1838 int max_number_of_static_properties = 0;
1839 FunctionTemplateInfo* info = *obj;
1841 if (!info->instance_template()->IsUndefined()) {
1843 ObjectTemplateInfo::cast(
1844 info->instance_template())->property_accessors();
1845 if (!props->IsUndefined()) {
1846 Handle<Object> props_handle(props, isolate());
1847 NeanderArray props_array(props_handle);
1848 max_number_of_additional_properties += props_array.length();
1851 if (!info->property_accessors()->IsUndefined()) {
1852 Object* props = info->property_accessors();
1853 if (!props->IsUndefined()) {
1854 Handle<Object> props_handle(props, isolate());
1855 NeanderArray props_array(props_handle);
1856 max_number_of_static_properties += props_array.length();
1859 Object* parent = info->parent_template();
1860 if (parent->IsUndefined()) break;
1861 info = FunctionTemplateInfo::cast(parent);
1864 Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);
1866 // Use a temporary FixedArray to acculumate static accessors
1867 int valid_descriptors = 0;
1868 Handle<FixedArray> array;
1869 if (max_number_of_static_properties > 0) {
1870 array = NewFixedArray(max_number_of_static_properties);
1874 // Install instance descriptors
1875 if (!obj->instance_template()->IsUndefined()) {
1876 Handle<ObjectTemplateInfo> instance =
1877 Handle<ObjectTemplateInfo>(
1878 ObjectTemplateInfo::cast(obj->instance_template()), isolate());
1879 Handle<Object> props = Handle<Object>(instance->property_accessors(),
1881 if (!props->IsUndefined()) {
1882 Map::AppendCallbackDescriptors(map, props);
1885 // Accumulate static accessors
1886 if (!obj->property_accessors()->IsUndefined()) {
1887 Handle<Object> props = Handle<Object>(obj->property_accessors(),
1890 AccessorInfo::AppendUnique(props, array, valid_descriptors);
1892 // Climb parent chain
1893 Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
1894 if (parent->IsUndefined()) break;
1895 obj = Handle<FunctionTemplateInfo>::cast(parent);
1898 // Install accumulated static accessors
1899 for (int i = 0; i < valid_descriptors; i++) {
1900 Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
1901 JSObject::SetAccessor(result, accessor);
1904 ASSERT(result->shared()->IsApiFunction());
1909 Handle<MapCache> Factory::NewMapCache(int at_least_space_for) {
1910 CALL_HEAP_FUNCTION(isolate(),
1911 MapCache::Allocate(isolate()->heap(),
1912 at_least_space_for),
1917 MUST_USE_RESULT static MaybeObject* UpdateMapCacheWith(Context* context,
1921 { MaybeObject* maybe_result =
1922 MapCache::cast(context->map_cache())->Put(keys, map);
1923 if (!maybe_result->ToObject(&result)) return maybe_result;
1925 context->set_map_cache(MapCache::cast(result));
1930 Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
1931 Handle<FixedArray> keys,
1933 CALL_HEAP_FUNCTION(isolate(),
1934 UpdateMapCacheWith(*context, *keys, *map), MapCache);
1938 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
1939 Handle<FixedArray> keys) {
1940 if (context->map_cache()->IsUndefined()) {
1941 // Allocate the new map cache for the native context.
1942 Handle<MapCache> new_cache = NewMapCache(24);
1943 context->set_map_cache(*new_cache);
1945 // Check to see whether there is a matching element in the cache.
1946 Handle<MapCache> cache =
1947 Handle<MapCache>(MapCache::cast(context->map_cache()));
1948 Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
1949 if (result->IsMap()) return Handle<Map>::cast(result);
1950 // Create a new map and add it to the cache.
1952 CopyMap(Handle<Map>(context->object_function()->initial_map()),
1954 AddToMapCache(context, keys, map);
1955 return Handle<Map>(map);
1959 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
1960 JSRegExp::Type type,
1961 Handle<String> source,
1962 JSRegExp::Flags flags,
1963 Handle<Object> data) {
1964 Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
1966 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1967 store->set(JSRegExp::kSourceIndex, *source);
1968 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1969 store->set(JSRegExp::kAtomPatternIndex, *data);
1970 regexp->set_data(*store);
1973 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
1974 JSRegExp::Type type,
1975 Handle<String> source,
1976 JSRegExp::Flags flags,
1977 int capture_count) {
1978 Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
1979 Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
1980 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1981 store->set(JSRegExp::kSourceIndex, *source);
1982 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1983 store->set(JSRegExp::kIrregexpASCIICodeIndex, uninitialized);
1984 store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
1985 store->set(JSRegExp::kIrregexpASCIICodeSavedIndex, uninitialized);
1986 store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
1987 store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
1988 store->set(JSRegExp::kIrregexpCaptureCountIndex,
1989 Smi::FromInt(capture_count));
1990 regexp->set_data(*store);
1995 void Factory::ConfigureInstance(Handle<FunctionTemplateInfo> desc,
1996 Handle<JSObject> instance,
1997 bool* pending_exception) {
1998 // Configure the instance by adding the properties specified by the
1999 // instance template.
2000 Handle<Object> instance_template(desc->instance_template(), isolate());
2001 if (!instance_template->IsUndefined()) {
2002 Execution::ConfigureInstance(isolate(),
2007 *pending_exception = false;
2012 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
2013 Heap* h = isolate()->heap();
2014 if (name->Equals(h->undefined_string())) return undefined_value();
2015 if (name->Equals(h->nan_string())) return nan_value();
2016 if (name->Equals(h->infinity_string())) return infinity_value();
2017 return Handle<Object>::null();
2021 Handle<Object> Factory::ToBoolean(bool value) {
2022 return value ? true_value() : false_value();
2026 } } // namespace v8::internal