code-stubs-hydrogen.cc 73 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/v8.h"
6

7
#include "src/bailout-reason.h"
8
#include "src/code-stubs.h"
9
#include "src/field-index.h"
10 11
#include "src/hydrogen.h"
#include "src/lithium.h"
12 13 14 15 16

namespace v8 {
namespace internal {


17
static LChunk* OptimizeGraph(HGraph* graph) {
18 19 20
  DisallowHeapAllocation no_allocation;
  DisallowHandleAllocation no_handles;
  DisallowHandleDereference no_deref;
21

22
  DCHECK(graph != NULL);
23
  BailoutReason bailout_reason = kNoReason;
24
  if (!graph->Optimize(&bailout_reason)) {
25
    FATAL(GetBailoutReason(bailout_reason));
26
  }
27
  LChunk* chunk = LChunk::NewChunk(graph);
28
  if (chunk == NULL) {
29
    FATAL(GetBailoutReason(graph->info()->bailout_reason()));
30 31
  }
  return chunk;
32 33 34 35 36 37
}


class CodeStubGraphBuilderBase : public HGraphBuilder {
 public:
  CodeStubGraphBuilderBase(Isolate* isolate, HydrogenCodeStub* stub)
38 39 40
      : HGraphBuilder(&info_),
        arguments_length_(NULL),
        info_(stub, isolate),
41
        descriptor_(stub),
42
        context_(NULL) {
43
    int parameter_count = descriptor_.GetEnvironmentParameterCount();
44
    parameters_.Reset(new HParameter*[parameter_count]);
45
  }
46 47 48
  virtual bool BuildGraph();

 protected:
49 50
  virtual HValue* BuildCodeStub() = 0;
  HParameter* GetParameter(int parameter) {
51
    DCHECK(parameter < descriptor_.GetEnvironmentParameterCount());
52 53 54 55
    return parameters_[parameter];
  }
  HValue* GetArgumentsLength() {
    // This is initialized in BuildGraph()
56
    DCHECK(arguments_length_ != NULL);
57 58
    return arguments_length_;
  }
59
  CompilationInfo* info() { return &info_; }
60
  HydrogenCodeStub* stub() { return info_.code_stub(); }
61
  HContext* context() { return context_; }
62
  Isolate* isolate() { return info_.isolate(); }
63

64
  HLoadNamedField* BuildLoadNamedField(HValue* object,
65
                                       FieldIndex index);
66
  void BuildStoreNamedField(HValue* object, HValue* value, FieldIndex index,
67 68
                            Representation representation,
                            bool transition_to_field);
69

70 71 72 73 74 75
  enum ArgumentClass {
    NONE,
    SINGLE,
    MULTIPLE
  };

76 77
  HValue* UnmappedCase(HValue* elements, HValue* key);

78
  HValue* BuildArrayConstructor(ElementsKind kind,
79
                                AllocationSiteOverrideMode override_mode,
80 81 82 83
                                ArgumentClass argument_class);
  HValue* BuildInternalArrayConstructor(ElementsKind kind,
                                        ArgumentClass argument_class);

84 85 86 87 88 89 90 91 92
  // BuildCheckAndInstallOptimizedCode emits code to install the optimized
  // function found in the optimized code map at map_index in js_function, if
  // the function at map_index matches the given native_context. Builder is
  // left in the "Then()" state after the install.
  void BuildCheckAndInstallOptimizedCode(HValue* js_function,
                                         HValue* native_context,
                                         IfBuilder* builder,
                                         HValue* optimized_map,
                                         HValue* map_index);
93
  void BuildInstallCode(HValue* js_function, HValue* shared_info);
94 95 96 97

  HInstruction* LoadFromOptimizedCodeMap(HValue* optimized_map,
                                         HValue* iterator,
                                         int field_offset);
98 99 100 101
  void BuildInstallFromOptimizedCodeMap(HValue* js_function,
                                        HValue* shared_info,
                                        HValue* native_context);

102
 private:
103 104 105 106
  HValue* BuildArraySingleArgumentConstructor(JSArrayBuilder* builder);
  HValue* BuildArrayNArgumentsConstructor(JSArrayBuilder* builder,
                                          ElementsKind kind);

107
  SmartArrayPointer<HParameter*> parameters_;
108
  HValue* arguments_length_;
109
  CompilationInfoWithZone info_;
110
  CodeStubDescriptor descriptor_;
111
  HContext* context_;
112 113 114 115
};


bool CodeStubGraphBuilderBase::BuildGraph() {
116 117 118
  // Update the static counter each time a new code stub is generated.
  isolate()->counters()->code_stubs()->Increment();

119
  if (FLAG_trace_hydrogen_stubs) {
120
    const char* name = CodeStub::MajorName(stub()->MajorKey(), false);
121
    PrintF("-----------------------------------------------------------\n");
122
    PrintF("Compiling stub %s using hydrogen\n", name);
123
    isolate()->GetHTracer()->TraceCompilation(&info_);
124 125
  }

126
  int param_count = descriptor_.GetEnvironmentParameterCount();
127
  HEnvironment* start_environment = graph()->start_environment();
128
  HBasicBlock* next_block = CreateBasicBlock(start_environment);
129
  Goto(next_block);
130 131 132
  next_block->SetJoinId(BailoutId::StubEntry());
  set_current_block(next_block);

133
  bool runtime_stack_params = descriptor_.stack_parameter_count().is_valid();
134
  HInstruction* stack_parameter_count = NULL;
135
  for (int i = 0; i < param_count; ++i) {
136
    Representation r = descriptor_.GetEnvironmentParameterRepresentation(i);
137 138
    HParameter* param = Add<HParameter>(i,
                                        HParameter::REGISTER_PARAMETER, r);
139
    start_environment->Bind(i, param);
140
    parameters_[i] = param;
141
    if (descriptor_.IsEnvironmentParameterCountRegister(i)) {
142 143 144 145
      param->set_type(HType::Smi());
      stack_parameter_count = param;
      arguments_length_ = stack_parameter_count;
    }
146
  }
147

148
  DCHECK(!runtime_stack_params || arguments_length_ != NULL);
149
  if (!runtime_stack_params) {
150 151
    stack_parameter_count = graph()->GetConstantMinus1();
    arguments_length_ = graph()->GetConstant0();
152 153
  }

154
  context_ = Add<HContext>();
155
  start_environment->BindContext(context_);
156

157
  Add<HSimulate>(BailoutId::StubEntry());
158

159 160
  NoObservableSideEffectsScope no_effects(this);

161
  HValue* return_value = BuildCodeStub();
162 163

  // We might have extra expressions to pop from the stack in addition to the
164
  // arguments above.
165
  HInstruction* stack_pop_count = stack_parameter_count;
166
  if (descriptor_.function_mode() == JS_FUNCTION_STUB_MODE) {
167
    if (!stack_parameter_count->IsConstant() &&
168
        descriptor_.hint_stack_parameter_count() < 0) {
169
      HInstruction* constant_one = graph()->GetConstant1();
170
      stack_pop_count = AddUncasted<HAdd>(stack_parameter_count, constant_one);
171
      stack_pop_count->ClearFlag(HValue::kCanOverflow);
172 173
      // TODO(mvstanton): verify that stack_parameter_count+1 really fits in a
      // smi.
174
    } else {
175
      int count = descriptor_.hint_stack_parameter_count();
176
      stack_pop_count = Add<HConstant>(count);
177
    }
178 179
  }

180
  if (current_block() != NULL) {
181 182
    HReturn* hreturn_instruction = New<HReturn>(return_value,
                                                stack_pop_count);
183
    FinishCurrentBlock(hreturn_instruction);
184
  }
185 186 187
  return true;
}

188

189 190 191
template <class Stub>
class CodeStubGraphBuilder: public CodeStubGraphBuilderBase {
 public:
192
  CodeStubGraphBuilder(Isolate* isolate, Stub* stub)
193
      : CodeStubGraphBuilderBase(isolate, stub) {}
194 195

 protected:
196
  virtual HValue* BuildCodeStub() {
197
    if (casted_stub()->IsUninitialized()) {
198
      return BuildCodeUninitializedStub();
199 200
    } else {
      return BuildCodeInitializedStub();
201 202 203 204 205 206 207 208 209 210 211
    }
  }

  virtual HValue* BuildCodeInitializedStub() {
    UNIMPLEMENTED();
    return NULL;
  }

