builtins.cc 22.5 KB
Newer Older
1
// Copyright 2006-2008 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 31 32 33 34 35 36 37 38 39 40 41 42
// 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"
#include "bootstrapper.h"
#include "builtins.h"
#include "ic-inl.h"

namespace v8 { namespace internal {

// ----------------------------------------------------------------------------
// Support macros for defining builtins in C.
// ----------------------------------------------------------------------------
//
// A builtin function is defined by writing:
//
43
//   BUILTIN(name) {
44 45 46 47
//     ...
//   }
//   BUILTIN_END
//
48 49
// In the body of the builtin function, the variable 'receiver' is visible.
// The arguments can be accessed through:
50 51 52 53 54 55 56 57
//
//   BUILTIN_ARG(0): Receiver (also available as 'receiver')
//   BUILTIN_ARG(1): First argument
//     ...
//   BUILTIN_ARG(n): Last argument
//
// and they evaluate to undefined values if too few arguments were
// passed to the builtin function invocation.
58 59
//
// __argc__ is the number of arguments including the receiver.
60 61 62
// ----------------------------------------------------------------------------


63 64 65
// TODO(1238487): We should consider passing whether or not the
// builtin was invoked as a constructor as part of the
// arguments. Maybe we also want to pass the called function?
66 67 68
#define BUILTIN(name)                                                   \
  static Object* Builtin_##name(int __argc__, Object** __argv__) {      \
    Handle<Object> receiver(&__argv__[0]);
69 70 71 72 73 74


// Use an inline function to avoid evaluating the index (n) more than
// once in the BUILTIN_ARG macro.
static inline Object* __builtin_arg__(int n, int argc, Object** argv) {
  ASSERT(n >= 0);
75
  return (argc > n) ? argv[-n] : Heap::undefined_value();
76 77 78 79 80 81 82 83 84 85 86 87 88
}


// NOTE: Argument 0 is the receiver. The first 'real' argument is
// argument 1 - BUILTIN_ARG(1).
#define BUILTIN_ARG(n) (__builtin_arg__(n, __argc__, __argv__))


#define BUILTIN_END                             \
  return Heap::undefined_value();               \
}


89 90 91 92 93 94 95 96
// TODO(1238487): Get rid of this function that determines if the
// builtin is called as a constructor. This may be a somewhat slow
// operation due to the stack frame iteration.
static inline bool CalledAsConstructor() {
  StackFrameIterator it;
  ASSERT(it.frame()->is_exit());
  it.Advance();
  StackFrame* frame = it.frame();
97
  return frame->is_construct();
98 99 100
}


101 102 103
// ----------------------------------------------------------------------------


104 105 106 107
Handle<Code> Builtins::GetCode(JavaScript id, bool* resolved) {
  Code* code = Builtins::builtin(Builtins::Illegal);
  *resolved = false;

108 109
  if (Top::context() != NULL) {
    Object* object = Top::builtins()->javascript_builtin(id);
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    if (object->IsJSFunction()) {
      Handle<JSFunction> function(JSFunction::cast(object));
      // Make sure the number of parameters match the formal parameter count.
      ASSERT(function->shared()->formal_parameter_count() ==
             Builtins::GetArgumentsCount(id));
      if (function->is_compiled() || CompileLazy(function, CLEAR_EXCEPTION)) {
        code = function->code();
        *resolved = true;
      }
    }
  }

  return Handle<Code>(code);
}


126
BUILTIN(Illegal) {
127 128 129 130 131
  UNREACHABLE();
}
BUILTIN_END


132
BUILTIN(EmptyFunction) {
133 134 135 136
}
BUILTIN_END


137
BUILTIN(ArrayCode) {
138
  JSArray* array;
139
  if (CalledAsConstructor()) {
140 141 142 143 144 145 146 147 148 149 150 151 152 153
    array = JSArray::cast(*receiver);
  } else {
    // Allocate the JS Array
    JSFunction* constructor =
        Top::context()->global_context()->array_function();
    Object* obj = Heap::AllocateJSObject(constructor);
    if (obj->IsFailure()) return obj;
    array = JSArray::cast(obj);
  }

  // 'array' now contains the JSArray we should initialize.

  // Optimize the case where there is one argument and the argument is a
  // small smi.
154
  if (__argc__ == 2) {
155 156 157
    Object* obj = BUILTIN_ARG(1);
    if (obj->IsSmi()) {
      int len = Smi::cast(obj)->value();
158
      if (len >= 0 && len < JSObject::kInitialMaxFastElementArray) {
159 160 161 162 163 164 165 166 167
        Object* obj = Heap::AllocateFixedArrayWithHoles(len);
        if (obj->IsFailure()) return obj;
        array->SetContent(FixedArray::cast(obj));
        return array;
      }
    }
    // Take the argument as the length.
    obj = array->Initialize(0);
    if (obj->IsFailure()) return obj;
168
    if (__argc__ == 2) return array->SetElementsLength(BUILTIN_ARG(1));
169 170
  }

171
  // Optimize the case where there are no parameters passed.
172
  if (__argc__ == 1) return array->Initialize(4);
173 174

  // Take the arguments as elements.
175 176 177
  int number_of_elements = __argc__ - 1;
  Smi* len = Smi::FromInt(number_of_elements);
  Object* obj = Heap::AllocateFixedArrayWithHoles(len->value());
178 179
  if (obj->IsFailure()) return obj;
  FixedArray* elms = FixedArray::cast(obj);
180
  WriteBarrierMode mode = elms->GetWriteBarrierMode();
181
  // Fill in the content
182
  for (int index = 0; index < number_of_elements; index++) {
183 184 185 186 187
    elms->set(index, BUILTIN_ARG(index+1), mode);
  }

  // Set length and elements on the array.
  array->set_elements(FixedArray::cast(obj));
188
  array->set_length(len, SKIP_WRITE_BARRIER);
189 190 191 192 193 194

  return array;
}
BUILTIN_END


195
BUILTIN(ArrayPush) {
196 197 198 199 200 201 202
  JSArray* array = JSArray::cast(*receiver);
  ASSERT(array->HasFastElements());

  // Make sure we have space for the elements.
  int len = Smi::cast(array->length())->value();

  // Set new length.
203
  int new_length = len + __argc__ - 1;
204 205 206 207
  FixedArray* elms = FixedArray::cast(array->elements());

  if (new_length <= elms->length()) {
    // Backing storage has extra space for the provided values.
208
    for (int index = 0; index < __argc__ - 1; index++) {
209 210 211 212 213 214 215 216
      elms->set(index + len, BUILTIN_ARG(index+1));
    }
  } else {
    // New backing storage is needed.
    int capacity = new_length + (new_length >> 1) + 16;
    Object* obj = Heap::AllocateFixedArrayWithHoles(capacity);
    if (obj->IsFailure()) return obj;
    FixedArray* new_elms = FixedArray::cast(obj);
217
    WriteBarrierMode mode = new_elms->GetWriteBarrierMode();
218 219 220
    // Fill out the new array with old elements.
    for (int i = 0; i < len; i++) new_elms->set(i, elms->get(i), mode);
    // Add the provided values.
221
    for (int index = 0; index < __argc__ - 1; index++) {
222 223 224 225 226 227
      new_elms->set(index + len, BUILTIN_ARG(index+1), mode);
    }
    // Set the new backing storage.
    array->set_elements(new_elms);
  }
  // Set the length.
228
  array->set_length(Smi::FromInt(new_length), SKIP_WRITE_BARRIER);
229 230 231 232 233
  return array->length();
}
BUILTIN_END


234
BUILTIN(ArrayPop) {
235 236 237 238 239 240 241 242 243 244 245 246
  JSArray* array = JSArray::cast(*receiver);
  ASSERT(array->HasFastElements());
  Object* undefined = Heap::undefined_value();

  int len = Smi::cast(array->length())->value();
  if (len == 0) return undefined;

  // Get top element
  FixedArray* elms = FixedArray::cast(array->elements());
  Object* top = elms->get(len - 1);

  // Set the length.
247
  array->set_length(Smi::FromInt(len - 1), SKIP_WRITE_BARRIER);
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

  if (!top->IsTheHole()) {
    // Delete the top element.
    elms->set_the_hole(len - 1);
    return top;
  }

  // Remember to check the prototype chain.
  JSFunction* array_function =
      Top::context()->global_context()->array_function();
  JSObject* prototype = JSObject::cast(array_function->prototype());
  top = prototype->GetElement(len - 1);

  return top;
}
BUILTIN_END


// -----------------------------------------------------------------------------
//


// Returns the holder JSObject if the function can legally be called
// with this receiver.  Returns Heap::null_value() if the call is
// illegal.  Any arguments that don't fit the expected type is
// overwritten with undefined.  Arguments that do fit the expected
// type is overwritten with the object in the prototype chain that
// actually has that type.
static inline Object* TypeCheck(int argc,
                                Object** argv,
                                FunctionTemplateInfo* info) {
  Object* recv = argv[0];
  Object* sig_obj = info->signature();
  if (sig_obj->IsUndefined()) return recv;
  SignatureInfo* sig = SignatureInfo::cast(sig_obj);
  // If necessary, check the receiver
  Object* recv_type = sig->receiver();

  Object* holder = recv;
  if (!recv_type->IsUndefined()) {
    for (; holder != Heap::null_value(); holder = holder->GetPrototype()) {
      if (holder->IsInstanceOf(FunctionTemplateInfo::cast(recv_type))) {
        break;
      }
    }
    if (holder == Heap::null_value()) return holder;
  }
  Object* args_obj = sig->args();
  // If there is no argument signature we're done
  if (args_obj->IsUndefined()) return holder;
  FixedArray* args = FixedArray::cast(args_obj);
  int length = args->length();
300
  if (argc <= length) length = argc - 1;
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
  for (int i = 0; i < length; i++) {
    Object* argtype = args->get(i);
    if (argtype->IsUndefined()) continue;
    Object** arg = &argv[-1 - i];
    Object* current = *arg;
    for (; current != Heap::null_value(); current = current->GetPrototype()) {
      if (current->IsInstanceOf(FunctionTemplateInfo::cast(argtype))) {
        *arg = current;
        break;
      }
    }
    if (current == Heap::null_value()) *arg = Heap::undefined_value();
  }
  return holder;
}


318
BUILTIN(HandleApiCall) {
319
  HandleScope scope;
320
  bool is_construct = CalledAsConstructor();
321 322

  // TODO(1238487): This is not nice. We need to get rid of this
323
  // kludgy behavior and start handling API calls in a more direct
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
  // way - maybe compile specialized stubs lazily?.
  Handle<JSFunction> function =
      Handle<JSFunction>(JSFunction::cast(Builtins::builtin_passed_function));

  if (is_construct) {
    Handle<FunctionTemplateInfo> desc =
        Handle<FunctionTemplateInfo>(
            FunctionTemplateInfo::cast(function->shared()->function_data()));
    bool pending_exception = false;
    Factory::ConfigureInstance(desc, Handle<JSObject>::cast(receiver),
                               &pending_exception);
    ASSERT(Top::has_pending_exception() == pending_exception);
    if (pending_exception) return Failure::Exception();
  }

  FunctionTemplateInfo* fun_data =
      FunctionTemplateInfo::cast(function->shared()->function_data());
  Object* raw_holder = TypeCheck(__argc__, __argv__, fun_data);

  if (raw_holder->IsNull()) {
    // This function cannot be called with the given receiver.  Abort!
    Handle<Object> obj =
        Factory::NewTypeError("illegal_invocation", HandleVector(&function, 1));
    return Top::Throw(*obj);
  }

  Object* raw_call_data = fun_data->call_code();
  if (!raw_call_data->IsUndefined()) {
    CallHandlerInfo* call_data = CallHandlerInfo::cast(raw_call_data);
    Object* callback_obj = call_data->callback();
    v8::InvocationCallback callback =
        v8::ToCData<v8::InvocationCallback>(callback_obj);
    Object* data_obj = call_data->data();
    Object* result;

    v8::Local<v8::Object> self =
        v8::Utils::ToLocal(Handle<JSObject>::cast(receiver));
    Handle<Object> data_handle(data_obj);
    v8::Local<v8::Value> data = v8::Utils::ToLocal(data_handle);
    ASSERT(raw_holder->IsJSObject());
    v8::Local<v8::Function> callee = v8::Utils::ToLocal(function);
    Handle<JSObject> holder_handle(JSObject::cast(raw_holder));
    v8::Local<v8::Object> holder = v8::Utils::ToLocal(holder_handle);
    LOG(ApiObjectAccess("call", JSObject::cast(*receiver)));
    v8::Arguments args = v8::ImplementationUtilities::NewArguments(
        data,
        holder,
        callee,
        is_construct,
        reinterpret_cast<void**>(__argv__ - 1),
374
        __argc__ - 1);
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398

    v8::Handle<v8::Value> value;
    {
      // Leaving JavaScript.
      VMState state(OTHER);
      value = callback(args);
    }
    if (value.IsEmpty()) {
      result = Heap::undefined_value();
    } else {
      result = *reinterpret_cast<Object**>(*value);
    }

    RETURN_IF_SCHEDULED_EXCEPTION();
    if (!is_construct || result->IsJSObject()) return result;
  }

  return *receiver;
}
BUILTIN_END


// Handle calls to non-function objects created through the API that
// support calls.
399
BUILTIN(HandleApiCallAsFunction) {
400
  // Non-functions are never called as constructors.
401
  ASSERT(!CalledAsConstructor());
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433

  // Get the object called.
  JSObject* obj = JSObject::cast(*receiver);

  // Get the invocation callback from the function descriptor that was
  // used to create the called object.
  ASSERT(obj->map()->has_instance_call_handler());
  JSFunction* constructor = JSFunction::cast(obj->map()->constructor());
  Object* template_info = constructor->shared()->function_data();
  Object* handler =
      FunctionTemplateInfo::cast(template_info)->instance_call_handler();
  ASSERT(!handler->IsUndefined());
  CallHandlerInfo* call_data = CallHandlerInfo::cast(handler);
  Object* callback_obj = call_data->callback();
  v8::InvocationCallback callback =
      v8::ToCData<v8::InvocationCallback>(callback_obj);

  // Get the data for the call and perform the callback.
  Object* data_obj = call_data->data();
  Object* result;
  { HandleScope scope;
    v8::Local<v8::Object> self =
        v8::Utils::ToLocal(Handle<JSObject>::cast(receiver));
    Handle<Object> data_handle(data_obj);
    v8::Local<v8::Value> data = v8::Utils::ToLocal(data_handle);
    Handle<JSFunction> callee_handle(constructor);
    v8::Local<v8::Function> callee = v8::Utils::ToLocal(callee_handle);
    LOG(ApiObjectAccess("call non-function", JSObject::cast(*receiver)));
    v8::Arguments args = v8::ImplementationUtilities::NewArguments(
        data,
        self,
        callee,
434
        false,
435
        reinterpret_cast<void**>(__argv__ - 1),
436
        __argc__ - 1);
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
    v8::Handle<v8::Value> value;
    {
      // Leaving JavaScript.
      VMState state(OTHER);
      value = callback(args);
    }
    if (value.IsEmpty()) {
      result = Heap::undefined_value();
    } else {
      result = *reinterpret_cast<Object**>(*value);
    }
  }
  // Check for exceptions and return result.
  RETURN_IF_SCHEDULED_EXCEPTION();
  return result;
}
BUILTIN_END


// TODO(1238487): This is a nasty hack. We need to improve the way we
// call builtins considerable to get rid of this and the hairy macros
// in builtins.cc.
Object* Builtins::builtin_passed_function;



static void Generate_LoadIC_ArrayLength(MacroAssembler* masm) {
  LoadIC::GenerateArrayLength(masm);
}


468 469
static void Generate_LoadIC_StringLength(MacroAssembler* masm) {
  LoadIC::GenerateStringLength(masm);
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
}


static void Generate_LoadIC_FunctionPrototype(MacroAssembler* masm) {
  LoadIC::GenerateFunctionPrototype(masm);
}


static void Generate_LoadIC_Initialize(MacroAssembler* masm) {
  LoadIC::GenerateInitialize(masm);
}


static void Generate_LoadIC_PreMonomorphic(MacroAssembler* masm) {
  LoadIC::GeneratePreMonomorphic(masm);
}


static void Generate_LoadIC_Miss(MacroAssembler* masm) {
  LoadIC::GenerateMiss(masm);
}


static void Generate_LoadIC_Megamorphic(MacroAssembler* masm) {
  LoadIC::GenerateMegamorphic(masm);
}


static void Generate_LoadIC_Normal(MacroAssembler* masm) {
  LoadIC::GenerateNormal(masm);
}


static void Generate_KeyedLoadIC_Initialize(MacroAssembler* masm) {
  KeyedLoadIC::GenerateInitialize(masm);
}


static void Generate_KeyedLoadIC_Miss(MacroAssembler* masm) {
  KeyedLoadIC::GenerateMiss(masm);
}


static void Generate_KeyedLoadIC_Generic(MacroAssembler* masm) {
  KeyedLoadIC::GenerateGeneric(masm);
}


static void Generate_KeyedLoadIC_PreMonomorphic(MacroAssembler* masm) {
  KeyedLoadIC::GeneratePreMonomorphic(masm);
}


static void Generate_StoreIC_Initialize(MacroAssembler* masm) {
  StoreIC::GenerateInitialize(masm);
}


static void Generate_StoreIC_Miss(MacroAssembler* masm) {
  StoreIC::GenerateMiss(masm);
}


533 534 535 536
static void Generate_StoreIC_ExtendStorage(MacroAssembler* masm) {
  StoreIC::GenerateExtendStorage(masm);
}

537 538 539 540 541 542 543 544 545 546
static void Generate_StoreIC_Megamorphic(MacroAssembler* masm) {
  StoreIC::GenerateMegamorphic(masm);
}


static void Generate_KeyedStoreIC_Generic(MacroAssembler* masm) {
  KeyedStoreIC::GenerateGeneric(masm);
}


547 548 549 550 551
static void Generate_KeyedStoreIC_ExtendStorage(MacroAssembler* masm) {
  KeyedStoreIC::GenerateExtendStorage(masm);
}


552 553 554 555 556 557 558 559 560 561
static void Generate_KeyedStoreIC_Miss(MacroAssembler* masm) {
  KeyedStoreIC::GenerateMiss(masm);
}


static void Generate_KeyedStoreIC_Initialize(MacroAssembler* masm) {
  KeyedStoreIC::GenerateInitialize(masm);
}


562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
static void Generate_LoadIC_DebugBreak(MacroAssembler* masm) {
  Debug::GenerateLoadICDebugBreak(masm);
}


static void Generate_StoreIC_DebugBreak(MacroAssembler* masm) {
  Debug::GenerateStoreICDebugBreak(masm);
}


static void Generate_KeyedLoadIC_DebugBreak(MacroAssembler* masm) {
  Debug::GenerateKeyedLoadICDebugBreak(masm);
}


static void Generate_KeyedStoreIC_DebugBreak(MacroAssembler* masm) {
  Debug::GenerateKeyedStoreICDebugBreak(masm);
}


static void Generate_ConstructCall_DebugBreak(MacroAssembler* masm) {
  Debug::GenerateConstructCallDebugBreak(masm);
}


static void Generate_Return_DebugBreak(MacroAssembler* masm) {
  Debug::GenerateReturnDebugBreak(masm);
}


static void Generate_Return_DebugBreakEntry(MacroAssembler* masm) {
  Debug::GenerateReturnDebugBreakEntry(masm);
}


static void Generate_StubNoRegisters_DebugBreak(MacroAssembler* masm) {
  Debug::GenerateStubNoRegistersDebugBreak(masm);
}


602 603 604
Object* Builtins::builtins_[builtin_count] = { NULL, };
const char* Builtins::names_[builtin_count] = { NULL, };

605
#define DEF_ENUM_C(name) FUNCTION_ADDR(Builtin_##name),
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
  Address Builtins::c_functions_[cfunction_count] = {
    BUILTIN_LIST_C(DEF_ENUM_C)
  };
#undef DEF_ENUM_C

#define DEF_JS_NAME(name, ignore) #name,
#define DEF_JS_ARGC(ignore, argc) argc,
const char* Builtins::javascript_names_[id_count] = {
  BUILTINS_LIST_JS(DEF_JS_NAME)
};

int Builtins::javascript_argc_[id_count] = {
  BUILTINS_LIST_JS(DEF_JS_ARGC)
};
#undef DEF_JS_NAME
#undef DEF_JS_ARGC

static bool is_initialized = false;
void Builtins::Setup(bool create_heap_objects) {
  ASSERT(!is_initialized);

  // Create a scope for the handles in the builtins.
  HandleScope scope;

  struct BuiltinDesc {
    byte* generator;
    byte* c_code;
    const char* s_name;  // name is only used for generating log information.
    int name;
    Code::Flags flags;
  };

638
#define DEF_FUNCTION_PTR_C(name)         \
639 640 641 642
    { FUNCTION_ADDR(Generate_Adaptor),   \
      FUNCTION_ADDR(Builtin_##name),     \
      #name,                             \
      c_##name,                          \
643
      Code::ComputeFlags(Code::BUILTIN)  \
644 645 646 647 648 649 650
    },

#define DEF_FUNCTION_PTR_A(name, kind, state) \
    { FUNCTION_ADDR(Generate_##name),         \
      NULL,                                   \
      #name,                                  \
      name,                                   \
651
      Code::ComputeFlags(Code::kind, state)   \
652 653 654 655 656 657
    },

  // Define array of pointers to generators and C builtin functions.
  static BuiltinDesc functions[] = {
      BUILTIN_LIST_C(DEF_FUNCTION_PTR_C)
      BUILTIN_LIST_A(DEF_FUNCTION_PTR_A)
658
      BUILTIN_LIST_DEBUG_A(DEF_FUNCTION_PTR_A)
659
      // Terminator:
660
      { NULL, NULL, NULL, builtin_count, static_cast<Code::Flags>(0) }
661 662 663 664 665 666
  };

#undef DEF_FUNCTION_PTR_C
#undef DEF_FUNCTION_PTR_A

  // For now we generate builtin adaptor code into a stack-allocated
667
  // buffer, before copying it into individual code objects.
668 669 670 671 672 673 674 675
  byte buffer[4*KB];

  // Traverse the list of builtins and generate an adaptor in a
  // separate code object for each one.
  for (int i = 0; i < builtin_count; i++) {
    if (create_heap_objects) {
      MacroAssembler masm(buffer, sizeof buffer);
      // Generate the code/adaptor.
676
      typedef void (*Generator)(MacroAssembler*, int);
677 678 679 680
      Generator g = FUNCTION_CAST<Generator>(functions[i].generator);
      // We pass all arguments to the generator, but it may not use all of
      // them.  This works because the first arguments are on top of the
      // stack.
681
      g(&masm, functions[i].name);
682 683 684 685
      // Move the code into the object heap.
      CodeDesc desc;
      masm.GetCode(&desc);
      Code::Flags flags =  functions[i].flags;
686 687 688 689 690
      Object* code;
      {
        // During startup it's OK to always allocate and defer GC to later.
        // This simplifies things because we don't need to retry.
        AlwaysAllocateScope __scope__;
691
        code = Heap::CreateCode(desc, NULL, flags, masm.CodeObject());
692 693 694
        if (code->IsFailure()) {
          v8::internal::V8::FatalProcessOutOfMemory("CreateCode");
        }
695 696 697 698 699 700 701
      }
      // Add any unresolved jumps or calls to the fixup list in the
      // bootstrapper.
      Bootstrapper::AddFixup(Code::cast(code), &masm);
      // Log the event and add the code to the builtins array.
      LOG(CodeCreateEvent("Builtin", Code::cast(code), functions[i].s_name));
      builtins_[i] = code;
702
#ifdef ENABLE_DISASSEMBLER
703 704
      if (FLAG_print_builtin_code) {
        PrintF("Builtin: %s\n", functions[i].s_name);
705
        Code::cast(code)->Disassemble(functions[i].s_name);
706 707 708
        PrintF("\n");
      }
#endif
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
    } else {
      // Deserializing. The values will be filled in during IterateBuiltins.
      builtins_[i] = NULL;
    }
    names_[i] = functions[i].s_name;
  }

  // Mark as initialized.
  is_initialized = true;
}


void Builtins::TearDown() {
  is_initialized = false;
}


void Builtins::IterateBuiltins(ObjectVisitor* v) {
  v->VisitPointers(&builtins_[0], &builtins_[0] + builtin_count);
}


const char* Builtins::Lookup(byte* pc) {
  if (is_initialized) {  // may be called during initialization (disassembler!)
    for (int i = 0; i < builtin_count; i++) {
      Code* entry = Code::cast(builtins_[i]);
      if (entry->contains(pc)) {
        return names_[i];
      }
    }
  }
  return NULL;
}


} }  // namespace v8::internal