factory.cc 59.8 KB
Newer Older
1
// Copyright 2013 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

#include "api.h"
31
#include "debug.h"
32 33
#include "execution.h"
#include "factory.h"
34
#include "isolate-inl.h"
35
#include "macro-assembler.h"
36
#include "objects.h"
37
#include "objects-visiting.h"
38
#include "platform.h"
39
#include "scopeinfo.h"
40

41 42
namespace v8 {
namespace internal {
43 44


45 46 47 48 49 50 51 52
Handle<Box> Factory::NewBox(Handle<Object> value, PretenureFlag pretenure) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateBox(*value, pretenure),
      Box);
}


53 54
Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
  ASSERT(0 <= size);
55 56 57 58
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateFixedArray(size, pretenure),
      FixedArray);
59 60 61
}


62 63
Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
                                                   PretenureFlag pretenure) {
64
  ASSERT(0 <= size);
65 66 67 68
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateFixedArrayWithHoles(size, pretenure),
      FixedArray);
69 70 71
}


72 73
Handle<FixedDoubleArray> Factory::NewFixedDoubleArray(int size,
                                                      PretenureFlag pretenure) {
74 75 76 77
  ASSERT(0 <= size);
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
78
      FixedDoubleArray);
79 80 81
}


82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
    int number_of_int64_entries,
    int number_of_ptr_entries,
    int number_of_int32_entries) {
  ASSERT(number_of_int64_entries > 0 || number_of_ptr_entries > 0 ||
         number_of_int32_entries > 0);
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateConstantPoolArray(number_of_int64_entries,
                                                   number_of_ptr_entries,
                                                   number_of_int32_entries),
      ConstantPoolArray);
}


97
Handle<NameDictionary> Factory::NewNameDictionary(int at_least_space_for) {
98
  ASSERT(0 <= at_least_space_for);
99
  CALL_HEAP_FUNCTION(isolate(),
100 101
                     NameDictionary::Allocate(isolate()->heap(),
                                              at_least_space_for),
102
                     NameDictionary);
103 104 105
}


106 107
Handle<SeededNumberDictionary> Factory::NewSeededNumberDictionary(
    int at_least_space_for) {
108
  ASSERT(0 <= at_least_space_for);
109
  CALL_HEAP_FUNCTION(isolate(),
110 111
                     SeededNumberDictionary::Allocate(isolate()->heap(),
                                                      at_least_space_for),
112 113 114 115 116 117 118 119
                     SeededNumberDictionary);
}


Handle<UnseededNumberDictionary> Factory::NewUnseededNumberDictionary(
    int at_least_space_for) {
  ASSERT(0 <= at_least_space_for);
  CALL_HEAP_FUNCTION(isolate(),
120 121
                     UnseededNumberDictionary::Allocate(isolate()->heap(),
                                                        at_least_space_for),
122
                     UnseededNumberDictionary);
123 124 125
}


126 127 128
Handle<ObjectHashSet> Factory::NewObjectHashSet(int at_least_space_for) {
  ASSERT(0 <= at_least_space_for);
  CALL_HEAP_FUNCTION(isolate(),
129 130
                     ObjectHashSet::Allocate(isolate()->heap(),
                                             at_least_space_for),
131 132 133 134
                     ObjectHashSet);
}


135 136 137
Handle<ObjectHashTable> Factory::NewObjectHashTable(
    int at_least_space_for,
    MinimumCapacity capacity_option) {
138 139
  ASSERT(0 <= at_least_space_for);
  CALL_HEAP_FUNCTION(isolate(),
140
                     ObjectHashTable::Allocate(isolate()->heap(),
141 142
                                               at_least_space_for,
                                               capacity_option),
143 144 145 146
                     ObjectHashTable);
}


147 148 149 150 151 152
Handle<WeakHashTable> Factory::NewWeakHashTable(int at_least_space_for) {
  ASSERT(0 <= at_least_space_for);
  CALL_HEAP_FUNCTION(
      isolate(),
      WeakHashTable::Allocate(isolate()->heap(),
                              at_least_space_for,
153
                              USE_DEFAULT_MINIMUM_CAPACITY,
154 155 156 157 158
                              TENURED),
      WeakHashTable);
}


159 160
Handle<DescriptorArray> Factory::NewDescriptorArray(int number_of_descriptors,
                                                    int slack) {
161
  ASSERT(0 <= number_of_descriptors);
162
  CALL_HEAP_FUNCTION(isolate(),
163 164
                     DescriptorArray::Allocate(
                         isolate(), number_of_descriptors, slack),
165 166 167 168
                     DescriptorArray);
}


169 170 171 172
Handle<DeoptimizationInputData> Factory::NewDeoptimizationInputData(
    int deopt_entry_count,
    PretenureFlag pretenure) {
  ASSERT(deopt_entry_count > 0);
173
  CALL_HEAP_FUNCTION(isolate(),
174 175
                     DeoptimizationInputData::Allocate(isolate(),
                                                       deopt_entry_count,
176 177 178 179 180 181 182 183 184
                                                       pretenure),
                     DeoptimizationInputData);
}


Handle<DeoptimizationOutputData> Factory::NewDeoptimizationOutputData(
    int deopt_entry_count,
    PretenureFlag pretenure) {
  ASSERT(deopt_entry_count > 0);
185
  CALL_HEAP_FUNCTION(isolate(),
186 187
                     DeoptimizationOutputData::Allocate(isolate(),
                                                        deopt_entry_count,
188 189 190 191 192
                                                        pretenure),
                     DeoptimizationOutputData);
}


193 194 195 196 197 198 199
Handle<AccessorPair> Factory::NewAccessorPair() {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateAccessorPair(),
                     AccessorPair);
}


200 201 202 203 204 205 206
Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateTypeFeedbackInfo(),
                     TypeFeedbackInfo);
}


207 208
// Internalized strings are created in the old generation (data space).
Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
209
  CALL_HEAP_FUNCTION(isolate(),
210
                     isolate()->heap()->InternalizeUtf8String(string),
211
                     String);
212 213
}

214

215 216
// Internalized strings are created in the old generation (data space).
Handle<String> Factory::InternalizeString(Handle<String> string) {
217
  CALL_HEAP_FUNCTION(isolate(),
218
                     isolate()->heap()->InternalizeString(*string),
219 220 221
                     String);
}

222

223
Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
224
  CALL_HEAP_FUNCTION(isolate(),
225
                     isolate()->heap()->InternalizeOneByteString(string),
226
                     String);
227 228
}

229

230 231
Handle<String> Factory::InternalizeOneByteString(
    Handle<SeqOneByteString> string, int from, int length) {
232
  CALL_HEAP_FUNCTION(isolate(),
233 234
                     isolate()->heap()->InternalizeOneByteString(
                         string, from, length),
235 236 237 238
                     String);
}


239
Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
240
  CALL_HEAP_FUNCTION(isolate(),
241
                     isolate()->heap()->InternalizeTwoByteString(string),
242
                     String);
243 244
}

245

246 247
Handle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
                                             PretenureFlag pretenure) {
248 249
  CALL_HEAP_FUNCTION(
      isolate(),
250
      isolate()->heap()->AllocateStringFromOneByte(string, pretenure),
251
      String);
252 253 254
}

