stub-cache.cc 58.9 KB
Newer Older
1
// Copyright 2006-2009 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
// 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 "arguments.h"
#include "ic-inl.h"
#include "stub-cache.h"
34
#include "vm-state-inl.h"
35

36 37
namespace v8 {
namespace internal {
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

// -----------------------------------------------------------------------
// StubCache implementation.


StubCache::Entry StubCache::primary_[StubCache::kPrimaryTableSize];
StubCache::Entry StubCache::secondary_[StubCache::kSecondaryTableSize];

void StubCache::Initialize(bool create_heap_objects) {
  ASSERT(IsPowerOf2(kPrimaryTableSize));
  ASSERT(IsPowerOf2(kSecondaryTableSize));
  if (create_heap_objects) {
    HandleScope scope;
    Clear();
  }
}


Code* StubCache::Set(String* name, Map* map, Code* code) {
  // Get the flags from the code.
  Code::Flags flags = Code::RemoveTypeFromFlags(code->flags());

  // Validate that the name does not move on scavenge, and that we
  // can use identity checks instead of string equality checks.
  ASSERT(!Heap::InNewSpace(name));
  ASSERT(name->IsSymbol());

  // The state bits are not important to the hash function because
  // the stub cache only contains monomorphic stubs. Make sure that
  // the bits are the least significant so they will be the ones
  // masked out.
69 70
  ASSERT(Code::ExtractICStateFromFlags(flags) == MONOMORPHIC);
  ASSERT(Code::kFlagsICStateShift == 0);
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

  // Make sure that the code type is not included in the hash.
  ASSERT(Code::ExtractTypeFromFlags(flags) == 0);

  // Compute the primary entry.
  int primary_offset = PrimaryOffset(name, flags, map);
  Entry* primary = entry(primary_, primary_offset);
  Code* hit = primary->value;

  // If the primary entry has useful data in it, we retire it to the
  // secondary cache before overwriting it.
  if (hit != Builtins::builtin(Builtins::Illegal)) {
    Code::Flags primary_flags = Code::RemoveTypeFromFlags(hit->flags());
    int secondary_offset =
        SecondaryOffset(primary->key, primary_flags, primary_offset);
    Entry* secondary = entry(secondary_, secondary_offset);
    *secondary = *primary;
  }

  // Update primary cache.
  primary->key = name;
  primary->value = code;
  return code;
}


97 98
MaybeObject* StubCache::ComputeLoadNonexistent(String* name,
                                               JSObject* receiver) {
99
  ASSERT(receiver->IsGlobalObject() || receiver->HasFastProperties());
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
  // If no global objects are present in the prototype chain, the load
  // nonexistent IC stub can be shared for all names for a given map
  // and we use the empty string for the map cache in that case.  If
  // there are global objects involved, we need to check global
  // property cells in the stub and therefore the stub will be
  // specific to the name.
  String* cache_name = Heap::empty_string();
  if (receiver->IsGlobalObject()) cache_name = name;
  JSObject* last = receiver;
  while (last->GetPrototype() != Heap::null_value()) {
    last = JSObject::cast(last->GetPrototype());
    if (last->IsGlobalObject()) cache_name = name;
  }
  // Compile the stub that is either shared for all names or
  // name specific if there are global objects involved.
  Code::Flags flags =
      Code::ComputeMonomorphicFlags(Code::LOAD_IC, NONEXISTENT);
  Object* code = receiver->map()->FindInCodeCache(cache_name, flags);
  if (code->IsUndefined()) {
    LoadStubCompiler compiler;
120 121 122 123
    { MaybeObject* maybe_code =
          compiler.CompileLoadNonexistent(cache_name, receiver, last);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
124
    PROFILE(CodeCreateEvent(Logger::LOAD_IC_TAG, Code::cast(code), cache_name));
125 126 127 128 129
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(cache_name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
130
  }
131
  return code;
132 133 134
}


135 136 137 138
MaybeObject* StubCache::ComputeLoadField(String* name,
                                         JSObject* receiver,
                                         JSObject* holder,
                                         int field_index) {
139
  ASSERT(IC::GetCodeCacheForObject(receiver, holder) == OWN_MAP);
140
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::LOAD_IC, FIELD);
141
  Object* code = receiver->map()->FindInCodeCache(name, flags);
142 143
  if (code->IsUndefined()) {
    LoadStubCompiler compiler;
144 145 146 147
    { MaybeObject* maybe_code =
          compiler.CompileLoadField(receiver, holder, field_index, name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
148
    PROFILE(CodeCreateEvent(Logger::LOAD_IC_TAG, Code::cast(code), name));
149 150 151 152 153
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
154
  }
155
  return code;
156 157 158
}


159 160 161 162
MaybeObject* StubCache::ComputeLoadCallback(String* name,
                                            JSObject* receiver,
                                            JSObject* holder,
                                            AccessorInfo* callback) {
163
  ASSERT(v8::ToCData<Address>(callback->getter()) != 0);
164
  ASSERT(IC::GetCodeCacheForObject(receiver, holder) == OWN_MAP);
165
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::LOAD_IC, CALLBACKS);
166
  Object* code = receiver->map()->FindInCodeCache(name, flags);
167 168
  if (code->IsUndefined()) {
    LoadStubCompiler compiler;
169 170 171 172
    { MaybeObject* maybe_code =
          compiler.CompileLoadCallback(name, receiver, holder, callback);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
173
    PROFILE(CodeCreateEvent(Logger::LOAD_IC_TAG, Code::cast(code), name));
174 175 176 177 178
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
179
  }
180
  return code;
181 182 183
}


184 185 186 187
MaybeObject* StubCache::ComputeLoadConstant(String* name,
                                            JSObject* receiver,
                                            JSObject* holder,
                                            Object* value) {
188
  ASSERT(IC::GetCodeCacheForObject(receiver, holder) == OWN_MAP);
189 190
  Code::Flags flags =
      Code::ComputeMonomorphicFlags(Code::LOAD_IC, CONSTANT_FUNCTION);
191
  Object* code = receiver->map()->FindInCodeCache(name, flags);
192 193
  if (code->IsUndefined()) {
    LoadStubCompiler compiler;
194 195 196 197
    { MaybeObject* maybe_code =
          compiler.CompileLoadConstant(receiver, holder, value, name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
198
    PROFILE(CodeCreateEvent(Logger::LOAD_IC_TAG, Code::cast(code), name));
199 200 201 202 203
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
204
  }
205
  return code;
206 207 208
}


209 210 211
MaybeObject* StubCache::ComputeLoadInterceptor(String* name,
                                               JSObject* receiver,
                                               JSObject* holder) {
212
  ASSERT(IC::GetCodeCacheForObject(receiver, holder) == OWN_MAP);
213
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::LOAD_IC, INTERCEPTOR);
214
  Object* code = receiver->map()->FindInCodeCache(name, flags);
215 216
  if (code->IsUndefined()) {
    LoadStubCompiler compiler;
217 218 219 220
    { MaybeObject* maybe_code =
          compiler.CompileLoadInterceptor(receiver, holder, name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
221
    PROFILE(CodeCreateEvent(Logger::LOAD_IC_TAG, Code::cast(code), name));
222 223 224 225 226
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
227
  }
228
  return code;
229 230 231
}


232
MaybeObject* StubCache::ComputeLoadNormal() {
233
  return Builtins::builtin(Builtins::LoadIC_Normal);
234 235 236
}


237 238 239 240 241
MaybeObject* StubCache::ComputeLoadGlobal(String* name,
                                          JSObject* receiver,
                                          GlobalObject* holder,
                                          JSGlobalPropertyCell* cell,
                                          bool is_dont_delete) {
242
  ASSERT(IC::GetCodeCacheForObject(receiver, holder) == OWN_MAP);
243
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::LOAD_IC, NORMAL);
244
  Object* code = receiver->map()->FindInCodeCache(name, flags);
245 246
  if (code->IsUndefined()) {
    LoadStubCompiler compiler;
247 248 249 250 251 252 253
    { MaybeObject* maybe_code = compiler.CompileLoadGlobal(receiver,
                                                           holder,
                                                           cell,
                                                           name,
                                                           is_dont_delete);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
254
    PROFILE(CodeCreateEvent(Logger::LOAD_IC_TAG, Code::cast(code), name));
255 256 257 258 259
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
260
  }
261
  return code;
262 263 264
}


265 266 267 268
MaybeObject* StubCache::ComputeKeyedLoadField(String* name,
                                              JSObject* receiver,
                                              JSObject* holder,
                                              int field_index) {
269
  ASSERT(IC::GetCodeCacheForObject(receiver, holder) == OWN_MAP);
270
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::KEYED_LOAD_IC, FIELD);
271
  Object* code = receiver->map()->FindInCodeCache(name, flags);
272 273
  if (code->IsUndefined()) {
    KeyedLoadStubCompiler compiler;
274 275 276 277
    { MaybeObject* maybe_code =
          compiler.CompileLoadField(name, receiver, holder, field_index);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
278
    PROFILE(CodeCreateEvent(Logger::KEYED_LOAD_IC_TAG, Code::cast(code), name));
279 280 281 282 283
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
284 285 286 287 288
  }
  return code;
}


289 290 291 292
MaybeObject* StubCache::ComputeKeyedLoadConstant(String* name,
                                                 JSObject* receiver,
                                                 JSObject* holder,
                                                 Object* value) {
293
  ASSERT(IC::GetCodeCacheForObject(receiver, holder) == OWN_MAP);
294 295
  Code::Flags flags =
      Code::ComputeMonomorphicFlags(Code::KEYED_LOAD_IC, CONSTANT_FUNCTION);
296
  Object* code = receiver->map()->FindInCodeCache(name, flags);
297 298
  if (code->IsUndefined()) {
    KeyedLoadStubCompiler compiler;
299 300 301 302
    { MaybeObject* maybe_code =
          compiler.CompileLoadConstant(name, receiver, holder, value);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
303
    PROFILE(CodeCreateEvent(Logger::KEYED_LOAD_IC_TAG, Code::cast(code), name));
304 305 306 307 308
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
309 310 311 312 313
  }
  return code;
}


314 315 316
MaybeObject* StubCache::ComputeKeyedLoadInterceptor(String* name,
                                                    JSObject* receiver,
                                                    JSObject* holder) {
317
  ASSERT(IC::GetCodeCacheForObject(receiver, holder) == OWN_MAP);
318 319
  Code::Flags flags =
      Code::ComputeMonomorphicFlags(Code::KEYED_LOAD_IC, INTERCEPTOR);
320
  Object* code = receiver->map()->FindInCodeCache(name, flags);
321 322
  if (code->IsUndefined()) {
    KeyedLoadStubCompiler compiler;
323 324 325 326
    { MaybeObject* maybe_code =
          compiler.CompileLoadInterceptor(receiver, holder, name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
327
    PROFILE(CodeCreateEvent(Logger::KEYED_LOAD_IC_TAG, Code::cast(code), name));
328 329 330 331 332
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
333 334 335 336 337
  }
  return code;
}


338 339 340 341
MaybeObject* StubCache::ComputeKeyedLoadCallback(String* name,
                                                 JSObject* receiver,
                                                 JSObject* holder,
                                                 AccessorInfo* callback) {
342
  ASSERT(IC::GetCodeCacheForObject(receiver, holder) == OWN_MAP);
343 344
  Code::Flags flags =
      Code::ComputeMonomorphicFlags(Code::KEYED_LOAD_IC, CALLBACKS);
345
  Object* code = receiver->map()->FindInCodeCache(name, flags);
346 347
  if (code->IsUndefined()) {
    KeyedLoadStubCompiler compiler;
348 349 350 351
    { MaybeObject* maybe_code =
          compiler.CompileLoadCallback(name, receiver, holder, callback);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
352
    PROFILE(CodeCreateEvent(Logger::KEYED_LOAD_IC_TAG, Code::cast(code), name));
353 354 355 356 357
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
358 359 360 361 362 363
  }
  return code;
}



364 365
MaybeObject* StubCache::ComputeKeyedLoadArrayLength(String* name,
                                                    JSArray* receiver) {
366 367
  Code::Flags flags =
      Code::ComputeMonomorphicFlags(Code::KEYED_LOAD_IC, CALLBACKS);
368
  ASSERT(receiver->IsJSObject());
369
  Object* code = receiver->map()->FindInCodeCache(name, flags);
370 371
  if (code->IsUndefined()) {
    KeyedLoadStubCompiler compiler;
372 373 374
    { MaybeObject* maybe_code = compiler.CompileLoadArrayLength(name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
375
    PROFILE(CodeCreateEvent(Logger::KEYED_LOAD_IC_TAG, Code::cast(code), name));
376 377 378 379 380
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
381 382 383 384 385
  }
  return code;
}


386 387
MaybeObject* StubCache::ComputeKeyedLoadStringLength(String* name,
                                                     String* receiver) {
388 389
  Code::Flags flags =
      Code::ComputeMonomorphicFlags(Code::KEYED_LOAD_IC, CALLBACKS);
390 391
  Map* map = receiver->map();
  Object* code = map->FindInCodeCache(name, flags);
392 393
  if (code->IsUndefined()) {
    KeyedLoadStubCompiler compiler;
394 395 396
    { MaybeObject* maybe_code = compiler.CompileLoadStringLength(name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
397
    PROFILE(CodeCreateEvent(Logger::KEYED_LOAD_IC_TAG, Code::cast(code), name));
398 399 400 401
    Object* result;
    { MaybeObject* maybe_result = map->UpdateCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
402 403 404 405 406
  }
  return code;
}


407 408 409
MaybeObject* StubCache::ComputeKeyedLoadFunctionPrototype(
    String* name,
    JSFunction* receiver) {
410 411
  Code::Flags flags =
      Code::ComputeMonomorphicFlags(Code::KEYED_LOAD_IC, CALLBACKS);
412
  Object* code = receiver->map()->FindInCodeCache(name, flags);
413 414
  if (code->IsUndefined()) {
    KeyedLoadStubCompiler compiler;
415 416 417
    { MaybeObject* maybe_code = compiler.CompileLoadFunctionPrototype(name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
418
    PROFILE(CodeCreateEvent(Logger::KEYED_LOAD_IC_TAG, Code::cast(code), name));
419 420 421 422 423
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
424 425 426 427 428
  }
  return code;
}


429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
MaybeObject* StubCache::ComputeKeyedLoadSpecialized(JSObject* receiver) {
  Code::Flags flags =
      Code::ComputeMonomorphicFlags(Code::KEYED_LOAD_IC, NORMAL);
  String* name = Heap::KeyedLoadSpecialized_symbol();
  Object* code = receiver->map()->FindInCodeCache(name, flags);
  if (code->IsUndefined()) {
    KeyedLoadStubCompiler compiler;
    { MaybeObject* maybe_code = compiler.CompileLoadSpecialized(receiver);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
    PROFILE(CodeCreateEvent(Logger::KEYED_LOAD_IC_TAG, Code::cast(code), 0));
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
  }
  return code;
}


450 451 452 453
MaybeObject* StubCache::ComputeStoreField(String* name,
                                          JSObject* receiver,
                                          int field_index,
                                          Map* transition) {
454 455 456 457 458
  PropertyType type = (transition == NULL) ? FIELD : MAP_TRANSITION;
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::STORE_IC, type);
  Object* code = receiver->map()->FindInCodeCache(name, flags);
  if (code->IsUndefined()) {
    StoreStubCompiler compiler;
459 460 461 462
    { MaybeObject* maybe_code =
          compiler.CompileStoreField(receiver, field_index, transition, name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
463
    PROFILE(CodeCreateEvent(Logger::STORE_IC_TAG, Code::cast(code), name));
464 465 466 467 468
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
469
  }
470
  return code;
471 472 473
}


474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
MaybeObject* StubCache::ComputeKeyedStoreSpecialized(JSObject* receiver) {
  Code::Flags flags =
      Code::ComputeMonomorphicFlags(Code::KEYED_STORE_IC, NORMAL);
  String* name = Heap::KeyedStoreSpecialized_symbol();
  Object* code = receiver->map()->FindInCodeCache(name, flags);
  if (code->IsUndefined()) {
    KeyedStoreStubCompiler compiler;
    { MaybeObject* maybe_code = compiler.CompileStoreSpecialized(receiver);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
    PROFILE(CodeCreateEvent(Logger::KEYED_STORE_IC_TAG, Code::cast(code), 0));
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
  }
  return code;
}


495
MaybeObject* StubCache::ComputeStoreNormal() {
496 497 498 499
  return Builtins::builtin(Builtins::StoreIC_Normal);
}


500 501 502
MaybeObject* StubCache::ComputeStoreGlobal(String* name,
                                           GlobalObject* receiver,
                                           JSGlobalPropertyCell* cell) {
503 504 505 506
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::STORE_IC, NORMAL);
  Object* code = receiver->map()->FindInCodeCache(name, flags);
  if (code->IsUndefined()) {
    StoreStubCompiler compiler;
507 508 509 510
    { MaybeObject* maybe_code =
          compiler.CompileStoreGlobal(receiver, cell, name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
511
    PROFILE(CodeCreateEvent(Logger::STORE_IC_TAG, Code::cast(code), name));
512 513 514 515 516
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
517
  }
518
  return code;
519 520 521
}


522 523 524
MaybeObject* StubCache::ComputeStoreCallback(String* name,
                                             JSObject* receiver,
                                             AccessorInfo* callback) {
525 526 527 528 529
  ASSERT(v8::ToCData<Address>(callback->setter()) != 0);
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::STORE_IC, CALLBACKS);
  Object* code = receiver->map()->FindInCodeCache(name, flags);
  if (code->IsUndefined()) {
    StoreStubCompiler compiler;
530 531 532 533
    { MaybeObject* maybe_code =
          compiler.CompileStoreCallback(receiver, callback, name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
534
    PROFILE(CodeCreateEvent(Logger::STORE_IC_TAG, Code::cast(code), name));
535 536 537 538 539
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
540
  }
541
  return code;
542 543 544
}


545 546
MaybeObject* StubCache::ComputeStoreInterceptor(String* name,
                                                JSObject* receiver) {
547 548 549 550 551
  Code::Flags flags =
      Code::ComputeMonomorphicFlags(Code::STORE_IC, INTERCEPTOR);
  Object* code = receiver->map()->FindInCodeCache(name, flags);
  if (code->IsUndefined()) {
    StoreStubCompiler compiler;
552 553 554 555
    { MaybeObject* maybe_code =
          compiler.CompileStoreInterceptor(receiver, name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
556
    PROFILE(CodeCreateEvent(Logger::STORE_IC_TAG, Code::cast(code), name));
557 558 559 560 561
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
562
  }
563
  return code;
564 565 566
}


567 568 569 570
MaybeObject* StubCache::ComputeKeyedStoreField(String* name,
                                               JSObject* receiver,
                                               int field_index,
                                               Map* transition) {
571 572 573 574 575
  PropertyType type = (transition == NULL) ? FIELD : MAP_TRANSITION;
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::KEYED_STORE_IC, type);
  Object* code = receiver->map()->FindInCodeCache(name, flags);
  if (code->IsUndefined()) {
    KeyedStoreStubCompiler compiler;
576 577 578 579
    { MaybeObject* maybe_code =
          compiler.CompileStoreField(receiver, field_index, transition, name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
580 581
    PROFILE(CodeCreateEvent(
        Logger::KEYED_STORE_IC_TAG, Code::cast(code), name));
582 583 584 585 586
    Object* result;
    { MaybeObject* maybe_result =
          receiver->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
587 588 589 590
  }
  return code;
}

591 592
#define CALL_LOGGER_TAG(kind, type) \
    (kind == Code::CALL_IC ? Logger::type : Logger::KEYED_##type)
593

594 595 596 597 598 599 600
MaybeObject* StubCache::ComputeCallConstant(int argc,
                                            InLoopFlag in_loop,
                                            Code::Kind kind,
                                            String* name,
                                            Object* object,
                                            JSObject* holder,
                                            JSFunction* function) {
601
  // Compute the check type and the map.
602 603
  InlineCacheHolderFlag cache_holder =
      IC::GetCodeCacheForObject(object, holder);
604
  JSObject* map_holder = IC::GetCodeCacheHolder(object, cache_holder);
605 606

  // Compute check type based on receiver/holder.
607
  CheckType check = RECEIVER_MAP_CHECK;
608
  if (object->IsString()) {
609
    check = STRING_CHECK;
610
  } else if (object->IsNumber()) {
611
    check = NUMBER_CHECK;
612
  } else if (object->IsBoolean()) {
613
    check = BOOLEAN_CHECK;
614 615 616
  }

  Code::Flags flags =
617
      Code::ComputeMonomorphicFlags(kind,
618
                                    CONSTANT_FUNCTION,
619
                                    cache_holder,
620 621
                                    in_loop,
                                    argc);
622
  Object* code = map_holder->map()->FindInCodeCache(name, flags);
623 624 625 626 627 628 629
  if (code->IsUndefined()) {
    // If the function hasn't been compiled yet, we cannot do it now
    // because it may cause GC. To avoid this issue, we return an
    // internal error which will make sure we do not update any
    // caches.
    if (!function->is_compiled()) return Failure::InternalError();
    // Compile the stub - only create stubs for fully compiled functions.
630
    CallStubCompiler compiler(argc, in_loop, kind, cache_holder);
631 632 633 634
    { MaybeObject* maybe_code =
          compiler.CompileCallConstant(object, holder, function, name, check);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
635
    Code::cast(code)->set_check_type(check);
636
    ASSERT_EQ(flags, Code::cast(code)->flags());
637 638
    PROFILE(CodeCreateEvent(CALL_LOGGER_TAG(kind, CALL_IC_TAG),
                            Code::cast(code), name));
639 640 641 642 643
    Object* result;
    { MaybeObject* maybe_result =
          map_holder->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
644
  }
645
  return code;
646 647 648
}


649 650 651 652 653 654 655
MaybeObject* StubCache::ComputeCallField(int argc,
                                         InLoopFlag in_loop,
                                         Code::Kind kind,
                                         String* name,
                                         Object* object,
                                         JSObject* holder,
                                         int index) {
656
  // Compute the check type and the map.
657 658
  InlineCacheHolderFlag cache_holder =
      IC::GetCodeCacheForObject(object, holder);
659
  JSObject* map_holder = IC::GetCodeCacheHolder(object, cache_holder);
660 661 662 663 664 665 666 667

  // TODO(1233596): We cannot do receiver map check for non-JS objects
  // because they may be represented as immediates without a
  // map. Instead, we check against the map in the holder.
  if (object->IsNumber() || object->IsBoolean() || object->IsString()) {
    object = holder;
  }

668
  Code::Flags flags = Code::ComputeMonomorphicFlags(kind,
669
                                                    FIELD,
670
                                                    cache_holder,
671 672
                                                    in_loop,
                                                    argc);
673
  Object* code = map_holder->map()->FindInCodeCache(name, flags);
674
  if (code->IsUndefined()) {
675
    CallStubCompiler compiler(argc, in_loop, kind, cache_holder);
676 677 678 679 680 681 682
    { MaybeObject* maybe_code =
          compiler.CompileCallField(JSObject::cast(object),
                                    holder,
                                    index,
                                    name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
683
    ASSERT_EQ(flags, Code::cast(code)->flags());
684 685
    PROFILE(CodeCreateEvent(CALL_LOGGER_TAG(kind, CALL_IC_TAG),
                            Code::cast(code), name));
686 687 688 689 690
    Object* result;
    { MaybeObject* maybe_result =
          map_holder->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
691
  }
692
  return code;
693 694 695
}


696 697 698 699 700
MaybeObject* StubCache::ComputeCallInterceptor(int argc,
                                               Code::Kind kind,
                                               String* name,
                                               Object* object,
                                               JSObject* holder) {
701
  // Compute the check type and the map.
702 703
  InlineCacheHolderFlag cache_holder =
      IC::GetCodeCacheForObject(object, holder);
704
  JSObject* map_holder = IC::GetCodeCacheHolder(object, cache_holder);
705 706 707 708 709 710 711 712 713

  // TODO(1233596): We cannot do receiver map check for non-JS objects
  // because they may be represented as immediates without a
  // map. Instead, we check against the map in the holder.
  if (object->IsNumber() || object->IsBoolean() || object->IsString()) {
    object = holder;
  }

  Code::Flags flags =
714
      Code::ComputeMonomorphicFlags(kind,
715
                                    INTERCEPTOR,
716
                                    cache_holder,
717 718
                                    NOT_IN_LOOP,
                                    argc);
719
  Object* code = map_holder->map()->FindInCodeCache(name, flags);
720
  if (code->IsUndefined()) {
721
    CallStubCompiler compiler(argc, NOT_IN_LOOP, kind, cache_holder);
722 723 724 725
    { MaybeObject* maybe_code =
          compiler.CompileCallInterceptor(JSObject::cast(object), holder, name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
726
    ASSERT_EQ(flags, Code::cast(code)->flags());
727 728
    PROFILE(CodeCreateEvent(CALL_LOGGER_TAG(kind, CALL_IC_TAG),
                            Code::cast(code), name));
729 730 731 732 733
    Object* result;
    { MaybeObject* maybe_result =
          map_holder->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
734
  }
735
  return code;
736 737 738
}


739 740 741 742 743 744 745 746 747
MaybeObject* StubCache::ComputeCallNormal(int argc,
                                          InLoopFlag in_loop,
                                          Code::Kind kind,
                                          String* name,
                                          JSObject* receiver) {
  Object* code;
  { MaybeObject* maybe_code = ComputeCallNormal(argc, in_loop, kind);
    if (!maybe_code->ToObject(&code)) return maybe_code;
  }
748
  return code;
749 750 751
}


752 753 754 755 756 757 758 759
MaybeObject* StubCache::ComputeCallGlobal(int argc,
                                          InLoopFlag in_loop,
                                          Code::Kind kind,
                                          String* name,
                                          JSObject* receiver,
                                          GlobalObject* holder,
                                          JSGlobalPropertyCell* cell,
                                          JSFunction* function) {
760 761
  InlineCacheHolderFlag cache_holder =
      IC::GetCodeCacheForObject(receiver, holder);
762
  JSObject* map_holder = IC::GetCodeCacheHolder(receiver, cache_holder);
763
  Code::Flags flags =
764 765
      Code::ComputeMonomorphicFlags(kind,
                                    NORMAL,
766
                                    cache_holder,
767 768
                                    in_loop,
                                    argc);
769
  Object* code = map_holder->map()->FindInCodeCache(name, flags);
770 771 772 773 774 775
  if (code->IsUndefined()) {
    // If the function hasn't been compiled yet, we cannot do it now
    // because it may cause GC. To avoid this issue, we return an
    // internal error which will make sure we do not update any
    // caches.
    if (!function->is_compiled()) return Failure::InternalError();
776
    CallStubCompiler compiler(argc, in_loop, kind, cache_holder);
777 778 779 780
    { MaybeObject* maybe_code =
          compiler.CompileCallGlobal(receiver, holder, cell, function, name);
      if (!maybe_code->ToObject(&code)) return maybe_code;
    }
781
    ASSERT_EQ(flags, Code::cast(code)->flags());
782 783
    PROFILE(CodeCreateEvent(CALL_LOGGER_TAG(kind, CALL_IC_TAG),
                            Code::cast(code), name));
784 785 786 787 788
    Object* result;
    { MaybeObject* maybe_result =
          map_holder->UpdateMapCodeCache(name, Code::cast(code));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
789
  }
790
  return code;
791 792 793
}


794
static Object* GetProbeValue(Code::Flags flags) {
795 796
  // Use raw_unchecked... so we don't get assert failures during GC.
  NumberDictionary* dictionary = Heap::raw_unchecked_non_monomorphic_cache();
797
  int entry = dictionary->FindEntry(flags);
798
  if (entry != -1) return dictionary->ValueAt(entry);
799
  return Heap::raw_unchecked_undefined_value();
800 801 802
}


803
MUST_USE_RESULT static MaybeObject* ProbeCache(Code::Flags flags) {
804 805 806 807 808
  Object* probe = GetProbeValue(flags);
  if (probe != Heap::undefined_value()) return probe;
  // Seed the cache with an undefined value to make sure that any
  // generated code object can always be inserted into the cache
  // without causing  allocation failures.
809 810 811 812 813 814
  Object* result;
  { MaybeObject* maybe_result =
        Heap::non_monomorphic_cache()->AtNumberPut(flags,
                                                   Heap::undefined_value());
    if (!maybe_result->ToObject(&result)) return maybe_result;
  }
815
  Heap::public_set_non_monomorphic_cache(NumberDictionary::cast(result));
816 817 818 819
  return probe;
}


820 821 822 823 824 825 826 827 828 829 830 831 832 833
static MaybeObject* FillCache(MaybeObject* maybe_code) {
  Object* code;
  if (maybe_code->ToObject(&code)) {
    if (code->IsCode()) {
      int entry =
          Heap::non_monomorphic_cache()->FindEntry(
              Code::cast(code)->flags());
      // The entry must be present see comment in ProbeCache.
      ASSERT(entry != -1);
      ASSERT(Heap::non_monomorphic_cache()->ValueAt(entry) ==
             Heap::undefined_value());
      Heap::non_monomorphic_cache()->ValueAtPut(entry, code);
      CHECK(GetProbeValue(Code::cast(code)->flags()) == code);
    }
834
  }
835
  return maybe_code;
836 837 838
}


839 840 841
Code* StubCache::FindCallInitialize(int argc,
                                    InLoopFlag in_loop,
                                    Code::Kind kind) {
842
  Code::Flags flags =
843
      Code::ComputeFlags(kind, in_loop, UNINITIALIZED, NORMAL, argc);
844
  Object* result = ProbeCache(flags)->ToObjectUnchecked();
845 846 847 848 849 850 851
  ASSERT(!result->IsUndefined());
  // This might be called during the marking phase of the collector
  // hence the unchecked cast.
  return reinterpret_cast<Code*>(result);
}


852 853 854
MaybeObject* StubCache::ComputeCallInitialize(int argc,
                                              InLoopFlag in_loop,
                                              Code::Kind kind) {
855
  Code::Flags flags =
856
      Code::ComputeFlags(kind, in_loop, UNINITIALIZED, NORMAL, argc);
857 858 859 860
  Object* probe;
  { MaybeObject* maybe_probe = ProbeCache(flags);
    if (!maybe_probe->ToObject(&probe)) return maybe_probe;
  }
861 862 863 864 865 866
  if (!probe->IsUndefined()) return probe;
  StubCompiler compiler;
  return FillCache(compiler.CompileCallInitialize(flags));
}


867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
Handle<Code> StubCache::ComputeCallInitialize(int argc, InLoopFlag in_loop) {
  if (in_loop == IN_LOOP) {
    // Force the creation of the corresponding stub outside loops,
    // because it may be used when clearing the ICs later - it is
    // possible for a series of IC transitions to lose the in-loop
    // information, and the IC clearing code can't generate a stub
    // that it needs so we need to ensure it is generated already.
    ComputeCallInitialize(argc, NOT_IN_LOOP);
  }
  CALL_HEAP_FUNCTION(ComputeCallInitialize(argc, in_loop, Code::CALL_IC), Code);
}


Handle<Code> StubCache::ComputeKeyedCallInitialize(int argc,
                                                   InLoopFlag in_loop) {
  if (in_loop == IN_LOOP) {
    // Force the creation of the corresponding stub outside loops,
    // because it may be used when clearing the ICs later - it is
    // possible for a series of IC transitions to lose the in-loop
    // information, and the IC clearing code can't generate a stub
    // that it needs so we need to ensure it is generated already.
    ComputeKeyedCallInitialize(argc, NOT_IN_LOOP);
  }
  CALL_HEAP_FUNCTION(
      ComputeCallInitialize(argc, in_loop, Code::KEYED_CALL_IC), Code);
}


895 896 897
MaybeObject* StubCache::ComputeCallPreMonomorphic(int argc,
                                                  InLoopFlag in_loop,
                                                  Code::Kind kind) {
898
  Code::Flags flags =
899
      Code::ComputeFlags(kind, in_loop, PREMONOMORPHIC, NORMAL, argc);
900 901 902 903
  Object* probe;
  { MaybeObject* maybe_probe = ProbeCache(flags);
    if (!maybe_probe->ToObject(&probe)) return maybe_probe;
  }
904 905 906 907 908 909
  if (!probe->IsUndefined()) return probe;
  StubCompiler compiler;
  return FillCache(compiler.CompileCallPreMonomorphic(flags));
}


910 911 912
MaybeObject* StubCache::ComputeCallNormal(int argc,
                                          InLoopFlag in_loop,
                                          Code::Kind kind) {
913
  Code::Flags flags =
914
      Code::ComputeFlags(kind, in_loop, MONOMORPHIC, NORMAL, argc);
915 916 917 918
  Object* probe;
  { MaybeObject* maybe_probe = ProbeCache(flags);
    if (!maybe_probe->ToObject(&probe)) return maybe_probe;
  }
919 920 921 922 923 924
  if (!probe->IsUndefined()) return probe;
  StubCompiler compiler;
  return FillCache(compiler.CompileCallNormal(flags));
}


925 926 927
MaybeObject* StubCache::ComputeCallMegamorphic(int argc,
                                               InLoopFlag in_loop,
                                               Code::Kind kind) {
928
  Code::Flags flags =
929
      Code::ComputeFlags(kind, in_loop, MEGAMORPHIC, NORMAL, argc);
930 931 932 933
  Object* probe;
  { MaybeObject* maybe_probe = ProbeCache(flags);
    if (!maybe_probe->ToObject(&probe)) return maybe_probe;
  }
934 935 936 937 938 939
  if (!probe->IsUndefined()) return probe;
  StubCompiler compiler;
  return FillCache(compiler.CompileCallMegamorphic(flags));
}


940
MaybeObject* StubCache::ComputeCallMiss(int argc, Code::Kind kind) {
941 942 943 944
  // MONOMORPHIC_PROTOTYPE_FAILURE state is used to make sure that miss stubs
  // and monomorphic stubs are not mixed up together in the stub cache.
  Code::Flags flags = Code::ComputeFlags(
     kind, NOT_IN_LOOP, MONOMORPHIC_PROTOTYPE_FAILURE, NORMAL, argc);
945 946 947 948
  Object* probe;
  { MaybeObject* maybe_probe = ProbeCache(flags);
    if (!maybe_probe->ToObject(&probe)) return maybe_probe;
  }
949 950 951 952 953 954
  if (!probe->IsUndefined()) return probe;
  StubCompiler compiler;
  return FillCache(compiler.CompileCallMiss(flags));
}


955
#ifdef ENABLE_DEBUGGER_SUPPORT
956
MaybeObject* StubCache::ComputeCallDebugBreak(int argc, Code::Kind kind) {
957
  Code::Flags flags =
958
      Code::ComputeFlags(kind, NOT_IN_LOOP, DEBUG_BREAK, NORMAL, argc);
959 960 961 962
  Object* probe;
  { MaybeObject* maybe_probe = ProbeCache(flags);
    if (!maybe_probe->ToObject(&probe)) return maybe_probe;
  }
963 964 965 966 967 968
  if (!probe->IsUndefined()) return probe;
  StubCompiler compiler;
  return FillCache(compiler.CompileCallDebugBreak(flags));
}


969 970
MaybeObject* StubCache::ComputeCallDebugPrepareStepIn(int argc,
                                                      Code::Kind kind) {
971
  Code::Flags flags =
972
      Code::ComputeFlags(kind,
973 974 975 976
                         NOT_IN_LOOP,
                         DEBUG_PREPARE_STEP_IN,
                         NORMAL,
                         argc);
977 978 979 980
  Object* probe;
  { MaybeObject* maybe_probe = ProbeCache(flags);
    if (!maybe_probe->ToObject(&probe)) return maybe_probe;
  }
981 982 983 984
  if (!probe->IsUndefined()) return probe;
  StubCompiler compiler;
  return FillCache(compiler.CompileCallDebugPrepareStepIn(flags));
}
985
#endif
986 987 988 989 990 991 992 993 994 995 996 997 998 999


void StubCache::Clear() {
  for (int i = 0; i < kPrimaryTableSize; i++) {
    primary_[i].key = Heap::empty_string();
    primary_[i].value = Builtins::builtin(Builtins::Illegal);
  }
  for (int j = 0; j < kSecondaryTableSize; j++) {
    secondary_[j].key = Heap::empty_string();
    secondary_[j].value = Builtins::builtin(Builtins::Illegal);
  }
}


1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
void StubCache::CollectMatchingMaps(ZoneMapList* types,
                                    String* name,
                                    Code::Flags flags) {
  for (int i = 0; i < kPrimaryTableSize; i++) {
    if (primary_[i].key == name) {
      Map* map = primary_[i].value->FindFirstMap();
      // Map can be NULL, if the stub is constant function call
      // with a primitive receiver.
      if (map == NULL) continue;

      int offset = PrimaryOffset(name, flags, map);
      if (entry(primary_, offset) == &primary_[i]) {
        types->Add(Handle<Map>(map));
      }
    }
  }

  for (int i = 0; i < kSecondaryTableSize; i++) {
    if (secondary_[i].key == name) {
      Map* map = secondary_[i].value->FindFirstMap();
      // Map can be NULL, if the stub is constant function call
      // with a primitive receiver.
      if (map == NULL) continue;

      // Lookup in primary table and skip duplicates.
      int primary_offset = PrimaryOffset(name, flags, map);
      Entry* primary_entry = entry(primary_, primary_offset);
      if (primary_entry->key == name) {
        Map* primary_map = primary_entry->value->FindFirstMap();
        if (map == primary_map) continue;
      }

      // Lookup in secondary table and add matches.
      int offset = SecondaryOffset(name, flags, primary_offset);
      if (entry(secondary_, offset) == &secondary_[i]) {
        types->Add(Handle<Map>(map));
      }
    }
  }
}


1042 1043 1044 1045
// ------------------------------------------------------------------------
// StubCompiler implementation.


1046
MaybeObject* LoadCallbackProperty(Arguments args) {
1047 1048
  ASSERT(args[0]->IsJSObject());
  ASSERT(args[1]->IsJSObject());
1049
  AccessorInfo* callback = AccessorInfo::cast(args[3]);
1050 1051
  Address getter_address = v8::ToCData<Address>(callback->getter());
  v8::AccessorGetter fun = FUNCTION_CAST<v8::AccessorGetter>(getter_address);
1052
  ASSERT(fun != NULL);
1053
  v8::AccessorInfo info(&args[0]);
1054
  HandleScope scope;
1055 1056 1057
  v8::Handle<v8::Value> result;
  {
    // Leaving JavaScript.
1058
    VMState state(EXTERNAL);
1059
    ExternalCallbackScope call_scope(getter_address);
1060
    result = fun(v8::Utils::ToLocal(args.at<String>(4)), info);
1061 1062
  }
  RETURN_IF_SCHEDULED_EXCEPTION();
1063 1064
  if (result.IsEmpty()) return Heap::undefined_value();
  return *v8::Utils::OpenHandle(*result);
1065 1066 1067
}


1068
MaybeObject* StoreCallbackProperty(Arguments args) {
1069
  JSObject* recv = JSObject::cast(args[0]);
1070
  AccessorInfo* callback = AccessorInfo::cast(args[1]);
1071 1072
  Address setter_address = v8::ToCData<Address>(callback->setter());
  v8::AccessorSetter fun = FUNCTION_CAST<v8::AccessorSetter>(setter_address);
1073 1074 1075 1076
  ASSERT(fun != NULL);
  Handle<String> name = args.at<String>(2);
  Handle<Object> value = args.at<Object>(3);
  HandleScope scope;
1077 1078 1079
  LOG(ApiNamedPropertyAccess("store", recv, *name));
  CustomArguments custom_args(callback->data(), recv, recv);
  v8::AccessorInfo info(custom_args.end());
1080 1081
  {
    // Leaving JavaScript.
1082
    VMState state(EXTERNAL);
1083
    ExternalCallbackScope call_scope(setter_address);
1084 1085 1086 1087 1088 1089
    fun(v8::Utils::ToLocal(name), v8::Utils::ToLocal(value), info);
  }
  RETURN_IF_SCHEDULED_EXCEPTION();
  return *value;
}

1090 1091 1092 1093

static const int kAccessorInfoOffsetInInterceptorArgs = 2;


1094 1095 1096 1097 1098 1099 1100
/**
 * Attempts to load a property with an interceptor (which must be present),
 * but doesn't search the prototype chain.
 *
 * Returns |Heap::no_interceptor_result_sentinel()| if interceptor doesn't
 * provide any value for the given name.
 */
1101
MaybeObject* LoadPropertyWithInterceptorOnly(Arguments args) {
1102 1103 1104 1105 1106 1107
  Handle<String> name_handle = args.at<String>(0);
  Handle<InterceptorInfo> interceptor_info = args.at<InterceptorInfo>(1);
  ASSERT(kAccessorInfoOffsetInInterceptorArgs == 2);
  ASSERT(args[2]->IsJSObject());  // Receiver.
  ASSERT(args[3]->IsJSObject());  // Holder.
  ASSERT(args.length() == 5);  // Last arg is data object.
1108

1109 1110 1111 1112 1113 1114 1115
  Address getter_address = v8::ToCData<Address>(interceptor_info->getter());
  v8::NamedPropertyGetter getter =
      FUNCTION_CAST<v8::NamedPropertyGetter>(getter_address);
  ASSERT(getter != NULL);

  {
    // Use the interceptor getter.
1116 1117
    v8::AccessorInfo info(args.arguments() -
                          kAccessorInfoOffsetInInterceptorArgs);
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
    HandleScope scope;
    v8::Handle<v8::Value> r;
    {
      // Leaving JavaScript.
      VMState state(EXTERNAL);
      r = getter(v8::Utils::ToLocal(name_handle), info);
    }
    RETURN_IF_SCHEDULED_EXCEPTION();
    if (!r.IsEmpty()) {
      return *v8::Utils::OpenHandle(*r);
    }
  }

1131 1132
  return Heap::no_interceptor_result_sentinel();
}
1133 1134


1135
static MaybeObject* ThrowReferenceError(String* name) {
1136 1137 1138 1139 1140
  // If the load is non-contextual, just return the undefined result.
  // Note that both keyed and non-keyed loads may end up here, so we
  // can't use either LoadIC or KeyedLoadIC constructors.
  IC ic(IC::NO_EXTRA_FRAME);
  ASSERT(ic.target()->is_load_stub() || ic.target()->is_keyed_load_stub());
1141
  if (!ic.SlowIsContextual()) return Heap::undefined_value();
1142 1143

  // Throw a reference error.
1144 1145 1146 1147 1148 1149 1150 1151 1152
  HandleScope scope;
  Handle<String> name_handle(name);
  Handle<Object> error =
      Factory::NewReferenceError("not_defined",
                                  HandleVector(&name_handle, 1));
  return Top::Throw(*error);
}


1153 1154
static MaybeObject* LoadWithInterceptor(Arguments* args,
                                        PropertyAttributes* attrs) {
1155 1156 1157 1158 1159 1160
  Handle<String> name_handle = args->at<String>(0);
  Handle<InterceptorInfo> interceptor_info = args->at<InterceptorInfo>(1);
  ASSERT(kAccessorInfoOffsetInInterceptorArgs == 2);
  Handle<JSObject> receiver_handle = args->at<JSObject>(2);
  Handle<JSObject> holder_handle = args->at<JSObject>(3);
  ASSERT(args->length() == 5);  // Last arg is data object.
1161 1162 1163 1164 1165 1166

  Address getter_address = v8::ToCData<Address>(interceptor_info->getter());
  v8::NamedPropertyGetter getter =
      FUNCTION_CAST<v8::NamedPropertyGetter>(getter_address);
  ASSERT(getter != NULL);

1167
  {
1168
    // Use the interceptor getter.
1169 1170
    v8::AccessorInfo info(args->arguments() -
                          kAccessorInfoOffsetInInterceptorArgs);
1171
    HandleScope scope;
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    v8::Handle<v8::Value> r;
    {
      // Leaving JavaScript.
      VMState state(EXTERNAL);
      r = getter(v8::Utils::ToLocal(name_handle), info);
    }
    RETURN_IF_SCHEDULED_EXCEPTION();
    if (!r.IsEmpty()) {
      *attrs = NONE;
      return *v8::Utils::OpenHandle(*r);
    }
1183
  }
1184

1185
  MaybeObject* result = holder_handle->GetPropertyPostInterceptor(
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
      *receiver_handle,
      *name_handle,
      attrs);
  RETURN_IF_SCHEDULED_EXCEPTION();
  return result;
}


/**
 * Loads a property with an interceptor performing post interceptor
 * lookup if interceptor failed.
 */
1198
MaybeObject* LoadPropertyWithInterceptorForLoad(Arguments args) {
1199
  PropertyAttributes attr = NONE;
1200 1201 1202 1203
  Object* result;
  { MaybeObject* maybe_result = LoadWithInterceptor(&args, &attr);
    if (!maybe_result->ToObject(&result)) return maybe_result;
  }
1204 1205 1206

  // If the property is present, return it.
  if (attr != ABSENT) return result;
1207
  return ThrowReferenceError(String::cast(args[0]));
1208 1209 1210
}


1211
MaybeObject* LoadPropertyWithInterceptorForCall(Arguments args) {
1212
  PropertyAttributes attr;
1213
  MaybeObject* result = LoadWithInterceptor(&args, &attr);
1214 1215 1216 1217 1218
  RETURN_IF_SCHEDULED_EXCEPTION();
  // This is call IC. In this case, we simply return the undefined result which
  // will lead to an exception when trying to invoke the result as a
  // function.
  return result;
1219 1220 1221
}


1222
MaybeObject* StoreInterceptorProperty(Arguments args) {
1223 1224 1225
  JSObject* recv = JSObject::cast(args[0]);
  String* name = String::cast(args[1]);
  Object* value = args[2];
1226 1227
  ASSERT(recv->HasNamedInterceptor());
  PropertyAttributes attr = NONE;
1228
  MaybeObject* result = recv->SetPropertyWithInterceptor(name, value, attr);
1229
  return result;
1230 1231 1232
}


1233
MaybeObject* KeyedLoadPropertyWithInterceptor(Arguments args) {
1234
  JSObject* receiver = JSObject::cast(args[0]);
1235
  ASSERT(Smi::cast(args[1])->value() >= 0);
1236 1237 1238 1239 1240
  uint32_t index = Smi::cast(args[1])->value();
  return receiver->GetElementWithInterceptor(receiver, index);
}


1241
MaybeObject* StubCompiler::CompileCallInitialize(Code::Flags flags) {
1242 1243
  HandleScope scope;
  int argc = Code::ExtractArgumentsCountFromFlags(flags);
1244 1245 1246 1247 1248 1249
  Code::Kind kind = Code::ExtractKindFromFlags(flags);
  if (kind == Code::CALL_IC) {
    CallIC::GenerateInitialize(masm(), argc);
  } else {
    KeyedCallIC::GenerateInitialize(masm(), argc);
  }
1250 1251 1252 1253
  Object* result;
  { MaybeObject* maybe_result =
        GetCodeWithFlags(flags, "CompileCallInitialize");
    if (!maybe_result->ToObject(&result)) return maybe_result;
1254
  }
1255 1256 1257 1258 1259
  Counters::call_initialize_stubs.Increment();
  Code* code = Code::cast(result);
  USE(code);
  PROFILE(CodeCreateEvent(CALL_LOGGER_TAG(kind, CALL_INITIALIZE_TAG),
                          code, code->arguments_count()));
1260 1261 1262 1263
  return result;
}


1264
MaybeObject* StubCompiler::CompileCallPreMonomorphic(Code::Flags flags) {
1265 1266
  HandleScope scope;
  int argc = Code::ExtractArgumentsCountFromFlags(flags);
1267 1268
  // The code of the PreMonomorphic stub is the same as the code
  // of the Initialized stub.  They just differ on the code object flags.
1269 1270 1271 1272 1273 1274
  Code::Kind kind = Code::ExtractKindFromFlags(flags);
  if (kind == Code::CALL_IC) {
    CallIC::GenerateInitialize(masm(), argc);
  } else {
    KeyedCallIC::GenerateInitialize(masm(), argc);
  }
1275 1276 1277 1278
  Object* result;
  { MaybeObject* maybe_result =
        GetCodeWithFlags(flags, "CompileCallPreMonomorphic");
    if (!maybe_result->ToObject(&result)) return maybe_result;
1279
  }
1280 1281 1282 1283 1284
  Counters::call_premonomorphic_stubs.Increment();
  Code* code = Code::cast(result);
  USE(code);
  PROFILE(CodeCreateEvent(CALL_LOGGER_TAG(kind, CALL_PRE_MONOMORPHIC_TAG),
                          code, code->arguments_count()));
1285 1286 1287 1288
  return result;
}


1289
MaybeObject* StubCompiler::CompileCallNormal(Code::Flags flags) {
1290 1291
  HandleScope scope;
  int argc = Code::ExtractArgumentsCountFromFlags(flags);
1292 1293 1294 1295 1296 1297
  Code::Kind kind = Code::ExtractKindFromFlags(flags);
  if (kind == Code::CALL_IC) {
    CallIC::GenerateNormal(masm(), argc);
  } else {
    KeyedCallIC::GenerateNormal(masm(), argc);
  }
1298 1299 1300
  Object* result;
  { MaybeObject* maybe_result = GetCodeWithFlags(flags, "CompileCallNormal");
    if (!maybe_result->ToObject(&result)) return maybe_result;
1301
  }
1302 1303 1304 1305 1306
  Counters::call_normal_stubs.Increment();
  Code* code = Code::cast(result);
  USE(code);
  PROFILE(CodeCreateEvent(CALL_LOGGER_TAG(kind, CALL_NORMAL_TAG),
                          code, code->arguments_count()));
1307 1308 1309 1310
  return result;
}


1311
MaybeObject* StubCompiler::CompileCallMegamorphic(Code::Flags flags) {
1312 1313
  HandleScope scope;
  int argc = Code::ExtractArgumentsCountFromFlags(flags);
1314 1315 1316 1317 1318 1319 1320
  Code::Kind kind = Code::ExtractKindFromFlags(flags);
  if (kind == Code::CALL_IC) {
    CallIC::GenerateMegamorphic(masm(), argc);
  } else {
    KeyedCallIC::GenerateMegamorphic(masm(), argc);
  }

1321 1322 1323 1324
  Object* result;
  { MaybeObject* maybe_result =
        GetCodeWithFlags(flags, "CompileCallMegamorphic");
    if (!maybe_result->ToObject(&result)) return maybe_result;
1325
  }
1326 1327 1328 1329 1330
  Counters::call_megamorphic_stubs.Increment();
  Code* code = Code::cast(result);
  USE(code);
  PROFILE(CodeCreateEvent(CALL_LOGGER_TAG(kind, CALL_MEGAMORPHIC_TAG),
                          code, code->arguments_count()));
1331 1332 1333 1334
  return result;
}


1335
MaybeObject* StubCompiler::CompileCallMiss(Code::Flags flags) {
1336 1337
  HandleScope scope;
  int argc = Code::ExtractArgumentsCountFromFlags(flags);
1338 1339 1340 1341 1342 1343
  Code::Kind kind = Code::ExtractKindFromFlags(flags);
  if (kind == Code::CALL_IC) {
    CallIC::GenerateMiss(masm(), argc);
  } else {
    KeyedCallIC::GenerateMiss(masm(), argc);
  }
1344 1345 1346
  Object* result;
  { MaybeObject* maybe_result = GetCodeWithFlags(flags, "CompileCallMiss");
    if (!maybe_result->ToObject(&result)) return maybe_result;
1347
  }
1348 1349 1350 1351 1352
  Counters::call_megamorphic_stubs.Increment();
  Code* code = Code::cast(result);
  USE(code);
  PROFILE(CodeCreateEvent(CALL_LOGGER_TAG(kind, CALL_MISS_TAG),
                          code, code->arguments_count()));
1353 1354 1355 1356
  return result;
}


1357
#ifdef ENABLE_DEBUGGER_SUPPORT
1358
MaybeObject* StubCompiler::CompileCallDebugBreak(Code::Flags flags) {
1359
  HandleScope scope;
1360
  Debug::GenerateCallICDebugBreak(masm());
1361 1362 1363 1364
  Object* result;
  { MaybeObject* maybe_result =
        GetCodeWithFlags(flags, "CompileCallDebugBreak");
    if (!maybe_result->ToObject(&result)) return maybe_result;
1365
  }
1366 1367 1368 1369 1370 1371
  Code* code = Code::cast(result);
  USE(code);
  Code::Kind kind = Code::ExtractKindFromFlags(flags);
  USE(kind);
  PROFILE(CodeCreateEvent(CALL_LOGGER_TAG(kind, CALL_DEBUG_BREAK_TAG),
                          code, code->arguments_count()));
1372 1373 1374 1375
  return result;
}


1376
MaybeObject* StubCompiler::CompileCallDebugPrepareStepIn(Code::Flags flags) {
1377 1378 1379 1380
  HandleScope scope;
  // Use the same code for the the step in preparations as we do for
  // the miss case.
  int argc = Code::ExtractArgumentsCountFromFlags(flags);
1381 1382 1383 1384 1385 1386
  Code::Kind kind = Code::ExtractKindFromFlags(flags);
  if (kind == Code::CALL_IC) {
    CallIC::GenerateMiss(masm(), argc);
  } else {
    KeyedCallIC::GenerateMiss(masm(), argc);
  }
1387 1388 1389 1390
  Object* result;
  { MaybeObject* maybe_result =
        GetCodeWithFlags(flags, "CompileCallDebugPrepareStepIn");
    if (!maybe_result->ToObject(&result)) return maybe_result;
1391
  }
1392 1393 1394 1395 1396 1397
  Code* code = Code::cast(result);
  USE(code);
  PROFILE(CodeCreateEvent(
      CALL_LOGGER_TAG(kind, CALL_DEBUG_PREPARE_STEP_IN_TAG),
      code,
      code->arguments_count()));
1398 1399
  return result;
}
1400
#endif
1401

1402
#undef CALL_LOGGER_TAG
1403

1404 1405
MaybeObject* StubCompiler::GetCodeWithFlags(Code::Flags flags,
                                            const char* name) {
1406 1407 1408 1409
  // Check for allocation failures during stub compilation.
  if (failure_->IsFailure()) return failure_;

  // Create code object in the heap.
1410 1411
  CodeDesc desc;
  masm_.GetCode(&desc);
1412
  MaybeObject* result = Heap::CreateCode(desc, flags, masm_.CodeObject());
1413
#ifdef ENABLE_DISASSEMBLER
1414
  if (FLAG_print_code_stubs && !result->IsFailure()) {
1415
    Code::cast(result->ToObjectUnchecked())->Disassemble(name);
1416 1417 1418 1419 1420 1421
  }
#endif
  return result;
}


1422
MaybeObject* StubCompiler::GetCodeWithFlags(Code::Flags flags, String* name) {
1423 1424 1425 1426 1427 1428
  if (FLAG_print_code_stubs && (name != NULL)) {
    return GetCodeWithFlags(flags, *name->ToCString());
  }
  return GetCodeWithFlags(flags, reinterpret_cast<char*>(NULL));
}

1429

1430 1431 1432 1433
void StubCompiler::LookupPostInterceptor(JSObject* holder,
                                         String* name,
                                         LookupResult* lookup) {
  holder->LocalLookupRealNamedProperty(name, lookup);
1434 1435
  if (!lookup->IsProperty()) {
    lookup->NotFound();
1436 1437 1438 1439 1440 1441 1442 1443
    Object* proto = holder->GetPrototype();
    if (proto != Heap::null_value()) {
      proto->Lookup(name, lookup);
    }
  }
}


1444

1445
MaybeObject* LoadStubCompiler::GetCode(PropertyType type, String* name) {
1446
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::LOAD_IC, type);
1447
  MaybeObject* result = GetCodeWithFlags(flags, name);
1448
  if (!result->IsFailure()) {
1449 1450 1451
    PROFILE(CodeCreateEvent(Logger::LOAD_IC_TAG,
                            Code::cast(result->ToObjectUnchecked()),
                            name));
1452 1453
  }
  return result;
1454 1455 1456
}


1457
MaybeObject* KeyedLoadStubCompiler::GetCode(PropertyType type, String* name) {
1458
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::KEYED_LOAD_IC, type);
1459
  MaybeObject* result = GetCodeWithFlags(flags, name);
1460
  if (!result->IsFailure()) {
1461 1462 1463
    PROFILE(CodeCreateEvent(Logger::KEYED_LOAD_IC_TAG,
                            Code::cast(result->ToObjectUnchecked()),
                            name));
1464 1465
  }
  return result;
1466 1467 1468
}


1469
MaybeObject* StoreStubCompiler::GetCode(PropertyType type, String* name) {
1470
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::STORE_IC, type);
1471
  MaybeObject* result = GetCodeWithFlags(flags, name);
1472
  if (!result->IsFailure()) {
1473 1474 1475
    PROFILE(CodeCreateEvent(Logger::STORE_IC_TAG,
                            Code::cast(result->ToObjectUnchecked()),
                            name));
1476 1477
  }
  return result;
1478 1479 1480
}


1481
MaybeObject* KeyedStoreStubCompiler::GetCode(PropertyType type, String* name) {
1482
  Code::Flags flags = Code::ComputeMonomorphicFlags(Code::KEYED_STORE_IC, type);
1483
  MaybeObject* result = GetCodeWithFlags(flags, name);
1484
  if (!result->IsFailure()) {
1485 1486 1487
    PROFILE(CodeCreateEvent(Logger::KEYED_STORE_IC_TAG,
                            Code::cast(result->ToObjectUnchecked()),
                            name));
1488 1489
  }
  return result;
1490 1491 1492
}


1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
CallStubCompiler::CallStubCompiler(int argc,
                                   InLoopFlag in_loop,
                                   Code::Kind kind,
                                   InlineCacheHolderFlag cache_holder)
    : arguments_(argc)
    , in_loop_(in_loop)
    , kind_(kind)
    , cache_holder_(cache_holder) {
}


1504 1505 1506 1507 1508 1509 1510 1511 1512
bool CallStubCompiler::HasCustomCallGenerator(BuiltinFunctionId id) {
#define CALL_GENERATOR_CASE(name) if (id == k##name) return true;
  CUSTOM_CALL_IC_GENERATORS(CALL_GENERATOR_CASE)
#undef CALL_GENERATOR_CASE
  return false;
}


MaybeObject* CallStubCompiler::CompileCustomCall(BuiltinFunctionId id,
1513 1514 1515 1516 1517
                                                 Object* object,
                                                 JSObject* holder,
                                                 JSGlobalPropertyCell* cell,
                                                 JSFunction* function,
                                                 String* fname) {
1518 1519 1520 1521 1522 1523 1524 1525 1526
#define CALL_GENERATOR_CASE(name)                          \
  if (id == k##name) {                                     \
    return CallStubCompiler::Compile##name##Call(object,   \
                                                 holder,   \
                                                 cell,     \
                                                 function, \
                                                 fname);   \
  }
  CUSTOM_CALL_IC_GENERATORS(CALL_GENERATOR_CASE)
1527
#undef CALL_GENERATOR_CASE
1528
  ASSERT(!HasCustomCallGenerator(id));
1529
  return Heap::undefined_value();
1530 1531 1532
}


1533
MaybeObject* CallStubCompiler::GetCode(PropertyType type, String* name) {
1534
  int argc = arguments_.immediate();
1535
  Code::Flags flags = Code::ComputeMonomorphicFlags(kind_,
1536
                                                    type,
1537
                                                    cache_holder_,
1538
                                                    in_loop_,
1539
                                                    argc);
1540
  return GetCodeWithFlags(flags, name);
1541 1542 1543
}


1544
MaybeObject* CallStubCompiler::GetCode(JSFunction* function) {
1545 1546 1547 1548 1549 1550 1551 1552
  String* function_name = NULL;
  if (function->shared()->name()->IsString()) {
    function_name = String::cast(function->shared()->name());
  }
  return GetCode(CONSTANT_FUNCTION, function_name);
}


1553
MaybeObject* ConstructStubCompiler::GetCode() {
1554
  Code::Flags flags = Code::ComputeFlags(Code::STUB);
1555 1556 1557
  Object* result;
  { MaybeObject* maybe_result = GetCodeWithFlags(flags, "ConstructStub");
    if (!maybe_result->ToObject(&result)) return maybe_result;
1558
  }
1559 1560 1561
  Code* code = Code::cast(result);
  USE(code);
  PROFILE(CodeCreateEvent(Logger::STUB_TAG, code, "ConstructStub"));
1562
  return result;
1563 1564 1565
}


1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
CallOptimization::CallOptimization(LookupResult* lookup) {
  if (!lookup->IsProperty() || !lookup->IsCacheable() ||
      lookup->type() != CONSTANT_FUNCTION) {
    Initialize(NULL);
  } else {
    // We only optimize constant function calls.
    Initialize(lookup->GetConstantFunction());
  }
}

CallOptimization::CallOptimization(JSFunction* function) {
  Initialize(function);
}


int CallOptimization::GetPrototypeDepthOfExpectedType(JSObject* object,
                                                      JSObject* holder) const {
  ASSERT(is_simple_api_call_);
  if (expected_receiver_type_ == NULL) return 0;
  int depth = 0;
  while (object != holder) {
    if (object->IsInstanceOf(expected_receiver_type_)) return depth;
    object = JSObject::cast(object->GetPrototype());
    ++depth;
  }
  if (holder->IsInstanceOf(expected_receiver_type_)) return depth;
  return kInvalidProtoDepth;
}


void CallOptimization::Initialize(JSFunction* function) {
  constant_function_ = NULL;
  is_simple_api_call_ = false;
  expected_receiver_type_ = NULL;
  api_call_info_ = NULL;

  if (function == NULL || !function->is_compiled()) return;

  constant_function_ = function;
  AnalyzePossibleApiFunction(function);
}


void CallOptimization::AnalyzePossibleApiFunction(JSFunction* function) {
  SharedFunctionInfo* sfi = function->shared();
  if (!sfi->IsApiFunction()) return;
  FunctionTemplateInfo* info = sfi->get_api_func_data();

  // Require a C++ callback.
  if (info->call_code()->IsUndefined()) return;
  api_call_info_ = CallHandlerInfo::cast(info->call_code());

  // Accept signatures that either have no restrictions at all or
  // only have restrictions on the receiver.
  if (!info->signature()->IsUndefined()) {
    SignatureInfo* signature = SignatureInfo::cast(info->signature());
    if (!signature->args()->IsUndefined()) return;
    if (!signature->receiver()->IsUndefined()) {
      expected_receiver_type_ =
          FunctionTemplateInfo::cast(signature->receiver());
    }
  }

  is_simple_api_call_ = true;
}


1633
} }  // namespace v8::internal