  virtual HValue* BuildCodeUninitializedStub() {
    // Force a deopt that falls back to the runtime.
    HValue* undefined = graph()->GetConstantUndefined();
212 213 214
    IfBuilder builder(this);
    builder.IfNot<HCompareObjectEqAndBranch, HValue*>(undefined, undefined);
    builder.Then();
215
    builder.ElseDeopt("Forced deopt to runtime");
216 217 218
    return undefined;
  }

219 220 221 222
  Stub* casted_stub() { return static_cast<Stub*>(stub()); }
};


223 224
Handle<Code> HydrogenCodeStub::GenerateLightweightMissCode(
    ExternalReference miss) {
225
  Factory* factory = isolate()->factory();
226 227

  // Generate the new code.
228
  MacroAssembler masm(isolate(), NULL, 256);
229 230 231

  {
    // Update the static counter each time a new code stub is generated.
232
    isolate()->counters()->code_stubs()->Increment();
233 234 235

    // Generate the code for the stub.
    masm.set_generating_stub(true);
236 237
    // TODO(yangguo): remove this once we can serialize IC stubs.
    masm.enable_serializer();
238
    NoCurrentFrameScope scope(&masm);
239
    GenerateLightweightMiss(&masm, miss);
240 241 242 243 244 245 246 247 248 249 250
  }

  // Create the code object.
  CodeDesc desc;
  masm.GetCode(&desc);

  // Copy the generated code into a heap object.
  Code::Flags flags = Code::ComputeFlags(
      GetCodeKind(),
      GetICState(),
      GetExtraICState(),
251
      GetStubType());
252 253 254 255 256 257
  Handle<Code> new_object = factory->NewCode(
      desc, flags, masm.CodeObject(), NeedsImmovableCode());
  return new_object;
}


258
template <class Stub>
259 260
static Handle<Code> DoGenerateCode(Stub* stub) {
  Isolate* isolate = stub->isolate();
261
  CodeStubDescriptor descriptor(stub);
262 263

  // If we are uninitialized we can use a light-weight stub to enter
264 265
  // the runtime that is significantly faster than using the standard
  // stub-failure deopt mechanism.
266 267
  if (stub->IsUninitialized() && descriptor.has_miss_handler()) {
    DCHECK(!descriptor.stack_parameter_count().is_valid());
268
    return stub->GenerateLightweightMissCode(descriptor.miss_handler());
269
  }
270
  base::ElapsedTimer timer;
271 272 273
  if (FLAG_profile_hydrogen_code_stub_compilation) {
    timer.Start();
  }
274
  CodeStubGraphBuilder<Stub> builder(isolate, stub);
275
  LChunk* chunk = OptimizeGraph(builder.CreateGraph());
276 277
  Handle<Code> code = chunk->Codegen();
  if (FLAG_profile_hydrogen_code_stub_compilation) {
278 279
    OFStream os(stdout);
    os << "[Lazy compilation of " << stub << " took "
280
       << timer.Elapsed().InMillisecondsF() << " ms]" << std::endl;
281 282
  }
  return code;
283 284 285
}


286 287 288 289
template <>
HValue* CodeStubGraphBuilder<NumberToStringStub>::BuildCodeStub() {
  info()->MarkAsSavesCallerDoubles();
  HValue* number = GetParameter(NumberToStringStub::kNumber);
290
  return BuildNumberToString(number, Type::Number(zone()));
291 292 293
}


294 295
Handle<Code> NumberToStringStub::GenerateCode() {
  return DoGenerateCode(this);
296 297 298
}


299 300 301
template <>
HValue* CodeStubGraphBuilder<FastCloneShallowArrayStub>::BuildCodeStub() {
  Factory* factory = isolate()->factory();
302
  HValue* undefined = graph()->GetConstantUndefined();
303
  AllocationSiteMode alloc_site_mode = casted_stub()->allocation_site_mode();
304 305 306 307

  // This stub is very performance sensitive, the generated code must be tuned
  // so that it doesn't build and eager frame.
  info()->MarkMustNotHaveEagerFrame();
308

309 310 311 312
  HInstruction* allocation_site = Add<HLoadKeyed>(GetParameter(0),
                                                  GetParameter(1),
                                                  static_cast<HValue*>(NULL),
                                                  FAST_ELEMENTS);
313
  IfBuilder checker(this);
314 315
  checker.IfNot<HCompareObjectEqAndBranch, HValue*>(allocation_site,
                                                    undefined);
316
  checker.Then();
317

318 319
  HObjectAccess access = HObjectAccess::ForAllocationSiteOffset(
      AllocationSite::kTransitionInfoOffset);
320 321
  HInstruction* boilerplate = Add<HLoadNamedField>(
      allocation_site, static_cast<HValue*>(NULL), access);
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
  HValue* elements = AddLoadElements(boilerplate);
  HValue* capacity = AddLoadFixedArrayLength(elements);
  IfBuilder zero_capacity(this);
  zero_capacity.If<HCompareNumericAndBranch>(capacity, graph()->GetConstant0(),
                                           Token::EQ);
  zero_capacity.Then();
  Push(BuildCloneShallowArrayEmpty(boilerplate,
                                   allocation_site,
                                   alloc_site_mode));
  zero_capacity.Else();
  IfBuilder if_fixed_cow(this);
  if_fixed_cow.If<HCompareMap>(elements, factory->fixed_cow_array_map());
  if_fixed_cow.Then();
  Push(BuildCloneShallowArrayCow(boilerplate,
                                 allocation_site,
                                 alloc_site_mode,
                                 FAST_ELEMENTS));
  if_fixed_cow.Else();
  IfBuilder if_fixed(this);
  if_fixed.If<HCompareMap>(elements, factory->fixed_array_map());
  if_fixed.Then();
  Push(BuildCloneShallowArrayNonEmpty(boilerplate,
                                      allocation_site,
                                      alloc_site_mode,
                                      FAST_ELEMENTS));

  if_fixed.Else();
  Push(BuildCloneShallowArrayNonEmpty(boilerplate,
                                      allocation_site,
                                      alloc_site_mode,
                                      FAST_DOUBLE_ELEMENTS));
  if_fixed.End();
  if_fixed_cow.End();
  zero_capacity.End();
356

357
  checker.ElseDeopt("Uninitialized boilerplate literals");
358 359 360
  checker.End();

  return environment()->Pop();
361 362 363
}


364 365
Handle<Code> FastCloneShallowArrayStub::GenerateCode() {
  return DoGenerateCode(this);
366 367 368
}


369
template <>
370
HValue* CodeStubGraphBuilder<FastCloneShallowObjectStub>::BuildCodeStub() {
371
  HValue* undefined = graph()->GetConstantUndefined();
372

373 374 375 376
  HInstruction* allocation_site = Add<HLoadKeyed>(GetParameter(0),
                                                  GetParameter(1),
                                                  static_cast<HValue*>(NULL),
                                                  FAST_ELEMENTS);
377

378
  IfBuilder checker(this);
379
  checker.IfNot<HCompareObjectEqAndBranch, HValue*>(allocation_site,
380
                                                    undefined);
381
  checker.And();
382

383 384
  HObjectAccess access = HObjectAccess::ForAllocationSiteOffset(
      AllocationSite::kTransitionInfoOffset);
385 386
  HInstruction* boilerplate = Add<HLoadNamedField>(
      allocation_site, static_cast<HValue*>(NULL), access);
387

388 389 390 391 392 393
  int length = casted_stub()->length();
  if (length == 0) {
    // Empty objects have some slack added to them.
    length = JSObject::kInitialGlobalObjectUnusedPropertiesCount;
  }
  int size = JSObject::kHeaderSize + length * kPointerSize;
394 395 396 397 398
  int object_size = size;
  if (FLAG_allocation_site_pretenuring) {
    size += AllocationMemento::kSize;
  }

399
  HValue* boilerplate_map = Add<HLoadNamedField>(
400 401
      boilerplate, static_cast<HValue*>(NULL),
      HObjectAccess::ForMap());
402
  HValue* boilerplate_size = Add<HLoadNamedField>(
403 404
      boilerplate_map, static_cast<HValue*>(NULL),
      HObjectAccess::ForMapInstanceSize());
405
  HValue* size_in_words = Add<HConstant>(object_size >> kPointerSizeLog2);
406 407
  checker.If<HCompareNumericAndBranch>(boilerplate_size,
                                       size_in_words, Token::EQ);
408
  checker.Then();
409

410
  HValue* size_in_bytes = Add<HConstant>(size);
411

412
  HInstruction* object = Add<HAllocate>(size_in_bytes, HType::JSObject(),
413
      NOT_TENURED, JS_OBJECT_TYPE);
414

415
  for (int i = 0; i < object_size; i += kPointerSize) {
416
    HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(i);
417 418
    Add<HStoreNamedField>(
        object, access, Add<HLoadNamedField>(
419
            boilerplate, static_cast<HValue*>(NULL), access));
420 421
  }

422
  DCHECK(FLAG_allocation_site_pretenuring || (size == object_size));
423
  if (FLAG_allocation_site_pretenuring) {
424 425
    BuildCreateAllocationMemento(
        object, Add<HConstant>(object_size), allocation_site);
426 427
  }

428
  environment()->Push(object);
429
  checker.ElseDeopt("Uninitialized boilerplate in fast clone");
430 431 432
  checker.End();

  return environment()->Pop();
433 434 435
}


436 437
Handle<Code> FastCloneShallowObjectStub::GenerateCode() {
  return DoGenerateCode(this);
438 439
}

dslomov@chromium.org's avatar
dslomov@chromium.org committed
440

441 442
template <>
HValue* CodeStubGraphBuilder<CreateAllocationSiteStub>::BuildCodeStub() {
443
  HValue* size = Add<HConstant>(AllocationSite::kSize);
444 445
  HInstruction* object = Add<HAllocate>(size, HType::JSObject(), TENURED,
      JS_OBJECT_TYPE);
446 447

  // Store the map
448
  Handle<Map> allocation_site_map = isolate()->factory()->allocation_site_map();
449 450 451
  AddStoreMapConstant(object, allocation_site_map);

  // Store the payload (smi elements kind)
452
  HValue* initial_elements_kind = Add<HConstant>(GetInitialFastElementsKind());
453
  Add<HStoreNamedField>(object,
454 455
                        HObjectAccess::ForAllocationSiteOffset(
                            AllocationSite::kTransitionInfoOffset),
456
                        initial_elements_kind);
457

458 459
  // Unlike literals, constructed arrays don't have nested sites
  Add<HStoreNamedField>(object,
460 461
                        HObjectAccess::ForAllocationSiteOffset(
                            AllocationSite::kNestedSiteOffset),
462
                        graph()->GetConstant0());
463

464
  // Pretenuring calculation field.
465 466
  Add<HStoreNamedField>(object,
                        HObjectAccess::ForAllocationSiteOffset(
467
                            AllocationSite::kPretenureDataOffset),
468
                        graph()->GetConstant0());
469

470
  // Pretenuring memento creation count field.
471 472
  Add<HStoreNamedField>(object,
                        HObjectAccess::ForAllocationSiteOffset(
473
                            AllocationSite::kPretenureCreateCountOffset),
474
                        graph()->GetConstant0());
475

476 477 478
  // Store an empty fixed array for the code dependency.
  HConstant* empty_fixed_array =
    Add<HConstant>(isolate()->factory()->empty_fixed_array());
479
  Add<HStoreNamedField>(
480
      object,
481 482
      HObjectAccess::ForAllocationSiteOffset(
          AllocationSite::kDependentCodeOffset),
483
      empty_fixed_array);
484

485 486 487
  // Link the object to the allocation site list
  HValue* site_list = Add<HConstant>(
      ExternalReference::allocation_sites_list_address(isolate()));
488 489 490
  HValue* site = Add<HLoadNamedField>(
      site_list, static_cast<HValue*>(NULL),
      HObjectAccess::ForAllocationSiteList());
491 492 493 494 495 496 497
  // TODO(mvstanton): This is a store to a weak pointer, which we may want to
  // mark as such in order to skip the write barrier, once we have a unified
  // system for weakness. For now we decided to keep it like this because having
  // an initial write barrier backed store makes this pointer strong until the
  // next GC, and allocation sites are designed to survive several GCs anyway.
  Add<HStoreNamedField>(
      object,
498
      HObjectAccess::ForAllocationSiteOffset(AllocationSite::kWeakNextOffset),
499
      site);
500
  Add<HStoreNamedField>(site_list, HObjectAccess::ForAllocationSiteList(),
501
                        object);
502

503 504 505 506 507
  HInstruction* feedback_vector = GetParameter(0);
  HInstruction* slot = GetParameter(1);
  Add<HStoreKeyed>(feedback_vector, slot, object, FAST_ELEMENTS,
                   INITIALIZING_STORE);
  return feedback_vector;
508 509 510
}


511 512
Handle<Code> CreateAllocationSiteStub::GenerateCode() {
  return DoGenerateCode(this);
513 514 515
}


516
template <>
517
HValue* CodeStubGraphBuilder<LoadScriptContextFieldStub>::BuildCodeStub() {
518 519 520
  int context_index = casted_stub()->context_index();
  int slot_index = casted_stub()->slot_index();

521 522
  HValue* script_context = BuildGetScriptContext(context_index);
  return Add<HLoadNamedField>(script_context, static_cast<HValue*>(NULL),
523 524 525 526
                              HObjectAccess::ForContextSlot(slot_index));
}


527
Handle<Code> LoadScriptContextFieldStub::GenerateCode() {
528 529 530 531
  return DoGenerateCode(this);
}


532
template <>
533
HValue* CodeStubGraphBuilder<StoreScriptContextFieldStub>::BuildCodeStub() {
534 535 536
  int context_index = casted_stub()->context_index();
  int slot_index = casted_stub()->slot_index();

537 538
  HValue* script_context = BuildGetScriptContext(context_index);
  Add<HStoreNamedField>(script_context,
539 540 541 542 543 544
                        HObjectAccess::ForContextSlot(slot_index),
                        GetParameter(2), STORE_TO_INITIALIZED_ENTRY);
  return GetParameter(2);
}


545
Handle<Code> StoreScriptContextFieldStub::GenerateCode() {
546 547 548 549
  return DoGenerateCode(this);
}


550
template <>
551
HValue* CodeStubGraphBuilder<LoadFastElementStub>::BuildCodeStub() {
552
  HInstruction* load = BuildUncheckedMonomorphicElementAccess(
553 554
      GetParameter(LoadDescriptor::kReceiverIndex),
      GetParameter(LoadDescriptor::kNameIndex), NULL,
555 556
      casted_stub()->is_js_array(), casted_stub()->elements_kind(), LOAD,
      NEVER_RETURN_HOLE, STANDARD_STORE);
557
  return load;
558 559 560
}


561
Handle<Code> LoadFastElementStub::GenerateCode() {
562
  return DoGenerateCode(this);
563 564 565
}


566
HLoadNamedField* CodeStubGraphBuilderBase::BuildLoadNamedField(
567 568 569 570 571 572
    HValue* object, FieldIndex index) {
  Representation representation = index.is_double()
      ? Representation::Double()
      : Representation::Tagged();
  int offset = index.offset();
  HObjectAccess access = index.is_inobject()
573 574
      ? HObjectAccess::ForObservableJSObjectOffset(offset, representation)
      : HObjectAccess::ForBackingStoreOffset(offset, representation);
575 576
  if (index.is_double() &&
      (!FLAG_unbox_double_fields || !index.is_inobject())) {
577 578 579 580 581 582 583 584 585 586 587
    // Load the heap number.
    object = Add<HLoadNamedField>(
        object, static_cast<HValue*>(NULL),
        access.WithRepresentation(Representation::Tagged()));
    // Load the double value from it.
    access = HObjectAccess::ForHeapNumberValue();
  }
  return Add<HLoadNamedField>(object, static_cast<HValue*>(NULL), access);
}


588 589
template<>
HValue* CodeStubGraphBuilder<LoadFieldStub>::BuildCodeStub() {
590
  return BuildLoadNamedField(GetParameter(0), casted_stub()->index());
591 592 593
}


594 595
Handle<Code> LoadFieldStub::GenerateCode() {
  return DoGenerateCode(this);
596 597 598
}


599 600 601 602 603 604 605 606
template <>
HValue* CodeStubGraphBuilder<LoadConstantStub>::BuildCodeStub() {
  HValue* map = AddLoadMap(GetParameter(0), NULL);
  HObjectAccess descriptors_access = HObjectAccess::ForObservableJSObjectOffset(
      Map::kDescriptorsOffset, Representation::Tagged());
  HValue* descriptors =
      Add<HLoadNamedField>(map, static_cast<HValue*>(NULL), descriptors_access);
  HObjectAccess value_access = HObjectAccess::ForObservableJSObjectOffset(
607
      DescriptorArray::GetValueOffset(casted_stub()->constant_index()));
608 609 610 611 612 613 614 615
  return Add<HLoadNamedField>(descriptors, static_cast<HValue*>(NULL),
                              value_access);
}


Handle<Code> LoadConstantStub::GenerateCode() { return DoGenerateCode(this); }


616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
HValue* CodeStubGraphBuilderBase::UnmappedCase(HValue* elements, HValue* key) {
  HValue* result;
  HInstruction* backing_store = Add<HLoadKeyed>(
      elements, graph()->GetConstant1(), static_cast<HValue*>(NULL),
      FAST_ELEMENTS, ALLOW_RETURN_HOLE);
  Add<HCheckMaps>(backing_store, isolate()->factory()->fixed_array_map());
  HValue* backing_store_length =
      Add<HLoadNamedField>(backing_store, static_cast<HValue*>(NULL),
                           HObjectAccess::ForFixedArrayLength());
  IfBuilder in_unmapped_range(this);
  in_unmapped_range.If<HCompareNumericAndBranch>(key, backing_store_length,
                                                 Token::LT);
  in_unmapped_range.Then();
  {
    result = Add<HLoadKeyed>(backing_store, key, static_cast<HValue*>(NULL),
                             FAST_HOLEY_ELEMENTS, NEVER_RETURN_HOLE);
  }
  in_unmapped_range.ElseDeopt("Outside of range");
  in_unmapped_range.End();
  return result;
}


template <>
HValue* CodeStubGraphBuilder<KeyedLoadSloppyArgumentsStub>::BuildCodeStub() {
  HValue* receiver = GetParameter(LoadDescriptor::kReceiverIndex);
  HValue* key = GetParameter(LoadDescriptor::kNameIndex);

  // Mapped arguments are actual arguments. Unmapped arguments are values added
  // to the arguments object after it was created for the call. Mapped arguments
  // are stored in the context at indexes given by elements[key + 2]. Unmapped
  // arguments are stored as regular indexed properties in the arguments array,
  // held at elements[1]. See NewSloppyArguments() in runtime.cc for a detailed
  // look at argument object construction.
  //
  // The sloppy arguments elements array has a special format:
  //
  // 0: context
  // 1: unmapped arguments array
  // 2: mapped_index0,
  // 3: mapped_index1,
  // ...
  //
  // length is 2 + min(number_of_actual_arguments, number_of_formal_arguments).
  // If key + 2 >= elements.length then attempt to look in the unmapped
  // arguments array (given by elements[1]) and return the value at key, missing
  // to the runtime if the unmapped arguments array is not a fixed array or if
  // key >= unmapped_arguments_array.length.
  //
  // Otherwise, t = elements[key + 2]. If t is the hole, then look up the value
  // in the unmapped arguments array, as described above. Otherwise, t is a Smi
  // index into the context array given at elements[0]. Return the value at
  // context[t].

  key = AddUncasted<HForceRepresentation>(key, Representation::Smi());
  IfBuilder positive_smi(this);
  positive_smi.If<HCompareNumericAndBranch>(key, graph()->GetConstant0(),
                                            Token::LT);
  positive_smi.ThenDeopt("key is negative");
  positive_smi.End();

  HValue* constant_two = Add<HConstant>(2);
  HValue* elements = AddLoadElements(receiver, static_cast<HValue*>(NULL));
  HValue* elements_length =
      Add<HLoadNamedField>(elements, static_cast<HValue*>(NULL),
                           HObjectAccess::ForFixedArrayLength());
  HValue* adjusted_length = AddUncasted<HSub>(elements_length, constant_two);
  IfBuilder in_range(this);
  in_range.If<HCompareNumericAndBranch>(key, adjusted_length, Token::LT);
  in_range.Then();
  {
    HValue* index = AddUncasted<HAdd>(key, constant_two);
    HInstruction* mapped_index =
        Add<HLoadKeyed>(elements, index, static_cast<HValue*>(NULL),
                        FAST_HOLEY_ELEMENTS, ALLOW_RETURN_HOLE);

    IfBuilder is_valid(this);
    is_valid.IfNot<HCompareObjectEqAndBranch>(mapped_index,
                                              graph()->GetConstantHole());
    is_valid.Then();
    {
      // TODO(mvstanton): I'd like to assert from this point, that if the
      // mapped_index is not the hole that it is indeed, a smi. An unnecessary
      // smi check is being emitted.
      HValue* the_context =
          Add<HLoadKeyed>(elements, graph()->GetConstant0(),
                          static_cast<HValue*>(NULL), FAST_ELEMENTS);
      DCHECK(Context::kHeaderSize == FixedArray::kHeaderSize);
      HValue* result =
          Add<HLoadKeyed>(the_context, mapped_index, static_cast<HValue*>(NULL),
                          FAST_ELEMENTS, ALLOW_RETURN_HOLE);
      environment()->Push(result);
    }
    is_valid.Else();
    {
      HValue* result = UnmappedCase(elements, key);
      environment()->Push(result);
    }
    is_valid.End();
  }
  in_range.Else();
  {
    HValue* result = UnmappedCase(elements, key);
    environment()->Push(result);
  }
  in_range.End();

  return environment()->Pop();
}


Handle<Code> KeyedLoadSloppyArgumentsStub::GenerateCode() {
  return DoGenerateCode(this);
}


732 733
void CodeStubGraphBuilderBase::BuildStoreNamedField(
    HValue* object, HValue* value, FieldIndex index,
734
    Representation representation, bool transition_to_field) {
735 736 737 738 739 740 741 742
  DCHECK(!index.is_double() || representation.IsDouble());
  int offset = index.offset();
  HObjectAccess access =
      index.is_inobject()
          ? HObjectAccess::ForObservableJSObjectOffset(offset, representation)
          : HObjectAccess::ForBackingStoreOffset(offset, representation);

  if (representation.IsDouble()) {
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    if (!FLAG_unbox_double_fields || !index.is_inobject()) {
      HObjectAccess heap_number_access =
          access.WithRepresentation(Representation::Tagged());
      if (transition_to_field) {
        // The store requires a mutable HeapNumber to be allocated.
        NoObservableSideEffectsScope no_side_effects(this);
        HInstruction* heap_number_size = Add<HConstant>(HeapNumber::kSize);

        // TODO(hpayer): Allocation site pretenuring support.
        HInstruction* heap_number =
            Add<HAllocate>(heap_number_size, HType::HeapObject(), NOT_TENURED,
                           MUTABLE_HEAP_NUMBER_TYPE);
        AddStoreMapConstant(heap_number,
                            isolate()->factory()->mutable_heap_number_map());
        Add<HStoreNamedField>(heap_number, HObjectAccess::ForHeapNumberValue(),
                              value);
        // Store the new mutable heap number into the object.
        access = heap_number_access;
        value = heap_number;
      } else {
        // Load the heap number.
        object = Add<HLoadNamedField>(object, static_cast<HValue*>(NULL),
                                      heap_number_access);
        // Store the double value into it.
        access = HObjectAccess::ForHeapNumberValue();
      }
769
    }
770 771 772 773
  } else if (representation.IsHeapObject()) {
    BuildCheckHeapObject(value);
  }

774
  Add<HStoreNamedField>(object, access, value, INITIALIZING_STORE);
775 776 777 778 779 780
}


template <>
HValue* CodeStubGraphBuilder<StoreFieldStub>::BuildCodeStub() {
  BuildStoreNamedField(GetParameter(0), GetParameter(2), casted_stub()->index(),
781
                       casted_stub()->representation(), false);
782 783 784 785 786 787 788
  return GetParameter(2);
}


Handle<Code> StoreFieldStub::GenerateCode() { return DoGenerateCode(this); }


789
template <>
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
HValue* CodeStubGraphBuilder<StoreTransitionStub>::BuildCodeStub() {
  HValue* object = GetParameter(StoreTransitionDescriptor::kReceiverIndex);

  switch (casted_stub()->store_mode()) {
    case StoreTransitionStub::ExtendStorageAndStoreMapAndValue: {
      HValue* properties =
          Add<HLoadNamedField>(object, static_cast<HValue*>(NULL),
                               HObjectAccess::ForPropertiesPointer());
      HValue* length = AddLoadFixedArrayLength(properties);
      HValue* delta =
          Add<HConstant>(static_cast<int32_t>(JSObject::kFieldsAdded));
      HValue* new_capacity = AddUncasted<HAdd>(length, delta);

      // Grow properties array.
      ElementsKind kind = FAST_ELEMENTS;
      Add<HBoundsCheck>(new_capacity,
                        Add<HConstant>((Page::kMaxRegularHeapObjectSize -
                                        FixedArray::kHeaderSize) >>
                                       ElementsKindToShiftSize(kind)));

      // Reuse this code for properties backing store allocation.
      HValue* new_properties =
          BuildAllocateAndInitializeArray(kind, new_capacity);

      BuildCopyProperties(properties, new_properties, length, new_capacity);

      Add<HStoreNamedField>(object, HObjectAccess::ForPropertiesPointer(),
                            new_properties);
    }
    // Fall through.
    case StoreTransitionStub::StoreMapAndValue:
821
      // Store the new value into the "extended" object.
822 823 824 825 826 827 828 829 830 831 832 833
      BuildStoreNamedField(
          object, GetParameter(StoreTransitionDescriptor::kValueIndex),
          casted_stub()->index(), casted_stub()->representation(), true);
    // Fall through.

    case StoreTransitionStub::StoreMapOnly:
      // And finally update the map.
      Add<HStoreNamedField>(object, HObjectAccess::ForMap(),
                            GetParameter(StoreTransitionDescriptor::kMapIndex));
      break;
  }
  return GetParameter(StoreTransitionDescriptor::kValueIndex);
834 835 836
}


837 838 839
Handle<Code> StoreTransitionStub::GenerateCode() {
  return DoGenerateCode(this);
}
840 841


842
template <>
843
HValue* CodeStubGraphBuilder<StringLengthStub>::BuildCodeStub() {
844 845 846 847
  HValue* string = BuildLoadNamedField(GetParameter(0),
      FieldIndex::ForInObjectOffset(JSValue::kValueOffset));
  return BuildLoadNamedField(string,
      FieldIndex::ForInObjectOffset(String::kLengthOffset));
848 849 850
}


851 852
Handle<Code> StringLengthStub::GenerateCode() {
  return DoGenerateCode(this);
853 854 855
}


856
template <>
857
HValue* CodeStubGraphBuilder<StoreFastElementStub>::BuildCodeStub() {
858
  BuildUncheckedMonomorphicElementAccess(
859 860 861
      GetParameter(StoreDescriptor::kReceiverIndex),
      GetParameter(StoreDescriptor::kNameIndex),
      GetParameter(StoreDescriptor::kValueIndex), casted_stub()->is_js_array(),
862 863
      casted_stub()->elements_kind(), STORE, NEVER_RETURN_HOLE,
      casted_stub()->store_mode());
864 865 866 867 868

  return GetParameter(2);
}


869
Handle<Code> StoreFastElementStub::GenerateCode() {
870
  return DoGenerateCode(this);
871 872 873
}


874
template <>
875
HValue* CodeStubGraphBuilder<TransitionElementsKindStub>::BuildCodeStub() {
876 877
  info()->MarkAsSavesCallerDoubles();

878 879 880 881
  BuildTransitionElementsKind(GetParameter(0),
                              GetParameter(1),
                              casted_stub()->from_kind(),
                              casted_stub()->to_kind(),
882
                              casted_stub()->is_js_array());
883

884
  return GetParameter(0);
885 886 887
}


888 889
Handle<Code> TransitionElementsKindStub::GenerateCode() {
  return DoGenerateCode(this);
890 891
}

892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907

template <>
HValue* CodeStubGraphBuilder<AllocateHeapNumberStub>::BuildCodeStub() {
  HValue* result =
      Add<HAllocate>(Add<HConstant>(HeapNumber::kSize), HType::HeapNumber(),
                     NOT_TENURED, HEAP_NUMBER_TYPE);
  AddStoreMapConstant(result, isolate()->factory()->heap_number_map());
  return result;
}


Handle<Code> AllocateHeapNumberStub::GenerateCode() {
  return DoGenerateCode(this);
}


908
HValue* CodeStubGraphBuilderBase::BuildArrayConstructor(
909 910
    ElementsKind kind,
    AllocationSiteOverrideMode override_mode,
911 912
    ArgumentClass argument_class) {
  HValue* constructor = GetParameter(ArrayConstructorStubBase::kConstructor);
913
  HValue* alloc_site = GetParameter(ArrayConstructorStubBase::kAllocationSite);
914
  JSArrayBuilder array_builder(this, kind, alloc_site, constructor,
915
                               override_mode);
916 917 918
  HValue* result = NULL;
  switch (argument_class) {
    case NONE:
919 920 921
      // This stub is very performance sensitive, the generated code must be
      // tuned so that it doesn't build and eager frame.
      info()->MarkMustNotHaveEagerFrame();
922 923 924 925 926 927 928 929 930
      result = array_builder.AllocateEmptyArray();
      break;
    case SINGLE:
      result = BuildArraySingleArgumentConstructor(&array_builder);
      break;
    case MULTIPLE:
      result = BuildArrayNArgumentsConstructor(&array_builder, kind);
      break;
  }
931

932
  return result;
933 934 935
}


936 937 938 939 940 941 942 943 944
HValue* CodeStubGraphBuilderBase::BuildInternalArrayConstructor(
    ElementsKind kind, ArgumentClass argument_class) {
  HValue* constructor = GetParameter(
      InternalArrayConstructorStubBase::kConstructor);
  JSArrayBuilder array_builder(this, kind, constructor);

  HValue* result = NULL;
  switch (argument_class) {
    case NONE:
945 946 947
      // This stub is very performance sensitive, the generated code must be
      // tuned so that it doesn't build and eager frame.
      info()->MarkMustNotHaveEagerFrame();
948 949 950 951 952 953 954 955 956 957
      result = array_builder.AllocateEmptyArray();
      break;
    case SINGLE:
      result = BuildArraySingleArgumentConstructor(&array_builder);
      break;
    case MULTIPLE:
      result = BuildArrayNArgumentsConstructor(&array_builder, kind);
      break;
  }
  return result;
958 959 960
}


961 962
HValue* CodeStubGraphBuilderBase::BuildArraySingleArgumentConstructor(
    JSArrayBuilder* array_builder) {
963 964 965 966
  // Smi check and range check on the input arg.
  HValue* constant_one = graph()->GetConstant1();
  HValue* constant_zero = graph()->GetConstant0();

967
  HInstruction* elements = Add<HArgumentsElements>(false);
968 969
  HInstruction* argument = Add<HAccessArgumentsAt>(
      elements, constant_one, constant_zero);
970

971
  return BuildAllocateArrayFromLength(array_builder, argument);
972 973 974
}


975 976
HValue* CodeStubGraphBuilderBase::BuildArrayNArgumentsConstructor(
    JSArrayBuilder* array_builder, ElementsKind kind) {
977 978 979 980 981 982 983 984 985
  // Insert a bounds check because the number of arguments might exceed
  // the kInitialMaxFastElementArray limit. This cannot happen for code
  // that was parsed, but calling via Array.apply(thisArg, [...]) might
  // trigger it.
  HValue* length = GetArgumentsLength();
  HConstant* max_alloc_length =
      Add<HConstant>(JSObject::kInitialMaxFastElementArray);
  HValue* checked_length = Add<HBoundsCheck>(length, max_alloc_length);

986 987 988 989 990
  // We need to fill with the hole if it's a smi array in the multi-argument
  // case because we might have to bail out while copying arguments into
  // the array because they aren't compatible with a smi array.
  // If it's a double array, no problem, and if it's fast then no
  // problem either because doubles are boxed.
991 992 993 994 995 996
  //
  // TODO(mvstanton): consider an instruction to memset fill the array
  // with zero in this case instead.
  JSArrayBuilder::FillMode fill_mode = IsFastSmiElementsKind(kind)
      ? JSArrayBuilder::FILL_WITH_HOLE
      : JSArrayBuilder::DONT_FILL_WITH_HOLE;
997
  HValue* new_object = array_builder->AllocateArray(checked_length,
998
                                                    max_alloc_length,
999
                                                    checked_length,
1000
                                                    fill_mode);
1001
  HValue* elements = array_builder->GetElementsLocation();
1002
  DCHECK(elements != NULL);
1003 1004 1005 1006 1007 1008

  // Now populate the elements correctly.
  LoopBuilder builder(this,
                      context(),
                      LoopBuilder::kPostIncrement);
  HValue* start = graph()->GetConstant0();
1009
  HValue* key = builder.BeginBody(start, checked_length, Token::LT);
1010
  HInstruction* argument_elements = Add<HArgumentsElements>(false);
1011
  HInstruction* argument = Add<HAccessArgumentsAt>(
1012
      argument_elements, checked_length, key);
1013

1014
  Add<HStoreKeyed>(elements, key, argument, kind);
1015 1016
  builder.EndBody();
  return new_object;
1017 1018 1019
}


1020 1021 1022
template <>
HValue* CodeStubGraphBuilder<ArrayNoArgumentConstructorStub>::BuildCodeStub() {
  ElementsKind kind = casted_stub()->elements_kind();
1023
  AllocationSiteOverrideMode override_mode = casted_stub()->override_mode();
1024
  return BuildArrayConstructor(kind, override_mode, NONE);
1025 1026 1027
}


1028 1029
Handle<Code> ArrayNoArgumentConstructorStub::GenerateCode() {
  return DoGenerateCode(this);
1030 1031 1032 1033 1034 1035 1036
}


template <>
HValue* CodeStubGraphBuilder<ArraySingleArgumentConstructorStub>::
    BuildCodeStub() {
  ElementsKind kind = casted_stub()->elements_kind();
1037
  AllocationSiteOverrideMode override_mode = casted_stub()->override_mode();
1038
  return BuildArrayConstructor(kind, override_mode, SINGLE);
1039 1040 1041
}


1042 1043
Handle<Code> ArraySingleArgumentConstructorStub::GenerateCode() {
  return DoGenerateCode(this);
1044 1045 1046 1047 1048 1049
}


template <>
HValue* CodeStubGraphBuilder<ArrayNArgumentsConstructorStub>::BuildCodeStub() {
  ElementsKind kind = casted_stub()->elements_kind();
1050
  AllocationSiteOverrideMode override_mode = casted_stub()->override_mode();
1051
  return BuildArrayConstructor(kind, override_mode, MULTIPLE);
1052 1053 1054
}


1055 1056
Handle<Code> ArrayNArgumentsConstructorStub::GenerateCode() {
  return DoGenerateCode(this);
1057 1058
}

1059

1060 1061 1062 1063 1064 1065 1066 1067
template <>
HValue* CodeStubGraphBuilder<InternalArrayNoArgumentConstructorStub>::
    BuildCodeStub() {
  ElementsKind kind = casted_stub()->elements_kind();
  return BuildInternalArrayConstructor(kind, NONE);
}


1068 1069
Handle<Code> InternalArrayNoArgumentConstructorStub::GenerateCode() {
  return DoGenerateCode(this);
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
}


template <>
HValue* CodeStubGraphBuilder<InternalArraySingleArgumentConstructorStub>::
    BuildCodeStub() {
  ElementsKind kind = casted_stub()->elements_kind();
  return BuildInternalArrayConstructor(kind, SINGLE);
}


1081 1082
Handle<Code> InternalArraySingleArgumentConstructorStub::GenerateCode() {
  return DoGenerateCode(this);
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
}


template <>
HValue* CodeStubGraphBuilder<InternalArrayNArgumentsConstructorStub>::
    BuildCodeStub() {
  ElementsKind kind = casted_stub()->elements_kind();
  return BuildInternalArrayConstructor(kind, MULTIPLE);
}


1094 1095
Handle<Code> InternalArrayNArgumentsConstructorStub::GenerateCode() {
  return DoGenerateCode(this);
1096 1097 1098
}


1099
template <>
1100
HValue* CodeStubGraphBuilder<CompareNilICStub>::BuildCodeInitializedStub() {
1101
  Isolate* isolate = graph()->isolate();
1102 1103
  CompareNilICStub* stub = casted_stub();
  HIfContinuation continuation;
1104
  Handle<Map> sentinel_map(isolate->heap()->meta_map());
1105
  Type* type = stub->GetType(zone(), sentinel_map);
1106
  BuildCompareNil(GetParameter(0), type, &continuation);
1107 1108 1109 1110
  IfBuilder if_nil(this, &continuation);
  if_nil.Then();
  if (continuation.IsFalseReachable()) {
    if_nil.Else();
1111
    if_nil.Return(graph()->GetConstant0());
1112 1113 1114
  }
  if_nil.End();
  return continuation.IsTrueReachable()
1115
      ? graph()->GetConstant1()
1116 1117 1118 1119
      : graph()->GetConstantUndefined();
}


1120 1121
Handle<Code> CompareNilICStub::GenerateCode() {
  return DoGenerateCode(this);
1122 1123
}

1124

1125
template <>
1126
HValue* CodeStubGraphBuilder<BinaryOpICStub>::BuildCodeInitializedStub() {
1127
  BinaryOpICState state = casted_stub()->state();
1128

1129 1130 1131
  HValue* left = GetParameter(BinaryOpICStub::kLeft);
  HValue* right = GetParameter(BinaryOpICStub::kRight);

1132 1133 1134
  Type* left_type = state.GetLeftType(zone());
  Type* right_type = state.GetRightType(zone());
  Type* result_type = state.GetResultType(zone());
1135

1136
  DCHECK(!left_type->Is(Type::None()) && !right_type->Is(Type::None()) &&
1137
         (state.HasSideEffects() || !result_type->Is(Type::None())));
1138 1139

  HValue* result = NULL;
1140
  HAllocationMode allocation_mode(NOT_TENURED);
1141
  if (state.op() == Token::ADD &&
1142 1143
      (left_type->Maybe(Type::String()) || right_type->Maybe(Type::String())) &&
      !left_type->Is(Type::String()) && !right_type->Is(Type::String())) {
1144
    // For the generic add stub a fast case for string addition is performance
1145 1146
    // critical.
    if (left_type->Maybe(Type::String())) {
1147 1148 1149 1150
      IfBuilder if_leftisstring(this);
      if_leftisstring.If<HIsStringAndBranch>(left);
      if_leftisstring.Then();
      {
1151
        Push(BuildBinaryOperation(
1152
                    state.op(), left, right,
1153
                    Type::String(zone()), right_type,
1154 1155
                    result_type, state.fixed_right_arg(),
                    allocation_mode));
1156 1157 1158
      }
      if_leftisstring.Else();
      {
1159
        Push(BuildBinaryOperation(
1160
                    state.op(), left, right,
1161
                    left_type, right_type, result_type,
1162
                    state.fixed_right_arg(), allocation_mode));
1163 1164
      }
      if_leftisstring.End();
1165 1166
      result = Pop();
    } else {
1167 1168 1169 1170
      IfBuilder if_rightisstring(this);
      if_rightisstring.If<HIsStringAndBranch>(right);
      if_rightisstring.Then();
      {
1171
        Push(BuildBinaryOperation(
1172
                    state.op(), left, right,
1173
                    left_type, Type::String(zone()),
1174 1175
                    result_type, state.fixed_right_arg(),
                    allocation_mode));
1176 1177 1178
      }
      if_rightisstring.Else();
      {
1179
        Push(BuildBinaryOperation(
1180
                    state.op(), left, right,
1181
                    left_type, right_type, result_type,
1182
                    state.fixed_right_arg(), allocation_mode));
1183 1184
      }
      if_rightisstring.End();
1185 1186 1187
      result = Pop();
    }
  } else {
1188
    result = BuildBinaryOperation(
1189
            state.op(), left, right,
1190
            left_type, right_type, result_type,
1191
            state.fixed_right_arg(), allocation_mode);
1192 1193 1194 1195
  }

  // If we encounter a generic argument, the number conversion is
  // observable, thus we cannot afford to bail out after the fact.
1196
  if (!state.HasSideEffects()) {
1197 1198 1199
    result = EnforceNumberType(result, result_type);
  }

1200 1201
  // Reuse the double box of one of the operands if we are allowed to (i.e.
  // chained binops).
1202 1203
  if (state.CanReuseDoubleBox()) {
    HValue* operand = (state.mode() == OVERWRITE_LEFT) ? left : right;
1204
    IfBuilder if_heap_number(this);
1205
    if_heap_number.If<HHasInstanceTypeAndBranch>(operand, HEAP_NUMBER_TYPE);
1206
    if_heap_number.Then();
1207
    Add<HStoreNamedField>(operand, HObjectAccess::ForHeapNumberValue(), result);
1208
    Push(operand);
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    if_heap_number.Else();
    Push(result);
    if_heap_number.End();
    result = Pop();
  }

  return result;
}


1219 1220
Handle<Code> BinaryOpICStub::GenerateCode() {
  return DoGenerateCode(this);
1221 1222 1223
}


1224 1225
template <>
HValue* CodeStubGraphBuilder<BinaryOpWithAllocationSiteStub>::BuildCodeStub() {
1226
  BinaryOpICState state = casted_stub()->state();
1227 1228 1229 1230 1231 1232

  HValue* allocation_site = GetParameter(
      BinaryOpWithAllocationSiteStub::kAllocationSite);
  HValue* left = GetParameter(BinaryOpWithAllocationSiteStub::kLeft);
  HValue* right = GetParameter(BinaryOpWithAllocationSiteStub::kRight);

1233 1234 1235
  Type* left_type = state.GetLeftType(zone());
  Type* right_type = state.GetRightType(zone());
  Type* result_type = state.GetResultType(zone());
1236 1237 1238 1239 1240 1241 1242 1243
  HAllocationMode allocation_mode(allocation_site);

  return BuildBinaryOperation(state.op(), left, right,
                              left_type, right_type, result_type,
                              state.fixed_right_arg(), allocation_mode);
}


1244 1245
Handle<Code> BinaryOpWithAllocationSiteStub::GenerateCode() {
  return DoGenerateCode(this);
1246 1247 1248
}


1249
template <>
1250 1251
HValue* CodeStubGraphBuilder<StringAddStub>::BuildCodeInitializedStub() {
  StringAddStub* stub = casted_stub();
1252 1253 1254
  StringAddFlags flags = stub->flags();
  PretenureFlag pretenure_flag = stub->pretenure_flag();

1255 1256
  HValue* left = GetParameter(StringAddStub::kLeft);
  HValue* right = GetParameter(StringAddStub::kRight);
1257 1258 1259

  // Make sure that both arguments are strings if not known in advance.
  if ((flags & STRING_ADD_CHECK_LEFT) == STRING_ADD_CHECK_LEFT) {
1260
    left = BuildCheckString(left);
1261 1262
  }
  if ((flags & STRING_ADD_CHECK_RIGHT) == STRING_ADD_CHECK_RIGHT) {
1263
    right = BuildCheckString(right);
1264 1265
  }

1266
  return BuildStringAdd(left, right, HAllocationMode(pretenure_flag));
1267 1268 1269
}


1270 1271
Handle<Code> StringAddStub::GenerateCode() {
  return DoGenerateCode(this);
1272 1273 1274
}


1275 1276 1277
template <>
HValue* CodeStubGraphBuilder<ToBooleanStub>::BuildCodeInitializedStub() {
  ToBooleanStub* stub = casted_stub();
1278 1279 1280
  HValue* true_value = NULL;
  HValue* false_value = NULL;

1281
  switch (stub->mode()) {
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
    case ToBooleanStub::RESULT_AS_SMI:
      true_value = graph()->GetConstant1();
      false_value = graph()->GetConstant0();
      break;
    case ToBooleanStub::RESULT_AS_ODDBALL:
      true_value = graph()->GetConstantTrue();
      false_value = graph()->GetConstantFalse();
      break;
    case ToBooleanStub::RESULT_AS_INVERSE_ODDBALL:
      true_value = graph()->GetConstantFalse();
      false_value = graph()->GetConstantTrue();
      break;
  }
1295 1296

  IfBuilder if_true(this);
1297
  if_true.If<HBranch>(GetParameter(0), stub->types());
1298
  if_true.Then();
1299
  if_true.Return(true_value);
1300 1301
  if_true.Else();
  if_true.End();
1302
  return false_value;
1303 1304 1305
}


1306 1307
Handle<Code> ToBooleanStub::GenerateCode() {
  return DoGenerateCode(this);
1308 1309 1310
}


1311 1312 1313 1314 1315 1316 1317
template <>
HValue* CodeStubGraphBuilder<StoreGlobalStub>::BuildCodeInitializedStub() {
  StoreGlobalStub* stub = casted_stub();
  Handle<Object> placeholer_value(Smi::FromInt(0), isolate());
  Handle<PropertyCell> placeholder_cell =
      isolate()->factory()->NewPropertyCell(placeholer_value);

1318
  HParameter* value = GetParameter(StoreDescriptor::kValueIndex);
1319

1320 1321 1322 1323 1324 1325
  if (stub->check_global()) {
    // Check that the map of the global has not changed: use a placeholder map
    // that will be replaced later with the global object's map.
    Handle<Map> placeholder_map = isolate()->factory()->meta_map();
    HValue* global = Add<HConstant>(
        StoreGlobalStub::global_placeholder(isolate()));
1326
    Add<HCheckMaps>(global, placeholder_map);
1327
  }
1328

1329
  HValue* cell = Add<HConstant>(placeholder_cell);
1330
  HObjectAccess access(HObjectAccess::ForCellPayload(isolate()));
1331 1332
  HValue* cell_contents = Add<HLoadNamedField>(
      cell, static_cast<HValue*>(NULL), access);
1333

1334 1335 1336 1337
  if (stub->is_constant()) {
    IfBuilder builder(this);
    builder.If<HCompareObjectEqAndBranch>(cell_contents, value);
    builder.Then();
1338
    builder.ElseDeopt("Unexpected cell contents in constant global store");
1339 1340
    builder.End();
  } else {
1341 1342 1343 1344
    // Load the payload of the global parameter cell. A hole indicates that the
    // property has been deleted and that the store must be handled by the
    // runtime.
    IfBuilder builder(this);
1345
    HValue* hole_value = graph()->GetConstantHole();
1346 1347
    builder.If<HCompareObjectEqAndBranch>(cell_contents, hole_value);
    builder.Then();
1348
    builder.Deopt("Unexpected cell contents in global store");
1349
    builder.Else();
1350
    Add<HStoreNamedField>(cell, access, value);
1351 1352
    builder.End();
  }
1353

1354 1355 1356 1357
  return value;
}


1358 1359
Handle<Code> StoreGlobalStub::GenerateCode() {
  return DoGenerateCode(this);
1360 1361 1362
}


1363 1364
template<>
HValue* CodeStubGraphBuilder<ElementsTransitionAndStoreStub>::BuildCodeStub() {
1365 1366 1367 1368
  HValue* value = GetParameter(ElementsTransitionAndStoreStub::kValueIndex);
  HValue* map = GetParameter(ElementsTransitionAndStoreStub::kMapIndex);
  HValue* key = GetParameter(ElementsTransitionAndStoreStub::kKeyIndex);
  HValue* object = GetParameter(ElementsTransitionAndStoreStub::kObjectIndex);
1369 1370 1371

  if (FLAG_trace_elements_transitions) {
    // Tracing elements transitions is the job of the runtime.
1372
    Add<HDeoptimize>("Tracing elements transitions", Deoptimizer::EAGER);
1373 1374 1375 1376 1377 1378 1379 1380
  } else {
    info()->MarkAsSavesCallerDoubles();

    BuildTransitionElementsKind(object, map,
                                casted_stub()->from_kind(),
                                casted_stub()->to_kind(),
                                casted_stub()->is_jsarray());

1381 1382 1383
    BuildUncheckedMonomorphicElementAccess(object, key, value,
                                           casted_stub()->is_jsarray(),
                                           casted_stub()->to_kind(),
1384
                                           STORE, ALLOW_RETURN_HOLE,
1385
                                           casted_stub()->store_mode());
1386 1387 1388 1389 1390 1391
  }

  return value;
}


1392 1393
Handle<Code> ElementsTransitionAndStoreStub::GenerateCode() {
  return DoGenerateCode(this);
1394 1395 1396
}


1397
void CodeStubGraphBuilderBase::BuildCheckAndInstallOptimizedCode(
1398 1399
    HValue* js_function,
    HValue* native_context,
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
    IfBuilder* builder,
    HValue* optimized_map,
    HValue* map_index) {
  HValue* osr_ast_id_none = Add<HConstant>(BailoutId::None().ToInt());
  HValue* context_slot = LoadFromOptimizedCodeMap(
      optimized_map, map_index, SharedFunctionInfo::kContextOffset);
  HValue* osr_ast_slot = LoadFromOptimizedCodeMap(
      optimized_map, map_index, SharedFunctionInfo::kOsrAstIdOffset);
  builder->If<HCompareObjectEqAndBranch>(native_context,
                                         context_slot);
  builder->AndIf<HCompareObjectEqAndBranch>(osr_ast_slot, osr_ast_id_none);
  builder->Then();
  HValue* code_object = LoadFromOptimizedCodeMap(optimized_map,
      map_index, SharedFunctionInfo::kCachedCodeOffset);
  // and the literals
  HValue* literals = LoadFromOptimizedCodeMap(optimized_map,
      map_index, SharedFunctionInfo::kLiteralsOffset);

1418
  Counters* counters = isolate()->counters();
1419
  AddIncrementCounter(counters->fast_new_closure_install_optimized());
1420 1421 1422 1423 1424

  // TODO(fschneider): Idea: store proper code pointers in the optimized code
  // map and either unmangle them on marking or do nothing as the whole map is
  // discarded on major GC anyway.
  Add<HStoreCodeEntry>(js_function, code_object);
1425 1426
  Add<HStoreNamedField>(js_function, HObjectAccess::ForLiteralsPointer(),
                        literals);
1427 1428

  // Now link a function into a list of optimized functions.
1429 1430
  HValue* optimized_functions_list = Add<HLoadNamedField>(
      native_context, static_cast<HValue*>(NULL),
1431 1432 1433
      HObjectAccess::ForContextSlot(Context::OPTIMIZED_FUNCTIONS_LIST));
  Add<HStoreNamedField>(js_function,
                        HObjectAccess::ForNextFunctionLinkPointer(),
1434
                        optimized_functions_list);
1435 1436 1437 1438

  // This store is the only one that should have a write barrier.
  Add<HStoreNamedField>(native_context,
           HObjectAccess::ForContextSlot(Context::OPTIMIZED_FUNCTIONS_LIST),
1439
           js_function);
1440 1441

  // The builder continues in the "then" after this function.
1442 1443 1444 1445 1446 1447 1448
}


void CodeStubGraphBuilderBase::BuildInstallCode(HValue* js_function,
                                                HValue* shared_info) {
  Add<HStoreNamedField>(js_function,
                        HObjectAccess::ForNextFunctionLinkPointer(),
1449
                        graph()->GetConstantUndefined());
1450 1451
  HValue* code_object = Add<HLoadNamedField>(
      shared_info, static_cast<HValue*>(NULL), HObjectAccess::ForCodeOffset());
1452 1453 1454 1455
  Add<HStoreCodeEntry>(js_function, code_object);
}


1456 1457 1458 1459 1460 1461
HInstruction* CodeStubGraphBuilderBase::LoadFromOptimizedCodeMap(
    HValue* optimized_map,
    HValue* iterator,
    int field_offset) {
  // By making sure to express these loads in the form [<hvalue> + constant]
  // the keyed load can be hoisted.
1462
  DCHECK(field_offset >= 0 && field_offset < SharedFunctionInfo::kEntryLength);
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
  HValue* field_slot = iterator;
  if (field_offset > 0) {
    HValue* field_offset_value = Add<HConstant>(field_offset);
    field_slot = AddUncasted<HAdd>(iterator, field_offset_value);
  }
  HInstruction* field_entry = Add<HLoadKeyed>(optimized_map, field_slot,
      static_cast<HValue*>(NULL), FAST_ELEMENTS);
  return field_entry;
}


1474 1475 1476 1477 1478 1479
void CodeStubGraphBuilderBase::BuildInstallFromOptimizedCodeMap(
    HValue* js_function,
    HValue* shared_info,
    HValue* native_context) {
  Counters* counters = isolate()->counters();
  IfBuilder is_optimized(this);
1480 1481
  HInstruction* optimized_map = Add<HLoadNamedField>(
      shared_info, static_cast<HValue*>(NULL),
1482 1483 1484 1485 1486 1487 1488 1489 1490
      HObjectAccess::ForOptimizedCodeMap());
  HValue* null_constant = Add<HConstant>(0);
  is_optimized.If<HCompareObjectEqAndBranch>(optimized_map, null_constant);
  is_optimized.Then();
  {
    BuildInstallCode(js_function, shared_info);
  }
  is_optimized.Else();
  {
1491
    AddIncrementCounter(counters->fast_new_closure_try_optimized());
1492 1493 1494
    // optimized_map points to fixed array of 3-element entries
    // (native context, optimized code, literals).
    // Map must never be empty, so check the first elements.
1495 1496
    HValue* first_entry_index =
        Add<HConstant>(SharedFunctionInfo::kEntriesStart);
1497
    IfBuilder already_in(this);
1498 1499
    BuildCheckAndInstallOptimizedCode(js_function, native_context, &already_in,
                                      optimized_map, first_entry_index);
1500 1501
    already_in.Else();
    {
1502 1503 1504 1505 1506 1507
      // Iterate through the rest of map backwards. Do not double check first
      // entry. After the loop, if no matching optimized code was found,
      // install unoptimized code.
      // for(i = map.length() - SharedFunctionInfo::kEntryLength;
      //     i > SharedFunctionInfo::kEntriesStart;
      //     i -= SharedFunctionInfo::kEntryLength) { .. }
1508 1509 1510 1511 1512 1513
      HValue* shared_function_entry_length =
          Add<HConstant>(SharedFunctionInfo::kEntryLength);
      LoopBuilder loop_builder(this,
                               context(),
                               LoopBuilder::kPostDecrement,
                               shared_function_entry_length);
1514 1515
      HValue* array_length = Add<HLoadNamedField>(
          optimized_map, static_cast<HValue*>(NULL),
1516
          HObjectAccess::ForFixedArrayLength());
1517 1518 1519 1520 1521
      HValue* start_pos = AddUncasted<HSub>(array_length,
                                            shared_function_entry_length);
      HValue* slot_iterator = loop_builder.BeginBody(start_pos,
                                                     first_entry_index,
                                                     Token::GT);
1522
      {
1523 1524 1525 1526 1527 1528 1529
        IfBuilder done_check(this);
        BuildCheckAndInstallOptimizedCode(js_function, native_context,
                                          &done_check,
                                          optimized_map,
                                          slot_iterator);
        // Fall out of the loop
        loop_builder.Break();
1530 1531
      }
      loop_builder.EndBody();
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542

      // If slot_iterator equals first entry index, then we failed to find and
      // install optimized code
      IfBuilder no_optimized_code_check(this);
      no_optimized_code_check.If<HCompareNumericAndBranch>(
          slot_iterator, first_entry_index, Token::EQ);
      no_optimized_code_check.Then();
      {
        // Store the unoptimized code
        BuildInstallCode(js_function, shared_info);
      }
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
    }
  }
}


template<>
HValue* CodeStubGraphBuilder<FastNewClosureStub>::BuildCodeStub() {
  Counters* counters = isolate()->counters();
  Factory* factory = isolate()->factory();
  HInstruction* empty_fixed_array =
      Add<HConstant>(factory->empty_fixed_array());
  HValue* shared_info = GetParameter(0);

1556 1557
  AddIncrementCounter(counters->fast_new_closure_total());

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
  IfBuilder optimize_now(this);
  HInstruction* compile_hint = Add<HLoadNamedField>(
      shared_info, static_cast<HValue*>(NULL), HObjectAccess::ForCompileHint());
  HValue* hint_mask = Add<HConstant>(
      static_cast<int32_t>(1 << SharedFunctionInfo::kOptimizeNextClosure));
  HInstruction* optimize =
      AddUncasted<HBitwise>(Token::BIT_AND, compile_hint, hint_mask);
  optimize_now.If<HCompareNumericAndBranch>(optimize, hint_mask, Token::EQ);
  optimize_now.Then();
  {
    Add<HPushArguments>(context(), shared_info, graph()->GetConstantFalse());
    Push(Add<HCallRuntime>(isolate()->factory()->empty_string(),
                           Runtime::FunctionForId(Runtime::kNewClosure), 3));
1571
  }
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
  optimize_now.Else();
  {
    // Create a new closure from the given function info in new space
    HValue* size = Add<HConstant>(JSFunction::kSize);
    HInstruction* js_function =
        Add<HAllocate>(size, HType::JSObject(), NOT_TENURED, JS_FUNCTION_TYPE);

    int map_index = Context::FunctionMapIndex(casted_stub()->strict_mode(),
                                              casted_stub()->kind());

    // Compute the function map in the current native context and set that
    // as the map of the allocated object.
    HInstruction* native_context = BuildGetNativeContext();
    HInstruction* map_slot_value =
        Add<HLoadNamedField>(native_context, static_cast<HValue*>(NULL),
                             HObjectAccess::ForContextSlot(map_index));
    Add<HStoreNamedField>(js_function, HObjectAccess::ForMap(), map_slot_value);

    // Initialize the rest of the function.
    Add<HStoreNamedField>(js_function, HObjectAccess::ForPropertiesPointer(),
                          empty_fixed_array);
    Add<HStoreNamedField>(js_function, HObjectAccess::ForElementsPointer(),
                          empty_fixed_array);
    Add<HStoreNamedField>(js_function, HObjectAccess::ForLiteralsPointer(),
                          empty_fixed_array);
    Add<HStoreNamedField>(js_function,
                          HObjectAccess::ForPrototypeOrInitialMap(),
                          graph()->GetConstantHole());
    Add<HStoreNamedField>(js_function,
                          HObjectAccess::ForSharedFunctionInfoPointer(),
                          shared_info);
    Add<HStoreNamedField>(
        js_function, HObjectAccess::ForFunctionContextPointer(), context());

    // Initialize the code pointer in the function to be the one
    // found in the shared function info object.
    // But first check if there is an optimized version for our context.
    if (FLAG_cache_optimized_code) {
      BuildInstallFromOptimizedCodeMap(js_function, shared_info,
                                       native_context);
    } else {
      BuildInstallCode(js_function, shared_info);
    }
    Push(js_function);
  }
  optimize_now.End();
  return Pop();
1619 1620 1621
}


1622 1623
Handle<Code> FastNewClosureStub::GenerateCode() {
  return DoGenerateCode(this);
1624 1625 1626
}


1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
template<>
HValue* CodeStubGraphBuilder<FastNewContextStub>::BuildCodeStub() {
  int length = casted_stub()->slots() + Context::MIN_CONTEXT_SLOTS;

  // Get the function.
  HParameter* function = GetParameter(FastNewContextStub::kFunction);

  // Allocate the context in new space.
  HAllocate* function_context = Add<HAllocate>(
      Add<HConstant>(length * kPointerSize + FixedArray::kHeaderSize),
1637
      HType::HeapObject(), NOT_TENURED, FIXED_ARRAY_TYPE);
1638 1639 1640 1641 1642 1643

  // Set up the object header.
  AddStoreMapConstant(function_context,
                      isolate()->factory()->function_context_map());
  Add<HStoreNamedField>(function_context,
                        HObjectAccess::ForFixedArrayLength(),
1644
                        Add<HConstant>(length));
1645 1646 1647 1648

  // Set up the fixed slots.
  Add<HStoreNamedField>(function_context,
                        HObjectAccess::ForContextSlot(Context::CLOSURE_INDEX),
1649
                        function);
1650 1651
  Add<HStoreNamedField>(function_context,
                        HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX),
1652
                        context());
1653 1654
  Add<HStoreNamedField>(function_context,
                        HObjectAccess::ForContextSlot(Context::EXTENSION_INDEX),
1655
                        graph()->GetConstant0());
1656 1657 1658