Handle<String> Factory::NewStringFromUtf8(Vector<const char> string,
255
                                          PretenureFlag pretenure) {
256 257
  CALL_HEAP_FUNCTION(
      isolate(),
258
      isolate()->heap()->AllocateStringFromUtf8(string, pretenure),
259
      String);
260 261 262
}


263 264
Handle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
                                             PretenureFlag pretenure) {
265 266 267 268
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateStringFromTwoByte(string, pretenure),
      String);
269 270 271
}


272
Handle<SeqOneByteString> Factory::NewRawOneByteString(int length,
273
                                                  PretenureFlag pretenure) {
274 275
  CALL_HEAP_FUNCTION(
      isolate(),
276
      isolate()->heap()->AllocateRawOneByteString(length, pretenure),
277
      SeqOneByteString);
278 279 280
}


281 282
Handle<SeqTwoByteString> Factory::NewRawTwoByteString(int length,
                                                      PretenureFlag pretenure) {
283 284 285
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
286
      SeqTwoByteString);
287 288 289
}


290 291 292 293 294
Handle<String> Factory::NewConsString(Handle<String> first,
                                      Handle<String> second) {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateConsString(*first, *second),
                     String);
295 296 297
}


298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
template<typename SinkChar, typename StringType>
Handle<String> ConcatStringContent(Handle<StringType> result,
                                   Handle<String> first,
                                   Handle<String> second) {
  DisallowHeapAllocation pointer_stays_valid;
  SinkChar* sink = result->GetChars();
  String::WriteToFlat(*first, sink, 0, first->length());
  String::WriteToFlat(*second, sink + first->length(), 0, second->length());
  return result;
}


Handle<String> Factory::NewFlatConcatString(Handle<String> first,
                                            Handle<String> second) {
  int total_length = first->length() + second->length();
313
  if (first->IsOneByteRepresentation() && second->IsOneByteRepresentation()) {
314 315 316 317 318 319 320 321 322
    return ConcatStringContent<uint8_t>(
        NewRawOneByteString(total_length), first, second);
  } else {
    return ConcatStringContent<uc16>(
        NewRawTwoByteString(total_length), first, second);
  }
}


323 324 325
Handle<String> Factory::NewSubString(Handle<String> str,
                                     int begin,
                                     int end) {
326
  CALL_HEAP_FUNCTION(isolate(),
327 328
                     str->SubString(begin, end),
                     String);
329 330 331
}


332
Handle<String> Factory::NewProperSubString(Handle<String> str,
333 334 335
                                           int begin,
                                           int end) {
  ASSERT(begin > 0 || end < str->length());
336 337 338
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateSubString(*str, begin, end),
                     String);
339 340 341
}


342
Handle<String> Factory::NewExternalStringFromAscii(
343
    const ExternalAsciiString::Resource* resource) {
344 345 346 347
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateExternalStringFromAscii(resource),
      String);
348 349 350 351
}


Handle<String> Factory::NewExternalStringFromTwoByte(
352
    const ExternalTwoByteString::Resource* resource) {
353 354 355 356
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateExternalStringFromTwoByte(resource),
      String);
357 358 359
}


360 361 362 363 364 365 366 367
Handle<Symbol> Factory::NewSymbol() {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateSymbol(),
      Symbol);
}


368 369 370 371 372 373 374 375
Handle<Symbol> Factory::NewPrivateSymbol() {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocatePrivateSymbol(),
      Symbol);
}


376
Handle<Context> Factory::NewNativeContext() {
377 378
  CALL_HEAP_FUNCTION(
      isolate(),
379
      isolate()->heap()->AllocateNativeContext(),
380
      Context);
381 382 383
}


384 385 386 387 388 389 390 391 392
Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
                                          Handle<ScopeInfo> scope_info) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateGlobalContext(*function, *scope_info),
      Context);
}


393
Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
394 395
  CALL_HEAP_FUNCTION(
      isolate(),
396
      isolate()->heap()->AllocateModuleContext(*scope_info),
397 398 399 400
      Context);
}


401
Handle<Context> Factory::NewFunctionContext(int length,
402
                                            Handle<JSFunction> function) {
403 404
  CALL_HEAP_FUNCTION(
      isolate(),
405
      isolate()->heap()->AllocateFunctionContext(length, *function),
406
      Context);
407 408 409
}


410 411
Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
                                         Handle<Context> previous,
412 413
                                         Handle<String> name,
                                         Handle<Object> thrown_object) {
414 415
  CALL_HEAP_FUNCTION(
      isolate(),
416 417 418 419
      isolate()->heap()->AllocateCatchContext(*function,
                                              *previous,
                                              *name,
                                              *thrown_object),
420 421 422 423
      Context);
}


424 425
Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
                                        Handle<Context> previous,
426
                                        Handle<JSObject> extension) {
427 428
  CALL_HEAP_FUNCTION(
      isolate(),
429
      isolate()->heap()->AllocateWithContext(*function, *previous, *extension),
430
      Context);
431 432 433
}


434 435 436
Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
                                         Handle<Context> previous,
                                         Handle<ScopeInfo> scope_info) {
437 438 439 440 441 442 443 444 445
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateBlockContext(*function,
                                              *previous,
                                              *scope_info),
      Context);
}


446
Handle<Struct> Factory::NewStruct(InstanceType type) {
447 448 449 450
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateStruct(type),
      Struct);
451 452 453
}


454 455 456 457 458 459 460 461 462
Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
    int aliased_context_slot) {
  Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
      NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
  entry->set_aliased_context_slot(aliased_context_slot);
  return entry;
}


463 464 465 466 467 468
Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
  return Handle<DeclaredAccessorDescriptor>::cast(
      NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
}


469 470 471 472 473 474 475 476 477 478 479 480 481
Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
  Handle<DeclaredAccessorInfo> info =
      Handle<DeclaredAccessorInfo>::cast(
          NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
  info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
  return info;
}


Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
  Handle<ExecutableAccessorInfo> info =
      Handle<ExecutableAccessorInfo>::cast(
          NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
482 483 484 485 486 487
  info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
  return info;
}


Handle<Script> Factory::NewScript(Handle<String> source) {
488
  // Generate id for this script.
489
  Heap* heap = isolate()->heap();
490 491 492
  int id = heap->last_script_id()->value() + 1;
  if (!Smi::IsValid(id) || id < 0) id = 1;
  heap->set_last_script_id(Smi::FromInt(id));
493

494
  // Create and initialize script object.
495
  Handle<Foreign> wrapper = NewForeign(0, TENURED);
496 497
  Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
  script->set_source(*source);
498
  script->set_name(heap->undefined_value());
499
  script->set_id(Smi::FromInt(id));
500 501
  script->set_line_offset(Smi::FromInt(0));
  script->set_column_offset(Smi::FromInt(0));
502 503
  script->set_data(heap->undefined_value());
  script->set_context_data(heap->undefined_value());
504
  script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
505
  script->set_wrapper(*wrapper);
506 507
  script->set_line_ends(heap->undefined_value());
  script->set_eval_from_shared(heap->undefined_value());
508
  script->set_eval_from_instructions_offset(Smi::FromInt(0));
509
  script->set_flags(Smi::FromInt(0));
510

511 512 513 514
  return script;
}


