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