  // Copy the global object from the previous context.
  HValue* global_object = Add<HLoadNamedField>(
1659 1660
      context(), static_cast<HValue*>(NULL),
      HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
1661 1662 1663
  Add<HStoreNamedField>(function_context,
                        HObjectAccess::ForContextSlot(
                            Context::GLOBAL_OBJECT_INDEX),
1664
                        global_object);
1665 1666 1667 1668 1669

  // Initialize the rest of the slots to undefined.
  for (int i = Context::MIN_CONTEXT_SLOTS; i < length; ++i) {
    Add<HStoreNamedField>(function_context,
                          HObjectAccess::ForContextSlot(i),
1670
                          graph()->GetConstantUndefined());
1671 1672 1673 1674 1675 1676
  }

  return function_context;
}


1677 1678
Handle<Code> FastNewContextStub::GenerateCode() {
  return DoGenerateCode(this);
1679 1680 1681
}


1682 1683
template <>
HValue* CodeStubGraphBuilder<LoadDictionaryElementStub>::BuildCodeStub() {
1684 1685
  HValue* receiver = GetParameter(LoadDescriptor::kReceiverIndex);
  HValue* key = GetParameter(LoadDescriptor::kNameIndex);
1686 1687 1688

  Add<HCheckSmi>(key);

1689 1690 1691 1692 1693
  HValue* elements = AddLoadElements(receiver);

  HValue* hash = BuildElementIndexHash(key);

  return BuildUncheckedDictionaryElementLoad(receiver, elements, key, hash);
1694 1695 1696
}


1697
Handle<Code> LoadDictionaryElementStub::GenerateCode() {
1698
  return DoGenerateCode(this);
1699 1700 1701
}


1702 1703 1704 1705 1706 1707 1708
template<>
HValue* CodeStubGraphBuilder<RegExpConstructResultStub>::BuildCodeStub() {
  // Determine the parameters.
  HValue* length = GetParameter(RegExpConstructResultStub::kLength);
  HValue* index = GetParameter(RegExpConstructResultStub::kIndex);
  HValue* input = GetParameter(RegExpConstructResultStub::kInput);

1709 1710
  info()->MarkMustNotHaveEagerFrame();

1711 1712 1713 1714
  return BuildRegExpConstructResult(length, index, input);
}


1715 1716
Handle<Code> RegExpConstructResultStub::GenerateCode() {
  return DoGenerateCode(this);
1717 1718 1719
}


1720
template <>
1721 1722
class CodeStubGraphBuilder<KeyedLoadGenericStub>
    : public CodeStubGraphBuilderBase {
1723
 public:
1724 1725
  CodeStubGraphBuilder(Isolate* isolate, KeyedLoadGenericStub* stub)
      : CodeStubGraphBuilderBase(isolate, stub) {}
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747

 protected:
  virtual HValue* BuildCodeStub();

  void BuildElementsKindLimitCheck(HGraphBuilder::IfBuilder* if_builder,
                                   HValue* bit_field2,
                                   ElementsKind kind);

  void BuildFastElementLoad(HGraphBuilder::IfBuilder* if_builder,
                            HValue* receiver,
                            HValue* key,
                            HValue* instance_type,
                            HValue* bit_field2,
                            ElementsKind kind);

  void BuildExternalElementLoad(HGraphBuilder::IfBuilder* if_builder,
                                HValue* receiver,
                                HValue* key,
                                HValue* instance_type,
                                HValue* bit_field2,
                                ElementsKind kind);

1748 1749
  KeyedLoadGenericStub* casted_stub() {
    return static_cast<KeyedLoadGenericStub*>(stub());
1750 1751 1752 1753
  }
};


1754 1755
void CodeStubGraphBuilder<KeyedLoadGenericStub>::BuildElementsKindLimitCheck(
    HGraphBuilder::IfBuilder* if_builder, HValue* bit_field2,
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
    ElementsKind kind) {
  ElementsKind next_kind = static_cast<ElementsKind>(kind + 1);
  HValue* kind_limit = Add<HConstant>(
      static_cast<int>(Map::ElementsKindBits::encode(next_kind)));

  if_builder->If<HCompareNumericAndBranch>(bit_field2, kind_limit, Token::LT);
  if_builder->Then();
}


1766 1767 1768
void CodeStubGraphBuilder<KeyedLoadGenericStub>::BuildFastElementLoad(
    HGraphBuilder::IfBuilder* if_builder, HValue* receiver, HValue* key,
    HValue* instance_type, HValue* bit_field2, ElementsKind kind) {
1769
  DCHECK(!IsExternalArrayElementsKind(kind));
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789

  BuildElementsKindLimitCheck(if_builder, bit_field2, kind);

  IfBuilder js_array_check(this);
  js_array_check.If<HCompareNumericAndBranch>(
      instance_type, Add<HConstant>(JS_ARRAY_TYPE), Token::EQ);
  js_array_check.Then();
  Push(BuildUncheckedMonomorphicElementAccess(receiver, key, NULL,
                                              true, kind,
                                              LOAD, NEVER_RETURN_HOLE,
                                              STANDARD_STORE));
  js_array_check.Else();
  Push(BuildUncheckedMonomorphicElementAccess(receiver, key, NULL,
                                              false, kind,
                                              LOAD, NEVER_RETURN_HOLE,
                                              STANDARD_STORE));
  js_array_check.End();
}


1790 1791 1792
void CodeStubGraphBuilder<KeyedLoadGenericStub>::BuildExternalElementLoad(
    HGraphBuilder::IfBuilder* if_builder, HValue* receiver, HValue* key,
    HValue* instance_type, HValue* bit_field2, ElementsKind kind) {
1793
  DCHECK(IsExternalArrayElementsKind(kind));
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803

  BuildElementsKindLimitCheck(if_builder, bit_field2, kind);

  Push(BuildUncheckedMonomorphicElementAccess(receiver, key, NULL,
                                              false, kind,
                                              LOAD, NEVER_RETURN_HOLE,
                                              STANDARD_STORE));
}


1804
HValue* CodeStubGraphBuilder<KeyedLoadGenericStub>::BuildCodeStub() {
1805 1806
  HValue* receiver = GetParameter(LoadDescriptor::kReceiverIndex);
  HValue* key = GetParameter(LoadDescriptor::kNameIndex);
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860

  // Split into a smi/integer case and unique string case.
  HIfContinuation index_name_split_continuation(graph()->CreateBasicBlock(),
                                                graph()->CreateBasicBlock());

  BuildKeyedIndexCheck(key, &index_name_split_continuation);

  IfBuilder index_name_split(this, &index_name_split_continuation);
  index_name_split.Then();
  {
    // Key is an index (number)
    key = Pop();

    int bit_field_mask = (1 << Map::kIsAccessCheckNeeded) |
      (1 << Map::kHasIndexedInterceptor);
    BuildJSObjectCheck(receiver, bit_field_mask);

    HValue* map = Add<HLoadNamedField>(receiver, static_cast<HValue*>(NULL),
                                       HObjectAccess::ForMap());

    HValue* instance_type =
      Add<HLoadNamedField>(map, static_cast<HValue*>(NULL),
                           HObjectAccess::ForMapInstanceType());

    HValue* bit_field2 = Add<HLoadNamedField>(map,
                                              static_cast<HValue*>(NULL),
                                              HObjectAccess::ForMapBitField2());

    IfBuilder kind_if(this);
    BuildFastElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
                         FAST_HOLEY_ELEMENTS);

    kind_if.Else();
    {
      BuildFastElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
                           FAST_HOLEY_DOUBLE_ELEMENTS);
    }
    kind_if.Else();