515
Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
516
  CALL_HEAP_FUNCTION(isolate(),
517 518
                     isolate()->heap()->AllocateForeign(addr, pretenure),
                     Foreign);
519 520 521
}


522 523
Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
  return NewForeign((Address) desc, TENURED);
524 525 526
}


527
Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
528
  ASSERT(0 <= length);
529 530 531 532
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateByteArray(length, pretenure),
      ByteArray);
533 534 535
}


536 537 538 539 540
Handle<ExternalArray> Factory::NewExternalArray(int length,
                                                ExternalArrayType array_type,
                                                void* external_pointer,
                                                PretenureFlag pretenure) {
  ASSERT(0 <= length);
541 542 543 544 545 546 547
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateExternalArray(length,
                                               array_type,
                                               external_pointer,
                                               pretenure),
      ExternalArray);
548 549 550
}


551 552 553 554 555 556 557 558 559
Handle<Cell> Factory::NewCell(Handle<Object> value) {
  AllowDeferredHandleDereference convert_to_cell;
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateCell(*value),
      Cell);
}


560
Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
561 562
  CALL_HEAP_FUNCTION(
      isolate(),
563
      isolate()->heap()->AllocatePropertyCell(),
564
      PropertyCell);
565 566 567
}


568 569 570 571 572 573 574 575
Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
  AllowDeferredHandleDereference convert_to_cell;
  Handle<PropertyCell> cell = NewPropertyCellWithHole();
  PropertyCell::SetValueInferType(cell, value);
  return cell;
}


576 577 578 579 580 581 582 583
Handle<AllocationSite> Factory::NewAllocationSite() {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateAllocationSite(),
      AllocationSite);
}


584 585 586
Handle<Map> Factory::NewMap(InstanceType type,
                            int instance_size,
                            ElementsKind elements_kind) {
587 588
  CALL_HEAP_FUNCTION(
      isolate(),
589
      isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
590
      Map);
591 592 593 594
}


Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
  // Make sure to use globals from the function's context, since the function
  // can be from a different context.
  Handle<Context> native_context(function->context()->native_context());
  Handle<Map> new_map;
  if (function->shared()->is_generator()) {
    // Generator prototypes can share maps since they don't have "constructor"
    // properties.
    new_map = handle(native_context->generator_object_prototype_map());
  } else {
    // Each function prototype gets a fresh map to avoid unwanted sharing of
    // maps between prototypes of different constructors.
    Handle<JSFunction> object_function(native_context->object_function());
    ASSERT(object_function->has_initial_map());
    new_map = Map::Copy(handle(object_function->initial_map()));
  }

  Handle<JSObject> prototype = NewJSObjectFromMap(new_map);

  if (!function->shared()->is_generator()) {
    JSObject::SetLocalPropertyIgnoreAttributes(prototype,
                                               constructor_string(),
                                               function,
                                               DONT_ENUM);
  }

  return prototype;
621 622 623
}


624 625 626
Handle<Map> Factory::CopyWithPreallocatedFieldDescriptors(Handle<Map> src) {
  CALL_HEAP_FUNCTION(
      isolate(), src->CopyWithPreallocatedFieldDescriptors(), Map);
627 628 629
}


630 631
Handle<Map> Factory::CopyMap(Handle<Map> src,
                             int extra_inobject_properties) {
632
  Handle<Map> copy = CopyWithPreallocatedFieldDescriptors(src);
633 634 635 636 637
  // Check that we do not overflow the instance size when adding the
  // extra inobject properties.
  int instance_size_delta = extra_inobject_properties * kPointerSize;
  int max_instance_size_delta =
      JSObject::kMaxInstanceSize - copy->instance_size();
638 639
  int max_extra_properties = max_instance_size_delta >> kPointerSizeLog2;
  if (extra_inobject_properties > max_extra_properties) {
640 641 642
    // If the instance size overflows, we allocate as many properties
    // as we can as inobject properties.
    instance_size_delta = max_instance_size_delta;
643
    extra_inobject_properties = max_extra_properties;
644 645 646 647 648 649 650
  }
  // Adjust the map with the extra inobject properties.
  int inobject_properties =
      copy->inobject_properties() + extra_inobject_properties;
  copy->set_inobject_properties(inobject_properties);
  copy->set_unused_property_fields(inobject_properties);
  copy->set_instance_size(copy->instance_size() + instance_size_delta);
651
  copy->set_visitor_id(StaticVisitorBase::GetVisitorId(*copy));
652 653 654
  return copy;
}

655

656
Handle<Map> Factory::CopyMap(Handle<Map> src) {
657
  CALL_HEAP_FUNCTION(isolate(), src->Copy(), Map);
658 659 660
}


661
Handle<Map> Factory::GetElementsTransitionMap(
662 663
    Handle<JSObject> src,
    ElementsKind elements_kind) {
664 665 666
  Isolate* i = isolate();
  CALL_HEAP_FUNCTION(i,
                     src->GetElementsTransitionMap(i, elements_kind),
667
                     Map);
668 669 670
}


671
Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
672
  CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedArray);
673 674 675
}


676
Handle<FixedArray> Factory::CopySizeFixedArray(Handle<FixedArray> array,
677 678 679 680 681
                                               int new_length,
                                               PretenureFlag pretenure) {
  CALL_HEAP_FUNCTION(isolate(),
                     array->CopySize(new_length, pretenure),
                     FixedArray);
682 683 684
}


685 686 687 688 689 690
Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
    Handle<FixedDoubleArray> array) {
  CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedDoubleArray);
}


691 692 693 694 695 696
Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
    Handle<ConstantPoolArray> array) {
  CALL_HEAP_FUNCTION(isolate(), array->Copy(), ConstantPoolArray);
}


697 698
Handle<JSFunction> Factory::BaseNewFunctionFromSharedFunctionInfo(
    Handle<SharedFunctionInfo> function_info,
699 700
    Handle<Map> function_map,
    PretenureFlag pretenure) {
701 702 703 704 705 706
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateFunction(*function_map,
                                          *function_info,
                                          isolate()->heap()->the_hole_value(),
                                          pretenure),
707 708 709 710
                     JSFunction);
}


711 712 713 714 715 716 717 718 719
static Handle<Map> MapForNewFunction(Isolate *isolate,
                                     Handle<SharedFunctionInfo> function_info) {
  Context *context = isolate->context()->native_context();
  int map_index = Context::FunctionMapIndex(function_info->language_mode(),
                                            function_info->is_generator());
  return Handle<Map>(Map::cast(context->get(map_index)));
}


720 721
Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
    Handle<SharedFunctionInfo> function_info,
