1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #include "src/code-stubs.h"
8 #include "src/field-index.h"
9 #include "src/hydrogen.h"
10 #include "src/lithium.h"
16 static LChunk* OptimizeGraph(HGraph* graph) {
17 DisallowHeapAllocation no_allocation;
18 DisallowHandleAllocation no_handles;
19 DisallowHandleDereference no_deref;
21 DCHECK(graph != NULL);
22 BailoutReason bailout_reason = kNoReason;
23 if (!graph->Optimize(&bailout_reason)) {
24 FATAL(GetBailoutReason(bailout_reason));
26 LChunk* chunk = LChunk::NewChunk(graph);
28 FATAL(GetBailoutReason(graph->info()->bailout_reason()));
34 class CodeStubGraphBuilderBase : public HGraphBuilder {
36 CodeStubGraphBuilderBase(Isolate* isolate, HydrogenCodeStub* stub)
37 : HGraphBuilder(&info_),
38 arguments_length_(NULL),
41 descriptor_ = stub->GetInterfaceDescriptor();
42 int parameter_count = descriptor_->GetEnvironmentParameterCount();
43 parameters_.Reset(new HParameter*[parameter_count]);
45 virtual bool BuildGraph();
48 virtual HValue* BuildCodeStub() = 0;
49 HParameter* GetParameter(int parameter) {
50 DCHECK(parameter < descriptor_->GetEnvironmentParameterCount());
51 return parameters_[parameter];
53 HValue* GetArgumentsLength() {
54 // This is initialized in BuildGraph()
55 DCHECK(arguments_length_ != NULL);
56 return arguments_length_;
58 CompilationInfo* info() { return &info_; }
59 HydrogenCodeStub* stub() { return info_.code_stub(); }
60 HContext* context() { return context_; }
61 Isolate* isolate() { return info_.isolate(); }
63 HLoadNamedField* BuildLoadNamedField(HValue* object,
65 void BuildStoreNamedField(HValue* object, HValue* value, FieldIndex index,
66 Representation representation);
74 HValue* BuildArrayConstructor(ElementsKind kind,
75 AllocationSiteOverrideMode override_mode,
76 ArgumentClass argument_class);
77 HValue* BuildInternalArrayConstructor(ElementsKind kind,
78 ArgumentClass argument_class);
80 // BuildCheckAndInstallOptimizedCode emits code to install the optimized
81 // function found in the optimized code map at map_index in js_function, if
82 // the function at map_index matches the given native_context. Builder is
83 // left in the "Then()" state after the install.
84 void BuildCheckAndInstallOptimizedCode(HValue* js_function,
85 HValue* native_context,
87 HValue* optimized_map,
89 void BuildInstallCode(HValue* js_function, HValue* shared_info);
91 HInstruction* LoadFromOptimizedCodeMap(HValue* optimized_map,
94 void BuildInstallFromOptimizedCodeMap(HValue* js_function,
96 HValue* native_context);
99 HValue* BuildArraySingleArgumentConstructor(JSArrayBuilder* builder);
100 HValue* BuildArrayNArgumentsConstructor(JSArrayBuilder* builder,
103 SmartArrayPointer<HParameter*> parameters_;
104 HValue* arguments_length_;
105 CompilationInfoWithZone info_;
106 CodeStubInterfaceDescriptor* descriptor_;
111 bool CodeStubGraphBuilderBase::BuildGraph() {
112 // Update the static counter each time a new code stub is generated.
113 isolate()->counters()->code_stubs()->Increment();
115 if (FLAG_trace_hydrogen_stubs) {
116 const char* name = CodeStub::MajorName(stub()->MajorKey(), false);
117 PrintF("-----------------------------------------------------------\n");
118 PrintF("Compiling stub %s using hydrogen\n", name);
119 isolate()->GetHTracer()->TraceCompilation(&info_);
122 int param_count = descriptor_->GetEnvironmentParameterCount();
123 HEnvironment* start_environment = graph()->start_environment();
124 HBasicBlock* next_block = CreateBasicBlock(start_environment);
126 next_block->SetJoinId(BailoutId::StubEntry());
127 set_current_block(next_block);
129 bool runtime_stack_params = descriptor_->stack_parameter_count().is_valid();
130 HInstruction* stack_parameter_count = NULL;
131 for (int i = 0; i < param_count; ++i) {
132 Representation r = descriptor_->GetEnvironmentParameterRepresentation(i);
133 HParameter* param = Add<HParameter>(i,
134 HParameter::REGISTER_PARAMETER, r);
135 start_environment->Bind(i, param);
136 parameters_[i] = param;
137 if (descriptor_->IsEnvironmentParameterCountRegister(i)) {
138 param->set_type(HType::Smi());
139 stack_parameter_count = param;
140 arguments_length_ = stack_parameter_count;
144 DCHECK(!runtime_stack_params || arguments_length_ != NULL);
145 if (!runtime_stack_params) {
146 stack_parameter_count = graph()->GetConstantMinus1();
147 arguments_length_ = graph()->GetConstant0();
150 context_ = Add<HContext>();
151 start_environment->BindContext(context_);
153 Add<HSimulate>(BailoutId::StubEntry());
155 NoObservableSideEffectsScope no_effects(this);
157 HValue* return_value = BuildCodeStub();
159 // We might have extra expressions to pop from the stack in addition to the
161 HInstruction* stack_pop_count = stack_parameter_count;
162 if (descriptor_->function_mode() == JS_FUNCTION_STUB_MODE) {
163 if (!stack_parameter_count->IsConstant() &&
164 descriptor_->hint_stack_parameter_count() < 0) {
165 HInstruction* constant_one = graph()->GetConstant1();
166 stack_pop_count = AddUncasted<HAdd>(stack_parameter_count, constant_one);
167 stack_pop_count->ClearFlag(HValue::kCanOverflow);
168 // TODO(mvstanton): verify that stack_parameter_count+1 really fits in a
171 int count = descriptor_->hint_stack_parameter_count();
172 stack_pop_count = Add<HConstant>(count);
176 if (current_block() != NULL) {
177 HReturn* hreturn_instruction = New<HReturn>(return_value,
179 FinishCurrentBlock(hreturn_instruction);
185 template <class Stub>
186 class CodeStubGraphBuilder: public CodeStubGraphBuilderBase {
188 CodeStubGraphBuilder(Isolate* isolate, Stub* stub)
189 : CodeStubGraphBuilderBase(isolate, stub) {}
192 virtual HValue* BuildCodeStub() {
193 if (casted_stub()->IsUninitialized()) {
194 return BuildCodeUninitializedStub();
196 return BuildCodeInitializedStub();
200 virtual HValue* BuildCodeInitializedStub() {
205 virtual HValue* BuildCodeUninitializedStub() {
206 // Force a deopt that falls back to the runtime.
207 HValue* undefined = graph()->GetConstantUndefined();
208 IfBuilder builder(this);
209 builder.IfNot<HCompareObjectEqAndBranch, HValue*>(undefined, undefined);
211 builder.ElseDeopt("Forced deopt to runtime");
215 Stub* casted_stub() { return static_cast<Stub*>(stub()); }
219 Handle<Code> HydrogenCodeStub::GenerateLightweightMissCode() {
220 Factory* factory = isolate()->factory();
222 // Generate the new code.
223 MacroAssembler masm(isolate(), NULL, 256);
226 // Update the static counter each time a new code stub is generated.
227 isolate()->counters()->code_stubs()->Increment();
229 // Generate the code for the stub.
230 masm.set_generating_stub(true);
231 NoCurrentFrameScope scope(&masm);
232 GenerateLightweightMiss(&masm);
235 // Create the code object.
239 // Copy the generated code into a heap object.
240 Code::Flags flags = Code::ComputeFlags(
245 Handle<Code> new_object = factory->NewCode(
246 desc, flags, masm.CodeObject(), NeedsImmovableCode());
251 template <class Stub>
252 static Handle<Code> DoGenerateCode(Stub* stub) {
253 Isolate* isolate = stub->isolate();
254 CodeStub::Major major_key = static_cast<CodeStub*>(stub)->MajorKey();
255 CodeStubInterfaceDescriptor* descriptor =
256 isolate->code_stub_interface_descriptor(major_key);
257 if (!descriptor->IsInitialized()) {
258 stub->InitializeInterfaceDescriptor(descriptor);
261 // If we are uninitialized we can use a light-weight stub to enter
262 // the runtime that is significantly faster than using the standard
263 // stub-failure deopt mechanism.
264 if (stub->IsUninitialized() && descriptor->has_miss_handler()) {
265 DCHECK(!descriptor->stack_parameter_count().is_valid());
266 return stub->GenerateLightweightMissCode();
268 base::ElapsedTimer timer;
269 if (FLAG_profile_hydrogen_code_stub_compilation) {
272 CodeStubGraphBuilder<Stub> builder(isolate, stub);
273 LChunk* chunk = OptimizeGraph(builder.CreateGraph());
274 // TODO(yangguo) remove this once the code serializer handles code stubs.
275 if (FLAG_serialize_toplevel) chunk->info()->PrepareForSerializing();
276 Handle<Code> code = chunk->Codegen();
277 if (FLAG_profile_hydrogen_code_stub_compilation) {
279 os << "[Lazy compilation of " << stub << " took "
280 << timer.Elapsed().InMillisecondsF() << " ms]" << endl;
287 HValue* CodeStubGraphBuilder<ToNumberStub>::BuildCodeStub() {
288 HValue* value = GetParameter(0);
290 // Check if the parameter is already a SMI or heap number.
291 IfBuilder if_number(this);
292 if_number.If<HIsSmiAndBranch>(value);
293 if_number.OrIf<HCompareMap>(value, isolate()->factory()->heap_number_map());
296 // Return the number.
301 // Convert the parameter to number using the builtin.
302 HValue* function = AddLoadJSBuiltin(Builtins::TO_NUMBER);
303 Add<HPushArguments>(value);
304 Push(Add<HInvokeFunction>(function, 1));
312 Handle<Code> ToNumberStub::GenerateCode() {
313 return DoGenerateCode(this);
318 HValue* CodeStubGraphBuilder<NumberToStringStub>::BuildCodeStub() {
319 info()->MarkAsSavesCallerDoubles();
320 HValue* number = GetParameter(NumberToStringStub::kNumber);
321 return BuildNumberToString(number, Type::Number(zone()));
325 Handle<Code> NumberToStringStub::GenerateCode() {
326 return DoGenerateCode(this);
331 HValue* CodeStubGraphBuilder<FastCloneShallowArrayStub>::BuildCodeStub() {
332 Factory* factory = isolate()->factory();
333 HValue* undefined = graph()->GetConstantUndefined();
334 AllocationSiteMode alloc_site_mode = casted_stub()->allocation_site_mode();
336 // This stub is very performance sensitive, the generated code must be tuned
337 // so that it doesn't build and eager frame.
338 info()->MarkMustNotHaveEagerFrame();
340 HInstruction* allocation_site = Add<HLoadKeyed>(GetParameter(0),
342 static_cast<HValue*>(NULL),
344 IfBuilder checker(this);
345 checker.IfNot<HCompareObjectEqAndBranch, HValue*>(allocation_site,
349 HObjectAccess access = HObjectAccess::ForAllocationSiteOffset(
350 AllocationSite::kTransitionInfoOffset);
351 HInstruction* boilerplate = Add<HLoadNamedField>(
352 allocation_site, static_cast<HValue*>(NULL), access);
353 HValue* elements = AddLoadElements(boilerplate);
354 HValue* capacity = AddLoadFixedArrayLength(elements);
355 IfBuilder zero_capacity(this);
356 zero_capacity.If<HCompareNumericAndBranch>(capacity, graph()->GetConstant0(),
358 zero_capacity.Then();
359 Push(BuildCloneShallowArrayEmpty(boilerplate,
362 zero_capacity.Else();
363 IfBuilder if_fixed_cow(this);
364 if_fixed_cow.If<HCompareMap>(elements, factory->fixed_cow_array_map());
366 Push(BuildCloneShallowArrayCow(boilerplate,
371 IfBuilder if_fixed(this);
372 if_fixed.If<HCompareMap>(elements, factory->fixed_array_map());
374 Push(BuildCloneShallowArrayNonEmpty(boilerplate,
380 Push(BuildCloneShallowArrayNonEmpty(boilerplate,
383 FAST_DOUBLE_ELEMENTS));
388 checker.ElseDeopt("Uninitialized boilerplate literals");
391 return environment()->Pop();
395 Handle<Code> FastCloneShallowArrayStub::GenerateCode() {
396 return DoGenerateCode(this);
401 HValue* CodeStubGraphBuilder<FastCloneShallowObjectStub>::BuildCodeStub() {
402 HValue* undefined = graph()->GetConstantUndefined();
404 HInstruction* allocation_site = Add<HLoadKeyed>(GetParameter(0),
406 static_cast<HValue*>(NULL),
409 IfBuilder checker(this);
410 checker.IfNot<HCompareObjectEqAndBranch, HValue*>(allocation_site,
414 HObjectAccess access = HObjectAccess::ForAllocationSiteOffset(
415 AllocationSite::kTransitionInfoOffset);
416 HInstruction* boilerplate = Add<HLoadNamedField>(
417 allocation_site, static_cast<HValue*>(NULL), access);
419 int size = JSObject::kHeaderSize + casted_stub()->length() * kPointerSize;
420 int object_size = size;
421 if (FLAG_allocation_site_pretenuring) {
422 size += AllocationMemento::kSize;
425 HValue* boilerplate_map = Add<HLoadNamedField>(
426 boilerplate, static_cast<HValue*>(NULL),
427 HObjectAccess::ForMap());
428 HValue* boilerplate_size = Add<HLoadNamedField>(
429 boilerplate_map, static_cast<HValue*>(NULL),
430 HObjectAccess::ForMapInstanceSize());
431 HValue* size_in_words = Add<HConstant>(object_size >> kPointerSizeLog2);
432 checker.If<HCompareNumericAndBranch>(boilerplate_size,
433 size_in_words, Token::EQ);
436 HValue* size_in_bytes = Add<HConstant>(size);
438 HInstruction* object = Add<HAllocate>(size_in_bytes, HType::JSObject(),
439 NOT_TENURED, JS_OBJECT_TYPE);
441 for (int i = 0; i < object_size; i += kPointerSize) {
442 HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset(i);
443 Add<HStoreNamedField>(
444 object, access, Add<HLoadNamedField>(
445 boilerplate, static_cast<HValue*>(NULL), access));
448 DCHECK(FLAG_allocation_site_pretenuring || (size == object_size));
449 if (FLAG_allocation_site_pretenuring) {
450 BuildCreateAllocationMemento(
451 object, Add<HConstant>(object_size), allocation_site);
454 environment()->Push(object);
455 checker.ElseDeopt("Uninitialized boilerplate in fast clone");
458 return environment()->Pop();
462 Handle<Code> FastCloneShallowObjectStub::GenerateCode() {
463 return DoGenerateCode(this);
468 HValue* CodeStubGraphBuilder<CreateAllocationSiteStub>::BuildCodeStub() {
469 HValue* size = Add<HConstant>(AllocationSite::kSize);
470 HInstruction* object = Add<HAllocate>(size, HType::JSObject(), TENURED,
474 Handle<Map> allocation_site_map = isolate()->factory()->allocation_site_map();
475 AddStoreMapConstant(object, allocation_site_map);
477 // Store the payload (smi elements kind)
478 HValue* initial_elements_kind = Add<HConstant>(GetInitialFastElementsKind());
479 Add<HStoreNamedField>(object,
480 HObjectAccess::ForAllocationSiteOffset(
481 AllocationSite::kTransitionInfoOffset),
482 initial_elements_kind);
484 // Unlike literals, constructed arrays don't have nested sites
485 Add<HStoreNamedField>(object,
486 HObjectAccess::ForAllocationSiteOffset(
487 AllocationSite::kNestedSiteOffset),
488 graph()->GetConstant0());
490 // Pretenuring calculation field.
491 Add<HStoreNamedField>(object,
492 HObjectAccess::ForAllocationSiteOffset(
493 AllocationSite::kPretenureDataOffset),
494 graph()->GetConstant0());
496 // Pretenuring memento creation count field.
497 Add<HStoreNamedField>(object,
498 HObjectAccess::ForAllocationSiteOffset(
499 AllocationSite::kPretenureCreateCountOffset),
500 graph()->GetConstant0());
502 // Store an empty fixed array for the code dependency.
503 HConstant* empty_fixed_array =
504 Add<HConstant>(isolate()->factory()->empty_fixed_array());
505 Add<HStoreNamedField>(
507 HObjectAccess::ForAllocationSiteOffset(
508 AllocationSite::kDependentCodeOffset),
511 // Link the object to the allocation site list
512 HValue* site_list = Add<HConstant>(
513 ExternalReference::allocation_sites_list_address(isolate()));
514 HValue* site = Add<HLoadNamedField>(
515 site_list, static_cast<HValue*>(NULL),
516 HObjectAccess::ForAllocationSiteList());
517 // TODO(mvstanton): This is a store to a weak pointer, which we may want to
518 // mark as such in order to skip the write barrier, once we have a unified
519 // system for weakness. For now we decided to keep it like this because having
520 // an initial write barrier backed store makes this pointer strong until the
521 // next GC, and allocation sites are designed to survive several GCs anyway.
522 Add<HStoreNamedField>(
524 HObjectAccess::ForAllocationSiteOffset(AllocationSite::kWeakNextOffset),
526 Add<HStoreNamedField>(site_list, HObjectAccess::ForAllocationSiteList(),
529 HInstruction* feedback_vector = GetParameter(0);
530 HInstruction* slot = GetParameter(1);
531 Add<HStoreKeyed>(feedback_vector, slot, object, FAST_ELEMENTS,
533 return feedback_vector;
537 Handle<Code> CreateAllocationSiteStub::GenerateCode() {
538 return DoGenerateCode(this);
543 HValue* CodeStubGraphBuilder<LoadFastElementStub>::BuildCodeStub() {
544 HInstruction* load = BuildUncheckedMonomorphicElementAccess(
545 GetParameter(KeyedLoadIC::kReceiverIndex),
546 GetParameter(KeyedLoadIC::kNameIndex),
548 casted_stub()->is_js_array(),
549 casted_stub()->elements_kind(),
557 Handle<Code> LoadFastElementStub::GenerateCode() {
558 return DoGenerateCode(this);
562 HLoadNamedField* CodeStubGraphBuilderBase::BuildLoadNamedField(
563 HValue* object, FieldIndex index) {
564 Representation representation = index.is_double()
565 ? Representation::Double()
566 : Representation::Tagged();
567 int offset = index.offset();
568 HObjectAccess access = index.is_inobject()
569 ? HObjectAccess::ForObservableJSObjectOffset(offset, representation)
570 : HObjectAccess::ForBackingStoreOffset(offset, representation);
571 if (index.is_double()) {
572 // Load the heap number.
573 object = Add<HLoadNamedField>(
574 object, static_cast<HValue*>(NULL),
575 access.WithRepresentation(Representation::Tagged()));
576 // Load the double value from it.
577 access = HObjectAccess::ForHeapNumberValue();
579 return Add<HLoadNamedField>(object, static_cast<HValue*>(NULL), access);
584 HValue* CodeStubGraphBuilder<LoadFieldStub>::BuildCodeStub() {
585 return BuildLoadNamedField(GetParameter(0), casted_stub()->index());
589 Handle<Code> LoadFieldStub::GenerateCode() {
590 return DoGenerateCode(this);
595 HValue* CodeStubGraphBuilder<LoadConstantStub>::BuildCodeStub() {
596 HValue* map = AddLoadMap(GetParameter(0), NULL);
597 HObjectAccess descriptors_access = HObjectAccess::ForObservableJSObjectOffset(
598 Map::kDescriptorsOffset, Representation::Tagged());
599 HValue* descriptors =
600 Add<HLoadNamedField>(map, static_cast<HValue*>(NULL), descriptors_access);
601 HObjectAccess value_access = HObjectAccess::ForObservableJSObjectOffset(
602 DescriptorArray::GetValueOffset(casted_stub()->descriptor()));
603 return Add<HLoadNamedField>(descriptors, static_cast<HValue*>(NULL),
608 Handle<Code> LoadConstantStub::GenerateCode() { return DoGenerateCode(this); }
611 void CodeStubGraphBuilderBase::BuildStoreNamedField(
612 HValue* object, HValue* value, FieldIndex index,
613 Representation representation) {
614 DCHECK(!index.is_double() || representation.IsDouble());
615 int offset = index.offset();
616 HObjectAccess access =
618 ? HObjectAccess::ForObservableJSObjectOffset(offset, representation)
619 : HObjectAccess::ForBackingStoreOffset(offset, representation);
621 if (representation.IsDouble()) {
622 // Load the heap number.
623 object = Add<HLoadNamedField>(
624 object, static_cast<HValue*>(NULL),
625 access.WithRepresentation(Representation::Tagged()));
626 // Store the double value into it.
627 access = HObjectAccess::ForHeapNumberValue();
628 } else if (representation.IsHeapObject()) {
629 BuildCheckHeapObject(value);
632 Add<HStoreNamedField>(object, access, value, INITIALIZING_STORE);
637 HValue* CodeStubGraphBuilder<StoreFieldStub>::BuildCodeStub() {
638 BuildStoreNamedField(GetParameter(0), GetParameter(2), casted_stub()->index(),
639 casted_stub()->representation());
640 return GetParameter(2);
644 Handle<Code> StoreFieldStub::GenerateCode() { return DoGenerateCode(this); }
648 HValue* CodeStubGraphBuilder<StringLengthStub>::BuildCodeStub() {
649 HValue* string = BuildLoadNamedField(GetParameter(0),
650 FieldIndex::ForInObjectOffset(JSValue::kValueOffset));
651 return BuildLoadNamedField(string,
652 FieldIndex::ForInObjectOffset(String::kLengthOffset));
656 Handle<Code> StringLengthStub::GenerateCode() {
657 return DoGenerateCode(this);
662 HValue* CodeStubGraphBuilder<StoreFastElementStub>::BuildCodeStub() {
663 BuildUncheckedMonomorphicElementAccess(
664 GetParameter(StoreIC::kReceiverIndex),
665 GetParameter(StoreIC::kNameIndex),
666 GetParameter(StoreIC::kValueIndex),
667 casted_stub()->is_js_array(), casted_stub()->elements_kind(),
668 STORE, NEVER_RETURN_HOLE, casted_stub()->store_mode());
670 return GetParameter(2);
674 Handle<Code> StoreFastElementStub::GenerateCode() {
675 return DoGenerateCode(this);
680 HValue* CodeStubGraphBuilder<TransitionElementsKindStub>::BuildCodeStub() {
681 info()->MarkAsSavesCallerDoubles();
683 BuildTransitionElementsKind(GetParameter(0),
685 casted_stub()->from_kind(),
686 casted_stub()->to_kind(),
687 casted_stub()->is_js_array());
689 return GetParameter(0);
693 Handle<Code> TransitionElementsKindStub::GenerateCode() {
694 return DoGenerateCode(this);
697 HValue* CodeStubGraphBuilderBase::BuildArrayConstructor(
699 AllocationSiteOverrideMode override_mode,
700 ArgumentClass argument_class) {
701 HValue* constructor = GetParameter(ArrayConstructorStubBase::kConstructor);
702 HValue* alloc_site = GetParameter(ArrayConstructorStubBase::kAllocationSite);
703 JSArrayBuilder array_builder(this, kind, alloc_site, constructor,
705 HValue* result = NULL;
706 switch (argument_class) {
708 // This stub is very performance sensitive, the generated code must be
709 // tuned so that it doesn't build and eager frame.
710 info()->MarkMustNotHaveEagerFrame();
711 result = array_builder.AllocateEmptyArray();
714 result = BuildArraySingleArgumentConstructor(&array_builder);
717 result = BuildArrayNArgumentsConstructor(&array_builder, kind);
725 HValue* CodeStubGraphBuilderBase::BuildInternalArrayConstructor(
726 ElementsKind kind, ArgumentClass argument_class) {
727 HValue* constructor = GetParameter(
728 InternalArrayConstructorStubBase::kConstructor);
729 JSArrayBuilder array_builder(this, kind, constructor);
731 HValue* result = NULL;
732 switch (argument_class) {
734 // This stub is very performance sensitive, the generated code must be
735 // tuned so that it doesn't build and eager frame.
736 info()->MarkMustNotHaveEagerFrame();
737 result = array_builder.AllocateEmptyArray();
740 result = BuildArraySingleArgumentConstructor(&array_builder);
743 result = BuildArrayNArgumentsConstructor(&array_builder, kind);
750 HValue* CodeStubGraphBuilderBase::BuildArraySingleArgumentConstructor(
751 JSArrayBuilder* array_builder) {
752 // Smi check and range check on the input arg.
753 HValue* constant_one = graph()->GetConstant1();
754 HValue* constant_zero = graph()->GetConstant0();
756 HInstruction* elements = Add<HArgumentsElements>(false);
757 HInstruction* argument = Add<HAccessArgumentsAt>(
758 elements, constant_one, constant_zero);
760 return BuildAllocateArrayFromLength(array_builder, argument);
764 HValue* CodeStubGraphBuilderBase::BuildArrayNArgumentsConstructor(
765 JSArrayBuilder* array_builder, ElementsKind kind) {
766 // Insert a bounds check because the number of arguments might exceed
767 // the kInitialMaxFastElementArray limit. This cannot happen for code
768 // that was parsed, but calling via Array.apply(thisArg, [...]) might
770 HValue* length = GetArgumentsLength();
771 HConstant* max_alloc_length =
772 Add<HConstant>(JSObject::kInitialMaxFastElementArray);
773 HValue* checked_length = Add<HBoundsCheck>(length, max_alloc_length);
775 // We need to fill with the hole if it's a smi array in the multi-argument
776 // case because we might have to bail out while copying arguments into
777 // the array because they aren't compatible with a smi array.
778 // If it's a double array, no problem, and if it's fast then no
779 // problem either because doubles are boxed.
781 // TODO(mvstanton): consider an instruction to memset fill the array
782 // with zero in this case instead.
783 JSArrayBuilder::FillMode fill_mode = IsFastSmiElementsKind(kind)
784 ? JSArrayBuilder::FILL_WITH_HOLE
785 : JSArrayBuilder::DONT_FILL_WITH_HOLE;
786 HValue* new_object = array_builder->AllocateArray(checked_length,
790 HValue* elements = array_builder->GetElementsLocation();
791 DCHECK(elements != NULL);
793 // Now populate the elements correctly.
794 LoopBuilder builder(this,
796 LoopBuilder::kPostIncrement);
797 HValue* start = graph()->GetConstant0();
798 HValue* key = builder.BeginBody(start, checked_length, Token::LT);
799 HInstruction* argument_elements = Add<HArgumentsElements>(false);
800 HInstruction* argument = Add<HAccessArgumentsAt>(
801 argument_elements, checked_length, key);
803 Add<HStoreKeyed>(elements, key, argument, kind);
810 HValue* CodeStubGraphBuilder<ArrayNoArgumentConstructorStub>::BuildCodeStub() {
811 ElementsKind kind = casted_stub()->elements_kind();
812 AllocationSiteOverrideMode override_mode = casted_stub()->override_mode();
813 return BuildArrayConstructor(kind, override_mode, NONE);
817 Handle<Code> ArrayNoArgumentConstructorStub::GenerateCode() {
818 return DoGenerateCode(this);
823 HValue* CodeStubGraphBuilder<ArraySingleArgumentConstructorStub>::
825 ElementsKind kind = casted_stub()->elements_kind();
826 AllocationSiteOverrideMode override_mode = casted_stub()->override_mode();
827 return BuildArrayConstructor(kind, override_mode, SINGLE);
831 Handle<Code> ArraySingleArgumentConstructorStub::GenerateCode() {
832 return DoGenerateCode(this);
837 HValue* CodeStubGraphBuilder<ArrayNArgumentsConstructorStub>::BuildCodeStub() {
838 ElementsKind kind = casted_stub()->elements_kind();
839 AllocationSiteOverrideMode override_mode = casted_stub()->override_mode();
840 return BuildArrayConstructor(kind, override_mode, MULTIPLE);
844 Handle<Code> ArrayNArgumentsConstructorStub::GenerateCode() {
845 return DoGenerateCode(this);
850 HValue* CodeStubGraphBuilder<InternalArrayNoArgumentConstructorStub>::
852 ElementsKind kind = casted_stub()->elements_kind();
853 return BuildInternalArrayConstructor(kind, NONE);
857 Handle<Code> InternalArrayNoArgumentConstructorStub::GenerateCode() {
858 return DoGenerateCode(this);
863 HValue* CodeStubGraphBuilder<InternalArraySingleArgumentConstructorStub>::
865 ElementsKind kind = casted_stub()->elements_kind();
866 return BuildInternalArrayConstructor(kind, SINGLE);
870 Handle<Code> InternalArraySingleArgumentConstructorStub::GenerateCode() {
871 return DoGenerateCode(this);
876 HValue* CodeStubGraphBuilder<InternalArrayNArgumentsConstructorStub>::
878 ElementsKind kind = casted_stub()->elements_kind();
879 return BuildInternalArrayConstructor(kind, MULTIPLE);
883 Handle<Code> InternalArrayNArgumentsConstructorStub::GenerateCode() {
884 return DoGenerateCode(this);
889 HValue* CodeStubGraphBuilder<CompareNilICStub>::BuildCodeInitializedStub() {
890 Isolate* isolate = graph()->isolate();
891 CompareNilICStub* stub = casted_stub();
892 HIfContinuation continuation;
893 Handle<Map> sentinel_map(isolate->heap()->meta_map());
894 Type* type = stub->GetType(zone(), sentinel_map);
895 BuildCompareNil(GetParameter(0), type, &continuation);
896 IfBuilder if_nil(this, &continuation);
898 if (continuation.IsFalseReachable()) {
900 if_nil.Return(graph()->GetConstant0());
903 return continuation.IsTrueReachable()
904 ? graph()->GetConstant1()
905 : graph()->GetConstantUndefined();
909 Handle<Code> CompareNilICStub::GenerateCode() {
910 return DoGenerateCode(this);
915 HValue* CodeStubGraphBuilder<BinaryOpICStub>::BuildCodeInitializedStub() {
916 BinaryOpIC::State state = casted_stub()->state();
918 HValue* left = GetParameter(BinaryOpICStub::kLeft);
919 HValue* right = GetParameter(BinaryOpICStub::kRight);
921 Type* left_type = state.GetLeftType(zone());
922 Type* right_type = state.GetRightType(zone());
923 Type* result_type = state.GetResultType(zone());
925 DCHECK(!left_type->Is(Type::None()) && !right_type->Is(Type::None()) &&
926 (state.HasSideEffects() || !result_type->Is(Type::None())));
928 HValue* result = NULL;
929 HAllocationMode allocation_mode(NOT_TENURED);
930 if (state.op() == Token::ADD &&
931 (left_type->Maybe(Type::String()) || right_type->Maybe(Type::String())) &&
932 !left_type->Is(Type::String()) && !right_type->Is(Type::String())) {
933 // For the generic add stub a fast case for string addition is performance
935 if (left_type->Maybe(Type::String())) {
936 IfBuilder if_leftisstring(this);
937 if_leftisstring.If<HIsStringAndBranch>(left);
938 if_leftisstring.Then();
940 Push(BuildBinaryOperation(
941 state.op(), left, right,
942 Type::String(zone()), right_type,
943 result_type, state.fixed_right_arg(),
946 if_leftisstring.Else();
948 Push(BuildBinaryOperation(
949 state.op(), left, right,
950 left_type, right_type, result_type,
951 state.fixed_right_arg(), allocation_mode));
953 if_leftisstring.End();
956 IfBuilder if_rightisstring(this);
957 if_rightisstring.If<HIsStringAndBranch>(right);
958 if_rightisstring.Then();
960 Push(BuildBinaryOperation(
961 state.op(), left, right,
962 left_type, Type::String(zone()),
963 result_type, state.fixed_right_arg(),
966 if_rightisstring.Else();
968 Push(BuildBinaryOperation(
969 state.op(), left, right,
970 left_type, right_type, result_type,
971 state.fixed_right_arg(), allocation_mode));
973 if_rightisstring.End();
977 result = BuildBinaryOperation(
978 state.op(), left, right,
979 left_type, right_type, result_type,
980 state.fixed_right_arg(), allocation_mode);
983 // If we encounter a generic argument, the number conversion is
984 // observable, thus we cannot afford to bail out after the fact.
985 if (!state.HasSideEffects()) {
986 result = EnforceNumberType(result, result_type);
989 // Reuse the double box of one of the operands if we are allowed to (i.e.
991 if (state.CanReuseDoubleBox()) {
992 HValue* operand = (state.mode() == OVERWRITE_LEFT) ? left : right;
993 IfBuilder if_heap_number(this);
994 if_heap_number.If<HHasInstanceTypeAndBranch>(operand, HEAP_NUMBER_TYPE);
995 if_heap_number.Then();
996 Add<HStoreNamedField>(operand, HObjectAccess::ForHeapNumberValue(), result);
998 if_heap_number.Else();
1000 if_heap_number.End();
1008 Handle<Code> BinaryOpICStub::GenerateCode() {
1009 return DoGenerateCode(this);
1014 HValue* CodeStubGraphBuilder<BinaryOpWithAllocationSiteStub>::BuildCodeStub() {
1015 BinaryOpIC::State state = casted_stub()->state();
1017 HValue* allocation_site = GetParameter(
1018 BinaryOpWithAllocationSiteStub::kAllocationSite);
1019 HValue* left = GetParameter(BinaryOpWithAllocationSiteStub::kLeft);
1020 HValue* right = GetParameter(BinaryOpWithAllocationSiteStub::kRight);
1022 Type* left_type = state.GetLeftType(zone());
1023 Type* right_type = state.GetRightType(zone());
1024 Type* result_type = state.GetResultType(zone());
1025 HAllocationMode allocation_mode(allocation_site);
1027 return BuildBinaryOperation(state.op(), left, right,
1028 left_type, right_type, result_type,
1029 state.fixed_right_arg(), allocation_mode);
1033 Handle<Code> BinaryOpWithAllocationSiteStub::GenerateCode() {
1034 return DoGenerateCode(this);
1039 HValue* CodeStubGraphBuilder<StringAddStub>::BuildCodeInitializedStub() {
1040 StringAddStub* stub = casted_stub();
1041 StringAddFlags flags = stub->flags();
1042 PretenureFlag pretenure_flag = stub->pretenure_flag();
1044 HValue* left = GetParameter(StringAddStub::kLeft);
1045 HValue* right = GetParameter(StringAddStub::kRight);
1047 // Make sure that both arguments are strings if not known in advance.
1048 if ((flags & STRING_ADD_CHECK_LEFT) == STRING_ADD_CHECK_LEFT) {
1049 left = BuildCheckString(left);
1051 if ((flags & STRING_ADD_CHECK_RIGHT) == STRING_ADD_CHECK_RIGHT) {
1052 right = BuildCheckString(right);
1055 return BuildStringAdd(left, right, HAllocationMode(pretenure_flag));
1059 Handle<Code> StringAddStub::GenerateCode() {
1060 return DoGenerateCode(this);
1065 HValue* CodeStubGraphBuilder<ToBooleanStub>::BuildCodeInitializedStub() {
1066 ToBooleanStub* stub = casted_stub();
1067 HValue* true_value = NULL;
1068 HValue* false_value = NULL;
1070 switch (stub->GetMode()) {
1071 case ToBooleanStub::RESULT_AS_SMI:
1072 true_value = graph()->GetConstant1();
1073 false_value = graph()->GetConstant0();
1075 case ToBooleanStub::RESULT_AS_ODDBALL:
1076 true_value = graph()->GetConstantTrue();
1077 false_value = graph()->GetConstantFalse();
1079 case ToBooleanStub::RESULT_AS_INVERSE_ODDBALL:
1080 true_value = graph()->GetConstantFalse();
1081 false_value = graph()->GetConstantTrue();
1085 IfBuilder if_true(this);
1086 if_true.If<HBranch>(GetParameter(0), stub->GetTypes());
1088 if_true.Return(true_value);
1095 Handle<Code> ToBooleanStub::GenerateCode() {
1096 return DoGenerateCode(this);
1101 HValue* CodeStubGraphBuilder<StoreGlobalStub>::BuildCodeInitializedStub() {
1102 StoreGlobalStub* stub = casted_stub();
1103 Handle<Object> hole(isolate()->heap()->the_hole_value(), isolate());
1104 Handle<Object> placeholer_value(Smi::FromInt(0), isolate());
1105 Handle<PropertyCell> placeholder_cell =
1106 isolate()->factory()->NewPropertyCell(placeholer_value);
1108 HParameter* value = GetParameter(StoreIC::kValueIndex);
1110 if (stub->check_global()) {
1111 // Check that the map of the global has not changed: use a placeholder map
1112 // that will be replaced later with the global object's map.
1113 Handle<Map> placeholder_map = isolate()->factory()->meta_map();
1114 HValue* global = Add<HConstant>(
1115 StoreGlobalStub::global_placeholder(isolate()));
1116 Add<HCheckMaps>(global, placeholder_map);
1119 HValue* cell = Add<HConstant>(placeholder_cell);
1120 HObjectAccess access(HObjectAccess::ForCellPayload(isolate()));
1121 HValue* cell_contents = Add<HLoadNamedField>(
1122 cell, static_cast<HValue*>(NULL), access);
1124 if (stub->is_constant()) {
1125 IfBuilder builder(this);
1126 builder.If<HCompareObjectEqAndBranch>(cell_contents, value);
1128 builder.ElseDeopt("Unexpected cell contents in constant global store");
1131 // Load the payload of the global parameter cell. A hole indicates that the
1132 // property has been deleted and that the store must be handled by the
1134 IfBuilder builder(this);
1135 HValue* hole_value = Add<HConstant>(hole);
1136 builder.If<HCompareObjectEqAndBranch>(cell_contents, hole_value);
1138 builder.Deopt("Unexpected cell contents in global store");
1140 Add<HStoreNamedField>(cell, access, value);
1148 Handle<Code> StoreGlobalStub::GenerateCode() {
1149 return DoGenerateCode(this);
1154 HValue* CodeStubGraphBuilder<ElementsTransitionAndStoreStub>::BuildCodeStub() {
1155 HValue* value = GetParameter(ElementsTransitionAndStoreStub::kValueIndex);
1156 HValue* map = GetParameter(ElementsTransitionAndStoreStub::kMapIndex);
1157 HValue* key = GetParameter(ElementsTransitionAndStoreStub::kKeyIndex);
1158 HValue* object = GetParameter(ElementsTransitionAndStoreStub::kObjectIndex);
1160 if (FLAG_trace_elements_transitions) {
1161 // Tracing elements transitions is the job of the runtime.
1162 Add<HDeoptimize>("Tracing elements transitions", Deoptimizer::EAGER);
1164 info()->MarkAsSavesCallerDoubles();
1166 BuildTransitionElementsKind(object, map,
1167 casted_stub()->from_kind(),
1168 casted_stub()->to_kind(),
1169 casted_stub()->is_jsarray());
1171 BuildUncheckedMonomorphicElementAccess(object, key, value,
1172 casted_stub()->is_jsarray(),
1173 casted_stub()->to_kind(),
1174 STORE, ALLOW_RETURN_HOLE,
1175 casted_stub()->store_mode());
1182 Handle<Code> ElementsTransitionAndStoreStub::GenerateCode() {
1183 return DoGenerateCode(this);
1187 void CodeStubGraphBuilderBase::BuildCheckAndInstallOptimizedCode(
1188 HValue* js_function,
1189 HValue* native_context,
1191 HValue* optimized_map,
1192 HValue* map_index) {
1193 HValue* osr_ast_id_none = Add<HConstant>(BailoutId::None().ToInt());
1194 HValue* context_slot = LoadFromOptimizedCodeMap(
1195 optimized_map, map_index, SharedFunctionInfo::kContextOffset);
1196 HValue* osr_ast_slot = LoadFromOptimizedCodeMap(
1197 optimized_map, map_index, SharedFunctionInfo::kOsrAstIdOffset);
1198 builder->If<HCompareObjectEqAndBranch>(native_context,
1200 builder->AndIf<HCompareObjectEqAndBranch>(osr_ast_slot, osr_ast_id_none);
1202 HValue* code_object = LoadFromOptimizedCodeMap(optimized_map,
1203 map_index, SharedFunctionInfo::kCachedCodeOffset);
1205 HValue* literals = LoadFromOptimizedCodeMap(optimized_map,
1206 map_index, SharedFunctionInfo::kLiteralsOffset);
1208 Counters* counters = isolate()->counters();
1209 AddIncrementCounter(counters->fast_new_closure_install_optimized());
1211 // TODO(fschneider): Idea: store proper code pointers in the optimized code
1212 // map and either unmangle them on marking or do nothing as the whole map is
1213 // discarded on major GC anyway.
1214 Add<HStoreCodeEntry>(js_function, code_object);
1215 Add<HStoreNamedField>(js_function, HObjectAccess::ForLiteralsPointer(),
1218 // Now link a function into a list of optimized functions.
1219 HValue* optimized_functions_list = Add<HLoadNamedField>(
1220 native_context, static_cast<HValue*>(NULL),
1221 HObjectAccess::ForContextSlot(Context::OPTIMIZED_FUNCTIONS_LIST));
1222 Add<HStoreNamedField>(js_function,
1223 HObjectAccess::ForNextFunctionLinkPointer(),
1224 optimized_functions_list);
1226 // This store is the only one that should have a write barrier.
1227 Add<HStoreNamedField>(native_context,
1228 HObjectAccess::ForContextSlot(Context::OPTIMIZED_FUNCTIONS_LIST),
1231 // The builder continues in the "then" after this function.
1235 void CodeStubGraphBuilderBase::BuildInstallCode(HValue* js_function,
1236 HValue* shared_info) {
1237 Add<HStoreNamedField>(js_function,
1238 HObjectAccess::ForNextFunctionLinkPointer(),
1239 graph()->GetConstantUndefined());
1240 HValue* code_object = Add<HLoadNamedField>(
1241 shared_info, static_cast<HValue*>(NULL), HObjectAccess::ForCodeOffset());
1242 Add<HStoreCodeEntry>(js_function, code_object);
1246 HInstruction* CodeStubGraphBuilderBase::LoadFromOptimizedCodeMap(
1247 HValue* optimized_map,
1250 // By making sure to express these loads in the form [<hvalue> + constant]
1251 // the keyed load can be hoisted.
1252 DCHECK(field_offset >= 0 && field_offset < SharedFunctionInfo::kEntryLength);
1253 HValue* field_slot = iterator;
1254 if (field_offset > 0) {
1255 HValue* field_offset_value = Add<HConstant>(field_offset);
1256 field_slot = AddUncasted<HAdd>(iterator, field_offset_value);
1258 HInstruction* field_entry = Add<HLoadKeyed>(optimized_map, field_slot,
1259 static_cast<HValue*>(NULL), FAST_ELEMENTS);
1264 void CodeStubGraphBuilderBase::BuildInstallFromOptimizedCodeMap(
1265 HValue* js_function,
1266 HValue* shared_info,
1267 HValue* native_context) {
1268 Counters* counters = isolate()->counters();
1269 IfBuilder is_optimized(this);
1270 HInstruction* optimized_map = Add<HLoadNamedField>(
1271 shared_info, static_cast<HValue*>(NULL),
1272 HObjectAccess::ForOptimizedCodeMap());
1273 HValue* null_constant = Add<HConstant>(0);
1274 is_optimized.If<HCompareObjectEqAndBranch>(optimized_map, null_constant);
1275 is_optimized.Then();
1277 BuildInstallCode(js_function, shared_info);
1279 is_optimized.Else();
1281 AddIncrementCounter(counters->fast_new_closure_try_optimized());
1282 // optimized_map points to fixed array of 3-element entries
1283 // (native context, optimized code, literals).
1284 // Map must never be empty, so check the first elements.
1285 HValue* first_entry_index =
1286 Add<HConstant>(SharedFunctionInfo::kEntriesStart);
1287 IfBuilder already_in(this);
1288 BuildCheckAndInstallOptimizedCode(js_function, native_context, &already_in,
1289 optimized_map, first_entry_index);
1292 // Iterate through the rest of map backwards. Do not double check first
1293 // entry. After the loop, if no matching optimized code was found,
1294 // install unoptimized code.
1295 // for(i = map.length() - SharedFunctionInfo::kEntryLength;
1296 // i > SharedFunctionInfo::kEntriesStart;
1297 // i -= SharedFunctionInfo::kEntryLength) { .. }
1298 HValue* shared_function_entry_length =
1299 Add<HConstant>(SharedFunctionInfo::kEntryLength);
1300 LoopBuilder loop_builder(this,
1302 LoopBuilder::kPostDecrement,
1303 shared_function_entry_length);
1304 HValue* array_length = Add<HLoadNamedField>(
1305 optimized_map, static_cast<HValue*>(NULL),
1306 HObjectAccess::ForFixedArrayLength());
1307 HValue* start_pos = AddUncasted<HSub>(array_length,
1308 shared_function_entry_length);
1309 HValue* slot_iterator = loop_builder.BeginBody(start_pos,
1313 IfBuilder done_check(this);
1314 BuildCheckAndInstallOptimizedCode(js_function, native_context,
1318 // Fall out of the loop
1319 loop_builder.Break();
1321 loop_builder.EndBody();
1323 // If slot_iterator equals first entry index, then we failed to find and
1324 // install optimized code
1325 IfBuilder no_optimized_code_check(this);
1326 no_optimized_code_check.If<HCompareNumericAndBranch>(
1327 slot_iterator, first_entry_index, Token::EQ);
1328 no_optimized_code_check.Then();
1330 // Store the unoptimized code
1331 BuildInstallCode(js_function, shared_info);
1339 HValue* CodeStubGraphBuilder<FastNewClosureStub>::BuildCodeStub() {
1340 Counters* counters = isolate()->counters();
1341 Factory* factory = isolate()->factory();
1342 HInstruction* empty_fixed_array =
1343 Add<HConstant>(factory->empty_fixed_array());
1344 HValue* shared_info = GetParameter(0);
1346 AddIncrementCounter(counters->fast_new_closure_total());
1348 // Create a new closure from the given function info in new space
1349 HValue* size = Add<HConstant>(JSFunction::kSize);
1350 HInstruction* js_function = Add<HAllocate>(size, HType::JSObject(),
1351 NOT_TENURED, JS_FUNCTION_TYPE);
1353 int map_index = Context::FunctionMapIndex(casted_stub()->strict_mode(),
1354 casted_stub()->is_generator());
1356 // Compute the function map in the current native context and set that
1357 // as the map of the allocated object.
1358 HInstruction* native_context = BuildGetNativeContext();
1359 HInstruction* map_slot_value = Add<HLoadNamedField>(
1360 native_context, static_cast<HValue*>(NULL),
1361 HObjectAccess::ForContextSlot(map_index));
1362 Add<HStoreNamedField>(js_function, HObjectAccess::ForMap(), map_slot_value);
1364 // Initialize the rest of the function.
1365 Add<HStoreNamedField>(js_function, HObjectAccess::ForPropertiesPointer(),
1367 Add<HStoreNamedField>(js_function, HObjectAccess::ForElementsPointer(),
1369 Add<HStoreNamedField>(js_function, HObjectAccess::ForLiteralsPointer(),
1371 Add<HStoreNamedField>(js_function, HObjectAccess::ForPrototypeOrInitialMap(),
1372 graph()->GetConstantHole());
1373 Add<HStoreNamedField>(js_function,
1374 HObjectAccess::ForSharedFunctionInfoPointer(),
1376 Add<HStoreNamedField>(js_function, HObjectAccess::ForFunctionContextPointer(),
1379 // Initialize the code pointer in the function to be the one
1380 // found in the shared function info object.
1381 // But first check if there is an optimized version for our context.
1382 if (FLAG_cache_optimized_code) {
1383 BuildInstallFromOptimizedCodeMap(js_function, shared_info, native_context);
1385 BuildInstallCode(js_function, shared_info);
1392 Handle<Code> FastNewClosureStub::GenerateCode() {
1393 return DoGenerateCode(this);
1398 HValue* CodeStubGraphBuilder<FastNewContextStub>::BuildCodeStub() {
1399 int length = casted_stub()->slots() + Context::MIN_CONTEXT_SLOTS;
1401 // Get the function.
1402 HParameter* function = GetParameter(FastNewContextStub::kFunction);
1404 // Allocate the context in new space.
1405 HAllocate* function_context = Add<HAllocate>(
1406 Add<HConstant>(length * kPointerSize + FixedArray::kHeaderSize),
1407 HType::HeapObject(), NOT_TENURED, FIXED_ARRAY_TYPE);
1409 // Set up the object header.
1410 AddStoreMapConstant(function_context,
1411 isolate()->factory()->function_context_map());
1412 Add<HStoreNamedField>(function_context,
1413 HObjectAccess::ForFixedArrayLength(),
1414 Add<HConstant>(length));
1416 // Set up the fixed slots.
1417 Add<HStoreNamedField>(function_context,
1418 HObjectAccess::ForContextSlot(Context::CLOSURE_INDEX),
1420 Add<HStoreNamedField>(function_context,
1421 HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX),
1423 Add<HStoreNamedField>(function_context,
1424 HObjectAccess::ForContextSlot(Context::EXTENSION_INDEX),
1425 graph()->GetConstant0());
1427 // Copy the global object from the previous context.
1428 HValue* global_object = Add<HLoadNamedField>(
1429 context(), static_cast<HValue*>(NULL),
1430 HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX));
1431 Add<HStoreNamedField>(function_context,
1432 HObjectAccess::ForContextSlot(
1433 Context::GLOBAL_OBJECT_INDEX),
1436 // Initialize the rest of the slots to undefined.
1437 for (int i = Context::MIN_CONTEXT_SLOTS; i < length; ++i) {
1438 Add<HStoreNamedField>(function_context,
1439 HObjectAccess::ForContextSlot(i),
1440 graph()->GetConstantUndefined());
1443 return function_context;
1447 Handle<Code> FastNewContextStub::GenerateCode() {
1448 return DoGenerateCode(this);
1453 HValue* CodeStubGraphBuilder<LoadDictionaryElementStub>::BuildCodeStub() {
1454 HValue* receiver = GetParameter(KeyedLoadIC::kReceiverIndex);
1455 HValue* key = GetParameter(KeyedLoadIC::kNameIndex);
1457 Add<HCheckSmi>(key);
1459 HValue* elements = AddLoadElements(receiver);
1461 HValue* hash = BuildElementIndexHash(key);
1463 return BuildUncheckedDictionaryElementLoad(receiver, elements, key, hash);
1467 Handle<Code> LoadDictionaryElementStub::GenerateCode() {
1468 return DoGenerateCode(this);
1473 HValue* CodeStubGraphBuilder<RegExpConstructResultStub>::BuildCodeStub() {
1474 // Determine the parameters.
1475 HValue* length = GetParameter(RegExpConstructResultStub::kLength);
1476 HValue* index = GetParameter(RegExpConstructResultStub::kIndex);
1477 HValue* input = GetParameter(RegExpConstructResultStub::kInput);
1479 info()->MarkMustNotHaveEagerFrame();
1481 return BuildRegExpConstructResult(length, index, input);
1485 Handle<Code> RegExpConstructResultStub::GenerateCode() {
1486 return DoGenerateCode(this);
1491 class CodeStubGraphBuilder<KeyedLoadGenericStub>
1492 : public CodeStubGraphBuilderBase {
1494 CodeStubGraphBuilder(Isolate* isolate, KeyedLoadGenericStub* stub)
1495 : CodeStubGraphBuilderBase(isolate, stub) {}
1498 virtual HValue* BuildCodeStub();
1500 void BuildElementsKindLimitCheck(HGraphBuilder::IfBuilder* if_builder,
1504 void BuildFastElementLoad(HGraphBuilder::IfBuilder* if_builder,
1507 HValue* instance_type,
1511 void BuildExternalElementLoad(HGraphBuilder::IfBuilder* if_builder,
1514 HValue* instance_type,
1518 KeyedLoadGenericStub* casted_stub() {
1519 return static_cast<KeyedLoadGenericStub*>(stub());
1524 void CodeStubGraphBuilder<KeyedLoadGenericStub>::BuildElementsKindLimitCheck(
1525 HGraphBuilder::IfBuilder* if_builder, HValue* bit_field2,
1526 ElementsKind kind) {
1527 ElementsKind next_kind = static_cast<ElementsKind>(kind + 1);
1528 HValue* kind_limit = Add<HConstant>(
1529 static_cast<int>(Map::ElementsKindBits::encode(next_kind)));
1531 if_builder->If<HCompareNumericAndBranch>(bit_field2, kind_limit, Token::LT);
1536 void CodeStubGraphBuilder<KeyedLoadGenericStub>::BuildFastElementLoad(
1537 HGraphBuilder::IfBuilder* if_builder, HValue* receiver, HValue* key,
1538 HValue* instance_type, HValue* bit_field2, ElementsKind kind) {
1539 DCHECK(!IsExternalArrayElementsKind(kind));
1541 BuildElementsKindLimitCheck(if_builder, bit_field2, kind);
1543 IfBuilder js_array_check(this);
1544 js_array_check.If<HCompareNumericAndBranch>(
1545 instance_type, Add<HConstant>(JS_ARRAY_TYPE), Token::EQ);
1546 js_array_check.Then();
1547 Push(BuildUncheckedMonomorphicElementAccess(receiver, key, NULL,
1549 LOAD, NEVER_RETURN_HOLE,
1551 js_array_check.Else();
1552 Push(BuildUncheckedMonomorphicElementAccess(receiver, key, NULL,
1554 LOAD, NEVER_RETURN_HOLE,
1556 js_array_check.End();
1560 void CodeStubGraphBuilder<KeyedLoadGenericStub>::BuildExternalElementLoad(
1561 HGraphBuilder::IfBuilder* if_builder, HValue* receiver, HValue* key,
1562 HValue* instance_type, HValue* bit_field2, ElementsKind kind) {
1563 DCHECK(IsExternalArrayElementsKind(kind));
1565 BuildElementsKindLimitCheck(if_builder, bit_field2, kind);
1567 Push(BuildUncheckedMonomorphicElementAccess(receiver, key, NULL,
1569 LOAD, NEVER_RETURN_HOLE,
1574 HValue* CodeStubGraphBuilder<KeyedLoadGenericStub>::BuildCodeStub() {
1575 HValue* receiver = GetParameter(KeyedLoadIC::kReceiverIndex);
1576 HValue* key = GetParameter(KeyedLoadIC::kNameIndex);
1578 // Split into a smi/integer case and unique string case.
1579 HIfContinuation index_name_split_continuation(graph()->CreateBasicBlock(),
1580 graph()->CreateBasicBlock());
1582 BuildKeyedIndexCheck(key, &index_name_split_continuation);
1584 IfBuilder index_name_split(this, &index_name_split_continuation);
1585 index_name_split.Then();
1587 // Key is an index (number)
1590 int bit_field_mask = (1 << Map::kIsAccessCheckNeeded) |
1591 (1 << Map::kHasIndexedInterceptor);
1592 BuildJSObjectCheck(receiver, bit_field_mask);
1594 HValue* map = Add<HLoadNamedField>(receiver, static_cast<HValue*>(NULL),
1595 HObjectAccess::ForMap());
1597 HValue* instance_type =
1598 Add<HLoadNamedField>(map, static_cast<HValue*>(NULL),
1599 HObjectAccess::ForMapInstanceType());
1601 HValue* bit_field2 = Add<HLoadNamedField>(map,
1602 static_cast<HValue*>(NULL),
1603 HObjectAccess::ForMapBitField2());
1605 IfBuilder kind_if(this);
1606 BuildFastElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
1607 FAST_HOLEY_ELEMENTS);
1611 BuildFastElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
1612 FAST_HOLEY_DOUBLE_ELEMENTS);
1616 // The DICTIONARY_ELEMENTS check generates a "kind_if.Then"
1617 BuildElementsKindLimitCheck(&kind_if, bit_field2, DICTIONARY_ELEMENTS);
1619 HValue* elements = AddLoadElements(receiver);
1621 HValue* hash = BuildElementIndexHash(key);
1623 Push(BuildUncheckedDictionaryElementLoad(receiver, elements, key, hash));
1627 // The SLOPPY_ARGUMENTS_ELEMENTS check generates a "kind_if.Then"
1628 BuildElementsKindLimitCheck(&kind_if, bit_field2,
1629 SLOPPY_ARGUMENTS_ELEMENTS);
1630 // Non-strict elements are not handled.
1631 Add<HDeoptimize>("non-strict elements in KeyedLoadGenericStub",
1632 Deoptimizer::EAGER);
1633 Push(graph()->GetConstant0());
1636 BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
1637 EXTERNAL_INT8_ELEMENTS);
1640 BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
1641 EXTERNAL_UINT8_ELEMENTS);
1644 BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
1645 EXTERNAL_INT16_ELEMENTS);
1648 BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
1649 EXTERNAL_UINT16_ELEMENTS);
1652 BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
1653 EXTERNAL_INT32_ELEMENTS);
1656 BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
1657 EXTERNAL_UINT32_ELEMENTS);
1660 BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
1661 EXTERNAL_FLOAT32_ELEMENTS);
1664 BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
1665 EXTERNAL_FLOAT64_ELEMENTS);
1668 BuildExternalElementLoad(&kind_if, receiver, key, instance_type, bit_field2,
1669 EXTERNAL_UINT8_CLAMPED_ELEMENTS);
1671 kind_if.ElseDeopt("ElementsKind unhandled in KeyedLoadGenericStub");
1675 index_name_split.Else();
1677 // Key is a unique string.
1680 int bit_field_mask = (1 << Map::kIsAccessCheckNeeded) |
1681 (1 << Map::kHasNamedInterceptor);
1682 BuildJSObjectCheck(receiver, bit_field_mask);
1684 HIfContinuation continuation;
1685 BuildTestForDictionaryProperties(receiver, &continuation);
1686 IfBuilder if_dict_properties(this, &continuation);
1687 if_dict_properties.Then();
1689 // Key is string, properties are dictionary mode
1690 BuildNonGlobalObjectCheck(receiver);
1692 HValue* properties = Add<HLoadNamedField>(
1693 receiver, static_cast<HValue*>(NULL),
1694 HObjectAccess::ForPropertiesPointer());
1697 Add<HLoadNamedField>(key, static_cast<HValue*>(NULL),
1698 HObjectAccess::ForNameHashField());
1700 hash = AddUncasted<HShr>(hash, Add<HConstant>(Name::kHashShift));
1702 HValue* value = BuildUncheckedDictionaryElementLoad(receiver,
1708 if_dict_properties.Else();
1710 // Key is string, properties are fast mode
1711 HValue* hash = BuildKeyedLookupCacheHash(receiver, key);
1713 ExternalReference cache_keys_ref =
1714 ExternalReference::keyed_lookup_cache_keys(isolate());
1715 HValue* cache_keys = Add<HConstant>(cache_keys_ref);
1717 HValue* map = Add<HLoadNamedField>(receiver, static_cast<HValue*>(NULL),
1718 HObjectAccess::ForMap());
1719 HValue* base_index = AddUncasted<HMul>(hash, Add<HConstant>(2));
1720 base_index->ClearFlag(HValue::kCanOverflow);
1722 HIfContinuation inline_or_runtime_continuation(
1723 graph()->CreateBasicBlock(), graph()->CreateBasicBlock());
1725 IfBuilder lookup_ifs[KeyedLookupCache::kEntriesPerBucket];
1726 for (int probe = 0; probe < KeyedLookupCache::kEntriesPerBucket;
1728 IfBuilder* lookup_if = &lookup_ifs[probe];
1729 lookup_if->Initialize(this);
1730 int probe_base = probe * KeyedLookupCache::kEntryLength;
1731 HValue* map_index = AddUncasted<HAdd>(
1733 Add<HConstant>(probe_base + KeyedLookupCache::kMapIndex));
1734 map_index->ClearFlag(HValue::kCanOverflow);
1735 HValue* key_index = AddUncasted<HAdd>(
1737 Add<HConstant>(probe_base + KeyedLookupCache::kKeyIndex));
1738 key_index->ClearFlag(HValue::kCanOverflow);
1739 HValue* map_to_check =
1740 Add<HLoadKeyed>(cache_keys, map_index, static_cast<HValue*>(NULL),
1741 FAST_ELEMENTS, NEVER_RETURN_HOLE, 0);
1742 lookup_if->If<HCompareObjectEqAndBranch>(map_to_check, map);
1744 HValue* key_to_check =
1745 Add<HLoadKeyed>(cache_keys, key_index, static_cast<HValue*>(NULL),
1746 FAST_ELEMENTS, NEVER_RETURN_HOLE, 0);
1747 lookup_if->If<HCompareObjectEqAndBranch>(key_to_check, key);
1750 ExternalReference cache_field_offsets_ref =
1751 ExternalReference::keyed_lookup_cache_field_offsets(isolate());
1752 HValue* cache_field_offsets =
1753 Add<HConstant>(cache_field_offsets_ref);
1754 HValue* index = AddUncasted<HAdd>(hash, Add<HConstant>(probe));
1755 index->ClearFlag(HValue::kCanOverflow);
1756 HValue* property_index = Add<HLoadKeyed>(
1757 cache_field_offsets, index, static_cast<HValue*>(NULL),
1758 EXTERNAL_INT32_ELEMENTS, NEVER_RETURN_HOLE, 0);
1759 Push(property_index);
1763 for (int i = 0; i < KeyedLookupCache::kEntriesPerBucket; ++i) {
1764 lookup_ifs[i].JoinContinuation(&inline_or_runtime_continuation);
1768 IfBuilder inline_or_runtime(this, &inline_or_runtime_continuation);
1769 inline_or_runtime.Then();
1771 // Found a cached index, load property inline.
1772 Push(Add<HLoadFieldByIndex>(receiver, Pop()));
1774 inline_or_runtime.Else();
1776 // KeyedLookupCache miss; call runtime.
1777 Add<HPushArguments>(receiver, key);
1778 Push(Add<HCallRuntime>(
1779 isolate()->factory()->empty_string(),
1780 Runtime::FunctionForId(Runtime::kKeyedGetProperty), 2));
1782 inline_or_runtime.End();
1784 if_dict_properties.End();
1786 index_name_split.End();
1792 Handle<Code> KeyedLoadGenericStub::GenerateCode() {
1793 return DoGenerateCode(this);
1797 } } // namespace v8::internal