    // The DICTIONARY_ELEMENTS check generates a "kind_if.Then"
    BuildElementsKindLimitCheck(&kind_if, bit_field2, DICTIONARY_ELEMENTS);
    {
      HValue* elements = AddLoadElements(receiver);

      HValue* hash = BuildElementIndexHash(key);

      Push(BuildUncheckedDictionaryElementLoad(receiver, elements, key, hash));
    }
    kind_if.Else();

    // The SLOPPY_ARGUMENTS_ELEMENTS check generates a "kind_if.Then"
    BuildElementsKindLimitCheck(&kind_if, bit_field2,
                                SLOPPY_ARGUMENTS_ELEMENTS);
    // Non-strict elements are not handled.
1861
    Add<HDeoptimize>("non-strict elements in KeyedLoadGenericStub",
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
                     Deoptimizer::EAGER);
    Push(graph()->GetConstant0());

    kind_if.Else();
    BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
                             EXTERNAL_INT8_ELEMENTS);

    kind_if.Else();
    BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
                             EXTERNAL_UINT8_ELEMENTS);

    kind_if.Else();
    BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
                             EXTERNAL_INT16_ELEMENTS);

    kind_if.Else();
    BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
                             EXTERNAL_UINT16_ELEMENTS);

    kind_if.Else();
    BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
                             EXTERNAL_INT32_ELEMENTS);

    kind_if.Else();
    BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
                             EXTERNAL_UINT32_ELEMENTS);

    kind_if.Else();
    BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
                             EXTERNAL_FLOAT32_ELEMENTS);

    kind_if.Else();
    BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
                             EXTERNAL_FLOAT64_ELEMENTS);

    kind_if.Else();
    BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
                             EXTERNAL_UINT8_CLAMPED_ELEMENTS);