722 723
    Handle<Context> context,
    PretenureFlag pretenure) {
724
  Handle<JSFunction> result = BaseNewFunctionFromSharedFunctionInfo(
725
      function_info,
726
      MapForNewFunction(isolate(), function_info),
727 728
      pretenure);

729 730 731 732
  if (function_info->ic_age() != isolate()->heap()->global_ic_age()) {
    function_info->ResetForNewContext(isolate()->heap()->global_ic_age());
  }

733
  result->set_context(*context);
734

735
  int index = function_info->SearchOptimizedCodeMap(context->native_context());
736 737 738 739
  if (!function_info->bound() && index < 0) {
    int number_of_literals = function_info->num_literals();
    Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
    if (number_of_literals > 0) {
740
      // Store the native context in the literals array prefix. This
741 742
      // context will be used when creating object, regexp and array
      // literals in this function.
743 744
      literals->set(JSFunction::kLiteralNativeContextIndex,
                    context->native_context());
745
    }
746
    result->set_literals(*literals);
747
  }
748 749 750

  if (index > 0) {
    // Caching of optimized code enabled and optimized code found.
751
    function_info->InstallFromOptimizedCodeMap(*result, index);
752 753 754
    return result;
  }

755
  if (isolate()->use_crankshaft() &&
756 757 758
      FLAG_always_opt &&
      result->is_compiled() &&
      !function_info->is_toplevel() &&
759
      function_info->allows_lazy_compilation() &&
760 761
      !function_info->optimization_disabled() &&
      !isolate()->DebuggerHasBreakPoints()) {
762
    result->MarkForLazyRecompilation();
763
  }
764 765 766 767 768 769
  return result;
}


Handle<Object> Factory::NewNumber(double value,
                                  PretenureFlag pretenure) {
770 771 772
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->NumberFromDouble(value, pretenure), Object);
773 774 775
}


776 777
Handle<Object> Factory::NewNumberFromInt(int32_t value,
                                         PretenureFlag pretenure) {
778 779
  CALL_HEAP_FUNCTION(
      isolate(),
780
      isolate()->heap()->NumberFromInt32(value, pretenure), Object);
781 782 783
}


784 785
Handle<Object> Factory::NewNumberFromUint(uint32_t value,
                                         PretenureFlag pretenure) {
786 787
  CALL_HEAP_FUNCTION(
      isolate(),
788
      isolate()->heap()->NumberFromUint32(value, pretenure), Object);
789 790 791
}


792 793 794 795 796 797 798 799
Handle<HeapNumber> Factory::NewHeapNumber(double value,
                                          PretenureFlag pretenure) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateHeapNumber(value, pretenure), HeapNumber);
}


800
Handle<JSObject> Factory::NewNeanderObject() {
801 802 803 804 805
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSObjectFromMap(
          isolate()->heap()->neander_map()),
      JSObject);
806 807 808
}


809
Handle<Object> Factory::NewTypeError(const char* message,
810
                                     Vector< Handle<Object> > args) {
811
  return NewError("MakeTypeError", message, args);
812 813 814 815 816 817 818 819
}


Handle<Object> Factory::NewTypeError(Handle<String> message) {
  return NewError("$TypeError", message);
}


820
Handle<Object> Factory::NewRangeError(const char* message,
821
                                      Vector< Handle<Object> > args) {
822
  return NewError("MakeRangeError", message, args);
823 824 825 826 827 828 829 830
}


Handle<Object> Factory::NewRangeError(Handle<String> message) {
  return NewError("$RangeError", message);
}


831 832 833
Handle<Object> Factory::NewSyntaxError(const char* message,
                                       Handle<JSArray> args) {
  return NewError("MakeSyntaxError", message, args);
834 835 836 837 838 839 840 841
}


Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
  return NewError("$SyntaxError", message);
}


842
Handle<Object> Factory::NewReferenceError(const char* message,
843
                                          Vector< Handle<Object> > args) {
844
  return NewError("MakeReferenceError", message, args);
845 846 847 848 849 850 851 852
}


Handle<Object> Factory::NewReferenceError(Handle<String> message) {
  return NewError("$ReferenceError", message);
}


853
Handle<Object> Factory::NewError(const char* maker,
854
                                 const char* message,
855 856 857
                                 Vector< Handle<Object> > args) {
  // Instantiate a closeable HandleScope for EscapeFrom.
  v8::HandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
858
  Handle<FixedArray> array = NewFixedArray(args.length());
859 860 861
  for (int i = 0; i < args.length(); i++) {
    array->set(i, *args[i]);
  }
862
  Handle<JSArray> object = NewJSArrayWithElements(array);
863
  Handle<Object> result = NewError(maker, message, object);
864 865 866 867
  return result.EscapeFrom(&scope);
}


868
Handle<Object> Factory::NewEvalError(const char* message,
869
                                     Vector< Handle<Object> > args) {
870
  return NewError("MakeEvalError", message, args);
871 872 873
}


874
Handle<Object> Factory::NewError(const char* message,
875
                                 Vector< Handle<Object> > args) {
876
  return NewError("MakeError", message, args);
877 878 879
}


880
Handle<String> Factory::EmergencyNewError(const char* message,
881 882 883 884 885 886 887
                                          Handle<JSArray> args) {
  const int kBufferSize = 1000;
  char buffer[kBufferSize];
  size_t space = kBufferSize;
  char* p = &buffer[0];

  Vector<char> v(buffer, kBufferSize);
888 889
  OS::StrNCpy(v, message, space);
  space -= Min(space, strlen(message));
890 891 892 893 894 895 896
  p = &buffer[kBufferSize] - space;

  for (unsigned i = 0; i < ARRAY_SIZE(args); i++) {
    if (space > 0) {
      *p++ = ' ';
      space--;
      if (space > 0) {
897
        MaybeObject* maybe_arg = args->GetElement(isolate(), i);
898 899
        Handle<String> arg_str(reinterpret_cast<String*>(maybe_arg));
        const char* arg = *arg_str->ToCString();
900
        Vector<char> v2(p, static_cast<int>(space));
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
        OS::StrNCpy(v2, arg, space);
        space -= Min(space, strlen(arg));
        p = &buffer[kBufferSize] - space;
      }
    }
  }
  if (space > 0) {
    *p = '\0';
  } else {
    buffer[kBufferSize - 1] = '\0';
  }
  Handle<String> error_string = NewStringFromUtf8(CStrVector(buffer), TENURED);
  return error_string;
}


917
Handle<Object> Factory::NewError(const char* maker,
918
                                 const char* message,
919
                                 Handle<JSArray> args) {
920
  Handle<String> make_str = InternalizeUtf8String(maker);
921
  Handle<Object> fun_obj(
922 923
      isolate()->js_builtins_object()->GetPropertyNoExceptionThrown(*make_str),
      isolate());
924 925
  // If the builtins haven't been properly configured yet this error
  // constructor may not have been defined.  Bail out.
926
  if (!fun_obj->IsJSFunction()) {
927
    return EmergencyNewError(message, args);
928
  }
929
  Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
930 931
  Handle<Object> message_obj = InternalizeUtf8String(message);
  Handle<Object> argv[] = { message_obj, args };
932 933 934 935 936

  // Invoke the JavaScript factory method. If an exception is thrown while
  // running the factory method, use the exception as the result.
  bool caught_exception;
  Handle<Object> result = Execution::TryCall(fun,
937 938 939 940
                                             isolate()->js_builtins_object(),
                                             ARRAY_SIZE(argv),
                                             argv,
                                             &caught_exception);
941 942 943 944 945 946 947 948 949 950 951
  return result;
}


Handle<Object> Factory::NewError(Handle<String> message) {
  return NewError("$Error", message);
}


