Home | History | Annotate | Download | only in src
      1 // Copyright 2012 the V8 project authors. All rights reserved.
      2 // Redistribution and use in source and binary forms, with or without
      3 // modification, are permitted provided that the following conditions are
      4 // met:
      5 //
      6 //     * Redistributions of source code must retain the above copyright
      7 //       notice, this list of conditions and the following disclaimer.
      8 //     * Redistributions in binary form must reproduce the above
      9 //       copyright notice, this list of conditions and the following
     10 //       disclaimer in the documentation and/or other materials provided
     11 //       with the distribution.
     12 //     * Neither the name of Google Inc. nor the names of its
     13 //       contributors may be used to endorse or promote products derived
     14 //       from this software without specific prior written permission.
     15 //
     16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27 
     28 #include "v8.h"
     29 
     30 #include "accessors.h"
     31 #include "api.h"
     32 #include "arguments.h"
     33 #include "codegen.h"
     34 #include "execution.h"
     35 #include "ic-inl.h"
     36 #include "runtime.h"
     37 #include "stub-cache.h"
     38 
     39 namespace v8 {
     40 namespace internal {
     41 
     42 #ifdef DEBUG
     43 char IC::TransitionMarkFromState(IC::State state) {
     44   switch (state) {
     45     case UNINITIALIZED: return '0';
     46     case PREMONOMORPHIC: return '.';
     47     case MONOMORPHIC: return '1';
     48     case MONOMORPHIC_PROTOTYPE_FAILURE: return '^';
     49     case POLYMORPHIC: return 'P';
     50     case MEGAMORPHIC: return 'N';
     51     case GENERIC: return 'G';
     52 
     53     // We never see the debugger states here, because the state is
     54     // computed from the original code - not the patched code. Let
     55     // these cases fall through to the unreachable code below.
     56     case DEBUG_STUB: break;
     57   }
     58   UNREACHABLE();
     59   return 0;
     60 }
     61 
     62 
     63 const char* GetTransitionMarkModifier(KeyedAccessStoreMode mode) {
     64   if (mode == STORE_NO_TRANSITION_HANDLE_COW) return ".COW";
     65   if (mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
     66     return ".IGNORE_OOB";
     67   }
     68   if (IsGrowStoreMode(mode)) return ".GROW";
     69   return "";
     70 }
     71 
     72 
     73 void IC::TraceIC(const char* type,
     74                  Handle<Object> name) {
     75   if (FLAG_trace_ic) {
     76     Code* new_target = raw_target();
     77     State new_state = new_target->ic_state();
     78     PrintF("[%s%s in ", new_target->is_keyed_stub() ? "Keyed" : "", type);
     79     StackFrameIterator it(isolate());
     80     while (it.frame()->fp() != this->fp()) it.Advance();
     81     StackFrame* raw_frame = it.frame();
     82     if (raw_frame->is_internal()) {
     83       Code* apply_builtin = isolate()->builtins()->builtin(
     84           Builtins::kFunctionApply);
     85       if (raw_frame->unchecked_code() == apply_builtin) {
     86         PrintF("apply from ");
     87         it.Advance();
     88         raw_frame = it.frame();
     89       }
     90     }
     91     JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
     92     ExtraICState extra_state = new_target->extra_ic_state();
     93     const char* modifier =
     94         GetTransitionMarkModifier(
     95             KeyedStoreIC::GetKeyedAccessStoreMode(extra_state));
     96     PrintF(" (%c->%c%s)",
     97            TransitionMarkFromState(state()),
     98            TransitionMarkFromState(new_state),
     99            modifier);
    100     name->Print();
    101     PrintF("]\n");
    102   }
    103 }
    104 
    105 #define TRACE_GENERIC_IC(isolate, type, reason)                 \
    106   do {                                                          \
    107     if (FLAG_trace_ic) {                                        \
    108       PrintF("[%s patching generic stub in ", type);            \
    109       JavaScriptFrame::PrintTop(isolate, stdout, false, true);  \
    110       PrintF(" (%s)]\n", reason);                               \
    111     }                                                           \
    112   } while (false)
    113 
    114 #else
    115 #define TRACE_GENERIC_IC(isolate, type, reason)
    116 #endif  // DEBUG
    117 
    118 #define TRACE_IC(type, name)             \
    119   ASSERT((TraceIC(type, name), true))
    120 
    121 IC::IC(FrameDepth depth, Isolate* isolate)
    122     : isolate_(isolate),
    123       target_set_(false) {
    124   // To improve the performance of the (much used) IC code, we unfold a few
    125   // levels of the stack frame iteration code. This yields a ~35% speedup when
    126   // running DeltaBlue and a ~25% speedup of gbemu with the '--nouse-ic' flag.
    127   const Address entry =
    128       Isolate::c_entry_fp(isolate->thread_local_top());
    129   Address* pc_address =
    130       reinterpret_cast<Address*>(entry + ExitFrameConstants::kCallerPCOffset);
    131   Address fp = Memory::Address_at(entry + ExitFrameConstants::kCallerFPOffset);
    132   // If there's another JavaScript frame on the stack or a
    133   // StubFailureTrampoline, we need to look one frame further down the stack to
    134   // find the frame pointer and the return address stack slot.
    135   if (depth == EXTRA_CALL_FRAME) {
    136     const int kCallerPCOffset = StandardFrameConstants::kCallerPCOffset;
    137     pc_address = reinterpret_cast<Address*>(fp + kCallerPCOffset);
    138     fp = Memory::Address_at(fp + StandardFrameConstants::kCallerFPOffset);
    139   }
    140 #ifdef DEBUG
    141   StackFrameIterator it(isolate);
    142   for (int i = 0; i < depth + 1; i++) it.Advance();
    143   StackFrame* frame = it.frame();
    144   ASSERT(fp == frame->fp() && pc_address == frame->pc_address());
    145 #endif
    146   fp_ = fp;
    147   pc_address_ = StackFrame::ResolveReturnAddressLocation(pc_address);
    148   target_ = handle(raw_target(), isolate);
    149   state_ = target_->ic_state();
    150 }
    151 
    152 
    153 #ifdef ENABLE_DEBUGGER_SUPPORT
    154 Address IC::OriginalCodeAddress() const {
    155   HandleScope scope(isolate());
    156   // Compute the JavaScript frame for the frame pointer of this IC
    157   // structure. We need this to be able to find the function
    158   // corresponding to the frame.
    159   StackFrameIterator it(isolate());
    160   while (it.frame()->fp() != this->fp()) it.Advance();
    161   JavaScriptFrame* frame = JavaScriptFrame::cast(it.frame());
    162   // Find the function on the stack and both the active code for the
    163   // function and the original code.
    164   JSFunction* function = frame->function();
    165   Handle<SharedFunctionInfo> shared(function->shared(), isolate());
    166   Code* code = shared->code();
    167   ASSERT(Debug::HasDebugInfo(shared));
    168   Code* original_code = Debug::GetDebugInfo(shared)->original_code();
    169   ASSERT(original_code->IsCode());
    170   // Get the address of the call site in the active code. This is the
    171   // place where the call to DebugBreakXXX is and where the IC
    172   // normally would be.
    173   Address addr = Assembler::target_address_from_return_address(pc());
    174   // Return the address in the original code. This is the place where
    175   // the call which has been overwritten by the DebugBreakXXX resides
    176   // and the place where the inline cache system should look.
    177   intptr_t delta =
    178       original_code->instruction_start() - code->instruction_start();
    179   return addr + delta;
    180 }
    181 #endif
    182 
    183 
    184 static bool HasInterceptorGetter(JSObject* object) {
    185   return !object->GetNamedInterceptor()->getter()->IsUndefined();
    186 }
    187 
    188 
    189 static bool HasInterceptorSetter(JSObject* object) {
    190   return !object->GetNamedInterceptor()->setter()->IsUndefined();
    191 }
    192 
    193 
    194 static void LookupForRead(Handle<Object> object,
    195                           Handle<String> name,
    196                           LookupResult* lookup) {
    197   // Skip all the objects with named interceptors, but
    198   // without actual getter.
    199   while (true) {
    200     object->Lookup(*name, lookup);
    201     // Besides normal conditions (property not found or it's not
    202     // an interceptor), bail out if lookup is not cacheable: we won't
    203     // be able to IC it anyway and regular lookup should work fine.
    204     if (!lookup->IsInterceptor() || !lookup->IsCacheable()) {
    205       return;
    206     }
    207 
    208     Handle<JSObject> holder(lookup->holder(), lookup->isolate());
    209     if (HasInterceptorGetter(*holder)) {
    210       return;
    211     }
    212 
    213     holder->LocalLookupRealNamedProperty(*name, lookup);
    214     if (lookup->IsFound()) {
    215       ASSERT(!lookup->IsInterceptor());
    216       return;
    217     }
    218 
    219     Handle<Object> proto(holder->GetPrototype(), lookup->isolate());
    220     if (proto->IsNull()) {
    221       ASSERT(!lookup->IsFound());
    222       return;
    223     }
    224 
    225     object = proto;
    226   }
    227 }
    228 
    229 
    230 bool CallIC::TryUpdateExtraICState(LookupResult* lookup,
    231                                    Handle<Object> object) {
    232   if (!lookup->IsConstantFunction()) return false;
    233   JSFunction* function = lookup->GetConstantFunction();
    234   if (!function->shared()->HasBuiltinFunctionId()) return false;
    235 
    236   // Fetch the arguments passed to the called function.
    237   const int argc = target()->arguments_count();
    238   Address entry = isolate()->c_entry_fp(isolate()->thread_local_top());
    239   Address fp = Memory::Address_at(entry + ExitFrameConstants::kCallerFPOffset);
    240   Arguments args(argc + 1,
    241                  &Memory::Object_at(fp +
    242                                     StandardFrameConstants::kCallerSPOffset +
    243                                     argc * kPointerSize));
    244   switch (function->shared()->builtin_function_id()) {
    245     case kStringCharCodeAt:
    246     case kStringCharAt:
    247       if (object->IsString()) {
    248         String* string = String::cast(*object);
    249         // Check there's the right string value or wrapper in the receiver slot.
    250         ASSERT(string == args[0] || string == JSValue::cast(args[0])->value());
    251         // If we're in the default (fastest) state and the index is
    252         // out of bounds, update the state to record this fact.
    253         if (StringStubState::decode(extra_ic_state()) == DEFAULT_STRING_STUB &&
    254             argc >= 1 && args[1]->IsNumber()) {
    255           double index = DoubleToInteger(args.number_at(1));
    256           if (index < 0 || index >= string->length()) {
    257             extra_ic_state_ =
    258                 StringStubState::update(extra_ic_state(),
    259                                         STRING_INDEX_OUT_OF_BOUNDS);
    260             return true;
    261           }
    262         }
    263       }
    264       break;
    265     default:
    266       return false;
    267   }
    268   return false;
    269 }
    270 
    271 
    272 bool IC::TryRemoveInvalidPrototypeDependentStub(Handle<Object> receiver,
    273                                                 Handle<String> name) {
    274   if (target()->is_call_stub()) {
    275     LookupResult lookup(isolate());
    276     LookupForRead(receiver, name, &lookup);
    277     if (static_cast<CallIC*>(this)->TryUpdateExtraICState(&lookup, receiver)) {
    278       return true;
    279     }
    280   }
    281 
    282   if (target()->is_keyed_stub()) {
    283     // Determine whether the failure is due to a name failure.
    284     if (!name->IsName()) return false;
    285     Name* stub_name = target()->FindFirstName();
    286     if (*name != stub_name) return false;
    287   }
    288 
    289   InlineCacheHolderFlag cache_holder =
    290       Code::ExtractCacheHolderFromFlags(target()->flags());
    291 
    292   switch (cache_holder) {
    293     case OWN_MAP:
    294       // The stub was generated for JSObject but called for non-JSObject.
    295       // IC::GetCodeCacheHolder is not applicable.
    296       if (!receiver->IsJSObject()) return false;
    297       break;
    298     case PROTOTYPE_MAP:
    299       // IC::GetCodeCacheHolder is not applicable.
    300       if (receiver->GetPrototype(isolate())->IsNull()) return false;
    301       break;
    302   }
    303 
    304   Handle<Map> map(
    305       IC::GetCodeCacheHolder(isolate(), *receiver, cache_holder)->map());
    306 
    307   // Decide whether the inline cache failed because of changes to the
    308   // receiver itself or changes to one of its prototypes.
    309   //
    310   // If there are changes to the receiver itself, the map of the
    311   // receiver will have changed and the current target will not be in
    312   // the receiver map's code cache.  Therefore, if the current target
    313   // is in the receiver map's code cache, the inline cache failed due
    314   // to prototype check failure.
    315   int index = map->IndexInCodeCache(*name, *target());
    316   if (index >= 0) {
    317     map->RemoveFromCodeCache(*name, *target(), index);
    318     // Handlers are stored in addition to the ICs on the map. Remove those, too.
    319     TryRemoveInvalidHandlers(map, name);
    320     return true;
    321   }
    322 
    323   // The stub is not in the cache. We've ruled out all other kinds of failure
    324   // except for proptotype chain changes, a deprecated map, a map that's
    325   // different from the one that the stub expects, elements kind changes, or a
    326   // constant global property that will become mutable. Threat all those
    327   // situations as prototype failures (stay monomorphic if possible).
    328 
    329   // If the IC is shared between multiple receivers (slow dictionary mode), then
    330   // the map cannot be deprecated and the stub invalidated.
    331   if (cache_holder == OWN_MAP) {
    332     Map* old_map = target()->FindFirstMap();
    333     if (old_map == *map) return true;
    334     if (old_map != NULL) {
    335       if (old_map->is_deprecated()) return true;
    336       if (IsMoreGeneralElementsKindTransition(old_map->elements_kind(),
    337                                               map->elements_kind())) {
    338         return true;
    339       }
    340     }
    341   }
    342 
    343   if (receiver->IsGlobalObject()) {
    344     LookupResult lookup(isolate());
    345     GlobalObject* global = GlobalObject::cast(*receiver);
    346     global->LocalLookupRealNamedProperty(*name, &lookup);
    347     if (!lookup.IsFound()) return false;
    348     PropertyCell* cell = global->GetPropertyCell(&lookup);
    349     return cell->type()->IsConstant();
    350   }
    351 
    352   return false;
    353 }
    354 
    355 
    356 void IC::TryRemoveInvalidHandlers(Handle<Map> map, Handle<String> name) {
    357   CodeHandleList handlers;
    358   target()->FindHandlers(&handlers);
    359   for (int i = 0; i < handlers.length(); i++) {
    360     Handle<Code> handler = handlers.at(i);
    361     int index = map->IndexInCodeCache(*name, *handler);
    362     if (index >= 0) {
    363       map->RemoveFromCodeCache(*name, *handler, index);
    364       return;
    365     }
    366   }
    367 }
    368 
    369 
    370 void IC::UpdateState(Handle<Object> receiver, Handle<Object> name) {
    371   if (!name->IsString()) return;
    372   if (state() != MONOMORPHIC) {
    373     if (state() == POLYMORPHIC && receiver->IsHeapObject()) {
    374       TryRemoveInvalidHandlers(
    375           handle(Handle<HeapObject>::cast(receiver)->map()),
    376           Handle<String>::cast(name));
    377     }
    378     return;
    379   }
    380   if (receiver->IsUndefined() || receiver->IsNull()) return;
    381 
    382   // Remove the target from the code cache if it became invalid
    383   // because of changes in the prototype chain to avoid hitting it
    384   // again.
    385   if (TryRemoveInvalidPrototypeDependentStub(
    386           receiver, Handle<String>::cast(name))) {
    387     return MarkMonomorphicPrototypeFailure();
    388   }
    389 
    390   // The builtins object is special.  It only changes when JavaScript
    391   // builtins are loaded lazily.  It is important to keep inline
    392   // caches for the builtins object monomorphic.  Therefore, if we get
    393   // an inline cache miss for the builtins object after lazily loading
    394   // JavaScript builtins, we return uninitialized as the state to
    395   // force the inline cache back to monomorphic state.
    396   if (receiver->IsJSBuiltinsObject()) state_ = UNINITIALIZED;
    397 }
    398 
    399 
    400 RelocInfo::Mode IC::ComputeMode() {
    401   Address addr = address();
    402   Code* code = Code::cast(isolate()->FindCodeObject(addr));
    403   for (RelocIterator it(code, RelocInfo::kCodeTargetMask);
    404        !it.done(); it.next()) {
    405     RelocInfo* info = it.rinfo();
    406     if (info->pc() == addr) return info->rmode();
    407   }
    408   UNREACHABLE();
    409   return RelocInfo::NONE32;
    410 }
    411 
    412 
    413 Failure* IC::TypeError(const char* type,
    414                        Handle<Object> object,
    415                        Handle<Object> key) {
    416   HandleScope scope(isolate());
    417   Handle<Object> args[2] = { key, object };
    418   Handle<Object> error = isolate()->factory()->NewTypeError(
    419       type, HandleVector(args, 2));
    420   return isolate()->Throw(*error);
    421 }
    422 
    423 
    424 Failure* IC::ReferenceError(const char* type, Handle<String> name) {
    425   HandleScope scope(isolate());
    426   Handle<Object> error = isolate()->factory()->NewReferenceError(
    427       type, HandleVector(&name, 1));
    428   return isolate()->Throw(*error);
    429 }
    430 
    431 
    432 static int ComputeTypeInfoCountDelta(IC::State old_state, IC::State new_state) {
    433   bool was_uninitialized =
    434       old_state == UNINITIALIZED || old_state == PREMONOMORPHIC;
    435   bool is_uninitialized =
    436       new_state == UNINITIALIZED || new_state == PREMONOMORPHIC;
    437   return (was_uninitialized && !is_uninitialized) ?  1 :
    438          (!was_uninitialized && is_uninitialized) ? -1 : 0;
    439 }
    440 
    441 
    442 void IC::PostPatching(Address address, Code* target, Code* old_target) {
    443   if (FLAG_type_info_threshold == 0 && !FLAG_watch_ic_patching) {
    444     return;
    445   }
    446   Isolate* isolate = target->GetHeap()->isolate();
    447   Code* host = isolate->
    448       inner_pointer_to_code_cache()->GetCacheEntry(address)->code;
    449   if (host->kind() != Code::FUNCTION) return;
    450 
    451   if (FLAG_type_info_threshold > 0 &&
    452       old_target->is_inline_cache_stub() &&
    453       target->is_inline_cache_stub()) {
    454     int delta = ComputeTypeInfoCountDelta(old_target->ic_state(),
    455                                           target->ic_state());
    456     // Not all Code objects have TypeFeedbackInfo.
    457     if (host->type_feedback_info()->IsTypeFeedbackInfo() && delta != 0) {
    458       TypeFeedbackInfo* info =
    459           TypeFeedbackInfo::cast(host->type_feedback_info());
    460       info->change_ic_with_type_info_count(delta);
    461     }
    462   }
    463   if (host->type_feedback_info()->IsTypeFeedbackInfo()) {
    464     TypeFeedbackInfo* info =
    465         TypeFeedbackInfo::cast(host->type_feedback_info());
    466     info->change_own_type_change_checksum();
    467   }
    468   if (FLAG_watch_ic_patching) {
    469     host->set_profiler_ticks(0);
    470     isolate->runtime_profiler()->NotifyICChanged();
    471   }
    472   // TODO(2029): When an optimized function is patched, it would
    473   // be nice to propagate the corresponding type information to its
    474   // unoptimized version for the benefit of later inlining.
    475 }
    476 
    477 
    478 void IC::Clear(Isolate* isolate, Address address) {
    479   Code* target = GetTargetAtAddress(address);
    480 
    481   // Don't clear debug break inline cache as it will remove the break point.
    482   if (target->is_debug_stub()) return;
    483 
    484   switch (target->kind()) {
    485     case Code::LOAD_IC: return LoadIC::Clear(isolate, address, target);
    486     case Code::KEYED_LOAD_IC:
    487       return KeyedLoadIC::Clear(isolate, address, target);
    488     case Code::STORE_IC: return StoreIC::Clear(isolate, address, target);
    489     case Code::KEYED_STORE_IC:
    490       return KeyedStoreIC::Clear(isolate, address, target);
    491     case Code::CALL_IC: return CallIC::Clear(address, target);
    492     case Code::KEYED_CALL_IC:  return KeyedCallIC::Clear(address, target);
    493     case Code::COMPARE_IC: return CompareIC::Clear(isolate, address, target);
    494     case Code::COMPARE_NIL_IC: return CompareNilIC::Clear(address, target);
    495     case Code::BINARY_OP_IC:
    496     case Code::TO_BOOLEAN_IC:
    497       // Clearing these is tricky and does not
    498       // make any performance difference.
    499       return;
    500     default: UNREACHABLE();
    501   }
    502 }
    503 
    504 
    505 void CallICBase::Clear(Address address, Code* target) {
    506   if (IsCleared(target)) return;
    507   bool contextual = CallICBase::Contextual::decode(target->extra_ic_state());
    508   Code* code =
    509       target->GetIsolate()->stub_cache()->FindCallInitialize(
    510           target->arguments_count(),
    511           contextual ? RelocInfo::CODE_TARGET_CONTEXT : RelocInfo::CODE_TARGET,
    512           target->kind());
    513   SetTargetAtAddress(address, code);
    514 }
    515 
    516 
    517 void KeyedLoadIC::Clear(Isolate* isolate, Address address, Code* target) {
    518   if (IsCleared(target)) return;
    519   // Make sure to also clear the map used in inline fast cases.  If we
    520   // do not clear these maps, cached code can keep objects alive
    521   // through the embedded maps.
    522   SetTargetAtAddress(address, *pre_monomorphic_stub(isolate));
    523 }
    524 
    525 
    526 void LoadIC::Clear(Isolate* isolate, Address address, Code* target) {
    527   if (IsCleared(target)) return;
    528   SetTargetAtAddress(address, *pre_monomorphic_stub(isolate));
    529 }
    530 
    531 
    532 void StoreIC::Clear(Isolate* isolate, Address address, Code* target) {
    533   if (IsCleared(target)) return;
    534   SetTargetAtAddress(address,
    535       *pre_monomorphic_stub(
    536           isolate, StoreIC::GetStrictMode(target->extra_ic_state())));
    537 }
    538 
    539 
    540 void KeyedStoreIC::Clear(Isolate* isolate, Address address, Code* target) {
    541   if (IsCleared(target)) return;
    542   SetTargetAtAddress(address,
    543       *pre_monomorphic_stub(
    544           isolate, StoreIC::GetStrictMode(target->extra_ic_state())));
    545 }
    546 
    547 
    548 void CompareIC::Clear(Isolate* isolate, Address address, Code* target) {
    549   ASSERT(target->major_key() == CodeStub::CompareIC);
    550   CompareIC::State handler_state;
    551   Token::Value op;
    552   ICCompareStub::DecodeMinorKey(target->stub_info(), NULL, NULL,
    553                                 &handler_state, &op);
    554   // Only clear CompareICs that can retain objects.
    555   if (handler_state != KNOWN_OBJECT) return;
    556   SetTargetAtAddress(address, GetRawUninitialized(isolate, op));
    557   PatchInlinedSmiCode(address, DISABLE_INLINED_SMI_CHECK);
    558 }
    559 
    560 
    561 Handle<Object> CallICBase::TryCallAsFunction(Handle<Object> object) {
    562   Handle<Object> delegate = Execution::GetFunctionDelegate(isolate(), object);
    563 
    564   if (delegate->IsJSFunction() && !object->IsJSFunctionProxy()) {
    565     // Patch the receiver and use the delegate as the function to
    566     // invoke. This is used for invoking objects as if they were functions.
    567     const int argc = target()->arguments_count();
    568     StackFrameLocator locator(isolate());
    569     JavaScriptFrame* frame = locator.FindJavaScriptFrame(0);
    570     int index = frame->ComputeExpressionsCount() - (argc + 1);
    571     frame->SetExpression(index, *object);
    572   }
    573 
    574   return delegate;
    575 }
    576 
    577 
    578 void CallICBase::ReceiverToObjectIfRequired(Handle<Object> callee,
    579                                             Handle<Object> object) {
    580   while (callee->IsJSFunctionProxy()) {
    581     callee = Handle<Object>(JSFunctionProxy::cast(*callee)->call_trap(),
    582                             isolate());
    583   }
    584 
    585   if (callee->IsJSFunction()) {
    586     Handle<JSFunction> function = Handle<JSFunction>::cast(callee);
    587     if (!function->shared()->is_classic_mode() || function->IsBuiltin()) {
    588       // Do not wrap receiver for strict mode functions or for builtins.
    589       return;
    590     }
    591   }
    592 
    593   // And only wrap string, number or boolean.
    594   if (object->IsString() || object->IsNumber() || object->IsBoolean()) {
    595     // Change the receiver to the result of calling ToObject on it.
    596     const int argc = this->target()->arguments_count();
    597     StackFrameLocator locator(isolate());
    598     JavaScriptFrame* frame = locator.FindJavaScriptFrame(0);
    599     int index = frame->ComputeExpressionsCount() - (argc + 1);
    600     frame->SetExpression(index, *isolate()->factory()->ToObject(object));
    601   }
    602 }
    603 
    604 
    605 static bool MigrateDeprecated(Handle<Object> object) {
    606   if (!object->IsJSObject()) return false;
    607   Handle<JSObject> receiver = Handle<JSObject>::cast(object);
    608   if (!receiver->map()->is_deprecated()) return false;
    609   JSObject::MigrateInstance(Handle<JSObject>::cast(object));
    610   return true;
    611 }
    612 
    613 
    614 MaybeObject* CallICBase::LoadFunction(Handle<Object> object,
    615                                       Handle<String> name) {
    616   bool use_ic = MigrateDeprecated(object) ? false : FLAG_use_ic;
    617 
    618   // If the object is undefined or null it's illegal to try to get any
    619   // of its properties; throw a TypeError in that case.
    620   if (object->IsUndefined() || object->IsNull()) {
    621     return TypeError("non_object_property_call", object, name);
    622   }
    623 
    624   // Check if the name is trivially convertible to an index and get
    625   // the element if so.
    626   uint32_t index;
    627   if (name->AsArrayIndex(&index)) {
    628     Handle<Object> result = Object::GetElement(isolate(), object, index);
    629     RETURN_IF_EMPTY_HANDLE(isolate(), result);
    630     if (result->IsJSFunction()) return *result;
    631 
    632     // Try to find a suitable function delegate for the object at hand.
    633     result = TryCallAsFunction(result);
    634     if (result->IsJSFunction()) return *result;
    635 
    636     // Otherwise, it will fail in the lookup step.
    637   }
    638 
    639   // Lookup the property in the object.
    640   LookupResult lookup(isolate());
    641   LookupForRead(object, name, &lookup);
    642 
    643   if (!lookup.IsFound()) {
    644     // If the object does not have the requested property, check which
    645     // exception we need to throw.
    646     return IsUndeclaredGlobal(object)
    647         ? ReferenceError("not_defined", name)
    648         : TypeError("undefined_method", object, name);
    649   }
    650 
    651   // Lookup is valid: Update inline cache and stub cache.
    652   if (use_ic) UpdateCaches(&lookup, object, name);
    653 
    654   // Get the property.
    655   PropertyAttributes attr;
    656   Handle<Object> result =
    657       Object::GetProperty(object, object, &lookup, name, &attr);
    658   RETURN_IF_EMPTY_HANDLE(isolate(), result);
    659 
    660   if (lookup.IsInterceptor() && attr == ABSENT) {
    661     // If the object does not have the requested property, check which
    662     // exception we need to throw.
    663     return IsUndeclaredGlobal(object)
    664         ? ReferenceError("not_defined", name)
    665         : TypeError("undefined_method", object, name);
    666   }
    667 
    668   ASSERT(!result->IsTheHole());
    669 
    670   // Make receiver an object if the callee requires it. Strict mode or builtin
    671   // functions do not wrap the receiver, non-strict functions and objects
    672   // called as functions do.
    673   ReceiverToObjectIfRequired(result, object);
    674 
    675   if (result->IsJSFunction()) {
    676     Handle<JSFunction> function = Handle<JSFunction>::cast(result);
    677 #ifdef ENABLE_DEBUGGER_SUPPORT
    678     // Handle stepping into a function if step into is active.
    679     Debug* debug = isolate()->debug();
    680     if (debug->StepInActive()) {
    681       // Protect the result in a handle as the debugger can allocate and might
    682       // cause GC.
    683       debug->HandleStepIn(function, object, fp(), false);
    684     }
    685 #endif
    686     return *function;
    687   }
    688 
    689   // Try to find a suitable function delegate for the object at hand.
    690   result = TryCallAsFunction(result);
    691   if (result->IsJSFunction()) return *result;
    692 
    693   return TypeError("property_not_function", object, name);
    694 }
    695 
    696 
    697 Handle<Code> CallICBase::ComputeMonomorphicStub(LookupResult* lookup,
    698                                                 Handle<Object> object,
    699                                                 Handle<String> name) {
    700   int argc = target()->arguments_count();
    701   Handle<JSObject> holder(lookup->holder(), isolate());
    702   switch (lookup->type()) {
    703     case FIELD: {
    704       PropertyIndex index = lookup->GetFieldIndex();
    705       return isolate()->stub_cache()->ComputeCallField(
    706           argc, kind_, extra_ic_state(), name, object, holder, index);
    707     }
    708     case CONSTANT: {
    709       if (!lookup->IsConstantFunction()) return Handle<Code>::null();
    710       // Get the constant function and compute the code stub for this
    711       // call; used for rewriting to monomorphic state and making sure
    712       // that the code stub is in the stub cache.
    713       Handle<JSFunction> function(lookup->GetConstantFunction(), isolate());
    714       return isolate()->stub_cache()->ComputeCallConstant(
    715           argc, kind_, extra_ic_state(), name, object, holder, function);
    716     }
    717     case NORMAL: {
    718       // If we return a null handle, the IC will not be patched.
    719       if (!object->IsJSObject()) return Handle<Code>::null();
    720       Handle<JSObject> receiver = Handle<JSObject>::cast(object);
    721 
    722       if (holder->IsGlobalObject()) {
    723         Handle<GlobalObject> global = Handle<GlobalObject>::cast(holder);
    724         Handle<PropertyCell> cell(
    725             global->GetPropertyCell(lookup), isolate());
    726         if (!cell->value()->IsJSFunction()) return Handle<Code>::null();
    727         Handle<JSFunction> function(JSFunction::cast(cell->value()));
    728         return isolate()->stub_cache()->ComputeCallGlobal(
    729             argc, kind_, extra_ic_state(), name,
    730             receiver, global, cell, function);
    731       } else {
    732         // There is only one shared stub for calling normalized
    733         // properties. It does not traverse the prototype chain, so the
    734         // property must be found in the receiver for the stub to be
    735         // applicable.
    736         if (!holder.is_identical_to(receiver)) return Handle<Code>::null();
    737         return isolate()->stub_cache()->ComputeCallNormal(
    738             argc, kind_, extra_ic_state());
    739       }
    740       break;
    741     }
    742     case INTERCEPTOR:
    743       ASSERT(HasInterceptorGetter(*holder));
    744       return isolate()->stub_cache()->ComputeCallInterceptor(
    745           argc, kind_, extra_ic_state(), name, object, holder);
    746     default:
    747       return Handle<Code>::null();
    748   }
    749 }
    750 
    751 
    752 Handle<Code> CallICBase::megamorphic_stub() {
    753   return isolate()->stub_cache()->ComputeCallMegamorphic(
    754       target()->arguments_count(), kind_, extra_ic_state());
    755 }
    756 
    757 
    758 Handle<Code> CallICBase::pre_monomorphic_stub() {
    759   return isolate()->stub_cache()->ComputeCallPreMonomorphic(
    760       target()->arguments_count(), kind_, extra_ic_state());
    761 }
    762 
    763 
    764 void CallICBase::UpdateCaches(LookupResult* lookup,
    765                               Handle<Object> object,
    766                               Handle<String> name) {
    767   // Bail out if we didn't find a result.
    768   if (!lookup->IsProperty() || !lookup->IsCacheable()) return;
    769 
    770   if (state() == UNINITIALIZED) {
    771     set_target(*pre_monomorphic_stub());
    772     TRACE_IC("CallIC", name);
    773     return;
    774   }
    775 
    776   Handle<Code> code = ComputeMonomorphicStub(lookup, object, name);
    777   // If there's no appropriate stub we simply avoid updating the caches.
    778   // TODO(verwaest): Install a slow fallback in this case to avoid not learning,
    779   // and deopting Crankshaft code.
    780   if (code.is_null()) return;
    781 
    782   Handle<JSObject> cache_object = object->IsJSObject()
    783       ? Handle<JSObject>::cast(object)
    784       : Handle<JSObject>(JSObject::cast(object->GetPrototype(isolate())),
    785                          isolate());
    786 
    787   PatchCache(CurrentTypeOf(cache_object, isolate()), name, code);
    788   TRACE_IC("CallIC", name);
    789 }
    790 
    791 
    792 MaybeObject* KeyedCallIC::LoadFunction(Handle<Object> object,
    793                                        Handle<Object> key) {
    794   if (key->IsInternalizedString()) {
    795     return CallICBase::LoadFunction(object, Handle<String>::cast(key));
    796   }
    797 
    798   if (object->IsUndefined() || object->IsNull()) {
    799     return TypeError("non_object_property_call", object, key);
    800   }
    801 
    802   bool use_ic = MigrateDeprecated(object)
    803       ? false : FLAG_use_ic && !object->IsAccessCheckNeeded();
    804 
    805   if (use_ic && state() != MEGAMORPHIC) {
    806     ASSERT(!object->IsJSGlobalProxy());
    807     int argc = target()->arguments_count();
    808     Handle<Code> stub;
    809 
    810     // Use the KeyedArrayCallStub if the call is of the form array[smi](...),
    811     // where array is an instance of one of the initial array maps (without
    812     // extra named properties).
    813     // TODO(verwaest): Also support keyed calls on instances of other maps.
    814     if (object->IsJSArray() && key->IsSmi()) {
    815       Handle<JSArray> array = Handle<JSArray>::cast(object);
    816       ElementsKind kind = array->map()->elements_kind();
    817       if (IsFastObjectElementsKind(kind) &&
    818           array->map() == isolate()->get_initial_js_array_map(kind)) {
    819         KeyedArrayCallStub stub_gen(IsHoleyElementsKind(kind), argc);
    820         stub = stub_gen.GetCode(isolate());
    821       }
    822     }
    823 
    824     if (stub.is_null()) {
    825       stub = isolate()->stub_cache()->ComputeCallMegamorphic(
    826           argc, Code::KEYED_CALL_IC, kNoExtraICState);
    827       if (object->IsJSObject()) {
    828         Handle<JSObject> receiver = Handle<JSObject>::cast(object);
    829         if (receiver->elements()->map() ==
    830             isolate()->heap()->non_strict_arguments_elements_map()) {
    831           stub = isolate()->stub_cache()->ComputeCallArguments(argc);
    832         }
    833       }
    834       ASSERT(!stub.is_null());
    835     }
    836     set_target(*stub);
    837     TRACE_IC("CallIC", key);
    838   }
    839 
    840   Handle<Object> result = GetProperty(isolate(), object, key);
    841   RETURN_IF_EMPTY_HANDLE(isolate(), result);
    842 
    843   // Make receiver an object if the callee requires it. Strict mode or builtin
    844   // functions do not wrap the receiver, non-strict functions and objects
    845   // called as functions do.
    846   ReceiverToObjectIfRequired(result, object);
    847   if (result->IsJSFunction()) return *result;
    848 
    849   result = TryCallAsFunction(result);
    850   if (result->IsJSFunction()) return *result;
    851 
    852   return TypeError("property_not_function", object, key);
    853 }
    854 
    855 
    856 MaybeObject* LoadIC::Load(Handle<Object> object,
    857                           Handle<String> name) {
    858   // If the object is undefined or null it's illegal to try to get any
    859   // of its properties; throw a TypeError in that case.
    860   if (object->IsUndefined() || object->IsNull()) {
    861     return TypeError("non_object_property_load", object, name);
    862   }
    863 
    864   if (FLAG_use_ic) {
    865     // Use specialized code for getting the length of strings and
    866     // string wrapper objects.  The length property of string wrapper
    867     // objects is read-only and therefore always returns the length of
    868     // the underlying string value.  See ECMA-262 15.5.5.1.
    869     if (object->IsStringWrapper() &&
    870         name->Equals(isolate()->heap()->length_string())) {
    871       Handle<Code> stub;
    872       if (state() == UNINITIALIZED) {
    873         stub = pre_monomorphic_stub();
    874       } else if (state() == PREMONOMORPHIC || state() == MONOMORPHIC) {
    875         StringLengthStub string_length_stub(kind());
    876         stub = string_length_stub.GetCode(isolate());
    877       } else if (state() != MEGAMORPHIC) {
    878         ASSERT(state() != GENERIC);
    879         stub = megamorphic_stub();
    880       }
    881       if (!stub.is_null()) {
    882         set_target(*stub);
    883         if (FLAG_trace_ic) PrintF("[LoadIC : +#length /stringwrapper]\n");
    884       }
    885       // Get the string if we have a string wrapper object.
    886       String* string = String::cast(JSValue::cast(*object)->value());
    887       return Smi::FromInt(string->length());
    888     }
    889 
    890     // Use specialized code for getting prototype of functions.
    891     if (object->IsJSFunction() &&
    892         name->Equals(isolate()->heap()->prototype_string()) &&
    893         Handle<JSFunction>::cast(object)->should_have_prototype()) {
    894       Handle<Code> stub;
    895       if (state() == UNINITIALIZED) {
    896         stub = pre_monomorphic_stub();
    897       } else if (state() == PREMONOMORPHIC) {
    898         FunctionPrototypeStub function_prototype_stub(kind());
    899         stub = function_prototype_stub.GetCode(isolate());
    900       } else if (state() != MEGAMORPHIC) {
    901         ASSERT(state() != GENERIC);
    902         stub = megamorphic_stub();
    903       }
    904       if (!stub.is_null()) {
    905         set_target(*stub);
    906         if (FLAG_trace_ic) PrintF("[LoadIC : +#prototype /function]\n");
    907       }
    908       return *Accessors::FunctionGetPrototype(Handle<JSFunction>::cast(object));
    909     }
    910   }
    911 
    912   // Check if the name is trivially convertible to an index and get
    913   // the element or char if so.
    914   uint32_t index;
    915   if (kind() == Code::KEYED_LOAD_IC && name->AsArrayIndex(&index)) {
    916     // Rewrite to the generic keyed load stub.
    917     if (FLAG_use_ic) set_target(*generic_stub());
    918     return Runtime::GetElementOrCharAtOrFail(isolate(), object, index);
    919   }
    920 
    921   bool use_ic = MigrateDeprecated(object) ? false : FLAG_use_ic;
    922 
    923   // Named lookup in the object.
    924   LookupResult lookup(isolate());
    925   LookupForRead(object, name, &lookup);
    926 
    927   // If we did not find a property, check if we need to throw an exception.
    928   if (!lookup.IsFound()) {
    929     if (IsUndeclaredGlobal(object)) {
    930       return ReferenceError("not_defined", name);
    931     }
    932     LOG(isolate(), SuspectReadEvent(*name, *object));
    933   }
    934 
    935   // Update inline cache and stub cache.
    936   if (use_ic) UpdateCaches(&lookup, object, name);
    937 
    938   PropertyAttributes attr;
    939   // Get the property.
    940   Handle<Object> result =
    941       Object::GetProperty(object, object, &lookup, name, &attr);
    942   RETURN_IF_EMPTY_HANDLE(isolate(), result);
    943   // If the property is not present, check if we need to throw an
    944   // exception.
    945   if ((lookup.IsInterceptor() || lookup.IsHandler()) &&
    946       attr == ABSENT && IsUndeclaredGlobal(object)) {
    947     return ReferenceError("not_defined", name);
    948   }
    949   return *result;
    950 }
    951 
    952 
    953 static bool AddOneReceiverMapIfMissing(MapHandleList* receiver_maps,
    954                                        Handle<Map> new_receiver_map) {
    955   ASSERT(!new_receiver_map.is_null());
    956   for (int current = 0; current < receiver_maps->length(); ++current) {
    957     if (!receiver_maps->at(current).is_null() &&
    958         receiver_maps->at(current).is_identical_to(new_receiver_map)) {
    959       return false;
    960     }
    961   }
    962   receiver_maps->Add(new_receiver_map);
    963   return true;
    964 }
    965 
    966 
    967 bool IC::UpdatePolymorphicIC(Handle<Type> type,
    968                              Handle<String> name,
    969                              Handle<Code> code) {
    970   if (!code->is_handler()) return false;
    971   TypeHandleList types;
    972   CodeHandleList handlers;
    973 
    974   int number_of_valid_types;
    975   int handler_to_overwrite = -1;
    976 
    977   target()->FindAllTypes(&types);
    978   int number_of_types = types.length();
    979   number_of_valid_types = number_of_types;
    980 
    981   for (int i = 0; i < number_of_types; i++) {
    982     Handle<Type> current_type = types.at(i);
    983     // Filter out deprecated maps to ensure their instances get migrated.
    984     if (current_type->IsClass() && current_type->AsClass()->is_deprecated()) {
    985       number_of_valid_types--;
    986     // If the receiver type is already in the polymorphic IC, this indicates
    987     // there was a prototoype chain failure. In that case, just overwrite the
    988     // handler.
    989     } else if (type->IsCurrently(current_type)) {
    990       ASSERT(handler_to_overwrite == -1);
    991       number_of_valid_types--;
    992       handler_to_overwrite = i;
    993     }
    994   }
    995 
    996   if (number_of_valid_types >= 4) return false;
    997   if (number_of_types == 0) return false;
    998   if (!target()->FindHandlers(&handlers, types.length())) return false;
    999 
   1000   number_of_valid_types++;
   1001   if (handler_to_overwrite >= 0) {
   1002     handlers.Set(handler_to_overwrite, code);
   1003   } else {
   1004     types.Add(type);
   1005     handlers.Add(code);
   1006   }
   1007 
   1008   Handle<Code> ic = isolate()->stub_cache()->ComputePolymorphicIC(
   1009       &types, &handlers, number_of_valid_types, name, extra_ic_state());
   1010   set_target(*ic);
   1011   return true;
   1012 }
   1013 
   1014 
   1015 Handle<Type> IC::CurrentTypeOf(Handle<Object> object, Isolate* isolate) {
   1016   Type* type = object->IsJSGlobalObject()
   1017       ? Type::Constant(Handle<JSGlobalObject>::cast(object))
   1018       : Type::OfCurrently(object);
   1019   return handle(type, isolate);
   1020 }
   1021 
   1022 
   1023 Handle<Map> IC::TypeToMap(Type* type, Isolate* isolate) {
   1024   if (type->Is(Type::Number())) return isolate->factory()->heap_number_map();
   1025   if (type->Is(Type::Boolean())) return isolate->factory()->oddball_map();
   1026   if (type->IsConstant()) {
   1027     return handle(Handle<JSGlobalObject>::cast(type->AsConstant())->map());
   1028   }
   1029   ASSERT(type->IsClass());
   1030   return type->AsClass();
   1031 }
   1032 
   1033 
   1034 Type* IC::MapToType(Handle<Map> map) {
   1035   if (map->instance_type() == HEAP_NUMBER_TYPE) return Type::Number();
   1036   // The only oddballs that can be recorded in ICs are booleans.
   1037   if (map->instance_type() == ODDBALL_TYPE) return Type::Boolean();
   1038   return Type::Class(map);
   1039 }
   1040 
   1041 
   1042 void IC::UpdateMonomorphicIC(Handle<Type> type,
   1043                              Handle<Code> handler,
   1044                              Handle<String> name) {
   1045   if (!handler->is_handler()) return set_target(*handler);
   1046   Handle<Code> ic = isolate()->stub_cache()->ComputeMonomorphicIC(
   1047       name, type, handler, extra_ic_state());
   1048   set_target(*ic);
   1049 }
   1050 
   1051 
   1052 void IC::CopyICToMegamorphicCache(Handle<String> name) {
   1053   TypeHandleList types;
   1054   CodeHandleList handlers;
   1055   target()->FindAllTypes(&types);
   1056   if (!target()->FindHandlers(&handlers, types.length())) return;
   1057   for (int i = 0; i < types.length(); i++) {
   1058     UpdateMegamorphicCache(*types.at(i), *name, *handlers.at(i));
   1059   }
   1060 }
   1061 
   1062 
   1063 bool IC::IsTransitionOfMonomorphicTarget(Type* type) {
   1064   if (!type->IsClass()) return false;
   1065   Map* receiver_map = *type->AsClass();
   1066   Map* current_map = target()->FindFirstMap();
   1067   ElementsKind receiver_elements_kind = receiver_map->elements_kind();
   1068   bool more_general_transition =
   1069       IsMoreGeneralElementsKindTransition(
   1070         current_map->elements_kind(), receiver_elements_kind);
   1071   Map* transitioned_map = more_general_transition
   1072       ? current_map->LookupElementsTransitionMap(receiver_elements_kind)
   1073       : NULL;
   1074 
   1075   return transitioned_map == receiver_map;
   1076 }
   1077 
   1078 
   1079 void IC::PatchCache(Handle<Type> type,
   1080                     Handle<String> name,
   1081                     Handle<Code> code) {
   1082   switch (state()) {
   1083     case UNINITIALIZED:
   1084     case PREMONOMORPHIC:
   1085     case MONOMORPHIC_PROTOTYPE_FAILURE:
   1086       UpdateMonomorphicIC(type, code, name);
   1087       break;
   1088     case MONOMORPHIC: {
   1089       // For now, call stubs are allowed to rewrite to the same stub. This
   1090       // happens e.g., when the field does not contain a function.
   1091       ASSERT(target()->is_call_stub() ||
   1092              target()->is_keyed_call_stub() ||
   1093              !target().is_identical_to(code));
   1094       Code* old_handler = target()->FindFirstHandler();
   1095       if (old_handler == *code && IsTransitionOfMonomorphicTarget(*type)) {
   1096         UpdateMonomorphicIC(type, code, name);
   1097         break;
   1098       }
   1099       // Fall through.
   1100     }
   1101     case POLYMORPHIC:
   1102       if (!target()->is_keyed_stub()) {
   1103         if (UpdatePolymorphicIC(type, name, code)) break;
   1104         CopyICToMegamorphicCache(name);
   1105       }
   1106       set_target(*megamorphic_stub());
   1107       // Fall through.
   1108     case MEGAMORPHIC:
   1109       UpdateMegamorphicCache(*type, *name, *code);
   1110       break;
   1111     case DEBUG_STUB:
   1112       break;
   1113     case GENERIC:
   1114       UNREACHABLE();
   1115       break;
   1116   }
   1117 }
   1118 
   1119 
   1120 Handle<Code> LoadIC::SimpleFieldLoad(int offset,
   1121                                      bool inobject,
   1122                                      Representation representation) {
   1123   if (kind() == Code::LOAD_IC) {
   1124     LoadFieldStub stub(inobject, offset, representation);
   1125     return stub.GetCode(isolate());
   1126   } else {
   1127     KeyedLoadFieldStub stub(inobject, offset, representation);
   1128     return stub.GetCode(isolate());
   1129   }
   1130 }
   1131 
   1132 
   1133 void LoadIC::UpdateCaches(LookupResult* lookup,
   1134                           Handle<Object> object,
   1135                           Handle<String> name) {
   1136   if (state() == UNINITIALIZED) {
   1137     // This is the first time we execute this inline cache.
   1138     // Set the target to the pre monomorphic stub to delay
   1139     // setting the monomorphic state.
   1140     set_target(*pre_monomorphic_stub());
   1141     TRACE_IC("LoadIC", name);
   1142     return;
   1143   }
   1144 
   1145   Handle<Type> type = CurrentTypeOf(object, isolate());
   1146   Handle<Code> code;
   1147   if (!lookup->IsCacheable()) {
   1148     // Bail out if the result is not cacheable.
   1149     code = slow_stub();
   1150   } else if (!lookup->IsProperty()) {
   1151     if (kind() == Code::LOAD_IC) {
   1152       code = isolate()->stub_cache()->ComputeLoadNonexistent(name, type);
   1153     } else {
   1154       code = slow_stub();
   1155     }
   1156   } else {
   1157     code = ComputeHandler(lookup, object, name);
   1158   }
   1159 
   1160   PatchCache(type, name, code);
   1161   TRACE_IC("LoadIC", name);
   1162 }
   1163 
   1164 
   1165 void IC::UpdateMegamorphicCache(Type* type, Name* name, Code* code) {
   1166   // Cache code holding map should be consistent with
   1167   // GenerateMonomorphicCacheProbe.
   1168   Map* map = *TypeToMap(type, isolate());
   1169   isolate()->stub_cache()->Set(name, map, code);
   1170 }
   1171 
   1172 
   1173 Handle<Code> IC::ComputeHandler(LookupResult* lookup,
   1174                                 Handle<Object> object,
   1175                                 Handle<String> name,
   1176                                 Handle<Object> value) {
   1177   InlineCacheHolderFlag cache_holder = GetCodeCacheForObject(*object);
   1178   Handle<HeapObject> stub_holder(GetCodeCacheHolder(
   1179       isolate(), *object, cache_holder));
   1180 
   1181   Handle<Code> code = isolate()->stub_cache()->FindHandler(
   1182       name, handle(stub_holder->map()), kind(), cache_holder);
   1183   if (!code.is_null()) return code;
   1184 
   1185   code = CompileHandler(lookup, object, name, value, cache_holder);
   1186   ASSERT(code->is_handler());
   1187 
   1188   if (code->type() != Code::NORMAL) {
   1189     HeapObject::UpdateMapCodeCache(stub_holder, name, code);
   1190   }
   1191 
   1192   return code;
   1193 }
   1194 
   1195 
   1196 Handle<Code> LoadIC::CompileHandler(LookupResult* lookup,
   1197                                     Handle<Object> object,
   1198                                     Handle<String> name,
   1199                                     Handle<Object> unused,
   1200                                     InlineCacheHolderFlag cache_holder) {
   1201   if (object->IsString() && name->Equals(isolate()->heap()->length_string())) {
   1202     int length_index = String::kLengthOffset / kPointerSize;
   1203     return SimpleFieldLoad(length_index);
   1204   }
   1205 
   1206   Handle<Type> type = CurrentTypeOf(object, isolate());
   1207   Handle<JSObject> holder(lookup->holder());
   1208   LoadStubCompiler compiler(isolate(), kNoExtraICState, cache_holder, kind());
   1209 
   1210   switch (lookup->type()) {
   1211     case FIELD: {
   1212       PropertyIndex field = lookup->GetFieldIndex();
   1213       if (object.is_identical_to(holder)) {
   1214         return SimpleFieldLoad(field.translate(holder),
   1215                                field.is_inobject(holder),
   1216                                lookup->representation());
   1217       }
   1218       return compiler.CompileLoadField(
   1219           type, holder, name, field, lookup->representation());
   1220     }
   1221     case CONSTANT: {
   1222       Handle<Object> constant(lookup->GetConstant(), isolate());
   1223       // TODO(2803): Don't compute a stub for cons strings because they cannot
   1224       // be embedded into code.
   1225       if (constant->IsConsString()) break;
   1226       return compiler.CompileLoadConstant(type, holder, name, constant);
   1227     }
   1228     case NORMAL:
   1229       if (kind() != Code::LOAD_IC) break;
   1230       if (holder->IsGlobalObject()) {
   1231         Handle<GlobalObject> global = Handle<GlobalObject>::cast(holder);
   1232         Handle<PropertyCell> cell(
   1233             global->GetPropertyCell(lookup), isolate());
   1234         Handle<Code> code = compiler.CompileLoadGlobal(
   1235             type, global, cell, name, lookup->IsDontDelete());
   1236         // TODO(verwaest): Move caching of these NORMAL stubs outside as well.
   1237         Handle<HeapObject> stub_holder(GetCodeCacheHolder(
   1238             isolate(), *object, cache_holder));
   1239         HeapObject::UpdateMapCodeCache(stub_holder, name, code);
   1240         return code;
   1241       }
   1242       // There is only one shared stub for loading normalized
   1243       // properties. It does not traverse the prototype chain, so the
   1244       // property must be found in the object for the stub to be
   1245       // applicable.
   1246       if (!object.is_identical_to(holder)) break;
   1247       return isolate()->builtins()->LoadIC_Normal();
   1248     case CALLBACKS: {
   1249       // Use simple field loads for some well-known callback properties.
   1250       if (object->IsJSObject()) {
   1251         Handle<JSObject> receiver = Handle<JSObject>::cast(object);
   1252         Handle<Map> map(receiver->map());
   1253         int object_offset;
   1254         if (Accessors::IsJSObjectFieldAccessor(map, name, &object_offset)) {
   1255           return SimpleFieldLoad(object_offset / kPointerSize);
   1256         }
   1257       }
   1258 
   1259       Handle<Object> callback(lookup->GetCallbackObject(), isolate());
   1260       if (callback->IsExecutableAccessorInfo()) {
   1261         Handle<ExecutableAccessorInfo> info =
   1262             Handle<ExecutableAccessorInfo>::cast(callback);
   1263         if (v8::ToCData<Address>(info->getter()) == 0) break;
   1264         if (!info->IsCompatibleReceiver(*object)) break;
   1265         return compiler.CompileLoadCallback(type, holder, name, info);
   1266       } else if (callback->IsAccessorPair()) {
   1267         Handle<Object> getter(Handle<AccessorPair>::cast(callback)->getter(),
   1268                               isolate());
   1269         if (!getter->IsJSFunction()) break;
   1270         if (holder->IsGlobalObject()) break;
   1271         if (!holder->HasFastProperties()) break;
   1272         Handle<JSFunction> function = Handle<JSFunction>::cast(getter);
   1273         if (!object->IsJSObject() &&
   1274             !function->IsBuiltin() &&
   1275             function->shared()->is_classic_mode()) {
   1276           // Calling non-strict non-builtins with a value as the receiver
   1277           // requires boxing.
   1278           break;
   1279         }
   1280         CallOptimization call_optimization(function);
   1281         if (call_optimization.is_simple_api_call() &&
   1282             call_optimization.IsCompatibleReceiver(*object)) {
   1283           return compiler.CompileLoadCallback(
   1284               type, holder, name, call_optimization);
   1285         }
   1286         return compiler.CompileLoadViaGetter(type, holder, name, function);
   1287       }
   1288       // TODO(dcarney): Handle correctly.
   1289       if (callback->IsDeclaredAccessorInfo()) break;
   1290       ASSERT(callback->IsForeign());
   1291       // No IC support for old-style native accessors.
   1292       break;
   1293     }
   1294     case INTERCEPTOR:
   1295       ASSERT(HasInterceptorGetter(*holder));
   1296       return compiler.CompileLoadInterceptor(type, holder, name);
   1297     default:
   1298       break;
   1299   }
   1300 
   1301   return slow_stub();
   1302 }
   1303 
   1304 
   1305 static Handle<Object> TryConvertKey(Handle<Object> key, Isolate* isolate) {
   1306   // This helper implements a few common fast cases for converting
   1307   // non-smi keys of keyed loads/stores to a smi or a string.
   1308   if (key->IsHeapNumber()) {
   1309     double value = Handle<HeapNumber>::cast(key)->value();
   1310     if (std::isnan(value)) {
   1311       key = isolate->factory()->nan_string();
   1312     } else {
   1313       int int_value = FastD2I(value);
   1314       if (value == int_value && Smi::IsValid(int_value)) {
   1315         key = Handle<Smi>(Smi::FromInt(int_value), isolate);
   1316       }
   1317     }
   1318   } else if (key->IsUndefined()) {
   1319     key = isolate->factory()->undefined_string();
   1320   }
   1321   return key;
   1322 }
   1323 
   1324 
   1325 Handle<Code> KeyedLoadIC::LoadElementStub(Handle<JSObject> receiver) {
   1326   // Don't handle megamorphic property accesses for INTERCEPTORS or CALLBACKS
   1327   // via megamorphic stubs, since they don't have a map in their relocation info
   1328   // and so the stubs can't be harvested for the object needed for a map check.
   1329   if (target()->type() != Code::NORMAL) {
   1330     TRACE_GENERIC_IC(isolate(), "KeyedIC", "non-NORMAL target type");
   1331     return generic_stub();
   1332   }
   1333 
   1334   Handle<Map> receiver_map(receiver->map(), isolate());
   1335   MapHandleList target_receiver_maps;
   1336   if (state() == UNINITIALIZED || state() == PREMONOMORPHIC) {
   1337     // Optimistically assume that ICs that haven't reached the MONOMORPHIC state
   1338     // yet will do so and stay there.
   1339     return isolate()->stub_cache()->ComputeKeyedLoadElement(receiver_map);
   1340   }
   1341 
   1342   if (target().is_identical_to(string_stub())) {
   1343     target_receiver_maps.Add(isolate()->factory()->string_map());
   1344   } else {
   1345     target()->FindAllMaps(&target_receiver_maps);
   1346     if (target_receiver_maps.length() == 0) {
   1347       return isolate()->stub_cache()->ComputeKeyedLoadElement(receiver_map);
   1348     }
   1349   }
   1350 
   1351   // The first time a receiver is seen that is a transitioned version of the
   1352   // previous monomorphic receiver type, assume the new ElementsKind is the
   1353   // monomorphic type. This benefits global arrays that only transition
   1354   // once, and all call sites accessing them are faster if they remain
   1355   // monomorphic. If this optimistic assumption is not true, the IC will
   1356   // miss again and it will become polymorphic and support both the
   1357   // untransitioned and transitioned maps.
   1358   if (state() == MONOMORPHIC &&
   1359       IsMoreGeneralElementsKindTransition(
   1360           target_receiver_maps.at(0)->elements_kind(),
   1361           receiver->GetElementsKind())) {
   1362     return isolate()->stub_cache()->ComputeKeyedLoadElement(receiver_map);
   1363   }
   1364 
   1365   ASSERT(state() != GENERIC);
   1366 
   1367   // Determine the list of receiver maps that this call site has seen,
   1368   // adding the map that was just encountered.
   1369   if (!AddOneReceiverMapIfMissing(&target_receiver_maps, receiver_map)) {
   1370     // If the miss wasn't due to an unseen map, a polymorphic stub
   1371     // won't help, use the generic stub.
   1372     TRACE_GENERIC_IC(isolate(), "KeyedIC", "same map added twice");
   1373     return generic_stub();
   1374   }
   1375 
   1376   // If the maximum number of receiver maps has been exceeded, use the generic
   1377   // version of the IC.
   1378   if (target_receiver_maps.length() > kMaxKeyedPolymorphism) {
   1379     TRACE_GENERIC_IC(isolate(), "KeyedIC", "max polymorph exceeded");
   1380     return generic_stub();
   1381   }
   1382 
   1383   return isolate()->stub_cache()->ComputeLoadElementPolymorphic(
   1384       &target_receiver_maps);
   1385 }
   1386 
   1387 
   1388 MaybeObject* KeyedLoadIC::Load(Handle<Object> object, Handle<Object> key) {
   1389   if (MigrateDeprecated(object)) {
   1390     return Runtime::GetObjectPropertyOrFail(isolate(), object, key);
   1391   }
   1392 
   1393   MaybeObject* maybe_object = NULL;
   1394   Handle<Code> stub = generic_stub();
   1395 
   1396   // Check for values that can be converted into an internalized string directly
   1397   // or is representable as a smi.
   1398   key = TryConvertKey(key, isolate());
   1399 
   1400   if (key->IsInternalizedString()) {
   1401     maybe_object = LoadIC::Load(object, Handle<String>::cast(key));
   1402     if (maybe_object->IsFailure()) return maybe_object;
   1403   } else if (FLAG_use_ic && !object->IsAccessCheckNeeded()) {
   1404     ASSERT(!object->IsJSGlobalProxy());
   1405     if (object->IsString() && key->IsNumber()) {
   1406       if (state() == UNINITIALIZED) stub = string_stub();
   1407     } else if (object->IsJSObject()) {
   1408       Handle<JSObject> receiver = Handle<JSObject>::cast(object);
   1409       if (receiver->elements()->map() ==
   1410           isolate()->heap()->non_strict_arguments_elements_map()) {
   1411         stub = non_strict_arguments_stub();
   1412       } else if (receiver->HasIndexedInterceptor()) {
   1413         stub = indexed_interceptor_stub();
   1414       } else if (!key->ToSmi()->IsFailure() &&
   1415                  (!target().is_identical_to(non_strict_arguments_stub()))) {
   1416         stub = LoadElementStub(receiver);
   1417       }
   1418     }
   1419   }
   1420 
   1421   if (!is_target_set()) {
   1422     if (*stub == *generic_stub()) {
   1423       TRACE_GENERIC_IC(isolate(), "KeyedLoadIC", "set generic");
   1424     }
   1425     ASSERT(!stub.is_null());
   1426     set_target(*stub);
   1427     TRACE_IC("LoadIC", key);
   1428   }
   1429 
   1430   if (maybe_object != NULL) return maybe_object;
   1431   return Runtime::GetObjectPropertyOrFail(isolate(), object, key);
   1432 }
   1433 
   1434 
   1435 static bool LookupForWrite(Handle<JSObject> receiver,
   1436                            Handle<String> name,
   1437                            Handle<Object> value,
   1438                            LookupResult* lookup,
   1439                            IC* ic) {
   1440   Handle<JSObject> holder = receiver;
   1441   receiver->Lookup(*name, lookup);
   1442   if (lookup->IsFound()) {
   1443     if (lookup->IsReadOnly() || !lookup->IsCacheable()) return false;
   1444 
   1445     if (lookup->holder() == *receiver) {
   1446       if (lookup->IsInterceptor() && !HasInterceptorSetter(*receiver)) {
   1447         receiver->LocalLookupRealNamedProperty(*name, lookup);
   1448         return lookup->IsFound() &&
   1449             !lookup->IsReadOnly() &&
   1450             lookup->CanHoldValue(value) &&
   1451             lookup->IsCacheable();
   1452       }
   1453       return lookup->CanHoldValue(value);
   1454     }
   1455 
   1456     if (lookup->IsPropertyCallbacks()) return true;
   1457     // JSGlobalProxy always goes via the runtime, so it's safe to cache.
   1458     if (receiver->IsJSGlobalProxy()) return true;
   1459     // Currently normal holders in the prototype chain are not supported. They
   1460     // would require a runtime positive lookup and verification that the details
   1461     // have not changed.
   1462     if (lookup->IsInterceptor() || lookup->IsNormal()) return false;
   1463     holder = Handle<JSObject>(lookup->holder(), lookup->isolate());
   1464   }
   1465 
   1466   // While normally LookupTransition gets passed the receiver, in this case we
   1467   // pass the holder of the property that we overwrite. This keeps the holder in
   1468   // the LookupResult intact so we can later use it to generate a prototype
   1469   // chain check. This avoids a double lookup, but requires us to pass in the
   1470   // receiver when trying to fetch extra information from the transition.
   1471   receiver->map()->LookupTransition(*holder, *name, lookup);
   1472   if (!lookup->IsTransition()) return false;
   1473   PropertyDetails target_details = lookup->GetTransitionDetails();
   1474   if (target_details.IsReadOnly()) return false;
   1475 
   1476   // If the value that's being stored does not fit in the field that the
   1477   // instance would transition to, create a new transition that fits the value.
   1478   // This has to be done before generating the IC, since that IC will embed the
   1479   // transition target.
   1480   // Ensure the instance and its map were migrated before trying to update the
   1481   // transition target.
   1482   ASSERT(!receiver->map()->is_deprecated());
   1483   if (!value->FitsRepresentation(target_details.representation())) {
   1484     Handle<Map> target(lookup->GetTransitionTarget());
   1485     Map::GeneralizeRepresentation(
   1486         target, target->LastAdded(),
   1487         value->OptimalRepresentation(), FORCE_FIELD);
   1488     // Lookup the transition again since the transition tree may have changed
   1489     // entirely by the migration above.
   1490     receiver->map()->LookupTransition(*holder, *name, lookup);
   1491     if (!lookup->IsTransition()) return false;
   1492     ic->MarkMonomorphicPrototypeFailure();
   1493   }
   1494   return true;
   1495 }
   1496 
   1497 
   1498 MaybeObject* StoreIC::Store(Handle<Object> object,
   1499                             Handle<String> name,
   1500                             Handle<Object> value,
   1501                             JSReceiver::StoreFromKeyed store_mode) {
   1502   if (MigrateDeprecated(object) || object->IsJSProxy()) {
   1503     Handle<Object> result = JSReceiver::SetProperty(
   1504         Handle<JSReceiver>::cast(object), name, value, NONE, strict_mode());
   1505     RETURN_IF_EMPTY_HANDLE(isolate(), result);
   1506     return *result;
   1507   }
   1508 
   1509   // If the object is undefined or null it's illegal to try to set any
   1510   // properties on it; throw a TypeError in that case.
   1511   if (object->IsUndefined() || object->IsNull()) {
   1512     return TypeError("non_object_property_store", object, name);
   1513   }
   1514 
   1515   // The length property of string values is read-only. Throw in strict mode.
   1516   if (strict_mode() == kStrictMode && object->IsString() &&
   1517       name->Equals(isolate()->heap()->length_string())) {
   1518     return TypeError("strict_read_only_property", object, name);
   1519   }
   1520 
   1521   // Ignore other stores where the receiver is not a JSObject.
   1522   // TODO(1475): Must check prototype chains of object wrappers.
   1523   if (!object->IsJSObject()) return *value;
   1524 
   1525   Handle<JSObject> receiver = Handle<JSObject>::cast(object);
   1526 
   1527   // Check if the given name is an array index.
   1528   uint32_t index;
   1529   if (name->AsArrayIndex(&index)) {
   1530     Handle<Object> result =
   1531         JSObject::SetElement(receiver, index, value, NONE, strict_mode());
   1532     RETURN_IF_EMPTY_HANDLE(isolate(), result);
   1533     return *value;
   1534   }
   1535 
   1536   // Observed objects are always modified through the runtime.
   1537   if (FLAG_harmony_observation && receiver->map()->is_observed()) {
   1538     Handle<Object> result = JSReceiver::SetProperty(
   1539         receiver, name, value, NONE, strict_mode(), store_mode);
   1540     RETURN_IF_EMPTY_HANDLE(isolate(), result);
   1541     return *result;
   1542   }
   1543 
   1544   // Use specialized code for setting the length of arrays with fast
   1545   // properties. Slow properties might indicate redefinition of the length
   1546   // property. Note that when redefined using Object.freeze, it's possible
   1547   // to have fast properties but a read-only length.
   1548   if (FLAG_use_ic &&
   1549       receiver->IsJSArray() &&
   1550       name->Equals(isolate()->heap()->length_string()) &&
   1551       Handle<JSArray>::cast(receiver)->AllowsSetElementsLength() &&
   1552       receiver->HasFastProperties() &&
   1553       !receiver->map()->is_frozen()) {
   1554     Handle<Code> stub =
   1555         StoreArrayLengthStub(kind(), strict_mode()).GetCode(isolate());
   1556     set_target(*stub);
   1557     TRACE_IC("StoreIC", name);
   1558     Handle<Object> result = JSReceiver::SetProperty(
   1559         receiver, name, value, NONE, strict_mode(), store_mode);
   1560     RETURN_IF_EMPTY_HANDLE(isolate(), result);
   1561     return *result;
   1562   }
   1563 
   1564   LookupResult lookup(isolate());
   1565   bool can_store = LookupForWrite(receiver, name, value, &lookup, this);
   1566   if (!can_store &&
   1567       strict_mode() == kStrictMode &&
   1568       !(lookup.IsProperty() && lookup.IsReadOnly()) &&
   1569       IsUndeclaredGlobal(object)) {
   1570     // Strict mode doesn't allow setting non-existent global property.
   1571     return ReferenceError("not_defined", name);
   1572   }
   1573   if (FLAG_use_ic) {
   1574     if (state() == UNINITIALIZED) {
   1575       Handle<Code> stub = pre_monomorphic_stub();
   1576       set_target(*stub);
   1577       TRACE_IC("StoreIC", name);
   1578     } else if (can_store) {
   1579       UpdateCaches(&lookup, receiver, name, value);
   1580     } else if (!name->IsCacheable(isolate()) ||
   1581                lookup.IsNormal() ||
   1582                (lookup.IsField() && lookup.CanHoldValue(value))) {
   1583       Handle<Code> stub = generic_stub();
   1584       set_target(*stub);
   1585     }
   1586   }
   1587 
   1588   // Set the property.
   1589   Handle<Object> result = JSReceiver::SetProperty(
   1590       receiver, name, value, NONE, strict_mode(), store_mode);
   1591   RETURN_IF_EMPTY_HANDLE(isolate(), result);
   1592   return *result;
   1593 }
   1594 
   1595 
   1596 void StoreIC::UpdateCaches(LookupResult* lookup,
   1597                            Handle<JSObject> receiver,
   1598                            Handle<String> name,
   1599                            Handle<Object> value) {
   1600   ASSERT(lookup->IsFound());
   1601 
   1602   // These are not cacheable, so we never see such LookupResults here.
   1603   ASSERT(!lookup->IsHandler());
   1604 
   1605   Handle<Code> code = ComputeHandler(lookup, receiver, name, value);
   1606 
   1607   PatchCache(CurrentTypeOf(receiver, isolate()), name, code);
   1608   TRACE_IC("StoreIC", name);
   1609 }
   1610 
   1611 
   1612 Handle<Code> StoreIC::CompileHandler(LookupResult* lookup,
   1613                                      Handle<Object> object,
   1614                                      Handle<String> name,
   1615                                      Handle<Object> value,
   1616                                      InlineCacheHolderFlag cache_holder) {
   1617   if (object->IsJSGlobalProxy()) return slow_stub();
   1618   ASSERT(cache_holder == OWN_MAP);
   1619   // This is currently guaranteed by checks in StoreIC::Store.
   1620   Handle<JSObject> receiver = Handle<JSObject>::cast(object);
   1621 
   1622   Handle<JSObject> holder(lookup->holder());
   1623   // Handlers do not use strict mode.
   1624   StoreStubCompiler compiler(isolate(), kNonStrictMode, kind());
   1625   switch (lookup->type()) {
   1626     case FIELD:
   1627       return compiler.CompileStoreField(receiver, lookup, name);
   1628     case TRANSITION: {
   1629       // Explicitly pass in the receiver map since LookupForWrite may have
   1630       // stored something else than the receiver in the holder.
   1631       Handle<Map> transition(lookup->GetTransitionTarget());
   1632       PropertyDetails details = transition->GetLastDescriptorDetails();
   1633 
   1634       if (details.type() == CALLBACKS || details.attributes() != NONE) break;
   1635 
   1636       return compiler.CompileStoreTransition(
   1637           receiver, lookup, transition, name);
   1638     }
   1639     case NORMAL:
   1640       if (kind() == Code::KEYED_STORE_IC) break;
   1641       if (receiver->IsGlobalObject()) {
   1642         // The stub generated for the global object picks the value directly
   1643         // from the property cell. So the property must be directly on the
   1644         // global object.
   1645         Handle<GlobalObject> global = Handle<GlobalObject>::cast(receiver);
   1646         Handle<PropertyCell> cell(global->GetPropertyCell(lookup), isolate());
   1647         Handle<Type> union_type = PropertyCell::UpdatedType(cell, value);
   1648         StoreGlobalStub stub(union_type->IsConstant());
   1649 
   1650         Handle<Code> code = stub.GetCodeCopyFromTemplate(
   1651             isolate(), receiver->map(), *cell);
   1652         // TODO(verwaest): Move caching of these NORMAL stubs outside as well.
   1653         HeapObject::UpdateMapCodeCache(receiver, name, code);
   1654         return code;
   1655       }
   1656       ASSERT(holder.is_identical_to(receiver));
   1657       return isolate()->builtins()->StoreIC_Normal();
   1658     case CALLBACKS: {
   1659       if (kind() == Code::KEYED_STORE_IC) break;
   1660       Handle<Object> callback(lookup->GetCallbackObject(), isolate());
   1661       if (callback->IsExecutableAccessorInfo()) {
   1662         Handle<ExecutableAccessorInfo> info =
   1663             Handle<ExecutableAccessorInfo>::cast(callback);
   1664         if (v8::ToCData<Address>(info->setter()) == 0) break;
   1665         if (!holder->HasFastProperties()) break;
   1666         if (!info->IsCompatibleReceiver(*receiver)) break;
   1667         return compiler.CompileStoreCallback(receiver, holder, name, info);
   1668       } else if (callback->IsAccessorPair()) {
   1669         Handle<Object> setter(
   1670             Handle<AccessorPair>::cast(callback)->setter(), isolate());
   1671         if (!setter->IsJSFunction()) break;
   1672         if (holder->IsGlobalObject()) break;
   1673         if (!holder->HasFastProperties()) break;
   1674         Handle<JSFunction> function = Handle<JSFunction>::cast(setter);
   1675         CallOptimization call_optimization(function);
   1676         if (call_optimization.is_simple_api_call() &&
   1677             call_optimization.IsCompatibleReceiver(*receiver)) {
   1678           return compiler.CompileStoreCallback(
   1679               receiver, holder, name, call_optimization);
   1680         }
   1681         return compiler.CompileStoreViaSetter(
   1682             receiver, holder, name, Handle<JSFunction>::cast(setter));
   1683       }
   1684       // TODO(dcarney): Handle correctly.
   1685       if (callback->IsDeclaredAccessorInfo()) break;
   1686       ASSERT(callback->IsForeign());
   1687       // No IC support for old-style native accessors.
   1688       break;
   1689     }
   1690     case INTERCEPTOR:
   1691       if (kind() == Code::KEYED_STORE_IC) break;
   1692       ASSERT(HasInterceptorSetter(*receiver));
   1693       return compiler.CompileStoreInterceptor(receiver, name);
   1694     case CONSTANT:
   1695       break;
   1696     case NONEXISTENT:
   1697     case HANDLER:
   1698       UNREACHABLE();
   1699       break;
   1700   }
   1701   return slow_stub();
   1702 }
   1703 
   1704 
   1705 Handle<Code> KeyedStoreIC::StoreElementStub(Handle<JSObject> receiver,
   1706                                             KeyedAccessStoreMode store_mode) {
   1707   // Don't handle megamorphic property accesses for INTERCEPTORS or CALLBACKS
   1708   // via megamorphic stubs, since they don't have a map in their relocation info
   1709   // and so the stubs can't be harvested for the object needed for a map check.
   1710   if (target()->type() != Code::NORMAL) {
   1711     TRACE_GENERIC_IC(isolate(), "KeyedIC", "non-NORMAL target type");
   1712     return generic_stub();
   1713   }
   1714 
   1715   Handle<Map> receiver_map(receiver->map(), isolate());
   1716   if (state() == UNINITIALIZED || state() == PREMONOMORPHIC) {
   1717     // Optimistically assume that ICs that haven't reached the MONOMORPHIC state
   1718     // yet will do so and stay there.
   1719     Handle<Map> monomorphic_map = ComputeTransitionedMap(receiver, store_mode);
   1720     store_mode = GetNonTransitioningStoreMode(store_mode);
   1721     return isolate()->stub_cache()->ComputeKeyedStoreElement(
   1722         monomorphic_map, strict_mode(), store_mode);
   1723   }
   1724 
   1725   MapHandleList target_receiver_maps;
   1726   target()->FindAllMaps(&target_receiver_maps);
   1727   if (target_receiver_maps.length() == 0) {
   1728     // In the case that there is a non-map-specific IC is installed (e.g. keyed
   1729     // stores into properties in dictionary mode), then there will be not
   1730     // receiver maps in the target.
   1731     return generic_stub();
   1732   }
   1733 
   1734   // There are several special cases where an IC that is MONOMORPHIC can still
   1735   // transition to a different GetNonTransitioningStoreMode IC that handles a
   1736   // superset of the original IC. Handle those here if the receiver map hasn't
   1737   // changed or it has transitioned to a more general kind.
   1738   KeyedAccessStoreMode old_store_mode =
   1739       KeyedStoreIC::GetKeyedAccessStoreMode(target()->extra_ic_state());
   1740   Handle<Map> previous_receiver_map = target_receiver_maps.at(0);
   1741   if (state() == MONOMORPHIC) {
   1742       // If the "old" and "new" maps are in the same elements map family, stay
   1743       // MONOMORPHIC and use the map for the most generic ElementsKind.
   1744     Handle<Map> transitioned_receiver_map = receiver_map;
   1745     if (IsTransitionStoreMode(store_mode)) {
   1746       transitioned_receiver_map =
   1747           ComputeTransitionedMap(receiver, store_mode);
   1748     }
   1749     if (IsTransitionOfMonomorphicTarget(MapToType(transitioned_receiver_map))) {
   1750       // Element family is the same, use the "worst" case map.
   1751       store_mode = GetNonTransitioningStoreMode(store_mode);
   1752       return isolate()->stub_cache()->ComputeKeyedStoreElement(
   1753           transitioned_receiver_map, strict_mode(), store_mode);
   1754     } else if (*previous_receiver_map == receiver->map() &&
   1755                old_store_mode == STANDARD_STORE &&
   1756                (IsGrowStoreMode(store_mode) ||
   1757                 store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS ||
   1758                 store_mode == STORE_NO_TRANSITION_HANDLE_COW)) {
   1759       // A "normal" IC that handles stores can switch to a version that can
   1760       // grow at the end of the array, handle OOB accesses or copy COW arrays
   1761       // and still stay MONOMORPHIC.
   1762       return isolate()->stub_cache()->ComputeKeyedStoreElement(
   1763           receiver_map, strict_mode(), store_mode);
   1764     }
   1765   }
   1766 
   1767   ASSERT(state() != GENERIC);
   1768 
   1769   bool map_added =
   1770       AddOneReceiverMapIfMissing(&target_receiver_maps, receiver_map);
   1771 
   1772   if (IsTransitionStoreMode(store_mode)) {
   1773     Handle<Map> transitioned_receiver_map =
   1774         ComputeTransitionedMap(receiver, store_mode);
   1775     map_added |= AddOneReceiverMapIfMissing(&target_receiver_maps,
   1776                                             transitioned_receiver_map);
   1777   }
   1778 
   1779   if (!map_added) {
   1780     // If the miss wasn't due to an unseen map, a polymorphic stub
   1781     // won't help, use the generic stub.
   1782     TRACE_GENERIC_IC(isolate(), "KeyedIC", "same map added twice");
   1783     return generic_stub();
   1784   }
   1785 
   1786   // If the maximum number of receiver maps has been exceeded, use the generic
   1787   // version of the IC.
   1788   if (target_receiver_maps.length() > kMaxKeyedPolymorphism) {
   1789     TRACE_GENERIC_IC(isolate(), "KeyedIC", "max polymorph exceeded");
   1790     return generic_stub();
   1791   }
   1792 
   1793   // Make sure all polymorphic handlers have the same store mode, otherwise the
   1794   // generic stub must be used.
   1795   store_mode = GetNonTransitioningStoreMode(store_mode);
   1796   if (old_store_mode != STANDARD_STORE) {
   1797     if (store_mode == STANDARD_STORE) {
   1798       store_mode = old_store_mode;
   1799     } else if (store_mode != old_store_mode) {
   1800       TRACE_GENERIC_IC(isolate(), "KeyedIC", "store mode mismatch");
   1801       return generic_stub();
   1802     }
   1803   }
   1804 
   1805   // If the store mode isn't the standard mode, make sure that all polymorphic
   1806   // receivers are either external arrays, or all "normal" arrays. Otherwise,
   1807   // use the generic stub.
   1808   if (store_mode != STANDARD_STORE) {
   1809     int external_arrays = 0;
   1810     for (int i = 0; i < target_receiver_maps.length(); ++i) {
   1811       if (target_receiver_maps[i]->has_external_array_elements()) {
   1812         external_arrays++;
   1813       }
   1814     }
   1815     if (external_arrays != 0 &&
   1816         external_arrays != target_receiver_maps.length()) {
   1817       TRACE_GENERIC_IC(isolate(), "KeyedIC",
   1818           "unsupported combination of external and normal arrays");
   1819       return generic_stub();
   1820     }
   1821   }
   1822 
   1823   return isolate()->stub_cache()->ComputeStoreElementPolymorphic(
   1824       &target_receiver_maps, store_mode, strict_mode());
   1825 }
   1826 
   1827 
   1828 Handle<Map> KeyedStoreIC::ComputeTransitionedMap(
   1829     Handle<JSObject> receiver,
   1830     KeyedAccessStoreMode store_mode) {
   1831   switch (store_mode) {
   1832     case STORE_TRANSITION_SMI_TO_OBJECT:
   1833     case STORE_TRANSITION_DOUBLE_TO_OBJECT:
   1834     case STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT:
   1835     case STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT:
   1836       return JSObject::GetElementsTransitionMap(receiver, FAST_ELEMENTS);
   1837     case STORE_TRANSITION_SMI_TO_DOUBLE:
   1838     case STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE:
   1839       return JSObject::GetElementsTransitionMap(receiver, FAST_DOUBLE_ELEMENTS);
   1840     case STORE_TRANSITION_HOLEY_SMI_TO_OBJECT:
   1841     case STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT:
   1842     case STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT:
   1843     case STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT:
   1844       return JSObject::GetElementsTransitionMap(receiver,
   1845                                                 FAST_HOLEY_ELEMENTS);
   1846     case STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE:
   1847     case STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE:
   1848       return JSObject::GetElementsTransitionMap(receiver,
   1849                                                 FAST_HOLEY_DOUBLE_ELEMENTS);
   1850     case STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS:
   1851       ASSERT(receiver->map()->has_external_array_elements());
   1852       // Fall through
   1853     case STORE_NO_TRANSITION_HANDLE_COW:
   1854     case STANDARD_STORE:
   1855     case STORE_AND_GROW_NO_TRANSITION:
   1856       return Handle<Map>(receiver->map(), isolate());
   1857   }
   1858   return Handle<Map>::null();
   1859 }
   1860 
   1861 
   1862 bool IsOutOfBoundsAccess(Handle<JSObject> receiver,
   1863                          int index) {
   1864   if (receiver->IsJSArray()) {
   1865     return JSArray::cast(*receiver)->length()->IsSmi() &&
   1866         index >= Smi::cast(JSArray::cast(*receiver)->length())->value();
   1867   }
   1868   return index >= receiver->elements()->length();
   1869 }
   1870 
   1871 
   1872 KeyedAccessStoreMode KeyedStoreIC::GetStoreMode(Handle<JSObject> receiver,
   1873                                                 Handle<Object> key,
   1874                                                 Handle<Object> value) {
   1875   ASSERT(!key->ToSmi()->IsFailure());
   1876   Smi* smi_key = NULL;
   1877   key->ToSmi()->To(&smi_key);
   1878   int index = smi_key->value();
   1879   bool oob_access = IsOutOfBoundsAccess(receiver, index);
   1880   bool allow_growth = receiver->IsJSArray() && oob_access;
   1881   if (allow_growth) {
   1882     // Handle growing array in stub if necessary.
   1883     if (receiver->HasFastSmiElements()) {
   1884       if (value->IsHeapNumber()) {
   1885         if (receiver->HasFastHoleyElements()) {
   1886           return STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE;
   1887         } else {
   1888           return STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE;
   1889         }
   1890       }
   1891       if (value->IsHeapObject()) {
   1892         if (receiver->HasFastHoleyElements()) {
   1893           return STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT;
   1894         } else {
   1895           return STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT;
   1896         }
   1897       }
   1898     } else if (receiver->HasFastDoubleElements()) {
   1899       if (!value->IsSmi() && !value->IsHeapNumber()) {
   1900         if (receiver->HasFastHoleyElements()) {
   1901           return STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
   1902         } else {
   1903           return STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT;
   1904         }
   1905       }
   1906     }
   1907     return STORE_AND_GROW_NO_TRANSITION;
   1908   } else {
   1909     // Handle only in-bounds elements accesses.
   1910     if (receiver->HasFastSmiElements()) {
   1911       if (value->IsHeapNumber()) {
   1912         if (receiver->HasFastHoleyElements()) {
   1913           return STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE;
   1914         } else {
   1915           return STORE_TRANSITION_SMI_TO_DOUBLE;
   1916         }
   1917       } else if (value->IsHeapObject()) {
   1918         if (receiver->HasFastHoleyElements()) {
   1919           return STORE_TRANSITION_HOLEY_SMI_TO_OBJECT;
   1920         } else {
   1921           return STORE_TRANSITION_SMI_TO_OBJECT;
   1922         }
   1923       }
   1924     } else if (receiver->HasFastDoubleElements()) {
   1925       if (!value->IsSmi() && !value->IsHeapNumber()) {
   1926         if (receiver->HasFastHoleyElements()) {
   1927           return STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
   1928         } else {
   1929           return STORE_TRANSITION_DOUBLE_TO_OBJECT;
   1930         }
   1931       }
   1932     }
   1933     if (!FLAG_trace_external_array_abuse &&
   1934         receiver->map()->has_external_array_elements() && oob_access) {
   1935       return STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS;
   1936     }
   1937     Heap* heap = receiver->GetHeap();
   1938     if (receiver->elements()->map() == heap->fixed_cow_array_map()) {
   1939       return STORE_NO_TRANSITION_HANDLE_COW;
   1940     } else {
   1941       return STANDARD_STORE;
   1942     }
   1943   }
   1944 }
   1945 
   1946 
   1947 MaybeObject* KeyedStoreIC::Store(Handle<Object> object,
   1948                                  Handle<Object> key,
   1949                                  Handle<Object> value) {
   1950   if (MigrateDeprecated(object)) {
   1951     Handle<Object> result = Runtime::SetObjectProperty(isolate(), object,
   1952                                                        key,
   1953                                                        value,
   1954                                                        NONE,
   1955                                                        strict_mode());
   1956     RETURN_IF_EMPTY_HANDLE(isolate(), result);
   1957     return *result;
   1958   }
   1959 
   1960   // Check for values that can be converted into an internalized string directly
   1961   // or is representable as a smi.
   1962   key = TryConvertKey(key, isolate());
   1963 
   1964   MaybeObject* maybe_object = NULL;
   1965   Handle<Code> stub = generic_stub();
   1966 
   1967   if (key->IsInternalizedString()) {
   1968     maybe_object = StoreIC::Store(object,
   1969                                   Handle<String>::cast(key),
   1970                                   value,
   1971                                   JSReceiver::MAY_BE_STORE_FROM_KEYED);
   1972     if (maybe_object->IsFailure()) return maybe_object;
   1973   } else {
   1974     bool use_ic = FLAG_use_ic && !object->IsAccessCheckNeeded() &&
   1975         !(FLAG_harmony_observation && object->IsJSObject() &&
   1976           JSObject::cast(*object)->map()->is_observed());
   1977     if (use_ic && !object->IsSmi()) {
   1978       // Don't use ICs for maps of the objects in Array's prototype chain. We
   1979       // expect to be able to trap element sets to objects with those maps in
   1980       // the runtime to enable optimization of element hole access.
   1981       Handle<HeapObject> heap_object = Handle<HeapObject>::cast(object);
   1982       if (heap_object->map()->IsMapInArrayPrototypeChain()) use_ic = false;
   1983     }
   1984 
   1985     if (use_ic) {
   1986       ASSERT(!object->IsJSGlobalProxy());
   1987 
   1988       if (object->IsJSObject()) {
   1989         Handle<JSObject> receiver = Handle<JSObject>::cast(object);
   1990         bool key_is_smi_like = key->IsSmi() || !key->ToSmi()->IsFailure();
   1991         if (receiver->elements()->map() ==
   1992             isolate()->heap()->non_strict_arguments_elements_map()) {
   1993           stub = non_strict_arguments_stub();
   1994         } else if (key_is_smi_like &&
   1995                    !(target().is_identical_to(non_strict_arguments_stub()))) {
   1996           // We should go generic if receiver isn't a dictionary, but our
   1997           // prototype chain does have dictionary elements. This ensures that
   1998           // other non-dictionary receivers in the polymorphic case benefit
   1999           // from fast path keyed stores.
   2000           if (!(receiver->map()->DictionaryElementsInPrototypeChainOnly())) {
   2001             KeyedAccessStoreMode store_mode =
   2002                 GetStoreMode(receiver, key, value);
   2003             stub = StoreElementStub(receiver, store_mode);
   2004           }
   2005         }
   2006       }
   2007     }
   2008   }
   2009 
   2010   if (!is_target_set()) {
   2011     if (*stub == *generic_stub()) {
   2012       TRACE_GENERIC_IC(isolate(), "KeyedStoreIC", "set generic");
   2013     }
   2014     ASSERT(!stub.is_null());
   2015     set_target(*stub);
   2016     TRACE_IC("StoreIC", key);
   2017   }
   2018 
   2019   if (maybe_object) return maybe_object;
   2020   Handle<Object> result = Runtime::SetObjectProperty(isolate(), object, key,
   2021                                                      value,
   2022                                                      NONE,
   2023                                                      strict_mode());
   2024   RETURN_IF_EMPTY_HANDLE(isolate(), result);
   2025   return *result;
   2026 }
   2027 
   2028 
   2029 #undef TRACE_IC
   2030 
   2031 
   2032 // ----------------------------------------------------------------------------
   2033 // Static IC stub generators.
   2034 //
   2035 
   2036 // Used from ic-<arch>.cc.
   2037 RUNTIME_FUNCTION(MaybeObject*, CallIC_Miss) {
   2038   HandleScope scope(isolate);
   2039   ASSERT(args.length() == 2);
   2040   CallIC ic(isolate);
   2041   Handle<Object> receiver = args.at<Object>(0);
   2042   Handle<String> key = args.at<String>(1);
   2043   ic.UpdateState(receiver, key);
   2044   MaybeObject* maybe_result = ic.LoadFunction(receiver, key);
   2045   JSFunction* raw_function;
   2046   if (!maybe_result->To(&raw_function)) return maybe_result;
   2047 
   2048   // The first time the inline cache is updated may be the first time the
   2049   // function it references gets called. If the function is lazily compiled
   2050   // then the first call will trigger a compilation. We check for this case
   2051   // and we do the compilation immediately, instead of waiting for the stub
   2052   // currently attached to the JSFunction object to trigger compilation.
   2053   if (raw_function->is_compiled()) return raw_function;
   2054 
   2055   Handle<JSFunction> function(raw_function);
   2056   JSFunction::CompileLazy(function, CLEAR_EXCEPTION);
   2057   return *function;
   2058 }
   2059 
   2060 
   2061 // Used from ic-<arch>.cc.
   2062 RUNTIME_FUNCTION(MaybeObject*, KeyedCallIC_Miss) {
   2063   HandleScope scope(isolate);
   2064   ASSERT(args.length() == 2);
   2065   KeyedCallIC ic(isolate);
   2066   Handle<Object> receiver = args.at<Object>(0);
   2067   Handle<Object> key = args.at<Object>(1);
   2068   ic.UpdateState(receiver, key);
   2069   MaybeObject* maybe_result = ic.LoadFunction(receiver, key);
   2070   // Result could be a function or a failure.
   2071   JSFunction* raw_function = NULL;
   2072   if (!maybe_result->To(&raw_function)) return maybe_result;
   2073 
   2074   if (raw_function->is_compiled()) return raw_function;
   2075 
   2076   Handle<JSFunction> function(raw_function, isolate);
   2077   JSFunction::CompileLazy(function, CLEAR_EXCEPTION);
   2078   return *function;
   2079 }
   2080 
   2081 
   2082 // Used from ic-<arch>.cc.
   2083 RUNTIME_FUNCTION(MaybeObject*, LoadIC_Miss) {
   2084   HandleScope scope(isolate);
   2085   ASSERT(args.length() == 2);
   2086   LoadIC ic(IC::NO_EXTRA_FRAME, isolate);
   2087   Handle<Object> receiver = args.at<Object>(0);
   2088   Handle<String> key = args.at<String>(1);
   2089   ic.UpdateState(receiver, key);
   2090   return ic.Load(receiver, key);
   2091 }
   2092 
   2093 
   2094 // Used from ic-<arch>.cc
   2095 RUNTIME_FUNCTION(MaybeObject*, KeyedLoadIC_Miss) {
   2096   HandleScope scope(isolate);
   2097   ASSERT(args.length() == 2);
   2098   KeyedLoadIC ic(IC::NO_EXTRA_FRAME, isolate);
   2099   Handle<Object> receiver = args.at<Object>(0);
   2100   Handle<Object> key = args.at<Object>(1);
   2101   ic.UpdateState(receiver, key);
   2102   return ic.Load(receiver, key);
   2103 }
   2104 
   2105 
   2106 RUNTIME_FUNCTION(MaybeObject*, KeyedLoadIC_MissFromStubFailure) {
   2107   HandleScope scope(isolate);
   2108   ASSERT(args.length() == 2);
   2109   KeyedLoadIC ic(IC::EXTRA_CALL_FRAME, isolate);
   2110   Handle<Object> receiver = args.at<Object>(0);
   2111   Handle<Object> key = args.at<Object>(1);
   2112   ic.UpdateState(receiver, key);
   2113   return ic.Load(receiver, key);
   2114 }
   2115 
   2116 
   2117 // Used from ic-<arch>.cc.
   2118 RUNTIME_FUNCTION(MaybeObject*, StoreIC_Miss) {
   2119   HandleScope scope(isolate);
   2120   ASSERT(args.length() == 3);
   2121   StoreIC ic(IC::NO_EXTRA_FRAME, isolate);
   2122   Handle<Object> receiver = args.at<Object>(0);
   2123   Handle<String> key = args.at<String>(1);
   2124   ic.UpdateState(receiver, key);
   2125   return ic.Store(receiver, key, args.at<Object>(2));
   2126 }
   2127 
   2128 
   2129 RUNTIME_FUNCTION(MaybeObject*, StoreIC_MissFromStubFailure) {
   2130   HandleScope scope(isolate);
   2131   ASSERT(args.length() == 3);
   2132   StoreIC ic(IC::EXTRA_CALL_FRAME, isolate);
   2133   Handle<Object> receiver = args.at<Object>(0);
   2134   Handle<String> key = args.at<String>(1);
   2135   ic.UpdateState(receiver, key);
   2136   return ic.Store(receiver, key, args.at<Object>(2));
   2137 }
   2138 
   2139 
   2140 RUNTIME_FUNCTION(MaybeObject*, KeyedCallIC_MissFromStubFailure) {
   2141   HandleScope scope(isolate);
   2142   ASSERT(args.length() == 2);
   2143   KeyedCallIC ic(isolate);
   2144   Arguments* caller_args = reinterpret_cast<Arguments*>(args[0]);
   2145   Handle<Object> key = args.at<Object>(1);
   2146   Handle<Object> receiver((*caller_args)[0], isolate);
   2147 
   2148   ic.UpdateState(receiver, key);
   2149   MaybeObject* maybe_result = ic.LoadFunction(receiver, key);
   2150   // Result could be a function or a failure.
   2151   JSFunction* raw_function = NULL;
   2152   if (!maybe_result->To(&raw_function)) return maybe_result;
   2153 
   2154   if (raw_function->is_compiled()) return raw_function;
   2155 
   2156   Handle<JSFunction> function(raw_function, isolate);
   2157   JSFunction::CompileLazy(function, CLEAR_EXCEPTION);
   2158   return *function;
   2159 }
   2160 
   2161 
   2162 RUNTIME_FUNCTION(MaybeObject*, StoreIC_ArrayLength) {
   2163   SealHandleScope shs(isolate);
   2164 
   2165   ASSERT(args.length() == 2);
   2166   JSArray* receiver = JSArray::cast(args[0]);
   2167   Object* len = args[1];
   2168 
   2169   // The generated code should filter out non-Smis before we get here.
   2170   ASSERT(len->IsSmi());
   2171 
   2172 #ifdef DEBUG
   2173   // The length property has to be a writable callback property.
   2174   LookupResult debug_lookup(isolate);
   2175   receiver->LocalLookup(isolate->heap()->length_string(), &debug_lookup);
   2176   ASSERT(debug_lookup.IsPropertyCallbacks() && !debug_lookup.IsReadOnly());
   2177 #endif
   2178 
   2179   Object* result;
   2180   MaybeObject* maybe_result = receiver->SetElementsLength(len);
   2181   if (!maybe_result->To(&result)) return maybe_result;
   2182 
   2183   return len;
   2184 }
   2185 
   2186 
   2187 // Extend storage is called in a store inline cache when
   2188 // it is necessary to extend the properties array of a
   2189 // JSObject.
   2190 RUNTIME_FUNCTION(MaybeObject*, SharedStoreIC_ExtendStorage) {
   2191   SealHandleScope shs(isolate);
   2192   ASSERT(args.length() == 3);
   2193 
   2194   // Convert the parameters
   2195   JSObject* object = JSObject::cast(args[0]);
   2196   Map* transition = Map::cast(args[1]);
   2197   Object* value = args[2];
   2198 
   2199   // Check the object has run out out property space.
   2200   ASSERT(object->HasFastProperties());
   2201   ASSERT(object->map()->unused_property_fields() == 0);
   2202 
   2203   // Expand the properties array.
   2204   FixedArray* old_storage = object->properties();
   2205   int new_unused = transition->unused_property_fields();
   2206   int new_size = old_storage->length() + new_unused + 1;
   2207   Object* result;
   2208   MaybeObject* maybe_result = old_storage->CopySize(new_size);
   2209   if (!maybe_result->ToObject(&result)) return maybe_result;
   2210 
   2211   FixedArray* new_storage = FixedArray::cast(result);
   2212 
   2213   Object* to_store = value;
   2214 
   2215   if (FLAG_track_double_fields) {
   2216     DescriptorArray* descriptors = transition->instance_descriptors();
   2217     PropertyDetails details = descriptors->GetDetails(transition->LastAdded());
   2218     if (details.representation().IsDouble()) {
   2219       MaybeObject* maybe_storage =
   2220           isolate->heap()->AllocateHeapNumber(value->Number());
   2221       if (!maybe_storage->To(&to_store)) return maybe_storage;
   2222     }
   2223   }
   2224 
   2225   new_storage->set(old_storage->length(), to_store);
   2226 
   2227   // Set the new property value and do the map transition.
   2228   object->set_properties(new_storage);
   2229   object->set_map(transition);
   2230 
   2231   // Return the stored value.
   2232   return value;
   2233 }
   2234 
   2235 
   2236 // Used from ic-<arch>.cc.
   2237 RUNTIME_FUNCTION(MaybeObject*, KeyedStoreIC_Miss) {
   2238   HandleScope scope(isolate);
   2239   ASSERT(args.length() == 3);
   2240   KeyedStoreIC ic(IC::NO_EXTRA_FRAME, isolate);
   2241   Handle<Object> receiver = args.at<Object>(0);
   2242   Handle<Object> key = args.at<Object>(1);
   2243   ic.UpdateState(receiver, key);
   2244   return ic.Store(receiver, key, args.at<Object>(2));
   2245 }
   2246 
   2247 
   2248 RUNTIME_FUNCTION(MaybeObject*, KeyedStoreIC_MissFromStubFailure) {
   2249   HandleScope scope(isolate);
   2250   ASSERT(args.length() == 3);
   2251   KeyedStoreIC ic(IC::EXTRA_CALL_FRAME, isolate);
   2252   Handle<Object> receiver = args.at<Object>(0);
   2253   Handle<Object> key = args.at<Object>(1);
   2254   ic.UpdateState(receiver, key);
   2255   return ic.Store(receiver, key, args.at<Object>(2));
   2256 }
   2257 
   2258 
   2259 RUNTIME_FUNCTION(MaybeObject*, StoreIC_Slow) {
   2260   HandleScope scope(isolate);
   2261   ASSERT(args.length() == 3);
   2262   StoreIC ic(IC::NO_EXTRA_FRAME, isolate);
   2263   Handle<Object> object = args.at<Object>(0);
   2264   Handle<Object> key = args.at<Object>(1);
   2265   Handle<Object> value = args.at<Object>(2);
   2266   StrictModeFlag strict_mode = ic.strict_mode();
   2267   Handle<Object> result = Runtime::SetObjectProperty(isolate, object, key,
   2268                                                      value,
   2269                                                      NONE,
   2270                                                      strict_mode);
   2271   RETURN_IF_EMPTY_HANDLE(isolate, result);
   2272   return *result;
   2273 }
   2274 
   2275 
   2276 RUNTIME_FUNCTION(MaybeObject*, KeyedStoreIC_Slow) {
   2277   HandleScope scope(isolate);
   2278   ASSERT(args.length() == 3);
   2279   KeyedStoreIC ic(IC::NO_EXTRA_FRAME, isolate);
   2280   Handle<Object> object = args.at<Object>(0);
   2281   Handle<Object> key = args.at<Object>(1);
   2282   Handle<Object> value = args.at<Object>(2);
   2283   StrictModeFlag strict_mode = ic.strict_mode();
   2284   Handle<Object> result = Runtime::SetObjectProperty(isolate, object, key,
   2285                                                      value,
   2286                                                      NONE,
   2287                                                      strict_mode);
   2288   RETURN_IF_EMPTY_HANDLE(isolate, result);
   2289   return *result;
   2290 }
   2291 
   2292 
   2293 RUNTIME_FUNCTION(MaybeObject*, ElementsTransitionAndStoreIC_Miss) {
   2294   HandleScope scope(isolate);
   2295   ASSERT(args.length() == 4);
   2296   KeyedStoreIC ic(IC::EXTRA_CALL_FRAME, isolate);
   2297   Handle<Object> value = args.at<Object>(0);
   2298   Handle<Map> map = args.at<Map>(1);
   2299   Handle<Object> key = args.at<Object>(2);
   2300   Handle<Object> object = args.at<Object>(3);
   2301   StrictModeFlag strict_mode = ic.strict_mode();
   2302   if (object->IsJSObject()) {
   2303     JSObject::TransitionElementsKind(Handle<JSObject>::cast(object),
   2304                                      map->elements_kind());
   2305   }
   2306   Handle<Object> result = Runtime::SetObjectProperty(isolate, object, key,
   2307                                                      value,
   2308                                                      NONE,
   2309                                                      strict_mode);
   2310   RETURN_IF_EMPTY_HANDLE(isolate, result);
   2311   return *result;
   2312 }
   2313 
   2314 
   2315 BinaryOpIC::State::State(ExtraICState extra_ic_state) {
   2316   // We don't deserialize the SSE2 Field, since this is only used to be able
   2317   // to include SSE2 as well as non-SSE2 versions in the snapshot. For code
   2318   // generation we always want it to reflect the current state.
   2319   op_ = static_cast<Token::Value>(
   2320       FIRST_TOKEN + OpField::decode(extra_ic_state));
   2321   mode_ = OverwriteModeField::decode(extra_ic_state);
   2322   fixed_right_arg_ = Maybe<int>(
   2323       HasFixedRightArgField::decode(extra_ic_state),
   2324       1 << FixedRightArgValueField::decode(extra_ic_state));
   2325   left_kind_ = LeftKindField::decode(extra_ic_state);
   2326   if (fixed_right_arg_.has_value) {
   2327     right_kind_ = Smi::IsValid(fixed_right_arg_.value) ? SMI : INT32;
   2328   } else {
   2329     right_kind_ = RightKindField::decode(extra_ic_state);
   2330   }
   2331   result_kind_ = ResultKindField::decode(extra_ic_state);
   2332   ASSERT_LE(FIRST_TOKEN, op_);
   2333   ASSERT_LE(op_, LAST_TOKEN);
   2334 }
   2335 
   2336 
   2337 ExtraICState BinaryOpIC::State::GetExtraICState() const {
   2338   bool sse2 = (Max(result_kind_, Max(left_kind_, right_kind_)) > SMI &&
   2339                CpuFeatures::IsSafeForSnapshot(SSE2));
   2340   ExtraICState extra_ic_state =
   2341       SSE2Field::encode(sse2) |
   2342       OpField::encode(op_ - FIRST_TOKEN) |
   2343       OverwriteModeField::encode(mode_) |
   2344       LeftKindField::encode(left_kind_) |
   2345       ResultKindField::encode(result_kind_) |
   2346       HasFixedRightArgField::encode(fixed_right_arg_.has_value);
   2347   if (fixed_right_arg_.has_value) {
   2348     extra_ic_state = FixedRightArgValueField::update(
   2349         extra_ic_state, WhichPowerOf2(fixed_right_arg_.value));
   2350   } else {
   2351     extra_ic_state = RightKindField::update(extra_ic_state, right_kind_);
   2352   }
   2353   return extra_ic_state;
   2354 }
   2355 
   2356 
   2357 // static
   2358 void BinaryOpIC::State::GenerateAheadOfTime(
   2359     Isolate* isolate, void (*Generate)(Isolate*, const State&)) {
   2360   // TODO(olivf) We should investigate why adding stubs to the snapshot is so
   2361   // expensive at runtime. When solved we should be able to add most binops to
   2362   // the snapshot instead of hand-picking them.
   2363   // Generated list of commonly used stubs
   2364 #define GENERATE(op, left_kind, right_kind, result_kind, mode)  \
   2365   do {                                                          \
   2366     State state(op, mode);                                      \
   2367     state.left_kind_ = left_kind;                               \
   2368     state.fixed_right_arg_.has_value = false;                   \
   2369     state.right_kind_ = right_kind;                             \
   2370     state.result_kind_ = result_kind;                           \
   2371     Generate(isolate, state);                                   \
   2372   } while (false)
   2373   GENERATE(Token::ADD, INT32, INT32, INT32, NO_OVERWRITE);
   2374   GENERATE(Token::ADD, INT32, INT32, INT32, OVERWRITE_LEFT);
   2375   GENERATE(Token::ADD, INT32, INT32, NUMBER, NO_OVERWRITE);
   2376   GENERATE(Token::ADD, INT32, INT32, NUMBER, OVERWRITE_LEFT);
   2377   GENERATE(Token::ADD, INT32, NUMBER, NUMBER, NO_OVERWRITE);
   2378   GENERATE(Token::ADD, INT32, NUMBER, NUMBER, OVERWRITE_LEFT);
   2379   GENERATE(Token::ADD, INT32, NUMBER, NUMBER, OVERWRITE_RIGHT);
   2380   GENERATE(Token::ADD, INT32, SMI, INT32, NO_OVERWRITE);
   2381   GENERATE(Token::ADD, INT32, SMI, INT32, OVERWRITE_LEFT);
   2382   GENERATE(Token::ADD, INT32, SMI, INT32, OVERWRITE_RIGHT);
   2383   GENERATE(Token::ADD, NUMBER, INT32, NUMBER, NO_OVERWRITE);
   2384   GENERATE(Token::ADD, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
   2385   GENERATE(Token::ADD, NUMBER, INT32, NUMBER, OVERWRITE_RIGHT);
   2386   GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
   2387   GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
   2388   GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER, OVERWRITE_RIGHT);
   2389   GENERATE(Token::ADD, NUMBER, SMI, NUMBER, NO_OVERWRITE);
   2390   GENERATE(Token::ADD, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
   2391   GENERATE(Token::ADD, NUMBER, SMI, NUMBER, OVERWRITE_RIGHT);
   2392   GENERATE(Token::ADD, SMI, INT32, INT32, NO_OVERWRITE);
   2393   GENERATE(Token::ADD, SMI, INT32, INT32, OVERWRITE_LEFT);
   2394   GENERATE(Token::ADD, SMI, INT32, NUMBER, NO_OVERWRITE);
   2395   GENERATE(Token::ADD, SMI, NUMBER, NUMBER, NO_OVERWRITE);
   2396   GENERATE(Token::ADD, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
   2397   GENERATE(Token::ADD, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
   2398   GENERATE(Token::ADD, SMI, SMI, INT32, OVERWRITE_LEFT);
   2399   GENERATE(Token::ADD, SMI, SMI, SMI, OVERWRITE_RIGHT);
   2400   GENERATE(Token::BIT_AND, INT32, INT32, INT32, NO_OVERWRITE);
   2401   GENERATE(Token::BIT_AND, INT32, INT32, INT32, OVERWRITE_LEFT);
   2402   GENERATE(Token::BIT_AND, INT32, INT32, INT32, OVERWRITE_RIGHT);
   2403   GENERATE(Token::BIT_AND, INT32, INT32, SMI, NO_OVERWRITE);
   2404   GENERATE(Token::BIT_AND, INT32, INT32, SMI, OVERWRITE_RIGHT);
   2405   GENERATE(Token::BIT_AND, INT32, SMI, INT32, NO_OVERWRITE);
   2406   GENERATE(Token::BIT_AND, INT32, SMI, INT32, OVERWRITE_RIGHT);
   2407   GENERATE(Token::BIT_AND, INT32, SMI, SMI, NO_OVERWRITE);
   2408   GENERATE(Token::BIT_AND, INT32, SMI, SMI, OVERWRITE_LEFT);
   2409   GENERATE(Token::BIT_AND, INT32, SMI, SMI, OVERWRITE_RIGHT);
   2410   GENERATE(Token::BIT_AND, NUMBER, INT32, INT32, OVERWRITE_RIGHT);
   2411   GENERATE(Token::BIT_AND, NUMBER, SMI, SMI, NO_OVERWRITE);
   2412   GENERATE(Token::BIT_AND, NUMBER, SMI, SMI, OVERWRITE_RIGHT);
   2413   GENERATE(Token::BIT_AND, SMI, INT32, INT32, NO_OVERWRITE);
   2414   GENERATE(Token::BIT_AND, SMI, INT32, SMI, OVERWRITE_RIGHT);
   2415   GENERATE(Token::BIT_AND, SMI, NUMBER, SMI, OVERWRITE_RIGHT);
   2416   GENERATE(Token::BIT_AND, SMI, SMI, SMI, NO_OVERWRITE);
   2417   GENERATE(Token::BIT_AND, SMI, SMI, SMI, OVERWRITE_LEFT);
   2418   GENERATE(Token::BIT_AND, SMI, SMI, SMI, OVERWRITE_RIGHT);
   2419   GENERATE(Token::BIT_OR, INT32, INT32, INT32, OVERWRITE_LEFT);
   2420   GENERATE(Token::BIT_OR, INT32, INT32, INT32, OVERWRITE_RIGHT);
   2421   GENERATE(Token::BIT_OR, INT32, INT32, SMI, OVERWRITE_LEFT);
   2422   GENERATE(Token::BIT_OR, INT32, SMI, INT32, NO_OVERWRITE);
   2423   GENERATE(Token::BIT_OR, INT32, SMI, INT32, OVERWRITE_LEFT);
   2424   GENERATE(Token::BIT_OR, INT32, SMI, INT32, OVERWRITE_RIGHT);
   2425   GENERATE(Token::BIT_OR, INT32, SMI, SMI, NO_OVERWRITE);
   2426   GENERATE(Token::BIT_OR, INT32, SMI, SMI, OVERWRITE_RIGHT);
   2427   GENERATE(Token::BIT_OR, NUMBER, SMI, INT32, NO_OVERWRITE);
   2428   GENERATE(Token::BIT_OR, NUMBER, SMI, INT32, OVERWRITE_LEFT);
   2429   GENERATE(Token::BIT_OR, NUMBER, SMI, INT32, OVERWRITE_RIGHT);
   2430   GENERATE(Token::BIT_OR, NUMBER, SMI, SMI, NO_OVERWRITE);
   2431   GENERATE(Token::BIT_OR, NUMBER, SMI, SMI, OVERWRITE_LEFT);
   2432   GENERATE(Token::BIT_OR, SMI, INT32, INT32, OVERWRITE_LEFT);
   2433   GENERATE(Token::BIT_OR, SMI, INT32, INT32, OVERWRITE_RIGHT);
   2434   GENERATE(Token::BIT_OR, SMI, INT32, SMI, OVERWRITE_RIGHT);
   2435   GENERATE(Token::BIT_OR, SMI, SMI, SMI, OVERWRITE_LEFT);
   2436   GENERATE(Token::BIT_OR, SMI, SMI, SMI, OVERWRITE_RIGHT);
   2437   GENERATE(Token::BIT_XOR, INT32, INT32, INT32, NO_OVERWRITE);
   2438   GENERATE(Token::BIT_XOR, INT32, INT32, INT32, OVERWRITE_LEFT);
   2439   GENERATE(Token::BIT_XOR, INT32, INT32, INT32, OVERWRITE_RIGHT);
   2440   GENERATE(Token::BIT_XOR, INT32, INT32, SMI, NO_OVERWRITE);
   2441   GENERATE(Token::BIT_XOR, INT32, INT32, SMI, OVERWRITE_LEFT);
   2442   GENERATE(Token::BIT_XOR, INT32, NUMBER, SMI, NO_OVERWRITE);
   2443   GENERATE(Token::BIT_XOR, INT32, SMI, INT32, NO_OVERWRITE);
   2444   GENERATE(Token::BIT_XOR, INT32, SMI, INT32, OVERWRITE_LEFT);
   2445   GENERATE(Token::BIT_XOR, INT32, SMI, INT32, OVERWRITE_RIGHT);
   2446   GENERATE(Token::BIT_XOR, NUMBER, INT32, INT32, NO_OVERWRITE);
   2447   GENERATE(Token::BIT_XOR, NUMBER, SMI, INT32, NO_OVERWRITE);
   2448   GENERATE(Token::BIT_XOR, NUMBER, SMI, SMI, NO_OVERWRITE);
   2449   GENERATE(Token::BIT_XOR, SMI, INT32, INT32, NO_OVERWRITE);
   2450   GENERATE(Token::BIT_XOR, SMI, INT32, INT32, OVERWRITE_LEFT);
   2451   GENERATE(Token::BIT_XOR, SMI, INT32, SMI, OVERWRITE_LEFT);
   2452   GENERATE(Token::BIT_XOR, SMI, SMI, SMI, NO_OVERWRITE);
   2453   GENERATE(Token::BIT_XOR, SMI, SMI, SMI, OVERWRITE_LEFT);
   2454   GENERATE(Token::BIT_XOR, SMI, SMI, SMI, OVERWRITE_RIGHT);
   2455   GENERATE(Token::DIV, INT32, INT32, INT32, NO_OVERWRITE);
   2456   GENERATE(Token::DIV, INT32, INT32, NUMBER, NO_OVERWRITE);
   2457   GENERATE(Token::DIV, INT32, NUMBER, NUMBER, NO_OVERWRITE);
   2458   GENERATE(Token::DIV, INT32, NUMBER, NUMBER, OVERWRITE_LEFT);
   2459   GENERATE(Token::DIV, INT32, SMI, INT32, NO_OVERWRITE);
   2460   GENERATE(Token::DIV, INT32, SMI, NUMBER, NO_OVERWRITE);
   2461   GENERATE(Token::DIV, NUMBER, INT32, NUMBER, NO_OVERWRITE);
   2462   GENERATE(Token::DIV, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
   2463   GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
   2464   GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
   2465   GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER, OVERWRITE_RIGHT);
   2466   GENERATE(Token::DIV, NUMBER, SMI, NUMBER, NO_OVERWRITE);
   2467   GENERATE(Token::DIV, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
   2468   GENERATE(Token::DIV, SMI, INT32, INT32, NO_OVERWRITE);
   2469   GENERATE(Token::DIV, SMI, INT32, NUMBER, NO_OVERWRITE);
   2470   GENERATE(Token::DIV, SMI, INT32, NUMBER, OVERWRITE_LEFT);
   2471   GENERATE(Token::DIV, SMI, NUMBER, NUMBER, NO_OVERWRITE);
   2472   GENERATE(Token::DIV, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
   2473   GENERATE(Token::DIV, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
   2474   GENERATE(Token::DIV, SMI, SMI, NUMBER, NO_OVERWRITE);
   2475   GENERATE(Token::DIV, SMI, SMI, NUMBER, OVERWRITE_LEFT);
   2476   GENERATE(Token::DIV, SMI, SMI, NUMBER, OVERWRITE_RIGHT);
   2477   GENERATE(Token::DIV, SMI, SMI, SMI, NO_OVERWRITE);
   2478   GENERATE(Token::DIV, SMI, SMI, SMI, OVERWRITE_LEFT);
   2479   GENERATE(Token::DIV, SMI, SMI, SMI, OVERWRITE_RIGHT);
   2480   GENERATE(Token::MOD, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
   2481   GENERATE(Token::MOD, SMI, SMI, SMI, NO_OVERWRITE);
   2482   GENERATE(Token::MOD, SMI, SMI, SMI, OVERWRITE_LEFT);
   2483   GENERATE(Token::MUL, INT32, INT32, INT32, NO_OVERWRITE);
   2484   GENERATE(Token::MUL, INT32, INT32, NUMBER, NO_OVERWRITE);
   2485   GENERATE(Token::MUL, INT32, NUMBER, NUMBER, NO_OVERWRITE);
   2486   GENERATE(Token::MUL, INT32, NUMBER, NUMBER, OVERWRITE_LEFT);
   2487   GENERATE(Token::MUL, INT32, SMI, INT32, NO_OVERWRITE);
   2488   GENERATE(Token::MUL, INT32, SMI, INT32, OVERWRITE_LEFT);
   2489   GENERATE(Token::MUL, INT32, SMI, NUMBER, NO_OVERWRITE);
   2490   GENERATE(Token::MUL, NUMBER, INT32, NUMBER, NO_OVERWRITE);
   2491   GENERATE(Token::MUL, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
   2492   GENERATE(Token::MUL, NUMBER, INT32, NUMBER, OVERWRITE_RIGHT);
   2493   GENERATE(Token::MUL, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
   2494   GENERATE(Token::MUL, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
   2495   GENERATE(Token::MUL, NUMBER, SMI, NUMBER, NO_OVERWRITE);
   2496   GENERATE(Token::MUL, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
   2497   GENERATE(Token::MUL, NUMBER, SMI, NUMBER, OVERWRITE_RIGHT);
   2498   GENERATE(Token::MUL, SMI, INT32, INT32, NO_OVERWRITE);
   2499   GENERATE(Token::MUL, SMI, INT32, INT32, OVERWRITE_LEFT);
   2500   GENERATE(Token::MUL, SMI, INT32, NUMBER, NO_OVERWRITE);
   2501   GENERATE(Token::MUL, SMI, NUMBER, NUMBER, NO_OVERWRITE);
   2502   GENERATE(Token::MUL, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
   2503   GENERATE(Token::MUL, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
   2504   GENERATE(Token::MUL, SMI, SMI, INT32, NO_OVERWRITE);
   2505   GENERATE(Token::MUL, SMI, SMI, NUMBER, NO_OVERWRITE);
   2506   GENERATE(Token::MUL, SMI, SMI, NUMBER, OVERWRITE_LEFT);
   2507   GENERATE(Token::MUL, SMI, SMI, SMI, NO_OVERWRITE);
   2508   GENERATE(Token::MUL, SMI, SMI, SMI, OVERWRITE_LEFT);
   2509   GENERATE(Token::MUL, SMI, SMI, SMI, OVERWRITE_RIGHT);
   2510   GENERATE(Token::SAR, INT32, SMI, INT32, OVERWRITE_RIGHT);
   2511   GENERATE(Token::SAR, INT32, SMI, SMI, NO_OVERWRITE);
   2512   GENERATE(Token::SAR, INT32, SMI, SMI, OVERWRITE_RIGHT);
   2513   GENERATE(Token::SAR, NUMBER, SMI, SMI, NO_OVERWRITE);
   2514   GENERATE(Token::SAR, NUMBER, SMI, SMI, OVERWRITE_RIGHT);
   2515   GENERATE(Token::SAR, SMI, SMI, SMI, OVERWRITE_LEFT);
   2516   GENERATE(Token::SAR, SMI, SMI, SMI, OVERWRITE_RIGHT);
   2517   GENERATE(Token::SHL, INT32, SMI, INT32, NO_OVERWRITE);
   2518   GENERATE(Token::SHL, INT32, SMI, INT32, OVERWRITE_RIGHT);
   2519   GENERATE(Token::SHL, INT32, SMI, SMI, NO_OVERWRITE);
   2520   GENERATE(Token::SHL, INT32, SMI, SMI, OVERWRITE_RIGHT);
   2521   GENERATE(Token::SHL, NUMBER, SMI, SMI, OVERWRITE_RIGHT);
   2522   GENERATE(Token::SHL, SMI, SMI, INT32, NO_OVERWRITE);
   2523   GENERATE(Token::SHL, SMI, SMI, INT32, OVERWRITE_LEFT);
   2524   GENERATE(Token::SHL, SMI, SMI, INT32, OVERWRITE_RIGHT);
   2525   GENERATE(Token::SHL, SMI, SMI, SMI, NO_OVERWRITE);
   2526   GENERATE(Token::SHL, SMI, SMI, SMI, OVERWRITE_LEFT);
   2527   GENERATE(Token::SHL, SMI, SMI, SMI, OVERWRITE_RIGHT);
   2528   GENERATE(Token::SHR, INT32, SMI, SMI, NO_OVERWRITE);
   2529   GENERATE(Token::SHR, INT32, SMI, SMI, OVERWRITE_LEFT);
   2530   GENERATE(Token::SHR, INT32, SMI, SMI, OVERWRITE_RIGHT);
   2531   GENERATE(Token::SHR, NUMBER, SMI, SMI, NO_OVERWRITE);
   2532   GENERATE(Token::SHR, NUMBER, SMI, SMI, OVERWRITE_LEFT);
   2533   GENERATE(Token::SHR, NUMBER, SMI, INT32, OVERWRITE_RIGHT);
   2534   GENERATE(Token::SHR, SMI, SMI, SMI, NO_OVERWRITE);
   2535   GENERATE(Token::SHR, SMI, SMI, SMI, OVERWRITE_LEFT);
   2536   GENERATE(Token::SHR, SMI, SMI, SMI, OVERWRITE_RIGHT);
   2537   GENERATE(Token::SUB, INT32, INT32, INT32, NO_OVERWRITE);
   2538   GENERATE(Token::SUB, INT32, INT32, INT32, OVERWRITE_LEFT);
   2539   GENERATE(Token::SUB, INT32, NUMBER, NUMBER, NO_OVERWRITE);
   2540   GENERATE(Token::SUB, INT32, NUMBER, NUMBER, OVERWRITE_RIGHT);
   2541   GENERATE(Token::SUB, INT32, SMI, INT32, OVERWRITE_LEFT);
   2542   GENERATE(Token::SUB, INT32, SMI, INT32, OVERWRITE_RIGHT);
   2543   GENERATE(Token::SUB, NUMBER, INT32, NUMBER, NO_OVERWRITE);
   2544   GENERATE(Token::SUB, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
   2545   GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
   2546   GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
   2547   GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER, OVERWRITE_RIGHT);
   2548   GENERATE(Token::SUB, NUMBER, SMI, NUMBER, NO_OVERWRITE);
   2549   GENERATE(Token::SUB, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
   2550   GENERATE(Token::SUB, NUMBER, SMI, NUMBER, OVERWRITE_RIGHT);
   2551   GENERATE(Token::SUB, SMI, INT32, INT32, NO_OVERWRITE);
   2552   GENERATE(Token::SUB, SMI, NUMBER, NUMBER, NO_OVERWRITE);
   2553   GENERATE(Token::SUB, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
   2554   GENERATE(Token::SUB, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
   2555   GENERATE(Token::SUB, SMI, SMI, SMI, NO_OVERWRITE);
   2556   GENERATE(Token::SUB, SMI, SMI, SMI, OVERWRITE_LEFT);
   2557   GENERATE(Token::SUB, SMI, SMI, SMI, OVERWRITE_RIGHT);
   2558 #undef GENERATE
   2559 #define GENERATE(op, left_kind, fixed_right_arg_value, result_kind, mode) \
   2560   do {                                                                    \
   2561     State state(op, mode);                                                \
   2562     state.left_kind_ = left_kind;                                         \
   2563     state.fixed_right_arg_.has_value = true;                              \
   2564     state.fixed_right_arg_.value = fixed_right_arg_value;                 \
   2565     state.right_kind_ = SMI;                                              \
   2566     state.result_kind_ = result_kind;                                     \
   2567     Generate(isolate, state);                                             \
   2568   } while (false)
   2569   GENERATE(Token::MOD, SMI, 2, SMI, NO_OVERWRITE);
   2570   GENERATE(Token::MOD, SMI, 4, SMI, NO_OVERWRITE);
   2571   GENERATE(Token::MOD, SMI, 4, SMI, OVERWRITE_LEFT);
   2572   GENERATE(Token::MOD, SMI, 8, SMI, NO_OVERWRITE);
   2573   GENERATE(Token::MOD, SMI, 16, SMI, OVERWRITE_LEFT);
   2574   GENERATE(Token::MOD, SMI, 32, SMI, NO_OVERWRITE);
   2575   GENERATE(Token::MOD, SMI, 2048, SMI, NO_OVERWRITE);
   2576 #undef GENERATE
   2577 }
   2578 
   2579 
   2580 Handle<Type> BinaryOpIC::State::GetResultType(Isolate* isolate) const {
   2581   Kind result_kind = result_kind_;
   2582   if (HasSideEffects()) {
   2583     result_kind = NONE;
   2584   } else if (result_kind == GENERIC && op_ == Token::ADD) {
   2585     return handle(Type::Union(handle(Type::Number(), isolate),
   2586                               handle(Type::String(), isolate)), isolate);
   2587   } else if (result_kind == NUMBER && op_ == Token::SHR) {
   2588     return handle(Type::Unsigned32(), isolate);
   2589   }
   2590   ASSERT_NE(GENERIC, result_kind);
   2591   return KindToType(result_kind, isolate);
   2592 }
   2593 
   2594 
   2595 void BinaryOpIC::State::Print(StringStream* stream) const {
   2596   stream->Add("(%s", Token::Name(op_));
   2597   if (mode_ == OVERWRITE_LEFT) stream->Add("_ReuseLeft");
   2598   else if (mode_ == OVERWRITE_RIGHT) stream->Add("_ReuseRight");
   2599   stream->Add(":%s*", KindToString(left_kind_));
   2600   if (fixed_right_arg_.has_value) {
   2601     stream->Add("%d", fixed_right_arg_.value);
   2602   } else {
   2603     stream->Add("%s", KindToString(right_kind_));
   2604   }
   2605   stream->Add("->%s)", KindToString(result_kind_));
   2606 }
   2607 
   2608 
   2609 void BinaryOpIC::State::Update(Handle<Object> left,
   2610                                Handle<Object> right,
   2611                                Handle<Object> result) {
   2612   ExtraICState old_extra_ic_state = GetExtraICState();
   2613 
   2614   left_kind_ = UpdateKind(left, left_kind_);
   2615   right_kind_ = UpdateKind(right, right_kind_);
   2616 
   2617   int32_t fixed_right_arg_value = 0;
   2618   bool has_fixed_right_arg =
   2619       op_ == Token::MOD &&
   2620       right->ToInt32(&fixed_right_arg_value) &&
   2621       fixed_right_arg_value > 0 &&
   2622       IsPowerOf2(fixed_right_arg_value) &&
   2623       FixedRightArgValueField::is_valid(WhichPowerOf2(fixed_right_arg_value)) &&
   2624       (left_kind_ == SMI || left_kind_ == INT32) &&
   2625       (result_kind_ == NONE || !fixed_right_arg_.has_value);
   2626   fixed_right_arg_ = Maybe<int32_t>(has_fixed_right_arg,
   2627                                     fixed_right_arg_value);
   2628 
   2629   result_kind_ = UpdateKind(result, result_kind_);
   2630 
   2631   if (!Token::IsTruncatingBinaryOp(op_)) {
   2632     Kind input_kind = Max(left_kind_, right_kind_);
   2633     if (result_kind_ < input_kind && input_kind <= NUMBER) {
   2634       result_kind_ = input_kind;
   2635     }
   2636   }
   2637 
   2638   // Reset overwrite mode unless we can actually make use of it, or may be able
   2639   // to make use of it at some point in the future.
   2640   if ((mode_ == OVERWRITE_LEFT && left_kind_ > NUMBER) ||
   2641       (mode_ == OVERWRITE_RIGHT && right_kind_ > NUMBER) ||
   2642       result_kind_ > NUMBER) {
   2643     mode_ = NO_OVERWRITE;
   2644   }
   2645 
   2646   if (old_extra_ic_state == GetExtraICState()) {
   2647     // Tagged operations can lead to non-truncating HChanges
   2648     if (left->IsUndefined() || left->IsBoolean()) {
   2649       left_kind_ = GENERIC;
   2650     } else if (right->IsUndefined() || right->IsBoolean()) {
   2651       right_kind_ = GENERIC;
   2652     } else {
   2653       // Since the X87 is too precise, we might bail out on numbers which
   2654       // actually would truncate with 64 bit precision.
   2655       ASSERT(!CpuFeatures::IsSupported(SSE2));
   2656       ASSERT(result_kind_ < NUMBER);
   2657       result_kind_ = NUMBER;
   2658     }
   2659   }
   2660 }
   2661 
   2662 
   2663 BinaryOpIC::State::Kind BinaryOpIC::State::UpdateKind(Handle<Object> object,
   2664                                                       Kind kind) const {
   2665   Kind new_kind = GENERIC;
   2666   bool is_truncating = Token::IsTruncatingBinaryOp(op());
   2667   if (object->IsBoolean() && is_truncating) {
   2668     // Booleans will be automatically truncated by HChange.
   2669     new_kind = INT32;
   2670   } else if (object->IsUndefined()) {
   2671     // Undefined will be automatically truncated by HChange.
   2672     new_kind = is_truncating ? INT32 : NUMBER;
   2673   } else if (object->IsSmi()) {
   2674     new_kind = SMI;
   2675   } else if (object->IsHeapNumber()) {
   2676     double value = Handle<HeapNumber>::cast(object)->value();
   2677     new_kind = TypeInfo::IsInt32Double(value) ? INT32 : NUMBER;
   2678   } else if (object->IsString() && op() == Token::ADD) {
   2679     new_kind = STRING;
   2680   }
   2681   if (new_kind == INT32 && SmiValuesAre32Bits()) {
   2682     new_kind = NUMBER;
   2683   }
   2684   if (kind != NONE &&
   2685       ((new_kind <= NUMBER && kind > NUMBER) ||
   2686        (new_kind > NUMBER && kind <= NUMBER))) {
   2687     new_kind = GENERIC;
   2688   }
   2689   return Max(kind, new_kind);
   2690 }
   2691 
   2692 
   2693 // static
   2694 const char* BinaryOpIC::State::KindToString(Kind kind) {
   2695   switch (kind) {
   2696     case NONE: return "None";
   2697     case SMI: return "Smi";
   2698     case INT32: return "Int32";
   2699     case NUMBER: return "Number";
   2700     case STRING: return "String";
   2701     case GENERIC: return "Generic";
   2702   }
   2703   UNREACHABLE();
   2704   return NULL;
   2705 }
   2706 
   2707 
   2708 // static
   2709 Handle<Type> BinaryOpIC::State::KindToType(Kind kind, Isolate* isolate) {
   2710   Type* type = NULL;
   2711   switch (kind) {
   2712     case NONE: type = Type::None(); break;
   2713     case SMI: type = Type::Smi(); break;
   2714     case INT32: type = Type::Signed32(); break;
   2715     case NUMBER: type = Type::Number(); break;
   2716     case STRING: type = Type::String(); break;
   2717     case GENERIC: type = Type::Any(); break;
   2718   }
   2719   return handle(type, isolate);
   2720 }
   2721 
   2722 
   2723 MaybeObject* BinaryOpIC::Transition(Handle<Object> left, Handle<Object> right) {
   2724   State state(target()->extended_extra_ic_state());
   2725 
   2726   // Compute the actual result using the builtin for the binary operation.
   2727   Object* builtin = isolate()->js_builtins_object()->javascript_builtin(
   2728       TokenToJSBuiltin(state.op()));
   2729   Handle<JSFunction> function = handle(JSFunction::cast(builtin), isolate());
   2730   bool caught_exception;
   2731   Handle<Object> result = Execution::Call(
   2732       isolate(), function, left, 1, &right, &caught_exception);
   2733   if (caught_exception) return Failure::Exception();
   2734 
   2735   // Compute the new state.
   2736   State old_state = state;
   2737   state.Update(left, right, result);
   2738 
   2739   // Install the new stub.
   2740   BinaryOpICStub stub(state);
   2741   set_target(*stub.GetCode(isolate()));
   2742 
   2743   if (FLAG_trace_ic) {
   2744     char buffer[150];
   2745     NoAllocationStringAllocator allocator(
   2746         buffer, static_cast<unsigned>(sizeof(buffer)));
   2747     StringStream stream(&allocator);
   2748     stream.Add("[BinaryOpIC");
   2749     old_state.Print(&stream);
   2750     stream.Add(" => ");
   2751     state.Print(&stream);
   2752     stream.Add(" @ %p <- ", static_cast<void*>(*target()));
   2753     stream.OutputToStdOut();
   2754     JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
   2755     PrintF("]\n");
   2756   }
   2757 
   2758   // Patch the inlined smi code as necessary.
   2759   if (!old_state.UseInlinedSmiCode() && state.UseInlinedSmiCode()) {
   2760     PatchInlinedSmiCode(address(), ENABLE_INLINED_SMI_CHECK);
   2761   } else if (old_state.UseInlinedSmiCode() && !state.UseInlinedSmiCode()) {
   2762     PatchInlinedSmiCode(address(), DISABLE_INLINED_SMI_CHECK);
   2763   }
   2764 
   2765   return *result;
   2766 }
   2767 
   2768 
   2769 RUNTIME_FUNCTION(MaybeObject*, BinaryOpIC_Miss) {
   2770   HandleScope scope(isolate);
   2771   Handle<Object> left = args.at<Object>(BinaryOpICStub::kLeft);
   2772   Handle<Object> right = args.at<Object>(BinaryOpICStub::kRight);
   2773   BinaryOpIC ic(isolate);
   2774   return ic.Transition(left, right);
   2775 }
   2776 
   2777 
   2778 Code* CompareIC::GetRawUninitialized(Isolate* isolate, Token::Value op) {
   2779   ICCompareStub stub(op, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED);
   2780   Code* code = NULL;
   2781   CHECK(stub.FindCodeInCache(&code, isolate));
   2782   return code;
   2783 }
   2784 
   2785 
   2786 Handle<Code> CompareIC::GetUninitialized(Isolate* isolate, Token::Value op) {
   2787   ICCompareStub stub(op, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED);
   2788   return stub.GetCode(isolate);
   2789 }
   2790 
   2791 
   2792 const char* CompareIC::GetStateName(State state) {
   2793   switch (state) {
   2794     case UNINITIALIZED: return "UNINITIALIZED";
   2795     case SMI: return "SMI";
   2796     case NUMBER: return "NUMBER";
   2797     case INTERNALIZED_STRING: return "INTERNALIZED_STRING";
   2798     case STRING: return "STRING";
   2799     case UNIQUE_NAME: return "UNIQUE_NAME";
   2800     case OBJECT: return "OBJECT";
   2801     case KNOWN_OBJECT: return "KNOWN_OBJECT";
   2802     case GENERIC: return "GENERIC";
   2803   }
   2804   UNREACHABLE();
   2805   return NULL;
   2806 }
   2807 
   2808 
   2809 Handle<Type> CompareIC::StateToType(
   2810     Isolate* isolate,
   2811     CompareIC::State state,
   2812     Handle<Map> map) {
   2813   switch (state) {
   2814     case CompareIC::UNINITIALIZED:
   2815       return handle(Type::None(), isolate);
   2816     case CompareIC::SMI:
   2817       return handle(Type::Smi(), isolate);
   2818     case CompareIC::NUMBER:
   2819       return handle(Type::Number(), isolate);
   2820     case CompareIC::STRING:
   2821       return handle(Type::String(), isolate);
   2822     case CompareIC::INTERNALIZED_STRING:
   2823       return handle(Type::InternalizedString(), isolate);
   2824     case CompareIC::UNIQUE_NAME:
   2825       return handle(Type::UniqueName(), isolate);
   2826     case CompareIC::OBJECT:
   2827       return handle(Type::Receiver(), isolate);
   2828     case CompareIC::KNOWN_OBJECT:
   2829       return handle(
   2830           map.is_null() ? Type::Receiver() : Type::Class(map), isolate);
   2831     case CompareIC::GENERIC:
   2832       return handle(Type::Any(), isolate);
   2833   }
   2834   UNREACHABLE();
   2835   return Handle<Type>();
   2836 }
   2837 
   2838 
   2839 void CompareIC::StubInfoToType(int stub_minor_key,
   2840                                Handle<Type>* left_type,
   2841                                Handle<Type>* right_type,
   2842                                Handle<Type>* overall_type,
   2843                                Handle<Map> map,
   2844                                Isolate* isolate) {
   2845   State left_state, right_state, handler_state;
   2846   ICCompareStub::DecodeMinorKey(stub_minor_key, &left_state, &right_state,
   2847                                 &handler_state, NULL);
   2848   *left_type = StateToType(isolate, left_state);
   2849   *right_type = StateToType(isolate, right_state);
   2850   *overall_type = StateToType(isolate, handler_state, map);
   2851 }
   2852 
   2853 
   2854 CompareIC::State CompareIC::NewInputState(State old_state,
   2855                                           Handle<Object> value) {
   2856   switch (old_state) {
   2857     case UNINITIALIZED:
   2858       if (value->IsSmi()) return SMI;
   2859       if (value->IsHeapNumber()) return NUMBER;
   2860       if (value->IsInternalizedString()) return INTERNALIZED_STRING;
   2861       if (value->IsString()) return STRING;
   2862       if (value->IsSymbol()) return UNIQUE_NAME;
   2863       if (value->IsJSObject()) return OBJECT;
   2864       break;
   2865     case SMI:
   2866       if (value->IsSmi()) return SMI;
   2867       if (value->IsHeapNumber()) return NUMBER;
   2868       break;
   2869     case NUMBER:
   2870       if (value->IsNumber()) return NUMBER;
   2871       break;
   2872     case INTERNALIZED_STRING:
   2873       if (value->IsInternalizedString()) return INTERNALIZED_STRING;
   2874       if (value->IsString()) return STRING;
   2875       if (value->IsSymbol()) return UNIQUE_NAME;
   2876       break;
   2877     case STRING:
   2878       if (value->IsString()) return STRING;
   2879       break;
   2880     case UNIQUE_NAME:
   2881       if (value->IsUniqueName()) return UNIQUE_NAME;
   2882       break;
   2883     case OBJECT:
   2884       if (value->IsJSObject()) return OBJECT;
   2885       break;
   2886     case GENERIC:
   2887       break;
   2888     case KNOWN_OBJECT:
   2889       UNREACHABLE();
   2890       break;
   2891   }
   2892   return GENERIC;
   2893 }
   2894 
   2895 
   2896 CompareIC::State CompareIC::TargetState(State old_state,
   2897                                         State old_left,
   2898                                         State old_right,
   2899                                         bool has_inlined_smi_code,
   2900                                         Handle<Object> x,
   2901                                         Handle<Object> y) {
   2902   switch (old_state) {
   2903     case UNINITIALIZED:
   2904       if (x->IsSmi() && y->IsSmi()) return SMI;
   2905       if (x->IsNumber() && y->IsNumber()) return NUMBER;
   2906       if (Token::IsOrderedRelationalCompareOp(op_)) {
   2907         // Ordered comparisons treat undefined as NaN, so the
   2908         // NUMBER stub will do the right thing.
   2909         if ((x->IsNumber() && y->IsUndefined()) ||
   2910             (y->IsNumber() && x->IsUndefined())) {
   2911           return NUMBER;
   2912         }
   2913       }
   2914       if (x->IsInternalizedString() && y->IsInternalizedString()) {
   2915         // We compare internalized strings as plain ones if we need to determine
   2916         // the order in a non-equality compare.
   2917         return Token::IsEqualityOp(op_) ? INTERNALIZED_STRING : STRING;
   2918       }
   2919       if (x->IsString() && y->IsString()) return STRING;
   2920       if (!Token::IsEqualityOp(op_)) return GENERIC;
   2921       if (x->IsUniqueName() && y->IsUniqueName()) return UNIQUE_NAME;
   2922       if (x->IsJSObject() && y->IsJSObject()) {
   2923         if (Handle<JSObject>::cast(x)->map() ==
   2924             Handle<JSObject>::cast(y)->map()) {
   2925           return KNOWN_OBJECT;
   2926         } else {
   2927           return OBJECT;
   2928         }
   2929       }
   2930       return GENERIC;
   2931     case SMI:
   2932       return x->IsNumber() && y->IsNumber() ? NUMBER : GENERIC;
   2933     case INTERNALIZED_STRING:
   2934       ASSERT(Token::IsEqualityOp(op_));
   2935       if (x->IsString() && y->IsString()) return STRING;
   2936       if (x->IsUniqueName() && y->IsUniqueName()) return UNIQUE_NAME;
   2937       return GENERIC;
   2938     case NUMBER:
   2939       // If the failure was due to one side changing from smi to heap number,
   2940       // then keep the state (if other changed at the same time, we will get
   2941       // a second miss and then go to generic).
   2942       if (old_left == SMI && x->IsHeapNumber()) return NUMBER;
   2943       if (old_right == SMI && y->IsHeapNumber()) return NUMBER;
   2944       return GENERIC;
   2945     case KNOWN_OBJECT:
   2946       ASSERT(Token::IsEqualityOp(op_));
   2947       if (x->IsJSObject() && y->IsJSObject()) return OBJECT;
   2948       return GENERIC;
   2949     case STRING:
   2950     case UNIQUE_NAME:
   2951     case OBJECT:
   2952     case GENERIC:
   2953       return GENERIC;
   2954   }
   2955   UNREACHABLE();
   2956   return GENERIC;  // Make the compiler happy.
   2957 }
   2958 
   2959 
   2960 Code* CompareIC::UpdateCaches(Handle<Object> x, Handle<Object> y) {
   2961   HandleScope scope(isolate());
   2962   State previous_left, previous_right, previous_state;
   2963   ICCompareStub::DecodeMinorKey(target()->stub_info(), &previous_left,
   2964                                 &previous_right, &previous_state, NULL);
   2965   State new_left = NewInputState(previous_left, x);
   2966   State new_right = NewInputState(previous_right, y);
   2967   State state = TargetState(previous_state, previous_left, previous_right,
   2968                             HasInlinedSmiCode(address()), x, y);
   2969   ICCompareStub stub(op_, new_left, new_right, state);
   2970   if (state == KNOWN_OBJECT) {
   2971     stub.set_known_map(
   2972         Handle<Map>(Handle<JSObject>::cast(x)->map(), isolate()));
   2973   }
   2974   Handle<Code> new_target = stub.GetCode(isolate());
   2975   set_target(*new_target);
   2976 
   2977   if (FLAG_trace_ic) {
   2978     PrintF("[CompareIC in ");
   2979     JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
   2980     PrintF(" ((%s+%s=%s)->(%s+%s=%s))#%s @ %p]\n",
   2981            GetStateName(previous_left),
   2982            GetStateName(previous_right),
   2983            GetStateName(previous_state),
   2984            GetStateName(new_left),
   2985            GetStateName(new_right),
   2986            GetStateName(state),
   2987            Token::Name(op_),
   2988            static_cast<void*>(*stub.GetCode(isolate())));
   2989   }
   2990 
   2991   // Activate inlined smi code.
   2992   if (previous_state == UNINITIALIZED) {
   2993     PatchInlinedSmiCode(address(), ENABLE_INLINED_SMI_CHECK);
   2994   }
   2995 
   2996   return *new_target;
   2997 }
   2998 
   2999 
   3000 // Used from ICCompareStub::GenerateMiss in code-stubs-<arch>.cc.
   3001 RUNTIME_FUNCTION(Code*, CompareIC_Miss) {
   3002   HandleScope scope(isolate);
   3003   ASSERT(args.length() == 3);
   3004   CompareIC ic(isolate, static_cast<Token::Value>(args.smi_at(2)));
   3005   return ic.UpdateCaches(args.at<Object>(0), args.at<Object>(1));
   3006 }
   3007 
   3008 
   3009 void CompareNilIC::Clear(Address address, Code* target) {
   3010   if (IsCleared(target)) return;
   3011   ExtraICState state = target->extended_extra_ic_state();
   3012 
   3013   CompareNilICStub stub(state, HydrogenCodeStub::UNINITIALIZED);
   3014   stub.ClearState();
   3015 
   3016   Code* code = NULL;
   3017   CHECK(stub.FindCodeInCache(&code, target->GetIsolate()));
   3018 
   3019   SetTargetAtAddress(address, code);
   3020 }
   3021 
   3022 
   3023 MaybeObject* CompareNilIC::DoCompareNilSlow(NilValue nil,
   3024                                             Handle<Object> object) {
   3025   if (object->IsNull() || object->IsUndefined()) {
   3026     return Smi::FromInt(true);
   3027   }
   3028   return Smi::FromInt(object->IsUndetectableObject());
   3029 }
   3030 
   3031 
   3032 MaybeObject* CompareNilIC::CompareNil(Handle<Object> object) {
   3033   ExtraICState extra_ic_state = target()->extended_extra_ic_state();
   3034 
   3035   CompareNilICStub stub(extra_ic_state);
   3036 
   3037   // Extract the current supported types from the patched IC and calculate what
   3038   // types must be supported as a result of the miss.
   3039   bool already_monomorphic = stub.IsMonomorphic();
   3040 
   3041   stub.UpdateStatus(object);
   3042 
   3043   NilValue nil = stub.GetNilValue();
   3044 
   3045   // Find or create the specialized stub to support the new set of types.
   3046   Handle<Code> code;
   3047   if (stub.IsMonomorphic()) {
   3048     Handle<Map> monomorphic_map(already_monomorphic
   3049                                 ? target()->FindFirstMap()
   3050                                 : HeapObject::cast(*object)->map());
   3051     code = isolate()->stub_cache()->ComputeCompareNil(monomorphic_map, stub);
   3052   } else {
   3053     code = stub.GetCode(isolate());
   3054   }
   3055   set_target(*code);
   3056   return DoCompareNilSlow(nil, object);
   3057 }
   3058 
   3059 
   3060 RUNTIME_FUNCTION(MaybeObject*, CompareNilIC_Miss) {
   3061   HandleScope scope(isolate);
   3062   Handle<Object> object = args.at<Object>(0);
   3063   CompareNilIC ic(isolate);
   3064   return ic.CompareNil(object);
   3065 }
   3066 
   3067 
   3068 RUNTIME_FUNCTION(MaybeObject*, Unreachable) {
   3069   UNREACHABLE();
   3070   CHECK(false);
   3071   return isolate->heap()->undefined_value();
   3072 }
   3073 
   3074 
   3075 Builtins::JavaScript BinaryOpIC::TokenToJSBuiltin(Token::Value op) {
   3076   switch (op) {
   3077     default:
   3078       UNREACHABLE();
   3079     case Token::ADD:
   3080       return Builtins::ADD;
   3081       break;
   3082     case Token::SUB:
   3083       return Builtins::SUB;
   3084       break;
   3085     case Token::MUL:
   3086       return Builtins::MUL;
   3087       break;
   3088     case Token::DIV:
   3089       return Builtins::DIV;
   3090       break;
   3091     case Token::MOD:
   3092       return Builtins::MOD;
   3093       break;
   3094     case Token::BIT_OR:
   3095       return Builtins::BIT_OR;
   3096       break;
   3097     case Token::BIT_AND:
   3098       return Builtins::BIT_AND;
   3099       break;
   3100     case Token::BIT_XOR:
   3101       return Builtins::BIT_XOR;
   3102       break;
   3103     case Token::SAR:
   3104       return Builtins::SAR;
   3105       break;
   3106     case Token::SHR:
   3107       return Builtins::SHR;
   3108       break;
   3109     case Token::SHL:
   3110       return Builtins::SHL;
   3111       break;
   3112   }
   3113 }
   3114 
   3115 
   3116 MaybeObject* ToBooleanIC::ToBoolean(Handle<Object> object) {
   3117   ToBooleanStub stub(target()->extended_extra_ic_state());
   3118   bool to_boolean_value = stub.UpdateStatus(object);
   3119   Handle<Code> code = stub.GetCode(isolate());
   3120   set_target(*code);
   3121   return Smi::FromInt(to_boolean_value ? 1 : 0);
   3122 }
   3123 
   3124 
   3125 RUNTIME_FUNCTION(MaybeObject*, ToBooleanIC_Miss) {
   3126   ASSERT(args.length() == 1);
   3127   HandleScope scope(isolate);
   3128   Handle<Object> object = args.at<Object>(0);
   3129   ToBooleanIC ic(isolate);
   3130   return ic.ToBoolean(object);
   3131 }
   3132 
   3133 
   3134 static const Address IC_utilities[] = {
   3135 #define ADDR(name) FUNCTION_ADDR(name),
   3136     IC_UTIL_LIST(ADDR)
   3137     NULL
   3138 #undef ADDR
   3139 };
   3140 
   3141 
   3142 Address IC::AddressFromUtilityId(IC::UtilityId id) {
   3143   return IC_utilities[id];
   3144 }
   3145 
   3146 
   3147 } }  // namespace v8::internal
   3148