1901
    kind_if.ElseDeopt("ElementsKind unhandled in KeyedLoadGenericStub");
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929

    kind_if.End();
  }
  index_name_split.Else();
  {
    // Key is a unique string.
    key = Pop();

    int bit_field_mask = (1 << Map::kIsAccessCheckNeeded) |
        (1 << Map::kHasNamedInterceptor);
    BuildJSObjectCheck(receiver, bit_field_mask);

    HIfContinuation continuation;
    BuildTestForDictionaryProperties(receiver, &continuation);
    IfBuilder if_dict_properties(this, &continuation);
    if_dict_properties.Then();
    {
      //  Key is string, properties are dictionary mode
      BuildNonGlobalObjectCheck(receiver);

      HValue* properties = Add<HLoadNamedField>(
          receiver, static_cast<HValue*>(NULL),
          HObjectAccess::ForPropertiesPointer());

      HValue* hash =
          Add<HLoadNamedField>(key, static_cast<HValue*>(NULL),
          HObjectAccess::ForNameHashField());

1930 1931
      hash = AddUncasted<HShr>(hash, Add<HConstant>(Name::kHashShift));

1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
      HValue* value = BuildUncheckedDictionaryElementLoad(receiver,
                                                          properties,
                                                          key,
                                                          hash);
      Push(value);
    }
    if_dict_properties.Else();
    {
      //  Key is string, properties are fast mode
      HValue* hash = BuildKeyedLookupCacheHash(receiver, key);

      ExternalReference cache_keys_ref =
          ExternalReference::keyed_lookup_cache_keys(isolate());
      HValue* cache_keys = Add<HConstant>(cache_keys_ref);

      HValue* map = Add<HLoadNamedField>(receiver, static_cast<HValue*>(NULL),
                                         HObjectAccess::ForMap());
      HValue* base_index = AddUncasted<HMul>(hash, Add<HConstant>(2));
      base_index->ClearFlag(HValue::kCanOverflow);

1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
      HIfContinuation inline_or_runtime_continuation(
          graph()->CreateBasicBlock(), graph()->CreateBasicBlock());
      {
        IfBuilder lookup_ifs[KeyedLookupCache::kEntriesPerBucket];
        for (int probe = 0; probe < KeyedLookupCache::kEntriesPerBucket;
             ++probe) {
          IfBuilder* lookup_if = &lookup_ifs[probe];
          lookup_if->Initialize(this);
          int probe_base = probe * KeyedLookupCache::kEntryLength;
          HValue* map_index = AddUncasted<HAdd>(
              base_index,
              Add<HConstant>(probe_base + KeyedLookupCache::kMapIndex));
          map_index->ClearFlag(HValue::kCanOverflow);
          HValue* key_index = AddUncasted<HAdd>(
              base_index,
              Add<HConstant>(probe_base + KeyedLookupCache::kKeyIndex));
          key_index->ClearFlag(HValue::kCanOverflow);
          HValue* map_to_check =
              Add<HLoadKeyed>(cache_keys, map_index, static_cast<HValue*>(NULL),
                              FAST_ELEMENTS, NEVER_RETURN_HOLE, 0);
          lookup_if->If<HCompareObjectEqAndBranch>(map_to_check, map);
          lookup_if->And();
          HValue* key_to_check =
              Add<HLoadKeyed>(cache_keys, key_index, static_cast<HValue*>(NULL),
                              FAST_ELEMENTS, NEVER_RETURN_HOLE, 0);
          lookup_if->If<HCompareObjectEqAndBranch>(key_to_check, key);
          lookup_if->Then();
          {
            ExternalReference cache_field_offsets_ref =
                ExternalReference::keyed_lookup_cache_field_offsets(isolate());
            HValue* cache_field_offsets =
                Add<HConstant>(cache_field_offsets_ref);
            HValue* index = AddUncasted<HAdd>(hash, Add<HConstant>(probe));
            index->ClearFlag(HValue::kCanOverflow);
            HValue* property_index = Add<HLoadKeyed>(
                cache_field_offsets, index, static_cast<HValue*>(NULL),
                EXTERNAL_INT32_ELEMENTS, NEVER_RETURN_HOLE, 0);
            Push(property_index);
          }
          lookup_if->Else();
        }
        for (int i = 0; i < KeyedLookupCache::kEntriesPerBucket; ++i) {
          lookup_ifs[i].JoinContinuation(&inline_or_runtime_continuation);
1995 1996
        }
      }
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012

      IfBuilder inline_or_runtime(this, &inline_or_runtime_continuation);
      inline_or_runtime.Then();
      {
        // Found a cached index, load property inline.
        Push(Add<HLoadFieldByIndex>(receiver, Pop()));
      }
      inline_or_runtime.Else();
      {
        // KeyedLookupCache miss; call runtime.
        Add<HPushArguments>(receiver, key);
        Push(Add<HCallRuntime>(
            isolate()->factory()->empty_string(),
            Runtime::FunctionForId(Runtime::kKeyedGetProperty), 2));
      }
      inline_or_runtime.End();
2013 2014 2015 2016 2017 2018 2019 2020 2021
    }
    if_dict_properties.End();
  }
  index_name_split.End();

  return Pop();
}