Handle<Object> Factory::NewError(const char* constructor,
                                 Handle<String> message) {
952
  Handle<String> constr = InternalizeUtf8String(constructor);
953 954 955
  Handle<JSFunction> fun = Handle<JSFunction>(
      JSFunction::cast(isolate()->js_builtins_object()->
                       GetPropertyNoExceptionThrown(*constr)));
956
  Handle<Object> argv[] = { message };
957 958 959 960 961

  // Invoke the JavaScript factory method. If an exception is thrown while
  // running the factory method, use the exception as the result.
  bool caught_exception;
  Handle<Object> result = Execution::TryCall(fun,
962 963 964 965
                                             isolate()->js_builtins_object(),
                                             ARRAY_SIZE(argv),
                                             argv,
                                             &caught_exception);
966 967 968 969 970 971 972 973 974 975 976
  return result;
}


Handle<JSFunction> Factory::NewFunction(Handle<String> name,
                                        InstanceType type,
                                        int instance_size,
                                        Handle<Code> code,
                                        bool force_initial_map) {
  // Allocate the function
  Handle<JSFunction> function = NewFunction(name, the_hole_value());
977

978
  // Set up the code pointer in both the shared function info and in
979 980
  // the function itself.
  function->shared()->set_code(*code);
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
  function->set_code(*code);

  if (force_initial_map ||
      type != JS_OBJECT_TYPE ||
      instance_size != JSObject::kHeaderSize) {
    Handle<Map> initial_map = NewMap(type, instance_size);
    Handle<JSObject> prototype = NewFunctionPrototype(function);
    initial_map->set_prototype(*prototype);
    function->set_initial_map(*initial_map);
    initial_map->set_constructor(*function);
  } else {
    ASSERT(!function->has_initial_map());
    ASSERT(!function->has_prototype());
  }

  return function;
}


Handle<JSFunction> Factory::NewFunctionWithPrototype(Handle<String> name,
                                                     InstanceType type,
                                                     int instance_size,
                                                     Handle<JSObject> prototype,
                                                     Handle<Code> code,
                                                     bool force_initial_map) {
1006
  // Allocate the function.
1007 1008
  Handle<JSFunction> function = NewFunction(name, prototype);

1009
  // Set up the code pointer in both the shared function info and in
1010 1011
  // the function itself.
  function->shared()->set_code(*code);
1012 1013 1014 1015 1016
  function->set_code(*code);

  if (force_initial_map ||
      type != JS_OBJECT_TYPE ||
      instance_size != JSObject::kHeaderSize) {
1017 1018
    Handle<Map> initial_map = NewMap(type,
                                     instance_size,
1019
                                     GetInitialFastElementsKind());
1020 1021 1022 1023
    function->set_initial_map(*initial_map);
    initial_map->set_constructor(*function);
  }

1024
  JSFunction::SetPrototype(function, prototype);
1025 1026 1027
  return function;
}

1028

1029 1030
Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
                                                        Handle<Code> code) {
1031
  Handle<JSFunction> function = NewFunctionWithoutPrototype(name,
1032
                                                            CLASSIC_MODE);
1033
  function->shared()->set_code(*code);
1034 1035 1036 1037 1038 1039 1040
  function->set_code(*code);
  ASSERT(!function->has_initial_map());
  ASSERT(!function->has_prototype());
  return function;
}


1041
Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1042 1043
  CALL_HEAP_FUNCTION(
      isolate(),
1044 1045
      isolate()->heap()->AllocateScopeInfo(length),
      ScopeInfo);
1046 1047 1048
}


1049 1050 1051 1052 1053 1054 1055
Handle<JSObject> Factory::NewExternal(void* value) {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateExternal(value),
                     JSObject);
}


1056 1057
Handle<Code> Factory::NewCode(const CodeDesc& desc,
                              Code::Flags flags,
1058
                              Handle<Object> self_ref,
1059
                              bool immovable,
1060 1061
                              bool crankshafted,
                              int prologue_offset) {
1062 1063
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->CreateCode(
1064 1065
                         desc, flags, self_ref, immovable, crankshafted,
                         prologue_offset),
1066
                     Code);
1067 1068 1069 1070
}


Handle<Code> Factory::CopyCode(Handle<Code> code) {
1071 1072 1073
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->CopyCode(*code),
                     Code);
1074 1075 1076
}


1077
Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1078 1079 1080
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->CopyCode(*code, reloc_info),
                     Code);
1081 1082 1083
}


1084
Handle<String> Factory::InternalizedStringFromString(Handle<String> value) {
1085
  CALL_HEAP_FUNCTION(isolate(),
1086
                     isolate()->heap()->InternalizeString(*value), String);
1087 1088 1089 1090 1091
}


Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
                                      PretenureFlag pretenure) {
1092
  JSFunction::EnsureHasInitialMap(constructor);
1093 1094 1095
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1096 1097 1098
}


1099 1100
Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
                                      Handle<ScopeInfo> scope_info) {
1101 1102
  CALL_HEAP_FUNCTION(
      isolate(),
1103
      isolate()->heap()->AllocateJSModule(*context, *scope_info), JSModule);
1104 1105 1106
}


1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
// TODO(mstarzinger): Temporary wrapper until handlified.
static Handle<NameDictionary> NameDictionaryAdd(Handle<NameDictionary> dict,
                                                Handle<Name> name,
                                                Handle<Object> value,
                                                PropertyDetails details) {
  CALL_HEAP_FUNCTION(dict->GetIsolate(),
                     dict->Add(*name, *value, details),
                     NameDictionary);
}


static Handle<GlobalObject> NewGlobalObjectFromMap(Isolate* isolate,
                                                   Handle<Map> map) {
  CALL_HEAP_FUNCTION(isolate,
                     isolate->heap()->Allocate(*map, OLD_POINTER_SPACE),
1122
                     GlobalObject);
1123 1124 1125
}


1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
  ASSERT(constructor->has_initial_map());
  Handle<Map> map(constructor->initial_map());
  ASSERT(map->is_dictionary_map());

  // Make sure no field properties are described in the initial map.
  // This guarantees us that normalizing the properties does not
  // require us to change property values to PropertyCells.
  ASSERT(map->NextFreePropertyIndex() == 0);

  // Make sure we don't have a ton of pre-allocated slots in the
  // global objects. They will be unused once we normalize the object.
  ASSERT(map->unused_property_fields() == 0);
  ASSERT(map->inobject_properties() == 0);

  // Initial size of the backing store to avoid resize of the storage during
  // bootstrapping. The size differs between the JS global object ad the
  // builtins object.
  int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;

  // Allocate a dictionary object for backing storage.
  int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
  Handle<NameDictionary> dictionary = NewNameDictionary(at_least_space_for);

  // The global object might be created from an object template with accessors.
  // Fill these accessors into the dictionary.
  Handle<DescriptorArray> descs(map->instance_descriptors());
  for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
    PropertyDetails details = descs->GetDetails(i);
    ASSERT(details.type() == CALLBACKS);  // Only accessors are expected.
    PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
    Handle<Name> name(descs->GetKey(i));
    Handle<Object> value(descs->GetCallbacksObject(i), isolate());
    Handle<PropertyCell> cell = NewPropertyCell(value);
    NameDictionaryAdd(dictionary, name, cell, d);
  }

  // Allocate the global object and initialize it with the backing store.
  Handle<GlobalObject> global = NewGlobalObjectFromMap(isolate(), map);
  isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);

  // Create a new map for the global object.
  Handle<Map> new_map = Map::CopyDropDescriptors(map);
  new_map->set_dictionary_map(true);

  // Set up the global object as a normalized object.
  global->set_map(*new_map);
  global->set_properties(*dictionary);

  // Make sure result is a global object with properties in dictionary.
  ASSERT(global->IsGlobalObject() && !global->HasFastProperties());
  return global;
}