2022
Handle<Code> KeyedLoadGenericStub::GenerateCode() {
2023 2024 2025 2026
  return DoGenerateCode(this);
}


2027 2028
template <>
HValue* CodeStubGraphBuilder<VectorLoadStub>::BuildCodeStub() {
2029
  HValue* receiver = GetParameter(VectorLoadICDescriptor::kReceiverIndex);
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
  Add<HDeoptimize>("Always deopt", Deoptimizer::EAGER);
  return receiver;
}


Handle<Code> VectorLoadStub::GenerateCode() { return DoGenerateCode(this); }


template <>
HValue* CodeStubGraphBuilder<VectorKeyedLoadStub>::BuildCodeStub() {
2040
  HValue* receiver = GetParameter(VectorLoadICDescriptor::kReceiverIndex);
2041 2042 2043 2044 2045 2046 2047 2048
  Add<HDeoptimize>("Always deopt", Deoptimizer::EAGER);
  return receiver;
}


Handle<Code> VectorKeyedLoadStub::GenerateCode() {
  return DoGenerateCode(this);
}
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069


Handle<Code> MegamorphicLoadStub::GenerateCode() {
  return DoGenerateCode(this);
}


template <>
HValue* CodeStubGraphBuilder<MegamorphicLoadStub>::BuildCodeStub() {
  // The return address is on the stack.
  HValue* receiver = GetParameter(LoadDescriptor::kReceiverIndex);
  HValue* name = GetParameter(LoadDescriptor::kNameIndex);

  // Probe the stub cache.
  Code::Flags flags = Code::RemoveTypeAndHolderFromFlags(
      Code::ComputeHandlerFlags(Code::LOAD_IC));
  Add<HTailCallThroughMegamorphicCache>(receiver, name, flags);

  // We never continue.
  return graph()->GetConstant0();
}
2070
} }  // namespace v8::internal