1180

1181
Handle<JSObject> Factory::NewJSObjectFromMap(Handle<Map> map,
1182 1183
                                             PretenureFlag pretenure,
                                             bool alloc_props) {
1184 1185
  CALL_HEAP_FUNCTION(
      isolate(),
1186
      isolate()->heap()->AllocateJSObjectFromMap(*map, pretenure, alloc_props),
1187
      JSObject);
1188 1189 1190
}


1191
Handle<JSArray> Factory::NewJSArray(int capacity,
1192
                                    ElementsKind elements_kind,
1193
                                    PretenureFlag pretenure) {
1194 1195 1196
  if (capacity != 0) {
    elements_kind = GetHoleyElementsKind(elements_kind);
  }
1197
  CALL_HEAP_FUNCTION(isolate(),
1198 1199 1200 1201 1202 1203
                     isolate()->heap()->AllocateJSArrayAndStorage(
                         elements_kind,
                         0,
                         capacity,
                         INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE,
                         pretenure),
1204
                     JSArray);
1205 1206 1207
}


1208
Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1209
                                                ElementsKind elements_kind,
1210
                                                PretenureFlag pretenure) {
1211 1212 1213 1214
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSArrayWithElements(*elements,
                                                     elements_kind,
1215
                                                     elements->length(),
1216 1217
                                                     pretenure),
      JSArray);
1218 1219 1220
}


1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
void Factory::SetElementsCapacityAndLength(Handle<JSArray> array,
                                           int capacity,
                                           int length) {
  ElementsAccessor* accessor = array->GetElementsAccessor();
  CALL_HEAP_FUNCTION_VOID(
      isolate(),
      accessor->SetCapacityAndLength(*array, capacity, length));
}


1231
void Factory::SetContent(Handle<JSArray> array,
1232
                         Handle<FixedArrayBase> elements) {
1233 1234 1235 1236 1237 1238
  CALL_HEAP_FUNCTION_VOID(
      isolate(),
      array->SetContent(*elements));
}


1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
    Handle<JSFunction> function) {
  ASSERT(function->shared()->is_generator());
  JSFunction::EnsureHasInitialMap(function);
  Handle<Map> map(function->initial_map());
  ASSERT(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSObjectFromMap(*map),
      JSGeneratorObject);
}


1252
Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1253 1254
  Handle<JSFunction> array_buffer_fun(
      isolate()->context()->native_context()->array_buffer_fun());
1255 1256
  CALL_HEAP_FUNCTION(
      isolate(),
1257
      isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1258 1259 1260 1261
      JSArrayBuffer);
}


1262
Handle<JSDataView> Factory::NewJSDataView() {
1263 1264
  Handle<JSFunction> data_view_fun(
      isolate()->context()->native_context()->data_view_fun());
1265 1266
  CALL_HEAP_FUNCTION(
      isolate(),
1267
      isolate()->heap()->AllocateJSObject(*data_view_fun),
1268 1269 1270 1271
      JSDataView);
}


1272 1273 1274
static JSFunction* GetTypedArrayFun(ExternalArrayType type,
                                    Isolate* isolate) {
  Context* native_context = isolate->context()->native_context();
1275 1276
  switch (type) {
    case kExternalUnsignedByteArray:
1277
      return native_context->uint8_array_fun();
1278 1279

    case kExternalByteArray:
1280
      return native_context->int8_array_fun();
1281 1282

    case kExternalUnsignedShortArray:
1283
      return native_context->uint16_array_fun();
1284 1285

    case kExternalShortArray:
1286
      return native_context->int16_array_fun();
1287 1288

    case kExternalUnsignedIntArray:
1289
      return native_context->uint32_array_fun();
1290 1291

    case kExternalIntArray:
1292
      return native_context->int32_array_fun();
1293 1294

    case kExternalFloatArray:
1295
      return native_context->float_array_fun();
1296 1297

    case kExternalDoubleArray:
1298
      return native_context->double_array_fun();
1299

1300
    case kExternalPixelArray:
1301
      return native_context->uint8c_array_fun();
1302

1303 1304
    default:
      UNREACHABLE();
1305
      return NULL;
1306
  }
1307 1308 1309 1310 1311
}


Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
  Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1312 1313 1314

  CALL_HEAP_FUNCTION(
      isolate(),
1315
      isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1316 1317 1318 1319
      JSTypedArray);
}


1320 1321 1322 1323 1324 1325 1326 1327 1328
Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
                                    Handle<Object> prototype) {
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateJSProxy(*handler, *prototype),
      JSProxy);
}


1329
void Factory::BecomeJSObject(Handle<JSReceiver> object) {
1330 1331
  CALL_HEAP_FUNCTION_VOID(
      isolate(),
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
      isolate()->heap()->ReinitializeJSReceiver(
          *object, JS_OBJECT_TYPE, JSObject::kHeaderSize));
}


void Factory::BecomeJSFunction(Handle<JSReceiver> object) {
  CALL_HEAP_FUNCTION_VOID(
      isolate(),
      isolate()->heap()->ReinitializeJSReceiver(
          *object, JS_FUNCTION_TYPE, JSFunction::kSize));
1342 1343 1344
}


1345
Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1346 1347
    Handle<String> name,
    int number_of_literals,
1348
    bool is_generator,
1349
    Handle<Code> code,
1350
    Handle<ScopeInfo> scope_info) {
1351 1352
  Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name);
  shared->set_code(*code);
1353
  shared->set_scope_info(*scope_info);
1354 1355 1356 1357 1358 1359 1360 1361
  int literals_array_size = number_of_literals;
  // If the function contains object, regexp or array literals,
  // allocate extra space for a literals array prefix containing the
  // context.
  if (number_of_literals > 0) {
    literals_array_size += JSFunction::kLiteralsPrefixSize;
  }
  shared->set_num_literals(literals_array_size);
1362 1363
  if (is_generator) {
    shared->set_instance_class_name(isolate()->heap()->Generator_string());
1364
    shared->DisableOptimization(kGenerator);
1365
  }
1366 1367 1368 1369
  return shared;
}


1370 1371 1372 1373 1374 1375 1376 1377
Handle<JSMessageObject> Factory::NewJSMessageObject(
    Handle<String> type,
    Handle<JSArray> arguments,
    int start_position,
    int end_position,
    Handle<Object> script,
    Handle<Object> stack_trace,
    Handle<Object> stack_frames) {
1378 1379 1380 1381 1382 1383 1384 1385
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateJSMessageObject(*type,
                         *arguments,
                         start_position,
                         end_position,
                         *script,
                         *stack_trace,
                         *stack_frames),
1386 1387 1388
                     JSMessageObject);
}

1389

1390
Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(Handle<String> name) {
1391 1392
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateSharedFunctionInfo(*name),
1393 1394 1395 1396
                     SharedFunctionInfo);
}


1397
Handle<String> Factory::NumberToString(Handle<Object> number) {
1398 1399
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->NumberToString(*number), String);
1400 1401 1402
}


1403 1404 1405 1406 1407 1408
Handle<String> Factory::Uint32ToString(uint32_t value) {
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->Uint32ToString(value), String);
}


1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
Handle<SeededNumberDictionary> Factory::DictionaryAtNumberPut(
    Handle<SeededNumberDictionary> dictionary,
    uint32_t key,
    Handle<Object> value) {
  CALL_HEAP_FUNCTION(isolate(),
                     dictionary->AtNumberPut(key, *value),
                     SeededNumberDictionary);
}


Handle<UnseededNumberDictionary> Factory::DictionaryAtNumberPut(
    Handle<UnseededNumberDictionary> dictionary,
1421 1422
    uint32_t key,
    Handle<Object> value) {
1423 1424
  CALL_HEAP_FUNCTION(isolate(),
                     dictionary->AtNumberPut(key, *value),
1425
                     UnseededNumberDictionary);
1426 1427 1428 1429 1430 1431
}


Handle<JSFunction> Factory::NewFunctionHelper(Handle<String> name,
                                              Handle<Object> prototype) {
  Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1432 1433 1434 1435 1436 1437
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateFunction(*isolate()->function_map(),
                                          *function_share,
                                          *prototype),
      JSFunction);
1438 1439 1440 1441 1442 1443
}


Handle<JSFunction> Factory::NewFunction(Handle<String> name,
                                        Handle<Object> prototype) {
  Handle<JSFunction> fun = NewFunctionHelper(name, prototype);
1444
  fun->set_context(isolate()->context()->native_context());
1445 1446 1447 1448
  return fun;
}


1449
Handle<JSFunction> Factory::NewFunctionWithoutPrototypeHelper(
1450
    Handle<String> name,
1451
    LanguageMode language_mode) {
1452
  Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1453 1454 1455
  Handle<Map> map = (language_mode == CLASSIC_MODE)
      ? isolate()->function_without_prototype_map()
      : isolate()->strict_mode_function_without_prototype_map();
1456 1457
  CALL_HEAP_FUNCTION(isolate(),
                     isolate()->heap()->AllocateFunction(
1458
                         *map,
1459 1460 1461 1462 1463 1464
                         *function_share,
                         *the_hole_value()),
                     JSFunction);
}


1465 1466
Handle<JSFunction> Factory::NewFunctionWithoutPrototype(
    Handle<String> name,
1467 1468 1469
    LanguageMode language_mode) {
  Handle<JSFunction> fun =
      NewFunctionWithoutPrototypeHelper(name, language_mode);
1470
  fun->set_context(isolate()->context()->native_context());
1471 1472 1473 1474
  return fun;
}


sgjesse@chromium.org's avatar
sgjesse@chromium.org committed
1475
Handle<Object> Factory::ToObject(Handle<Object> object) {
1476
  CALL_HEAP_FUNCTION(isolate(), object->ToObject(isolate()), Object);
sgjesse@chromium.org's avatar
sgjesse@chromium.org committed
1477 1478 1479
}


1480
Handle<Object> Factory::ToObject(Handle<Object> object,
1481 1482
                                 Handle<Context> native_context) {
  CALL_HEAP_FUNCTION(isolate(), object->ToObject(*native_context), Object);
1483 1484 1485
}


1486
#ifdef ENABLE_DEBUGGER_SUPPORT
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
  // Get the original code of the function.
  Handle<Code> code(shared->code());

  // Create a copy of the code before allocating the debug info object to avoid
  // allocation while setting up the debug info object.
  Handle<Code> original_code(*Factory::CopyCode(code));

  // Allocate initial fixed array for active break points before allocating the
  // debug info object to avoid allocation while setting up the debug info
  // object.
  Handle<FixedArray> break_points(
1499
      NewFixedArray(Debug::kEstimatedNofBreakPointsInFunction));
1500 1501 1502 1503 1504

  // Create and set up the debug info object. Debug info contains function, a
  // copy of the original code, the executing code and initial fixed array for
  // active break points.
  Handle<DebugInfo> debug_info =
1505
      Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
  debug_info->set_shared(*shared);
  debug_info->set_original_code(*original_code);
  debug_info->set_code(*code);
  debug_info->set_break_points(*break_points);

  // Link debug info to function.
  shared->set_debug_info(*debug_info);

  return debug_info;
}
1516
#endif
1517 1518


1519 1520
Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
                                             int length) {
1521 1522 1523
  CALL_HEAP_FUNCTION(
      isolate(),
      isolate()->heap()->AllocateArgumentsObject(*callee, length), JSObject);
1524 1525 1526 1527
}


Handle<JSFunction> Factory::CreateApiFunction(
1528
    Handle<FunctionTemplateInfo> obj, ApiInstanceType instance_type) {
1529 1530
  Handle<Code> code = isolate()->builtins()->HandleApiCall();
  Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
1531

1532 1533 1534 1535 1536 1537 1538 1539 1540
  int internal_field_count = 0;
  if (!obj->instance_template()->IsUndefined()) {
    Handle<ObjectTemplateInfo> instance_template =
        Handle<ObjectTemplateInfo>(
            ObjectTemplateInfo::cast(obj->instance_template()));
    internal_field_count =
        Smi::cast(instance_template->internal_field_count())->value();
  }

1541 1542
  // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
  // JSObject::GetHeaderSize.
1543
  int instance_size = kPointerSize * internal_field_count;
1544
  InstanceType type;
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
  switch (instance_type) {
    case JavaScriptObject:
      type = JS_OBJECT_TYPE;
      instance_size += JSObject::kHeaderSize;
      break;
    case InnerGlobalObject:
      type = JS_GLOBAL_OBJECT_TYPE;
      instance_size += JSGlobalObject::kSize;
      break;
    case OuterGlobalObject:
      type = JS_GLOBAL_PROXY_TYPE;
      instance_size += JSGlobalProxy::kSize;
      break;
    default:
1559 1560
      UNREACHABLE();
      type = JS_OBJECT_TYPE;  // Keep the compiler happy.
1561
      break;
1562 1563 1564
  }

  Handle<JSFunction> result =
1565
      NewFunction(Factory::empty_string(),
1566 1567 1568 1569
                  type,
                  instance_size,
                  code,
                  true);
1570 1571 1572 1573

  // Set length.
  result->shared()->set_length(obj->length());

1574
  // Set class name.
1575
  Handle<Object> class_name = Handle<Object>(obj->class_name(), isolate());
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
  if (class_name->IsString()) {
    result->shared()->set_instance_class_name(*class_name);
    result->shared()->set_name(*class_name);
  }

  Handle<Map> map = Handle<Map>(result->initial_map());

  // Mark as undetectable if needed.
  if (obj->undetectable()) {
    map->set_is_undetectable();
  }

  // Mark as hidden for the __proto__ accessor if needed.
  if (obj->hidden_prototype()) {
    map->set_is_hidden_prototype();
  }

  // Mark as needs_access_check if needed.
  if (obj->needs_access_check()) {
1595
    map->set_is_access_check_needed(true);
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
  }

  // Set interceptor information in the map.
  if (!obj->named_property_handler()->IsUndefined()) {
    map->set_has_named_interceptor();
  }
  if (!obj->indexed_property_handler()->IsUndefined()) {
    map->set_has_indexed_interceptor();
  }

  // Set instance call-as-function information in the map.
  if (!obj->instance_call_handler()->IsUndefined()) {
    map->set_has_instance_call_handler();
  }

  result->shared()->set_function_data(*obj);
1612
  result->shared()->set_construct_stub(*construct_stub);
1613
  result->shared()->DontAdaptArguments();
1614

1615 1616
  // Recursively copy parent instance templates' accessors,
  // 'data' may be modified.
1617
  int max_number_of_additional_properties = 0;
1618
  int max_number_of_static_properties = 0;
1619 1620
  FunctionTemplateInfo* info = *obj;
  while (true) {
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
    if (!info->instance_template()->IsUndefined()) {
      Object* props =
          ObjectTemplateInfo::cast(
              info->instance_template())->property_accessors();
      if (!props->IsUndefined()) {
        Handle<Object> props_handle(props, isolate());
        NeanderArray props_array(props_handle);
        max_number_of_additional_properties += props_array.length();
      }
    }
    if (!info->property_accessors()->IsUndefined()) {
      Object* props = info->property_accessors();
      if (!props->IsUndefined()) {
        Handle<Object> props_handle(props, isolate());
        NeanderArray props_array(props_handle);
        max_number_of_static_properties += props_array.length();
      }
1638 1639 1640 1641 1642 1643 1644 1645
    }
    Object* parent = info->parent_template();
    if (parent->IsUndefined()) break;
    info = FunctionTemplateInfo::cast(parent);
  }

  Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);

1646 1647 1648 1649 1650 1651 1652
  // Use a temporary FixedArray to acculumate static accessors
  int valid_descriptors = 0;
  Handle<FixedArray> array;
  if (max_number_of_static_properties > 0) {
    array = NewFixedArray(max_number_of_static_properties);
  }

1653
  while (true) {
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
    // Install instance descriptors
    if (!obj->instance_template()->IsUndefined()) {
      Handle<ObjectTemplateInfo> instance =
          Handle<ObjectTemplateInfo>(
              ObjectTemplateInfo::cast(obj->instance_template()), isolate());
      Handle<Object> props = Handle<Object>(instance->property_accessors(),
                                            isolate());
      if (!props->IsUndefined()) {
        Map::AppendCallbackDescriptors(map, props);
      }
    }
    // Accumulate static accessors
    if (!obj->property_accessors()->IsUndefined()) {
      Handle<Object> props = Handle<Object>(obj->property_accessors(),
                                            isolate());
      valid_descriptors =
          AccessorInfo::AppendUnique(props, array, valid_descriptors);
1671
    }
1672
    // Climb parent chain
1673
    Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
1674 1675 1676 1677
    if (parent->IsUndefined()) break;
    obj = Handle<FunctionTemplateInfo>::cast(parent);
  }

1678 1679 1680 1681 1682 1683
  // Install accumulated static accessors
  for (int i = 0; i < valid_descriptors; i++) {
    Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
    JSObject::SetAccessor(result, accessor);
  }

1684
  ASSERT(result->shared()->IsApiFunction());
1685 1686 1687 1688
  return result;
}


1689
Handle<MapCache> Factory::NewMapCache(int at_least_space_for) {
1690
  CALL_HEAP_FUNCTION(isolate(),
1691 1692 1693
                     MapCache::Allocate(isolate()->heap(),
                                        at_least_space_for),
                     MapCache);
1694 1695 1696
}


1697 1698 1699 1700 1701 1702 1703 1704 1705
MUST_USE_RESULT static MaybeObject* UpdateMapCacheWith(Context* context,
                                                       FixedArray* keys,
                                                       Map* map) {
  Object* result;
  { MaybeObject* maybe_result =
        MapCache::cast(context->map_cache())->Put(keys, map);
    if (!maybe_result->ToObject(&result)) return maybe_result;
  }
  context->set_map_cache(MapCache::cast(result));
1706 1707 1708 1709 1710 1711 1712
  return result;
}


Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
                                        Handle<FixedArray> keys,
                                        Handle<Map> map) {
1713 1714
  CALL_HEAP_FUNCTION(isolate(),
                     UpdateMapCacheWith(*context, *keys, *map), MapCache);
1715 1716 1717 1718 1719 1720
}


Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
                                               Handle<FixedArray> keys) {
  if (context->map_cache()->IsUndefined()) {
1721
    // Allocate the new map cache for the native context.
1722 1723 1724
    Handle<MapCache> new_cache = NewMapCache(24);
    context->set_map_cache(*new_cache);
  }
1725
  // Check to see whether there is a matching element in the cache.
1726 1727
  Handle<MapCache> cache =
      Handle<MapCache>(MapCache::cast(context->map_cache()));
1728
  Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
1729 1730 1731
  if (result->IsMap()) return Handle<Map>::cast(result);
  // Create a new map and add it to the cache.
  Handle<Map> map =
1732 1733
      CopyMap(Handle<Map>(context->object_function()->initial_map()),
              keys->length());
1734 1735 1736 1737 1738
  AddToMapCache(context, keys, map);
  return Handle<Map>(map);
}


1739 1740 1741 1742 1743 1744 1745
void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
                                JSRegExp::Type type,
                                Handle<String> source,
                                JSRegExp::Flags flags,
                                Handle<Object> data) {
  Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);

1746 1747 1748 1749 1750 1751 1752
  store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
  store->set(JSRegExp::kSourceIndex, *source);
  store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
  store->set(JSRegExp::kAtomPatternIndex, *data);
  regexp->set_data(*store);
}

1753 1754 1755 1756 1757 1758
void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
                                    JSRegExp::Type type,
                                    Handle<String> source,
                                    JSRegExp::Flags flags,
                                    int capture_count) {
  Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
1759
  Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
1760 1761 1762
  store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
  store->set(JSRegExp::kSourceIndex, *source);
  store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1763 1764 1765 1766
  store->set(JSRegExp::kIrregexpASCIICodeIndex, uninitialized);
  store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
  store->set(JSRegExp::kIrregexpASCIICodeSavedIndex, uninitialized);
  store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
1767 1768 1769 1770 1771 1772 1773
  store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
  store->set(JSRegExp::kIrregexpCaptureCountIndex,
             Smi::FromInt(capture_count));
  regexp->set_data(*store);
}


1774

1775 1776 1777 1778 1779
void Factory::ConfigureInstance(Handle<FunctionTemplateInfo> desc,
                                Handle<JSObject> instance,
                                bool* pending_exception) {
  // Configure the instance by adding the properties specified by the
  // instance template.
1780
  Handle<Object> instance_template(desc->instance_template(), isolate());
1781
  if (!instance_template->IsUndefined()) {
1782 1783
    Execution::ConfigureInstance(isolate(),
                                 instance,
1784 1785 1786 1787 1788 1789 1790 1791
                                 instance_template,
                                 pending_exception);
  } else {
    *pending_exception = false;
  }
}


1792 1793
Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
  Heap* h = isolate()->heap();
1794 1795 1796
  if (name->Equals(h->undefined_string())) return undefined_value();
  if (name->Equals(h->nan_string())) return nan_value();
  if (name->Equals(h->infinity_string())) return infinity_value();
1797 1798 1799 1800
  return Handle<Object>::null();
}


1801
Handle<Object> Factory::ToBoolean(bool value) {
1802
  return value ? true_value() : false_value();
1803 1804 1805
}


1806
} }  // namespace v8::internal