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 #if V8_TARGET_ARCH_IA32
9 #include "src/base/bits.h"
10 #include "src/code-factory.h"
11 #include "src/code-stubs.h"
12 #include "src/codegen.h"
13 #include "src/cpu-profiler.h"
14 #include "src/deoptimizer.h"
15 #include "src/hydrogen-osr.h"
16 #include "src/ia32/lithium-codegen-ia32.h"
17 #include "src/ic/ic.h"
18 #include "src/ic/stub-cache.h"
23 // When invoking builtins, we need to record the safepoint in the middle of
24 // the invoke instruction sequence generated by the macro assembler.
25 class SafepointGenerator FINAL : public CallWrapper {
27 SafepointGenerator(LCodeGen* codegen,
28 LPointerMap* pointers,
29 Safepoint::DeoptMode mode)
33 virtual ~SafepointGenerator() {}
35 void BeforeCall(int call_size) const OVERRIDE {}
37 void AfterCall() const OVERRIDE {
38 codegen_->RecordSafepoint(pointers_, deopt_mode_);
43 LPointerMap* pointers_;
44 Safepoint::DeoptMode deopt_mode_;
50 bool LCodeGen::GenerateCode() {
51 LPhase phase("Z_Code generation", chunk());
55 // Open a frame scope to indicate that there is a frame on the stack. The
56 // MANUAL indicates that the scope shouldn't actually generate code to set up
57 // the frame (that is done in GeneratePrologue).
58 FrameScope frame_scope(masm_, StackFrame::MANUAL);
60 support_aligned_spilled_doubles_ = info()->IsOptimizing();
62 dynamic_frame_alignment_ = info()->IsOptimizing() &&
63 ((chunk()->num_double_slots() > 2 &&
64 !chunk()->graph()->is_recursive()) ||
65 !info()->osr_ast_id().IsNone());
67 return GeneratePrologue() &&
69 GenerateDeferredCode() &&
70 GenerateJumpTable() &&
71 GenerateSafepointTable();
75 void LCodeGen::FinishCode(Handle<Code> code) {
77 code->set_stack_slots(GetStackSlotCount());
78 code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
79 PopulateDeoptimizationData(code);
80 if (!info()->IsStub()) {
81 Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(code);
87 void LCodeGen::MakeSureStackPagesMapped(int offset) {
88 const int kPageSize = 4 * KB;
89 for (offset -= kPageSize; offset > 0; offset -= kPageSize) {
90 __ mov(Operand(esp, offset), eax);
96 void LCodeGen::SaveCallerDoubles() {
97 DCHECK(info()->saves_caller_doubles());
98 DCHECK(NeedsEagerFrame());
99 Comment(";;; Save clobbered callee double registers");
101 BitVector* doubles = chunk()->allocated_double_registers();
102 BitVector::Iterator save_iterator(doubles);
103 while (!save_iterator.Done()) {
104 __ movsd(MemOperand(esp, count * kDoubleSize),
105 XMMRegister::FromAllocationIndex(save_iterator.Current()));
106 save_iterator.Advance();
112 void LCodeGen::RestoreCallerDoubles() {
113 DCHECK(info()->saves_caller_doubles());
114 DCHECK(NeedsEagerFrame());
115 Comment(";;; Restore clobbered callee double registers");
116 BitVector* doubles = chunk()->allocated_double_registers();
117 BitVector::Iterator save_iterator(doubles);
119 while (!save_iterator.Done()) {
120 __ movsd(XMMRegister::FromAllocationIndex(save_iterator.Current()),
121 MemOperand(esp, count * kDoubleSize));
122 save_iterator.Advance();
128 bool LCodeGen::GeneratePrologue() {
129 DCHECK(is_generating());
131 if (info()->IsOptimizing()) {
132 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
135 if (strlen(FLAG_stop_at) > 0 &&
136 info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
141 // Sloppy mode functions and builtins need to replace the receiver with the
142 // global proxy when called as functions (without an explicit receiver
144 if (graph()->this_has_uses() && is_sloppy(info_->language_mode()) &&
145 !info_->is_native()) {
147 // +1 for return address.
148 int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
149 __ mov(ecx, Operand(esp, receiver_offset));
151 __ cmp(ecx, isolate()->factory()->undefined_value());
152 __ j(not_equal, &ok, Label::kNear);
154 __ mov(ecx, GlobalObjectOperand());
155 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
157 __ mov(Operand(esp, receiver_offset), ecx);
162 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
163 // Move state of dynamic frame alignment into edx.
164 __ Move(edx, Immediate(kNoAlignmentPadding));
166 Label do_not_pad, align_loop;
167 STATIC_ASSERT(kDoubleSize == 2 * kPointerSize);
168 // Align esp + 4 to a multiple of 2 * kPointerSize.
169 __ test(esp, Immediate(kPointerSize));
170 __ j(not_zero, &do_not_pad, Label::kNear);
171 __ push(Immediate(0));
173 __ mov(edx, Immediate(kAlignmentPaddingPushed));
174 // Copy arguments, receiver, and return address.
175 __ mov(ecx, Immediate(scope()->num_parameters() + 2));
177 __ bind(&align_loop);
178 __ mov(eax, Operand(ebx, 1 * kPointerSize));
179 __ mov(Operand(ebx, 0), eax);
180 __ add(Operand(ebx), Immediate(kPointerSize));
182 __ j(not_zero, &align_loop, Label::kNear);
183 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
184 __ bind(&do_not_pad);
188 info()->set_prologue_offset(masm_->pc_offset());
189 if (NeedsEagerFrame()) {
190 DCHECK(!frame_is_built_);
191 frame_is_built_ = true;
192 if (info()->IsStub()) {
195 __ Prologue(info()->IsCodePreAgingActive());
197 info()->AddNoFrameRange(0, masm_->pc_offset());
200 if (info()->IsOptimizing() &&
201 dynamic_frame_alignment_ &&
203 __ test(esp, Immediate(kPointerSize));
204 __ Assert(zero, kFrameIsExpectedToBeAligned);
207 // Reserve space for the stack slots needed by the code.
208 int slots = GetStackSlotCount();
209 DCHECK(slots != 0 || !info()->IsOptimizing());
212 if (dynamic_frame_alignment_) {
215 __ push(Immediate(kNoAlignmentPadding));
218 if (FLAG_debug_code) {
219 __ sub(Operand(esp), Immediate(slots * kPointerSize));
221 MakeSureStackPagesMapped(slots * kPointerSize);
224 __ mov(Operand(eax), Immediate(slots));
227 __ mov(MemOperand(esp, eax, times_4, 0),
228 Immediate(kSlotsZapValue));
230 __ j(not_zero, &loop);
233 __ sub(Operand(esp), Immediate(slots * kPointerSize));
235 MakeSureStackPagesMapped(slots * kPointerSize);
239 if (support_aligned_spilled_doubles_) {
240 Comment(";;; Store dynamic frame alignment tag for spilled doubles");
241 // Store dynamic frame alignment state in the first local.
242 int offset = JavaScriptFrameConstants::kDynamicAlignmentStateOffset;
243 if (dynamic_frame_alignment_) {
244 __ mov(Operand(ebp, offset), edx);
246 __ mov(Operand(ebp, offset), Immediate(kNoAlignmentPadding));
251 if (info()->saves_caller_doubles()) SaveCallerDoubles();
254 // Possibly allocate a local context.
255 int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
256 if (heap_slots > 0) {
257 Comment(";;; Allocate local context");
258 bool need_write_barrier = true;
259 // Argument to NewContext is the function, which is still in edi.
260 if (heap_slots <= FastNewContextStub::kMaximumSlots) {
261 FastNewContextStub stub(isolate(), heap_slots);
263 // Result of FastNewContextStub is always in new space.
264 need_write_barrier = false;
267 __ CallRuntime(Runtime::kNewFunctionContext, 1);
269 RecordSafepoint(Safepoint::kNoLazyDeopt);
270 // Context is returned in eax. It replaces the context passed to us.
271 // It's saved in the stack and kept live in esi.
273 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
275 // Copy parameters into context if necessary.
276 int num_parameters = scope()->num_parameters();
277 for (int i = 0; i < num_parameters; i++) {
278 Variable* var = scope()->parameter(i);
279 if (var->IsContextSlot()) {
280 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
281 (num_parameters - 1 - i) * kPointerSize;
282 // Load parameter from stack.
283 __ mov(eax, Operand(ebp, parameter_offset));
284 // Store it in the context.
285 int context_offset = Context::SlotOffset(var->index());
286 __ mov(Operand(esi, context_offset), eax);
287 // Update the write barrier. This clobbers eax and ebx.
288 if (need_write_barrier) {
289 __ RecordWriteContextSlot(esi,
294 } else if (FLAG_debug_code) {
296 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
297 __ Abort(kExpectedNewSpaceObject);
302 Comment(";;; End allocate local context");
306 if (FLAG_trace && info()->IsOptimizing()) {
307 // We have not executed any compiled code yet, so esi still holds the
309 __ CallRuntime(Runtime::kTraceEnter, 0);
311 return !is_aborted();
315 void LCodeGen::GenerateOsrPrologue() {
316 // Generate the OSR entry prologue at the first unknown OSR value, or if there
317 // are none, at the OSR entrypoint instruction.
318 if (osr_pc_offset_ >= 0) return;
320 osr_pc_offset_ = masm()->pc_offset();
322 // Move state of dynamic frame alignment into edx.
323 __ Move(edx, Immediate(kNoAlignmentPadding));
325 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
326 Label do_not_pad, align_loop;
327 // Align ebp + 4 to a multiple of 2 * kPointerSize.
328 __ test(ebp, Immediate(kPointerSize));
329 __ j(zero, &do_not_pad, Label::kNear);
330 __ push(Immediate(0));
332 __ mov(edx, Immediate(kAlignmentPaddingPushed));
334 // Move all parts of the frame over one word. The frame consists of:
335 // unoptimized frame slots, alignment state, context, frame pointer, return
336 // address, receiver, and the arguments.
337 __ mov(ecx, Immediate(scope()->num_parameters() +
338 5 + graph()->osr()->UnoptimizedFrameSlots()));
340 __ bind(&align_loop);
341 __ mov(eax, Operand(ebx, 1 * kPointerSize));
342 __ mov(Operand(ebx, 0), eax);
343 __ add(Operand(ebx), Immediate(kPointerSize));
345 __ j(not_zero, &align_loop, Label::kNear);
346 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
347 __ sub(Operand(ebp), Immediate(kPointerSize));
348 __ bind(&do_not_pad);
351 // Save the first local, which is overwritten by the alignment state.
352 Operand alignment_loc = MemOperand(ebp, -3 * kPointerSize);
353 __ push(alignment_loc);
355 // Set the dynamic frame alignment state.
356 __ mov(alignment_loc, edx);
358 // Adjust the frame size, subsuming the unoptimized frame into the
360 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
362 __ sub(esp, Immediate((slots - 1) * kPointerSize));
366 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
367 if (instr->IsCall()) {
368 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
370 if (!instr->IsLazyBailout() && !instr->IsGap()) {
371 safepoints_.BumpLastLazySafepointIndex();
376 void LCodeGen::GenerateBodyInstructionPost(LInstruction* instr) { }
379 bool LCodeGen::GenerateJumpTable() {
380 if (!jump_table_.length()) return !is_aborted();
383 Comment(";;; -------------------- Jump table --------------------");
385 for (int i = 0; i < jump_table_.length(); i++) {
386 Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
387 __ bind(&table_entry->label);
388 Address entry = table_entry->address;
389 DeoptComment(table_entry->deopt_info);
390 if (table_entry->needs_frame) {
391 DCHECK(!info()->saves_caller_doubles());
392 __ push(Immediate(ExternalReference::ForDeoptEntry(entry)));
393 __ call(&needs_frame);
395 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
396 __ call(entry, RelocInfo::RUNTIME_ENTRY);
398 info()->LogDeoptCallPosition(masm()->pc_offset(),
399 table_entry->deopt_info.inlining_id);
401 if (needs_frame.is_linked()) {
402 __ bind(&needs_frame);
405 3: return address <-- esp
410 __ sub(esp, Immediate(kPointerSize)); // Reserve space for stub marker.
411 __ push(MemOperand(esp, kPointerSize)); // Copy return address.
412 __ push(MemOperand(esp, 3 * kPointerSize)); // Copy entry address.
419 0: entry address <-- esp
421 __ mov(MemOperand(esp, 4 * kPointerSize), ebp); // Save ebp.
423 __ mov(ebp, MemOperand(ebp, StandardFrameConstants::kContextOffset));
424 __ mov(MemOperand(esp, 3 * kPointerSize), ebp);
425 // Fill ebp with the right stack frame address.
426 __ lea(ebp, MemOperand(esp, 4 * kPointerSize));
427 // This variant of deopt can only be used with stubs. Since we don't
428 // have a function pointer to install in the stack frame that we're
429 // building, install a special marker there instead.
430 DCHECK(info()->IsStub());
431 __ mov(MemOperand(esp, 2 * kPointerSize),
432 Immediate(Smi::FromInt(StackFrame::STUB)));
439 0: entry address <-- esp
441 __ ret(0); // Call the continuation without clobbering registers.
443 return !is_aborted();
447 bool LCodeGen::GenerateDeferredCode() {
448 DCHECK(is_generating());
449 if (deferred_.length() > 0) {
450 for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
451 LDeferredCode* code = deferred_[i];
454 instructions_->at(code->instruction_index())->hydrogen_value();
455 RecordAndWritePosition(
456 chunk()->graph()->SourcePositionToScriptPosition(value->position()));
458 Comment(";;; <@%d,#%d> "
459 "-------------------- Deferred %s --------------------",
460 code->instruction_index(),
461 code->instr()->hydrogen_value()->id(),
462 code->instr()->Mnemonic());
463 __ bind(code->entry());
464 if (NeedsDeferredFrame()) {
465 Comment(";;; Build frame");
466 DCHECK(!frame_is_built_);
467 DCHECK(info()->IsStub());
468 frame_is_built_ = true;
469 // Build the frame in such a way that esi isn't trashed.
470 __ push(ebp); // Caller's frame pointer.
471 __ push(Operand(ebp, StandardFrameConstants::kContextOffset));
472 __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
473 __ lea(ebp, Operand(esp, 2 * kPointerSize));
474 Comment(";;; Deferred code");
477 if (NeedsDeferredFrame()) {
478 __ bind(code->done());
479 Comment(";;; Destroy frame");
480 DCHECK(frame_is_built_);
481 frame_is_built_ = false;
485 __ jmp(code->exit());
489 // Deferred code is the last part of the instruction sequence. Mark
490 // the generated code as done unless we bailed out.
491 if (!is_aborted()) status_ = DONE;
492 return !is_aborted();
496 bool LCodeGen::GenerateSafepointTable() {
498 if (!info()->IsStub()) {
499 // For lazy deoptimization we need space to patch a call after every call.
500 // Ensure there is always space for such patching, even if the code ends
502 int target_offset = masm()->pc_offset() + Deoptimizer::patch_size();
503 while (masm()->pc_offset() < target_offset) {
507 safepoints_.Emit(masm(), GetStackSlotCount());
508 return !is_aborted();
512 Register LCodeGen::ToRegister(int index) const {
513 return Register::FromAllocationIndex(index);
517 XMMRegister LCodeGen::ToDoubleRegister(int index) const {
518 return XMMRegister::FromAllocationIndex(index);
522 Register LCodeGen::ToRegister(LOperand* op) const {
523 DCHECK(op->IsRegister());
524 return ToRegister(op->index());
528 XMMRegister LCodeGen::ToDoubleRegister(LOperand* op) const {
529 DCHECK(op->IsDoubleRegister());
530 return ToDoubleRegister(op->index());
534 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
535 return ToRepresentation(op, Representation::Integer32());
539 int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
540 const Representation& r) const {
541 HConstant* constant = chunk_->LookupConstant(op);
542 int32_t value = constant->Integer32Value();
543 if (r.IsInteger32()) return value;
544 DCHECK(r.IsSmiOrTagged());
545 return reinterpret_cast<int32_t>(Smi::FromInt(value));
549 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
550 HConstant* constant = chunk_->LookupConstant(op);
551 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
552 return constant->handle(isolate());
556 double LCodeGen::ToDouble(LConstantOperand* op) const {
557 HConstant* constant = chunk_->LookupConstant(op);
558 DCHECK(constant->HasDoubleValue());
559 return constant->DoubleValue();
563 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
564 HConstant* constant = chunk_->LookupConstant(op);
565 DCHECK(constant->HasExternalReferenceValue());
566 return constant->ExternalReferenceValue();
570 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
571 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
575 bool LCodeGen::IsSmi(LConstantOperand* op) const {
576 return chunk_->LookupLiteralRepresentation(op).IsSmi();
580 static int ArgumentsOffsetWithoutFrame(int index) {
582 return -(index + 1) * kPointerSize + kPCOnStackSize;
586 Operand LCodeGen::ToOperand(LOperand* op) const {
587 if (op->IsRegister()) return Operand(ToRegister(op));
588 if (op->IsDoubleRegister()) return Operand(ToDoubleRegister(op));
589 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
590 if (NeedsEagerFrame()) {
591 return Operand(ebp, StackSlotOffset(op->index()));
593 // Retrieve parameter without eager stack-frame relative to the
595 return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
600 Operand LCodeGen::HighOperand(LOperand* op) {
601 DCHECK(op->IsDoubleStackSlot());
602 if (NeedsEagerFrame()) {
603 return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
605 // Retrieve parameter without eager stack-frame relative to the
608 esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
613 void LCodeGen::WriteTranslation(LEnvironment* environment,
614 Translation* translation) {
615 if (environment == NULL) return;
617 // The translation includes one command per value in the environment.
618 int translation_size = environment->translation_size();
619 // The output frame height does not include the parameters.
620 int height = translation_size - environment->parameter_count();
622 WriteTranslation(environment->outer(), translation);
623 bool has_closure_id = !info()->closure().is_null() &&
624 !info()->closure().is_identical_to(environment->closure());
625 int closure_id = has_closure_id
626 ? DefineDeoptimizationLiteral(environment->closure())
627 : Translation::kSelfLiteralId;
628 switch (environment->frame_type()) {
630 translation->BeginJSFrame(environment->ast_id(), closure_id, height);
633 translation->BeginConstructStubFrame(closure_id, translation_size);
636 DCHECK(translation_size == 1);
638 translation->BeginGetterStubFrame(closure_id);
641 DCHECK(translation_size == 2);
643 translation->BeginSetterStubFrame(closure_id);
645 case ARGUMENTS_ADAPTOR:
646 translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
649 translation->BeginCompiledStubFrame();
655 int object_index = 0;
656 int dematerialized_index = 0;
657 for (int i = 0; i < translation_size; ++i) {
658 LOperand* value = environment->values()->at(i);
659 AddToTranslation(environment,
662 environment->HasTaggedValueAt(i),
663 environment->HasUint32ValueAt(i),
665 &dematerialized_index);
670 void LCodeGen::AddToTranslation(LEnvironment* environment,
671 Translation* translation,
675 int* object_index_pointer,
676 int* dematerialized_index_pointer) {
677 if (op == LEnvironment::materialization_marker()) {
678 int object_index = (*object_index_pointer)++;
679 if (environment->ObjectIsDuplicateAt(object_index)) {
680 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
681 translation->DuplicateObject(dupe_of);
684 int object_length = environment->ObjectLengthAt(object_index);
685 if (environment->ObjectIsArgumentsAt(object_index)) {
686 translation->BeginArgumentsObject(object_length);
688 translation->BeginCapturedObject(object_length);
690 int dematerialized_index = *dematerialized_index_pointer;
691 int env_offset = environment->translation_size() + dematerialized_index;
692 *dematerialized_index_pointer += object_length;
693 for (int i = 0; i < object_length; ++i) {
694 LOperand* value = environment->values()->at(env_offset + i);
695 AddToTranslation(environment,
698 environment->HasTaggedValueAt(env_offset + i),
699 environment->HasUint32ValueAt(env_offset + i),
700 object_index_pointer,
701 dematerialized_index_pointer);
706 if (op->IsStackSlot()) {
708 translation->StoreStackSlot(op->index());
709 } else if (is_uint32) {
710 translation->StoreUint32StackSlot(op->index());
712 translation->StoreInt32StackSlot(op->index());
714 } else if (op->IsDoubleStackSlot()) {
715 translation->StoreDoubleStackSlot(op->index());
716 } else if (op->IsRegister()) {
717 Register reg = ToRegister(op);
719 translation->StoreRegister(reg);
720 } else if (is_uint32) {
721 translation->StoreUint32Register(reg);
723 translation->StoreInt32Register(reg);
725 } else if (op->IsDoubleRegister()) {
726 XMMRegister reg = ToDoubleRegister(op);
727 translation->StoreDoubleRegister(reg);
728 } else if (op->IsConstantOperand()) {
729 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
730 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
731 translation->StoreLiteral(src_index);
738 void LCodeGen::CallCodeGeneric(Handle<Code> code,
739 RelocInfo::Mode mode,
741 SafepointMode safepoint_mode) {
742 DCHECK(instr != NULL);
744 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
746 // Signal that we don't inline smi code before these stubs in the
747 // optimizing code generator.
748 if (code->kind() == Code::BINARY_OP_IC ||
749 code->kind() == Code::COMPARE_IC) {
755 void LCodeGen::CallCode(Handle<Code> code,
756 RelocInfo::Mode mode,
757 LInstruction* instr) {
758 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
762 void LCodeGen::CallRuntime(const Runtime::Function* fun,
765 SaveFPRegsMode save_doubles) {
766 DCHECK(instr != NULL);
767 DCHECK(instr->HasPointerMap());
769 __ CallRuntime(fun, argc, save_doubles);
771 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
773 DCHECK(info()->is_calling());
777 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
778 if (context->IsRegister()) {
779 if (!ToRegister(context).is(esi)) {
780 __ mov(esi, ToRegister(context));
782 } else if (context->IsStackSlot()) {
783 __ mov(esi, ToOperand(context));
784 } else if (context->IsConstantOperand()) {
785 HConstant* constant =
786 chunk_->LookupConstant(LConstantOperand::cast(context));
787 __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
793 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
797 LoadContextFromDeferred(context);
799 __ CallRuntimeSaveDoubles(id);
800 RecordSafepointWithRegisters(
801 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
803 DCHECK(info()->is_calling());
807 void LCodeGen::RegisterEnvironmentForDeoptimization(
808 LEnvironment* environment, Safepoint::DeoptMode mode) {
809 environment->set_has_been_used();
810 if (!environment->HasBeenRegistered()) {
811 // Physical stack frame layout:
812 // -x ............. -4 0 ..................................... y
813 // [incoming arguments] [spill slots] [pushed outgoing arguments]
815 // Layout of the environment:
816 // 0 ..................................................... size-1
817 // [parameters] [locals] [expression stack including arguments]
819 // Layout of the translation:
820 // 0 ........................................................ size - 1 + 4
821 // [expression stack including arguments] [locals] [4 words] [parameters]
822 // |>------------ translation_size ------------<|
825 int jsframe_count = 0;
826 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
828 if (e->frame_type() == JS_FUNCTION) {
832 Translation translation(&translations_, frame_count, jsframe_count, zone());
833 WriteTranslation(environment, &translation);
834 int deoptimization_index = deoptimizations_.length();
835 int pc_offset = masm()->pc_offset();
836 environment->Register(deoptimization_index,
838 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
839 deoptimizations_.Add(environment, zone());
844 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
845 Deoptimizer::DeoptReason deopt_reason,
846 Deoptimizer::BailoutType bailout_type) {
847 LEnvironment* environment = instr->environment();
848 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
849 DCHECK(environment->HasBeenRegistered());
850 int id = environment->deoptimization_index();
851 DCHECK(info()->IsOptimizing() || info()->IsStub());
853 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
855 Abort(kBailoutWasNotPrepared);
859 if (DeoptEveryNTimes()) {
860 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
864 __ mov(eax, Operand::StaticVariable(count));
865 __ sub(eax, Immediate(1));
866 __ j(not_zero, &no_deopt, Label::kNear);
867 if (FLAG_trap_on_deopt) __ int3();
868 __ mov(eax, Immediate(FLAG_deopt_every_n_times));
869 __ mov(Operand::StaticVariable(count), eax);
872 DCHECK(frame_is_built_);
873 __ call(entry, RelocInfo::RUNTIME_ENTRY);
875 __ mov(Operand::StaticVariable(count), eax);
880 if (info()->ShouldTrapOnDeopt()) {
882 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
887 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
889 DCHECK(info()->IsStub() || frame_is_built_);
890 if (cc == no_condition && frame_is_built_) {
891 DeoptComment(deopt_info);
892 __ call(entry, RelocInfo::RUNTIME_ENTRY);
893 info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
895 Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
897 // We often have several deopts to the same entry, reuse the last
898 // jump entry if this is the case.
899 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
900 jump_table_.is_empty() ||
901 !table_entry.IsEquivalentTo(jump_table_.last())) {
902 jump_table_.Add(table_entry, zone());
904 if (cc == no_condition) {
905 __ jmp(&jump_table_.last().label);
907 __ j(cc, &jump_table_.last().label);
913 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
914 Deoptimizer::DeoptReason deopt_reason) {
915 Deoptimizer::BailoutType bailout_type = info()->IsStub()
917 : Deoptimizer::EAGER;
918 DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
922 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
923 int length = deoptimizations_.length();
924 if (length == 0) return;
925 Handle<DeoptimizationInputData> data =
926 DeoptimizationInputData::New(isolate(), length, TENURED);
928 Handle<ByteArray> translations =
929 translations_.CreateByteArray(isolate()->factory());
930 data->SetTranslationByteArray(*translations);
931 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
932 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
933 if (info_->IsOptimizing()) {
934 // Reference to shared function info does not change between phases.
935 AllowDeferredHandleDereference allow_handle_dereference;
936 data->SetSharedFunctionInfo(*info_->shared_info());
938 data->SetSharedFunctionInfo(Smi::FromInt(0));
940 data->SetWeakCellCache(Smi::FromInt(0));
942 Handle<FixedArray> literals =
943 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
944 { AllowDeferredHandleDereference copy_handles;
945 for (int i = 0; i < deoptimization_literals_.length(); i++) {
946 literals->set(i, *deoptimization_literals_[i]);
948 data->SetLiteralArray(*literals);
951 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
952 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
954 // Populate the deoptimization entries.
955 for (int i = 0; i < length; i++) {
956 LEnvironment* env = deoptimizations_[i];
957 data->SetAstId(i, env->ast_id());
958 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
959 data->SetArgumentsStackHeight(i,
960 Smi::FromInt(env->arguments_stack_height()));
961 data->SetPc(i, Smi::FromInt(env->pc_offset()));
963 code->set_deoptimization_data(*data);
967 int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
968 int result = deoptimization_literals_.length();
969 for (int i = 0; i < deoptimization_literals_.length(); ++i) {
970 if (deoptimization_literals_[i].is_identical_to(literal)) return i;
972 deoptimization_literals_.Add(literal, zone());
977 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
978 DCHECK(deoptimization_literals_.length() == 0);
980 const ZoneList<Handle<JSFunction> >* inlined_closures =
981 chunk()->inlined_closures();
983 for (int i = 0, length = inlined_closures->length();
986 DefineDeoptimizationLiteral(inlined_closures->at(i));
989 inlined_function_count_ = deoptimization_literals_.length();
993 void LCodeGen::RecordSafepointWithLazyDeopt(
994 LInstruction* instr, SafepointMode safepoint_mode) {
995 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
996 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
998 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
999 RecordSafepointWithRegisters(
1000 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
1005 void LCodeGen::RecordSafepoint(
1006 LPointerMap* pointers,
1007 Safepoint::Kind kind,
1009 Safepoint::DeoptMode deopt_mode) {
1010 DCHECK(kind == expected_safepoint_kind_);
1011 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
1012 Safepoint safepoint =
1013 safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
1014 for (int i = 0; i < operands->length(); i++) {
1015 LOperand* pointer = operands->at(i);
1016 if (pointer->IsStackSlot()) {
1017 safepoint.DefinePointerSlot(pointer->index(), zone());
1018 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
1019 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
1025 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
1026 Safepoint::DeoptMode mode) {
1027 RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
1031 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
1032 LPointerMap empty_pointers(zone());
1033 RecordSafepoint(&empty_pointers, mode);
1037 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
1039 Safepoint::DeoptMode mode) {
1040 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1044 void LCodeGen::RecordAndWritePosition(int position) {
1045 if (position == RelocInfo::kNoPosition) return;
1046 masm()->positions_recorder()->RecordPosition(position);
1047 masm()->positions_recorder()->WriteRecordedPositions();
1051 static const char* LabelType(LLabel* label) {
1052 if (label->is_loop_header()) return " (loop header)";
1053 if (label->is_osr_entry()) return " (OSR entry)";
1058 void LCodeGen::DoLabel(LLabel* label) {
1059 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1060 current_instruction_,
1061 label->hydrogen_value()->id(),
1064 __ bind(label->label());
1065 current_block_ = label->block_id();
1070 void LCodeGen::DoParallelMove(LParallelMove* move) {
1071 resolver_.Resolve(move);
1075 void LCodeGen::DoGap(LGap* gap) {
1076 for (int i = LGap::FIRST_INNER_POSITION;
1077 i <= LGap::LAST_INNER_POSITION;
1079 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1080 LParallelMove* move = gap->GetParallelMove(inner_pos);
1081 if (move != NULL) DoParallelMove(move);
1086 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1091 void LCodeGen::DoParameter(LParameter* instr) {
1096 void LCodeGen::DoCallStub(LCallStub* instr) {
1097 DCHECK(ToRegister(instr->context()).is(esi));
1098 DCHECK(ToRegister(instr->result()).is(eax));
1099 switch (instr->hydrogen()->major_key()) {
1100 case CodeStub::RegExpExec: {
1101 RegExpExecStub stub(isolate());
1102 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1105 case CodeStub::SubString: {
1106 SubStringStub stub(isolate());
1107 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1110 case CodeStub::StringCompare: {
1111 StringCompareStub stub(isolate());
1112 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1121 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1122 GenerateOsrPrologue();
1126 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1127 Register dividend = ToRegister(instr->dividend());
1128 int32_t divisor = instr->divisor();
1129 DCHECK(dividend.is(ToRegister(instr->result())));
1131 // Theoretically, a variation of the branch-free code for integer division by
1132 // a power of 2 (calculating the remainder via an additional multiplication
1133 // (which gets simplified to an 'and') and subtraction) should be faster, and
1134 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1135 // indicate that positive dividends are heavily favored, so the branching
1136 // version performs better.
1137 HMod* hmod = instr->hydrogen();
1138 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1139 Label dividend_is_not_negative, done;
1140 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1141 __ test(dividend, dividend);
1142 __ j(not_sign, ÷nd_is_not_negative, Label::kNear);
1143 // Note that this is correct even for kMinInt operands.
1145 __ and_(dividend, mask);
1147 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1148 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1150 __ jmp(&done, Label::kNear);
1153 __ bind(÷nd_is_not_negative);
1154 __ and_(dividend, mask);
1159 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1160 Register dividend = ToRegister(instr->dividend());
1161 int32_t divisor = instr->divisor();
1162 DCHECK(ToRegister(instr->result()).is(eax));
1165 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1169 __ TruncatingDiv(dividend, Abs(divisor));
1170 __ imul(edx, edx, Abs(divisor));
1171 __ mov(eax, dividend);
1174 // Check for negative zero.
1175 HMod* hmod = instr->hydrogen();
1176 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1177 Label remainder_not_zero;
1178 __ j(not_zero, &remainder_not_zero, Label::kNear);
1179 __ cmp(dividend, Immediate(0));
1180 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1181 __ bind(&remainder_not_zero);
1186 void LCodeGen::DoModI(LModI* instr) {
1187 HMod* hmod = instr->hydrogen();
1189 Register left_reg = ToRegister(instr->left());
1190 DCHECK(left_reg.is(eax));
1191 Register right_reg = ToRegister(instr->right());
1192 DCHECK(!right_reg.is(eax));
1193 DCHECK(!right_reg.is(edx));
1194 Register result_reg = ToRegister(instr->result());
1195 DCHECK(result_reg.is(edx));
1198 // Check for x % 0, idiv would signal a divide error. We have to
1199 // deopt in this case because we can't return a NaN.
1200 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1201 __ test(right_reg, Operand(right_reg));
1202 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1205 // Check for kMinInt % -1, idiv would signal a divide error. We
1206 // have to deopt if we care about -0, because we can't return that.
1207 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1208 Label no_overflow_possible;
1209 __ cmp(left_reg, kMinInt);
1210 __ j(not_equal, &no_overflow_possible, Label::kNear);
1211 __ cmp(right_reg, -1);
1212 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1213 DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1215 __ j(not_equal, &no_overflow_possible, Label::kNear);
1216 __ Move(result_reg, Immediate(0));
1217 __ jmp(&done, Label::kNear);
1219 __ bind(&no_overflow_possible);
1222 // Sign extend dividend in eax into edx:eax.
1225 // If we care about -0, test if the dividend is <0 and the result is 0.
1226 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1227 Label positive_left;
1228 __ test(left_reg, Operand(left_reg));
1229 __ j(not_sign, &positive_left, Label::kNear);
1231 __ test(result_reg, Operand(result_reg));
1232 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1233 __ jmp(&done, Label::kNear);
1234 __ bind(&positive_left);
1241 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1242 Register dividend = ToRegister(instr->dividend());
1243 int32_t divisor = instr->divisor();
1244 Register result = ToRegister(instr->result());
1245 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1246 DCHECK(!result.is(dividend));
1248 // Check for (0 / -x) that will produce negative zero.
1249 HDiv* hdiv = instr->hydrogen();
1250 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1251 __ test(dividend, dividend);
1252 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1254 // Check for (kMinInt / -1).
1255 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1256 __ cmp(dividend, kMinInt);
1257 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1259 // Deoptimize if remainder will not be 0.
1260 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1261 divisor != 1 && divisor != -1) {
1262 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1263 __ test(dividend, Immediate(mask));
1264 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1266 __ Move(result, dividend);
1267 int32_t shift = WhichPowerOf2Abs(divisor);
1269 // The arithmetic shift is always OK, the 'if' is an optimization only.
1270 if (shift > 1) __ sar(result, 31);
1271 __ shr(result, 32 - shift);
1272 __ add(result, dividend);
1273 __ sar(result, shift);
1275 if (divisor < 0) __ neg(result);
1279 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1280 Register dividend = ToRegister(instr->dividend());
1281 int32_t divisor = instr->divisor();
1282 DCHECK(ToRegister(instr->result()).is(edx));
1285 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1289 // Check for (0 / -x) that will produce negative zero.
1290 HDiv* hdiv = instr->hydrogen();
1291 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1292 __ test(dividend, dividend);
1293 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1296 __ TruncatingDiv(dividend, Abs(divisor));
1297 if (divisor < 0) __ neg(edx);
1299 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1301 __ imul(eax, eax, divisor);
1302 __ sub(eax, dividend);
1303 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1308 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1309 void LCodeGen::DoDivI(LDivI* instr) {
1310 HBinaryOperation* hdiv = instr->hydrogen();
1311 Register dividend = ToRegister(instr->dividend());
1312 Register divisor = ToRegister(instr->divisor());
1313 Register remainder = ToRegister(instr->temp());
1314 DCHECK(dividend.is(eax));
1315 DCHECK(remainder.is(edx));
1316 DCHECK(ToRegister(instr->result()).is(eax));
1317 DCHECK(!divisor.is(eax));
1318 DCHECK(!divisor.is(edx));
1321 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1322 __ test(divisor, divisor);
1323 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1326 // Check for (0 / -x) that will produce negative zero.
1327 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1328 Label dividend_not_zero;
1329 __ test(dividend, dividend);
1330 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1331 __ test(divisor, divisor);
1332 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1333 __ bind(÷nd_not_zero);
1336 // Check for (kMinInt / -1).
1337 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1338 Label dividend_not_min_int;
1339 __ cmp(dividend, kMinInt);
1340 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1341 __ cmp(divisor, -1);
1342 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1343 __ bind(÷nd_not_min_int);
1346 // Sign extend to edx (= remainder).
1350 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1351 // Deoptimize if remainder is not 0.
1352 __ test(remainder, remainder);
1353 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1358 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1359 Register dividend = ToRegister(instr->dividend());
1360 int32_t divisor = instr->divisor();
1361 DCHECK(dividend.is(ToRegister(instr->result())));
1363 // If the divisor is positive, things are easy: There can be no deopts and we
1364 // can simply do an arithmetic right shift.
1365 if (divisor == 1) return;
1366 int32_t shift = WhichPowerOf2Abs(divisor);
1368 __ sar(dividend, shift);
1372 // If the divisor is negative, we have to negate and handle edge cases.
1374 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1375 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1378 // Dividing by -1 is basically negation, unless we overflow.
1379 if (divisor == -1) {
1380 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1381 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1386 // If the negation could not overflow, simply shifting is OK.
1387 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1388 __ sar(dividend, shift);
1392 Label not_kmin_int, done;
1393 __ j(no_overflow, ¬_kmin_int, Label::kNear);
1394 __ mov(dividend, Immediate(kMinInt / divisor));
1395 __ jmp(&done, Label::kNear);
1396 __ bind(¬_kmin_int);
1397 __ sar(dividend, shift);
1402 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1403 Register dividend = ToRegister(instr->dividend());
1404 int32_t divisor = instr->divisor();
1405 DCHECK(ToRegister(instr->result()).is(edx));
1408 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1412 // Check for (0 / -x) that will produce negative zero.
1413 HMathFloorOfDiv* hdiv = instr->hydrogen();
1414 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1415 __ test(dividend, dividend);
1416 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1419 // Easy case: We need no dynamic check for the dividend and the flooring
1420 // division is the same as the truncating division.
1421 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1422 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1423 __ TruncatingDiv(dividend, Abs(divisor));
1424 if (divisor < 0) __ neg(edx);
1428 // In the general case we may need to adjust before and after the truncating
1429 // division to get a flooring division.
1430 Register temp = ToRegister(instr->temp3());
1431 DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1432 Label needs_adjustment, done;
1433 __ cmp(dividend, Immediate(0));
1434 __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1435 __ TruncatingDiv(dividend, Abs(divisor));
1436 if (divisor < 0) __ neg(edx);
1437 __ jmp(&done, Label::kNear);
1438 __ bind(&needs_adjustment);
1439 __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1440 __ TruncatingDiv(temp, Abs(divisor));
1441 if (divisor < 0) __ neg(edx);
1447 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1448 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1449 HBinaryOperation* hdiv = instr->hydrogen();
1450 Register dividend = ToRegister(instr->dividend());
1451 Register divisor = ToRegister(instr->divisor());
1452 Register remainder = ToRegister(instr->temp());
1453 Register result = ToRegister(instr->result());
1454 DCHECK(dividend.is(eax));
1455 DCHECK(remainder.is(edx));
1456 DCHECK(result.is(eax));
1457 DCHECK(!divisor.is(eax));
1458 DCHECK(!divisor.is(edx));
1461 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1462 __ test(divisor, divisor);
1463 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1466 // Check for (0 / -x) that will produce negative zero.
1467 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1468 Label dividend_not_zero;
1469 __ test(dividend, dividend);
1470 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1471 __ test(divisor, divisor);
1472 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1473 __ bind(÷nd_not_zero);
1476 // Check for (kMinInt / -1).
1477 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1478 Label dividend_not_min_int;
1479 __ cmp(dividend, kMinInt);
1480 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1481 __ cmp(divisor, -1);
1482 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1483 __ bind(÷nd_not_min_int);
1486 // Sign extend to edx (= remainder).
1491 __ test(remainder, remainder);
1492 __ j(zero, &done, Label::kNear);
1493 __ xor_(remainder, divisor);
1494 __ sar(remainder, 31);
1495 __ add(result, remainder);
1500 void LCodeGen::DoMulI(LMulI* instr) {
1501 Register left = ToRegister(instr->left());
1502 LOperand* right = instr->right();
1504 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1505 __ mov(ToRegister(instr->temp()), left);
1508 if (right->IsConstantOperand()) {
1509 // Try strength reductions on the multiplication.
1510 // All replacement instructions are at most as long as the imul
1511 // and have better latency.
1512 int constant = ToInteger32(LConstantOperand::cast(right));
1513 if (constant == -1) {
1515 } else if (constant == 0) {
1516 __ xor_(left, Operand(left));
1517 } else if (constant == 2) {
1518 __ add(left, Operand(left));
1519 } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1520 // If we know that the multiplication can't overflow, it's safe to
1521 // use instructions that don't set the overflow flag for the
1528 __ lea(left, Operand(left, left, times_2, 0));
1534 __ lea(left, Operand(left, left, times_4, 0));
1540 __ lea(left, Operand(left, left, times_8, 0));
1546 __ imul(left, left, constant);
1550 __ imul(left, left, constant);
1553 if (instr->hydrogen()->representation().IsSmi()) {
1556 __ imul(left, ToOperand(right));
1559 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1560 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1563 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1564 // Bail out if the result is supposed to be negative zero.
1566 __ test(left, Operand(left));
1567 __ j(not_zero, &done, Label::kNear);
1568 if (right->IsConstantOperand()) {
1569 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1570 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1571 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1572 __ cmp(ToRegister(instr->temp()), Immediate(0));
1573 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1576 // Test the non-zero operand for negative sign.
1577 __ or_(ToRegister(instr->temp()), ToOperand(right));
1578 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1585 void LCodeGen::DoBitI(LBitI* instr) {
1586 LOperand* left = instr->left();
1587 LOperand* right = instr->right();
1588 DCHECK(left->Equals(instr->result()));
1589 DCHECK(left->IsRegister());
1591 if (right->IsConstantOperand()) {
1592 int32_t right_operand =
1593 ToRepresentation(LConstantOperand::cast(right),
1594 instr->hydrogen()->representation());
1595 switch (instr->op()) {
1596 case Token::BIT_AND:
1597 __ and_(ToRegister(left), right_operand);
1600 __ or_(ToRegister(left), right_operand);
1602 case Token::BIT_XOR:
1603 if (right_operand == int32_t(~0)) {
1604 __ not_(ToRegister(left));
1606 __ xor_(ToRegister(left), right_operand);
1614 switch (instr->op()) {
1615 case Token::BIT_AND:
1616 __ and_(ToRegister(left), ToOperand(right));
1619 __ or_(ToRegister(left), ToOperand(right));
1621 case Token::BIT_XOR:
1622 __ xor_(ToRegister(left), ToOperand(right));
1632 void LCodeGen::DoShiftI(LShiftI* instr) {
1633 LOperand* left = instr->left();
1634 LOperand* right = instr->right();
1635 DCHECK(left->Equals(instr->result()));
1636 DCHECK(left->IsRegister());
1637 if (right->IsRegister()) {
1638 DCHECK(ToRegister(right).is(ecx));
1640 switch (instr->op()) {
1642 __ ror_cl(ToRegister(left));
1645 __ sar_cl(ToRegister(left));
1648 __ shr_cl(ToRegister(left));
1649 if (instr->can_deopt()) {
1650 __ test(ToRegister(left), ToRegister(left));
1651 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1655 __ shl_cl(ToRegister(left));
1662 int value = ToInteger32(LConstantOperand::cast(right));
1663 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1664 switch (instr->op()) {
1666 if (shift_count == 0 && instr->can_deopt()) {
1667 __ test(ToRegister(left), ToRegister(left));
1668 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1670 __ ror(ToRegister(left), shift_count);
1674 if (shift_count != 0) {
1675 __ sar(ToRegister(left), shift_count);
1679 if (shift_count != 0) {
1680 __ shr(ToRegister(left), shift_count);
1681 } else if (instr->can_deopt()) {
1682 __ test(ToRegister(left), ToRegister(left));
1683 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1687 if (shift_count != 0) {
1688 if (instr->hydrogen_value()->representation().IsSmi() &&
1689 instr->can_deopt()) {
1690 if (shift_count != 1) {
1691 __ shl(ToRegister(left), shift_count - 1);
1693 __ SmiTag(ToRegister(left));
1694 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1696 __ shl(ToRegister(left), shift_count);
1708 void LCodeGen::DoSubI(LSubI* instr) {
1709 LOperand* left = instr->left();
1710 LOperand* right = instr->right();
1711 DCHECK(left->Equals(instr->result()));
1713 if (right->IsConstantOperand()) {
1714 __ sub(ToOperand(left),
1715 ToImmediate(right, instr->hydrogen()->representation()));
1717 __ sub(ToRegister(left), ToOperand(right));
1719 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1720 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1725 void LCodeGen::DoConstantI(LConstantI* instr) {
1726 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1730 void LCodeGen::DoConstantS(LConstantS* instr) {
1731 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1735 void LCodeGen::DoConstantD(LConstantD* instr) {
1736 uint64_t const bits = instr->bits();
1737 uint32_t const lower = static_cast<uint32_t>(bits);
1738 uint32_t const upper = static_cast<uint32_t>(bits >> 32);
1739 DCHECK(instr->result()->IsDoubleRegister());
1741 XMMRegister result = ToDoubleRegister(instr->result());
1743 __ xorps(result, result);
1745 Register temp = ToRegister(instr->temp());
1746 if (CpuFeatures::IsSupported(SSE4_1)) {
1747 CpuFeatureScope scope2(masm(), SSE4_1);
1749 __ Move(temp, Immediate(lower));
1750 __ movd(result, Operand(temp));
1751 __ Move(temp, Immediate(upper));
1752 __ pinsrd(result, Operand(temp), 1);
1754 __ xorps(result, result);
1755 __ Move(temp, Immediate(upper));
1756 __ pinsrd(result, Operand(temp), 1);
1759 __ Move(temp, Immediate(upper));
1760 __ movd(result, Operand(temp));
1761 __ psllq(result, 32);
1763 XMMRegister xmm_scratch = double_scratch0();
1764 __ Move(temp, Immediate(lower));
1765 __ movd(xmm_scratch, Operand(temp));
1766 __ orps(result, xmm_scratch);
1773 void LCodeGen::DoConstantE(LConstantE* instr) {
1774 __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
1778 void LCodeGen::DoConstantT(LConstantT* instr) {
1779 Register reg = ToRegister(instr->result());
1780 Handle<Object> object = instr->value(isolate());
1781 AllowDeferredHandleDereference smi_check;
1782 __ LoadObject(reg, object);
1786 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
1787 Register result = ToRegister(instr->result());
1788 Register map = ToRegister(instr->value());
1789 __ EnumLength(result, map);
1793 void LCodeGen::DoDateField(LDateField* instr) {
1794 Register object = ToRegister(instr->date());
1795 Register result = ToRegister(instr->result());
1796 Register scratch = ToRegister(instr->temp());
1797 Smi* index = instr->index();
1798 Label runtime, done;
1799 DCHECK(object.is(result));
1800 DCHECK(object.is(eax));
1802 __ test(object, Immediate(kSmiTagMask));
1803 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
1804 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
1805 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotADateObject);
1807 if (index->value() == 0) {
1808 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
1810 if (index->value() < JSDate::kFirstUncachedField) {
1811 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
1812 __ mov(scratch, Operand::StaticVariable(stamp));
1813 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
1814 __ j(not_equal, &runtime, Label::kNear);
1815 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
1816 kPointerSize * index->value()));
1817 __ jmp(&done, Label::kNear);
1820 __ PrepareCallCFunction(2, scratch);
1821 __ mov(Operand(esp, 0), object);
1822 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
1823 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
1829 Operand LCodeGen::BuildSeqStringOperand(Register string,
1831 String::Encoding encoding) {
1832 if (index->IsConstantOperand()) {
1833 int offset = ToRepresentation(LConstantOperand::cast(index),
1834 Representation::Integer32());
1835 if (encoding == String::TWO_BYTE_ENCODING) {
1836 offset *= kUC16Size;
1838 STATIC_ASSERT(kCharSize == 1);
1839 return FieldOperand(string, SeqString::kHeaderSize + offset);
1841 return FieldOperand(
1842 string, ToRegister(index),
1843 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
1844 SeqString::kHeaderSize);
1848 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
1849 String::Encoding encoding = instr->hydrogen()->encoding();
1850 Register result = ToRegister(instr->result());
1851 Register string = ToRegister(instr->string());
1853 if (FLAG_debug_code) {
1855 __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
1856 __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
1858 __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
1859 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1860 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1861 __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
1862 ? one_byte_seq_type : two_byte_seq_type));
1863 __ Check(equal, kUnexpectedStringType);
1867 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1868 if (encoding == String::ONE_BYTE_ENCODING) {
1869 __ movzx_b(result, operand);
1871 __ movzx_w(result, operand);
1876 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
1877 String::Encoding encoding = instr->hydrogen()->encoding();
1878 Register string = ToRegister(instr->string());
1880 if (FLAG_debug_code) {
1881 Register value = ToRegister(instr->value());
1882 Register index = ToRegister(instr->index());
1883 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1884 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1886 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
1887 ? one_byte_seq_type : two_byte_seq_type;
1888 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
1891 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1892 if (instr->value()->IsConstantOperand()) {
1893 int value = ToRepresentation(LConstantOperand::cast(instr->value()),
1894 Representation::Integer32());
1895 DCHECK_LE(0, value);
1896 if (encoding == String::ONE_BYTE_ENCODING) {
1897 DCHECK_LE(value, String::kMaxOneByteCharCode);
1898 __ mov_b(operand, static_cast<int8_t>(value));
1900 DCHECK_LE(value, String::kMaxUtf16CodeUnit);
1901 __ mov_w(operand, static_cast<int16_t>(value));
1904 Register value = ToRegister(instr->value());
1905 if (encoding == String::ONE_BYTE_ENCODING) {
1906 __ mov_b(operand, value);
1908 __ mov_w(operand, value);
1914 void LCodeGen::DoAddI(LAddI* instr) {
1915 LOperand* left = instr->left();
1916 LOperand* right = instr->right();
1918 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
1919 if (right->IsConstantOperand()) {
1920 int32_t offset = ToRepresentation(LConstantOperand::cast(right),
1921 instr->hydrogen()->representation());
1922 __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
1924 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
1925 __ lea(ToRegister(instr->result()), address);
1928 if (right->IsConstantOperand()) {
1929 __ add(ToOperand(left),
1930 ToImmediate(right, instr->hydrogen()->representation()));
1932 __ add(ToRegister(left), ToOperand(right));
1934 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1935 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1941 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
1942 LOperand* left = instr->left();
1943 LOperand* right = instr->right();
1944 DCHECK(left->Equals(instr->result()));
1945 HMathMinMax::Operation operation = instr->hydrogen()->operation();
1946 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
1948 Condition condition = (operation == HMathMinMax::kMathMin)
1951 if (right->IsConstantOperand()) {
1952 Operand left_op = ToOperand(left);
1953 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
1954 instr->hydrogen()->representation());
1955 __ cmp(left_op, immediate);
1956 __ j(condition, &return_left, Label::kNear);
1957 __ mov(left_op, immediate);
1959 Register left_reg = ToRegister(left);
1960 Operand right_op = ToOperand(right);
1961 __ cmp(left_reg, right_op);
1962 __ j(condition, &return_left, Label::kNear);
1963 __ mov(left_reg, right_op);
1965 __ bind(&return_left);
1967 DCHECK(instr->hydrogen()->representation().IsDouble());
1968 Label check_nan_left, check_zero, return_left, return_right;
1969 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
1970 XMMRegister left_reg = ToDoubleRegister(left);
1971 XMMRegister right_reg = ToDoubleRegister(right);
1972 __ ucomisd(left_reg, right_reg);
1973 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
1974 __ j(equal, &check_zero, Label::kNear); // left == right.
1975 __ j(condition, &return_left, Label::kNear);
1976 __ jmp(&return_right, Label::kNear);
1978 __ bind(&check_zero);
1979 XMMRegister xmm_scratch = double_scratch0();
1980 __ xorps(xmm_scratch, xmm_scratch);
1981 __ ucomisd(left_reg, xmm_scratch);
1982 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
1983 // At this point, both left and right are either 0 or -0.
1984 if (operation == HMathMinMax::kMathMin) {
1985 __ orpd(left_reg, right_reg);
1987 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
1988 __ addsd(left_reg, right_reg);
1990 __ jmp(&return_left, Label::kNear);
1992 __ bind(&check_nan_left);
1993 __ ucomisd(left_reg, left_reg); // NaN check.
1994 __ j(parity_even, &return_left, Label::kNear); // left == NaN.
1995 __ bind(&return_right);
1996 __ movaps(left_reg, right_reg);
1998 __ bind(&return_left);
2003 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
2004 XMMRegister left = ToDoubleRegister(instr->left());
2005 XMMRegister right = ToDoubleRegister(instr->right());
2006 XMMRegister result = ToDoubleRegister(instr->result());
2007 switch (instr->op()) {
2009 if (CpuFeatures::IsSupported(AVX)) {
2010 CpuFeatureScope scope(masm(), AVX);
2011 __ vaddsd(result, left, right);
2013 DCHECK(result.is(left));
2014 __ addsd(left, right);
2018 if (CpuFeatures::IsSupported(AVX)) {
2019 CpuFeatureScope scope(masm(), AVX);
2020 __ vsubsd(result, left, right);
2022 DCHECK(result.is(left));
2023 __ subsd(left, right);
2027 if (CpuFeatures::IsSupported(AVX)) {
2028 CpuFeatureScope scope(masm(), AVX);
2029 __ vmulsd(result, left, right);
2031 DCHECK(result.is(left));
2032 __ mulsd(left, right);
2036 if (CpuFeatures::IsSupported(AVX)) {
2037 CpuFeatureScope scope(masm(), AVX);
2038 __ vdivsd(result, left, right);
2040 DCHECK(result.is(left));
2041 __ divsd(left, right);
2042 // Don't delete this mov. It may improve performance on some CPUs,
2043 // when there is a mulsd depending on the result
2044 __ movaps(left, left);
2048 // Pass two doubles as arguments on the stack.
2049 __ PrepareCallCFunction(4, eax);
2050 __ movsd(Operand(esp, 0 * kDoubleSize), left);
2051 __ movsd(Operand(esp, 1 * kDoubleSize), right);
2053 ExternalReference::mod_two_doubles_operation(isolate()),
2056 // Return value is in st(0) on ia32.
2057 // Store it into the result register.
2058 __ sub(Operand(esp), Immediate(kDoubleSize));
2059 __ fstp_d(Operand(esp, 0));
2060 __ movsd(result, Operand(esp, 0));
2061 __ add(Operand(esp), Immediate(kDoubleSize));
2071 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2072 DCHECK(ToRegister(instr->context()).is(esi));
2073 DCHECK(ToRegister(instr->left()).is(edx));
2074 DCHECK(ToRegister(instr->right()).is(eax));
2075 DCHECK(ToRegister(instr->result()).is(eax));
2077 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), instr->op()).code();
2078 CallCode(code, RelocInfo::CODE_TARGET, instr);
2082 template<class InstrType>
2083 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2084 int left_block = instr->TrueDestination(chunk_);
2085 int right_block = instr->FalseDestination(chunk_);
2087 int next_block = GetNextEmittedBlock();
2089 if (right_block == left_block || cc == no_condition) {
2090 EmitGoto(left_block);
2091 } else if (left_block == next_block) {
2092 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2093 } else if (right_block == next_block) {
2094 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2096 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2097 __ jmp(chunk_->GetAssemblyLabel(right_block));
2102 template<class InstrType>
2103 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2104 int false_block = instr->FalseDestination(chunk_);
2105 if (cc == no_condition) {
2106 __ jmp(chunk_->GetAssemblyLabel(false_block));
2108 __ j(cc, chunk_->GetAssemblyLabel(false_block));
2113 void LCodeGen::DoBranch(LBranch* instr) {
2114 Representation r = instr->hydrogen()->value()->representation();
2115 if (r.IsSmiOrInteger32()) {
2116 Register reg = ToRegister(instr->value());
2117 __ test(reg, Operand(reg));
2118 EmitBranch(instr, not_zero);
2119 } else if (r.IsDouble()) {
2120 DCHECK(!info()->IsStub());
2121 XMMRegister reg = ToDoubleRegister(instr->value());
2122 XMMRegister xmm_scratch = double_scratch0();
2123 __ xorps(xmm_scratch, xmm_scratch);
2124 __ ucomisd(reg, xmm_scratch);
2125 EmitBranch(instr, not_equal);
2127 DCHECK(r.IsTagged());
2128 Register reg = ToRegister(instr->value());
2129 HType type = instr->hydrogen()->value()->type();
2130 if (type.IsBoolean()) {
2131 DCHECK(!info()->IsStub());
2132 __ cmp(reg, factory()->true_value());
2133 EmitBranch(instr, equal);
2134 } else if (type.IsSmi()) {
2135 DCHECK(!info()->IsStub());
2136 __ test(reg, Operand(reg));
2137 EmitBranch(instr, not_equal);
2138 } else if (type.IsJSArray()) {
2139 DCHECK(!info()->IsStub());
2140 EmitBranch(instr, no_condition);
2141 } else if (type.IsHeapNumber()) {
2142 DCHECK(!info()->IsStub());
2143 XMMRegister xmm_scratch = double_scratch0();
2144 __ xorps(xmm_scratch, xmm_scratch);
2145 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2146 EmitBranch(instr, not_equal);
2147 } else if (type.IsString()) {
2148 DCHECK(!info()->IsStub());
2149 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2150 EmitBranch(instr, not_equal);
2152 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2153 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2155 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2156 // undefined -> false.
2157 __ cmp(reg, factory()->undefined_value());
2158 __ j(equal, instr->FalseLabel(chunk_));
2160 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2162 __ cmp(reg, factory()->true_value());
2163 __ j(equal, instr->TrueLabel(chunk_));
2165 __ cmp(reg, factory()->false_value());
2166 __ j(equal, instr->FalseLabel(chunk_));
2168 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2170 __ cmp(reg, factory()->null_value());
2171 __ j(equal, instr->FalseLabel(chunk_));
2174 if (expected.Contains(ToBooleanStub::SMI)) {
2175 // Smis: 0 -> false, all other -> true.
2176 __ test(reg, Operand(reg));
2177 __ j(equal, instr->FalseLabel(chunk_));
2178 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2179 } else if (expected.NeedsMap()) {
2180 // If we need a map later and have a Smi -> deopt.
2181 __ test(reg, Immediate(kSmiTagMask));
2182 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2185 Register map = no_reg; // Keep the compiler happy.
2186 if (expected.NeedsMap()) {
2187 map = ToRegister(instr->temp());
2188 DCHECK(!map.is(reg));
2189 __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2191 if (expected.CanBeUndetectable()) {
2192 // Undetectable -> false.
2193 __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2194 1 << Map::kIsUndetectable);
2195 __ j(not_zero, instr->FalseLabel(chunk_));
2199 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2200 // spec object -> true.
2201 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2202 __ j(above_equal, instr->TrueLabel(chunk_));
2205 if (expected.Contains(ToBooleanStub::STRING)) {
2206 // String value -> false iff empty.
2208 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2209 __ j(above_equal, ¬_string, Label::kNear);
2210 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2211 __ j(not_zero, instr->TrueLabel(chunk_));
2212 __ jmp(instr->FalseLabel(chunk_));
2213 __ bind(¬_string);
2216 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2217 // Symbol value -> true.
2218 __ CmpInstanceType(map, SYMBOL_TYPE);
2219 __ j(equal, instr->TrueLabel(chunk_));
2222 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2223 // heap number -> false iff +0, -0, or NaN.
2224 Label not_heap_number;
2225 __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2226 factory()->heap_number_map());
2227 __ j(not_equal, ¬_heap_number, Label::kNear);
2228 XMMRegister xmm_scratch = double_scratch0();
2229 __ xorps(xmm_scratch, xmm_scratch);
2230 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2231 __ j(zero, instr->FalseLabel(chunk_));
2232 __ jmp(instr->TrueLabel(chunk_));
2233 __ bind(¬_heap_number);
2236 if (!expected.IsGeneric()) {
2237 // We've seen something for the first time -> deopt.
2238 // This can only happen if we are not generic already.
2239 DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2246 void LCodeGen::EmitGoto(int block) {
2247 if (!IsNextEmittedBlock(block)) {
2248 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2253 void LCodeGen::DoGoto(LGoto* instr) {
2254 EmitGoto(instr->block_id());
2258 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2259 Condition cond = no_condition;
2262 case Token::EQ_STRICT:
2266 case Token::NE_STRICT:
2270 cond = is_unsigned ? below : less;
2273 cond = is_unsigned ? above : greater;
2276 cond = is_unsigned ? below_equal : less_equal;
2279 cond = is_unsigned ? above_equal : greater_equal;
2282 case Token::INSTANCEOF:
2290 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2291 LOperand* left = instr->left();
2292 LOperand* right = instr->right();
2294 instr->is_double() ||
2295 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2296 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2297 Condition cc = TokenToCondition(instr->op(), is_unsigned);
2299 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2300 // We can statically evaluate the comparison.
2301 double left_val = ToDouble(LConstantOperand::cast(left));
2302 double right_val = ToDouble(LConstantOperand::cast(right));
2303 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2304 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2305 EmitGoto(next_block);
2307 if (instr->is_double()) {
2308 __ ucomisd(ToDoubleRegister(left), ToDoubleRegister(right));
2309 // Don't base result on EFLAGS when a NaN is involved. Instead
2310 // jump to the false block.
2311 __ j(parity_even, instr->FalseLabel(chunk_));
2313 if (right->IsConstantOperand()) {
2314 __ cmp(ToOperand(left),
2315 ToImmediate(right, instr->hydrogen()->representation()));
2316 } else if (left->IsConstantOperand()) {
2317 __ cmp(ToOperand(right),
2318 ToImmediate(left, instr->hydrogen()->representation()));
2319 // We commuted the operands, so commute the condition.
2320 cc = CommuteCondition(cc);
2322 __ cmp(ToRegister(left), ToOperand(right));
2325 EmitBranch(instr, cc);
2330 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2331 Register left = ToRegister(instr->left());
2333 if (instr->right()->IsConstantOperand()) {
2334 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2335 __ CmpObject(left, right);
2337 Operand right = ToOperand(instr->right());
2338 __ cmp(left, right);
2340 EmitBranch(instr, equal);
2344 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2345 if (instr->hydrogen()->representation().IsTagged()) {
2346 Register input_reg = ToRegister(instr->object());
2347 __ cmp(input_reg, factory()->the_hole_value());
2348 EmitBranch(instr, equal);
2352 XMMRegister input_reg = ToDoubleRegister(instr->object());
2353 __ ucomisd(input_reg, input_reg);
2354 EmitFalseBranch(instr, parity_odd);
2356 __ sub(esp, Immediate(kDoubleSize));
2357 __ movsd(MemOperand(esp, 0), input_reg);
2359 __ add(esp, Immediate(kDoubleSize));
2360 int offset = sizeof(kHoleNanUpper32);
2361 __ cmp(MemOperand(esp, -offset), Immediate(kHoleNanUpper32));
2362 EmitBranch(instr, equal);
2366 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2367 Representation rep = instr->hydrogen()->value()->representation();
2368 DCHECK(!rep.IsInteger32());
2369 Register scratch = ToRegister(instr->temp());
2371 if (rep.IsDouble()) {
2372 XMMRegister value = ToDoubleRegister(instr->value());
2373 XMMRegister xmm_scratch = double_scratch0();
2374 __ xorps(xmm_scratch, xmm_scratch);
2375 __ ucomisd(xmm_scratch, value);
2376 EmitFalseBranch(instr, not_equal);
2377 __ movmskpd(scratch, value);
2378 __ test(scratch, Immediate(1));
2379 EmitBranch(instr, not_zero);
2381 Register value = ToRegister(instr->value());
2382 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2383 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2384 __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2386 EmitFalseBranch(instr, no_overflow);
2387 __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2388 Immediate(0x00000000));
2389 EmitBranch(instr, equal);
2394 Condition LCodeGen::EmitIsObject(Register input,
2396 Label* is_not_object,
2398 __ JumpIfSmi(input, is_not_object);
2400 __ cmp(input, isolate()->factory()->null_value());
2401 __ j(equal, is_object);
2403 __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
2404 // Undetectable objects behave like undefined.
2405 __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
2406 1 << Map::kIsUndetectable);
2407 __ j(not_zero, is_not_object);
2409 __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
2410 __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2411 __ j(below, is_not_object);
2412 __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2417 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2418 Register reg = ToRegister(instr->value());
2419 Register temp = ToRegister(instr->temp());
2421 Condition true_cond = EmitIsObject(
2422 reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2424 EmitBranch(instr, true_cond);
2428 Condition LCodeGen::EmitIsString(Register input,
2430 Label* is_not_string,
2431 SmiCheck check_needed = INLINE_SMI_CHECK) {
2432 if (check_needed == INLINE_SMI_CHECK) {
2433 __ JumpIfSmi(input, is_not_string);
2436 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2442 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2443 Register reg = ToRegister(instr->value());
2444 Register temp = ToRegister(instr->temp());
2446 SmiCheck check_needed =
2447 instr->hydrogen()->value()->type().IsHeapObject()
2448 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2450 Condition true_cond = EmitIsString(
2451 reg, temp, instr->FalseLabel(chunk_), check_needed);
2453 EmitBranch(instr, true_cond);
2457 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2458 Operand input = ToOperand(instr->value());
2460 __ test(input, Immediate(kSmiTagMask));
2461 EmitBranch(instr, zero);
2465 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2466 Register input = ToRegister(instr->value());
2467 Register temp = ToRegister(instr->temp());
2469 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2470 STATIC_ASSERT(kSmiTag == 0);
2471 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2473 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2474 __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2475 1 << Map::kIsUndetectable);
2476 EmitBranch(instr, not_zero);
2480 static Condition ComputeCompareCondition(Token::Value op) {
2482 case Token::EQ_STRICT:
2492 return greater_equal;
2495 return no_condition;
2500 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2501 Token::Value op = instr->op();
2503 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
2504 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2506 Condition condition = ComputeCompareCondition(op);
2507 __ test(eax, Operand(eax));
2509 EmitBranch(instr, condition);
2513 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2514 InstanceType from = instr->from();
2515 InstanceType to = instr->to();
2516 if (from == FIRST_TYPE) return to;
2517 DCHECK(from == to || to == LAST_TYPE);
2522 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2523 InstanceType from = instr->from();
2524 InstanceType to = instr->to();
2525 if (from == to) return equal;
2526 if (to == LAST_TYPE) return above_equal;
2527 if (from == FIRST_TYPE) return below_equal;
2533 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2534 Register input = ToRegister(instr->value());
2535 Register temp = ToRegister(instr->temp());
2537 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2538 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2541 __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2542 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2546 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2547 Register input = ToRegister(instr->value());
2548 Register result = ToRegister(instr->result());
2550 __ AssertString(input);
2552 __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2553 __ IndexFromHash(result, result);
2557 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2558 LHasCachedArrayIndexAndBranch* instr) {
2559 Register input = ToRegister(instr->value());
2561 __ test(FieldOperand(input, String::kHashFieldOffset),
2562 Immediate(String::kContainsCachedArrayIndexMask));
2563 EmitBranch(instr, equal);
2567 // Branches to a label or falls through with the answer in the z flag. Trashes
2568 // the temp registers, but not the input.
2569 void LCodeGen::EmitClassOfTest(Label* is_true,
2571 Handle<String>class_name,
2575 DCHECK(!input.is(temp));
2576 DCHECK(!input.is(temp2));
2577 DCHECK(!temp.is(temp2));
2578 __ JumpIfSmi(input, is_false);
2580 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2581 // Assuming the following assertions, we can use the same compares to test
2582 // for both being a function type and being in the object type range.
2583 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2584 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2585 FIRST_SPEC_OBJECT_TYPE + 1);
2586 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2587 LAST_SPEC_OBJECT_TYPE - 1);
2588 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2589 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2590 __ j(below, is_false);
2591 __ j(equal, is_true);
2592 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2593 __ j(equal, is_true);
2595 // Faster code path to avoid two compares: subtract lower bound from the
2596 // actual type and do a signed compare with the width of the type range.
2597 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2598 __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2599 __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2600 __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2601 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2602 __ j(above, is_false);
2605 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2606 // Check if the constructor in the map is a function.
2607 __ GetMapConstructor(temp, temp, temp2);
2608 // Objects with a non-function constructor have class 'Object'.
2609 __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2610 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2611 __ j(not_equal, is_true);
2613 __ j(not_equal, is_false);
2616 // temp now contains the constructor function. Grab the
2617 // instance class name from there.
2618 __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2619 __ mov(temp, FieldOperand(temp,
2620 SharedFunctionInfo::kInstanceClassNameOffset));
2621 // The class name we are testing against is internalized since it's a literal.
2622 // The name in the constructor is internalized because of the way the context
2623 // is booted. This routine isn't expected to work for random API-created
2624 // classes and it doesn't have to because you can't access it with natives
2625 // syntax. Since both sides are internalized it is sufficient to use an
2626 // identity comparison.
2627 __ cmp(temp, class_name);
2628 // End with the answer in the z flag.
2632 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2633 Register input = ToRegister(instr->value());
2634 Register temp = ToRegister(instr->temp());
2635 Register temp2 = ToRegister(instr->temp2());
2637 Handle<String> class_name = instr->hydrogen()->class_name();
2639 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2640 class_name, input, temp, temp2);
2642 EmitBranch(instr, equal);
2646 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2647 Register reg = ToRegister(instr->value());
2648 __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2649 EmitBranch(instr, equal);
2653 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2654 // Object and function are in fixed registers defined by the stub.
2655 DCHECK(ToRegister(instr->context()).is(esi));
2656 InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2657 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2659 Label true_value, done;
2660 __ test(eax, Operand(eax));
2661 __ j(zero, &true_value, Label::kNear);
2662 __ mov(ToRegister(instr->result()), factory()->false_value());
2663 __ jmp(&done, Label::kNear);
2664 __ bind(&true_value);
2665 __ mov(ToRegister(instr->result()), factory()->true_value());
2670 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2671 class DeferredInstanceOfKnownGlobal FINAL : public LDeferredCode {
2673 DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2674 LInstanceOfKnownGlobal* instr)
2675 : LDeferredCode(codegen), instr_(instr) { }
2676 void Generate() OVERRIDE {
2677 codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2679 LInstruction* instr() OVERRIDE { return instr_; }
2680 Label* map_check() { return &map_check_; }
2682 LInstanceOfKnownGlobal* instr_;
2686 DeferredInstanceOfKnownGlobal* deferred;
2687 deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr);
2689 Label done, false_result;
2690 Register object = ToRegister(instr->value());
2691 Register temp = ToRegister(instr->temp());
2693 // A Smi is not an instance of anything.
2694 __ JumpIfSmi(object, &false_result, Label::kNear);
2696 // This is the inlined call site instanceof cache. The two occurences of the
2697 // hole value will be patched to the last map/result pair generated by the
2700 Register map = ToRegister(instr->temp());
2701 __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2702 __ bind(deferred->map_check()); // Label for calculating code patching.
2703 Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2704 __ cmp(map, Operand::ForCell(cache_cell)); // Patched to cached map.
2705 __ j(not_equal, &cache_miss, Label::kNear);
2706 __ mov(eax, factory()->the_hole_value()); // Patched to either true or false.
2707 __ jmp(&done, Label::kNear);
2709 // The inlined call site cache did not match. Check for null and string
2710 // before calling the deferred code.
2711 __ bind(&cache_miss);
2712 // Null is not an instance of anything.
2713 __ cmp(object, factory()->null_value());
2714 __ j(equal, &false_result, Label::kNear);
2716 // String values are not instances of anything.
2717 Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2718 __ j(is_string, &false_result, Label::kNear);
2720 // Go to the deferred code.
2721 __ jmp(deferred->entry());
2723 __ bind(&false_result);
2724 __ mov(ToRegister(instr->result()), factory()->false_value());
2726 // Here result has either true or false. Deferred code also produces true or
2728 __ bind(deferred->exit());
2733 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
2735 PushSafepointRegistersScope scope(this);
2737 InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
2738 flags = static_cast<InstanceofStub::Flags>(
2739 flags | InstanceofStub::kArgsInRegisters);
2740 flags = static_cast<InstanceofStub::Flags>(
2741 flags | InstanceofStub::kCallSiteInlineCheck);
2742 flags = static_cast<InstanceofStub::Flags>(
2743 flags | InstanceofStub::kReturnTrueFalseObject);
2744 InstanceofStub stub(isolate(), flags);
2746 // Get the temp register reserved by the instruction. This needs to be a
2747 // register which is pushed last by PushSafepointRegisters as top of the
2748 // stack is used to pass the offset to the location of the map check to
2750 Register temp = ToRegister(instr->temp());
2751 DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
2752 __ LoadHeapObject(InstanceofStub::right(), instr->function());
2753 static const int kAdditionalDelta = 13;
2754 int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
2755 __ mov(temp, Immediate(delta));
2756 __ StoreToSafepointRegisterSlot(temp, temp);
2757 CallCodeGeneric(stub.GetCode(),
2758 RelocInfo::CODE_TARGET,
2760 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
2761 // Get the deoptimization index of the LLazyBailout-environment that
2762 // corresponds to this instruction.
2763 LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
2764 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
2766 // Put the result value into the eax slot and restore all registers.
2767 __ StoreToSafepointRegisterSlot(eax, eax);
2771 void LCodeGen::DoCmpT(LCmpT* instr) {
2772 Token::Value op = instr->op();
2774 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
2775 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2777 Condition condition = ComputeCompareCondition(op);
2778 Label true_value, done;
2779 __ test(eax, Operand(eax));
2780 __ j(condition, &true_value, Label::kNear);
2781 __ mov(ToRegister(instr->result()), factory()->false_value());
2782 __ jmp(&done, Label::kNear);
2783 __ bind(&true_value);
2784 __ mov(ToRegister(instr->result()), factory()->true_value());
2789 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
2790 int extra_value_count = dynamic_frame_alignment ? 2 : 1;
2792 if (instr->has_constant_parameter_count()) {
2793 int parameter_count = ToInteger32(instr->constant_parameter_count());
2794 if (dynamic_frame_alignment && FLAG_debug_code) {
2796 (parameter_count + extra_value_count) * kPointerSize),
2797 Immediate(kAlignmentZapValue));
2798 __ Assert(equal, kExpectedAlignmentMarker);
2800 __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
2802 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
2803 Register reg = ToRegister(instr->parameter_count());
2804 // The argument count parameter is a smi
2806 Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
2807 if (dynamic_frame_alignment && FLAG_debug_code) {
2808 DCHECK(extra_value_count == 2);
2809 __ cmp(Operand(esp, reg, times_pointer_size,
2810 extra_value_count * kPointerSize),
2811 Immediate(kAlignmentZapValue));
2812 __ Assert(equal, kExpectedAlignmentMarker);
2815 // emit code to restore stack based on instr->parameter_count()
2816 __ pop(return_addr_reg); // save return address
2817 if (dynamic_frame_alignment) {
2818 __ inc(reg); // 1 more for alignment
2821 __ shl(reg, kPointerSizeLog2);
2823 __ jmp(return_addr_reg);
2828 void LCodeGen::DoReturn(LReturn* instr) {
2829 if (FLAG_trace && info()->IsOptimizing()) {
2830 // Preserve the return value on the stack and rely on the runtime call
2831 // to return the value in the same register. We're leaving the code
2832 // managed by the register allocator and tearing down the frame, it's
2833 // safe to write to the context register.
2835 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2836 __ CallRuntime(Runtime::kTraceExit, 1);
2838 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
2839 if (dynamic_frame_alignment_) {
2840 // Fetch the state of the dynamic frame alignment.
2841 __ mov(edx, Operand(ebp,
2842 JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
2844 int no_frame_start = -1;
2845 if (NeedsEagerFrame()) {
2848 no_frame_start = masm_->pc_offset();
2850 if (dynamic_frame_alignment_) {
2852 __ cmp(edx, Immediate(kNoAlignmentPadding));
2853 __ j(equal, &no_padding, Label::kNear);
2855 EmitReturn(instr, true);
2856 __ bind(&no_padding);
2859 EmitReturn(instr, false);
2860 if (no_frame_start != -1) {
2861 info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
2867 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
2868 DCHECK(FLAG_vector_ics);
2869 Register vector_register = ToRegister(instr->temp_vector());
2870 Register slot_register = VectorLoadICDescriptor::SlotRegister();
2871 DCHECK(vector_register.is(VectorLoadICDescriptor::VectorRegister()));
2872 DCHECK(slot_register.is(eax));
2874 AllowDeferredHandleDereference vector_structure_check;
2875 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
2876 __ mov(vector_register, vector);
2877 // No need to allocate this register.
2878 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
2879 int index = vector->GetIndex(slot);
2880 __ mov(slot_register, Immediate(Smi::FromInt(index)));
2884 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
2885 DCHECK(ToRegister(instr->context()).is(esi));
2886 DCHECK(ToRegister(instr->global_object())
2887 .is(LoadDescriptor::ReceiverRegister()));
2888 DCHECK(ToRegister(instr->result()).is(eax));
2890 __ mov(LoadDescriptor::NameRegister(), instr->name());
2891 if (FLAG_vector_ics) {
2892 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
2894 ContextualMode mode = instr->for_typeof() ? NOT_CONTEXTUAL : CONTEXTUAL;
2895 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(isolate(), mode,
2896 PREMONOMORPHIC).code();
2897 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2901 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
2902 Register context = ToRegister(instr->context());
2903 Register result = ToRegister(instr->result());
2904 __ mov(result, ContextOperand(context, instr->slot_index()));
2906 if (instr->hydrogen()->RequiresHoleCheck()) {
2907 __ cmp(result, factory()->the_hole_value());
2908 if (instr->hydrogen()->DeoptimizesOnHole()) {
2909 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2912 __ j(not_equal, &is_not_hole, Label::kNear);
2913 __ mov(result, factory()->undefined_value());
2914 __ bind(&is_not_hole);
2920 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
2921 Register context = ToRegister(instr->context());
2922 Register value = ToRegister(instr->value());
2924 Label skip_assignment;
2926 Operand target = ContextOperand(context, instr->slot_index());
2927 if (instr->hydrogen()->RequiresHoleCheck()) {
2928 __ cmp(target, factory()->the_hole_value());
2929 if (instr->hydrogen()->DeoptimizesOnHole()) {
2930 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2932 __ j(not_equal, &skip_assignment, Label::kNear);
2936 __ mov(target, value);
2937 if (instr->hydrogen()->NeedsWriteBarrier()) {
2938 SmiCheck check_needed =
2939 instr->hydrogen()->value()->type().IsHeapObject()
2940 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2941 Register temp = ToRegister(instr->temp());
2942 int offset = Context::SlotOffset(instr->slot_index());
2943 __ RecordWriteContextSlot(context,
2948 EMIT_REMEMBERED_SET,
2952 __ bind(&skip_assignment);
2956 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
2957 HObjectAccess access = instr->hydrogen()->access();
2958 int offset = access.offset();
2960 if (access.IsExternalMemory()) {
2961 Register result = ToRegister(instr->result());
2962 MemOperand operand = instr->object()->IsConstantOperand()
2963 ? MemOperand::StaticVariable(ToExternalReference(
2964 LConstantOperand::cast(instr->object())))
2965 : MemOperand(ToRegister(instr->object()), offset);
2966 __ Load(result, operand, access.representation());
2970 Register object = ToRegister(instr->object());
2971 if (instr->hydrogen()->representation().IsDouble()) {
2972 XMMRegister result = ToDoubleRegister(instr->result());
2973 __ movsd(result, FieldOperand(object, offset));
2977 Register result = ToRegister(instr->result());
2978 if (!access.IsInobject()) {
2979 __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
2982 __ Load(result, FieldOperand(object, offset), access.representation());
2986 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
2987 DCHECK(!operand->IsDoubleRegister());
2988 if (operand->IsConstantOperand()) {
2989 Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
2990 AllowDeferredHandleDereference smi_check;
2991 if (object->IsSmi()) {
2992 __ Push(Handle<Smi>::cast(object));
2994 __ PushHeapObject(Handle<HeapObject>::cast(object));
2996 } else if (operand->IsRegister()) {
2997 __ push(ToRegister(operand));
2999 __ push(ToOperand(operand));
3004 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3005 DCHECK(ToRegister(instr->context()).is(esi));
3006 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3007 DCHECK(ToRegister(instr->result()).is(eax));
3009 __ mov(LoadDescriptor::NameRegister(), instr->name());
3010 if (FLAG_vector_ics) {
3011 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3013 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(
3014 isolate(), NOT_CONTEXTUAL,
3015 instr->hydrogen()->initialization_state()).code();
3016 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3020 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3021 Register function = ToRegister(instr->function());
3022 Register temp = ToRegister(instr->temp());
3023 Register result = ToRegister(instr->result());
3025 // Get the prototype or initial map from the function.
3027 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
3029 // Check that the function has a prototype or an initial map.
3030 __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3031 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3033 // If the function does not have an initial map, we're done.
3035 __ CmpObjectType(result, MAP_TYPE, temp);
3036 __ j(not_equal, &done, Label::kNear);
3038 // Get the prototype from the initial map.
3039 __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3046 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3047 Register result = ToRegister(instr->result());
3048 __ LoadRoot(result, instr->index());
3052 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3053 Register arguments = ToRegister(instr->arguments());
3054 Register result = ToRegister(instr->result());
3055 if (instr->length()->IsConstantOperand() &&
3056 instr->index()->IsConstantOperand()) {
3057 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3058 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3059 int index = (const_length - const_index) + 1;
3060 __ mov(result, Operand(arguments, index * kPointerSize));
3062 Register length = ToRegister(instr->length());
3063 Operand index = ToOperand(instr->index());
3064 // There are two words between the frame pointer and the last argument.
3065 // Subtracting from length accounts for one of them add one more.
3066 __ sub(length, index);
3067 __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3072 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3073 ElementsKind elements_kind = instr->elements_kind();
3074 LOperand* key = instr->key();
3075 if (!key->IsConstantOperand() &&
3076 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3078 __ SmiUntag(ToRegister(key));
3080 Operand operand(BuildFastArrayOperand(
3083 instr->hydrogen()->key()->representation(),
3085 instr->base_offset()));
3086 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
3087 elements_kind == FLOAT32_ELEMENTS) {
3088 XMMRegister result(ToDoubleRegister(instr->result()));
3089 __ movss(result, operand);
3090 __ cvtss2sd(result, result);
3091 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
3092 elements_kind == FLOAT64_ELEMENTS) {
3093 __ movsd(ToDoubleRegister(instr->result()), operand);
3095 Register result(ToRegister(instr->result()));
3096 switch (elements_kind) {
3097 case EXTERNAL_INT8_ELEMENTS:
3099 __ movsx_b(result, operand);
3101 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3102 case EXTERNAL_UINT8_ELEMENTS:
3103 case UINT8_ELEMENTS:
3104 case UINT8_CLAMPED_ELEMENTS:
3105 __ movzx_b(result, operand);
3107 case EXTERNAL_INT16_ELEMENTS:
3108 case INT16_ELEMENTS:
3109 __ movsx_w(result, operand);
3111 case EXTERNAL_UINT16_ELEMENTS:
3112 case UINT16_ELEMENTS:
3113 __ movzx_w(result, operand);
3115 case EXTERNAL_INT32_ELEMENTS:
3116 case INT32_ELEMENTS:
3117 __ mov(result, operand);
3119 case EXTERNAL_UINT32_ELEMENTS:
3120 case UINT32_ELEMENTS:
3121 __ mov(result, operand);
3122 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3123 __ test(result, Operand(result));
3124 DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3127 case EXTERNAL_FLOAT32_ELEMENTS:
3128 case EXTERNAL_FLOAT64_ELEMENTS:
3129 case FLOAT32_ELEMENTS:
3130 case FLOAT64_ELEMENTS:
3131 case FAST_SMI_ELEMENTS:
3133 case FAST_DOUBLE_ELEMENTS:
3134 case FAST_HOLEY_SMI_ELEMENTS:
3135 case FAST_HOLEY_ELEMENTS:
3136 case FAST_HOLEY_DOUBLE_ELEMENTS:
3137 case DICTIONARY_ELEMENTS:
3138 case SLOPPY_ARGUMENTS_ELEMENTS:
3146 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3147 if (instr->hydrogen()->RequiresHoleCheck()) {
3148 Operand hole_check_operand = BuildFastArrayOperand(
3149 instr->elements(), instr->key(),
3150 instr->hydrogen()->key()->representation(),
3151 FAST_DOUBLE_ELEMENTS,
3152 instr->base_offset() + sizeof(kHoleNanLower32));
3153 __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3154 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3157 Operand double_load_operand = BuildFastArrayOperand(
3160 instr->hydrogen()->key()->representation(),
3161 FAST_DOUBLE_ELEMENTS,
3162 instr->base_offset());
3163 XMMRegister result = ToDoubleRegister(instr->result());
3164 __ movsd(result, double_load_operand);
3168 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3169 Register result = ToRegister(instr->result());
3173 BuildFastArrayOperand(instr->elements(), instr->key(),
3174 instr->hydrogen()->key()->representation(),
3175 FAST_ELEMENTS, instr->base_offset()));
3177 // Check for the hole value.
3178 if (instr->hydrogen()->RequiresHoleCheck()) {
3179 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3180 __ test(result, Immediate(kSmiTagMask));
3181 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3183 __ cmp(result, factory()->the_hole_value());
3184 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3190 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3191 if (instr->is_typed_elements()) {
3192 DoLoadKeyedExternalArray(instr);
3193 } else if (instr->hydrogen()->representation().IsDouble()) {
3194 DoLoadKeyedFixedDoubleArray(instr);
3196 DoLoadKeyedFixedArray(instr);
3201 Operand LCodeGen::BuildFastArrayOperand(
3202 LOperand* elements_pointer,
3204 Representation key_representation,
3205 ElementsKind elements_kind,
3206 uint32_t base_offset) {
3207 Register elements_pointer_reg = ToRegister(elements_pointer);
3208 int element_shift_size = ElementsKindToShiftSize(elements_kind);
3209 int shift_size = element_shift_size;
3210 if (key->IsConstantOperand()) {
3211 int constant_value = ToInteger32(LConstantOperand::cast(key));
3212 if (constant_value & 0xF0000000) {
3213 Abort(kArrayIndexConstantValueTooBig);
3215 return Operand(elements_pointer_reg,
3216 ((constant_value) << shift_size)
3219 // Take the tag bit into account while computing the shift size.
3220 if (key_representation.IsSmi() && (shift_size >= 1)) {
3221 shift_size -= kSmiTagSize;
3223 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3224 return Operand(elements_pointer_reg,
3232 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3233 DCHECK(ToRegister(instr->context()).is(esi));
3234 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3235 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3237 if (FLAG_vector_ics) {
3238 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3242 CodeFactory::KeyedLoadICInOptimizedCode(
3243 isolate(), instr->hydrogen()->initialization_state()).code();
3244 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3248 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3249 Register result = ToRegister(instr->result());
3251 if (instr->hydrogen()->from_inlined()) {
3252 __ lea(result, Operand(esp, -2 * kPointerSize));
3254 // Check for arguments adapter frame.
3255 Label done, adapted;
3256 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3257 __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3258 __ cmp(Operand(result),
3259 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3260 __ j(equal, &adapted, Label::kNear);
3262 // No arguments adaptor frame.
3263 __ mov(result, Operand(ebp));
3264 __ jmp(&done, Label::kNear);
3266 // Arguments adaptor frame present.
3268 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3270 // Result is the frame pointer for the frame if not adapted and for the real
3271 // frame below the adaptor frame if adapted.
3277 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3278 Operand elem = ToOperand(instr->elements());
3279 Register result = ToRegister(instr->result());
3283 // If no arguments adaptor frame the number of arguments is fixed.
3285 __ mov(result, Immediate(scope()->num_parameters()));
3286 __ j(equal, &done, Label::kNear);
3288 // Arguments adaptor frame present. Get argument length from there.
3289 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3290 __ mov(result, Operand(result,
3291 ArgumentsAdaptorFrameConstants::kLengthOffset));
3292 __ SmiUntag(result);
3294 // Argument length is in result register.
3299 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3300 Register receiver = ToRegister(instr->receiver());
3301 Register function = ToRegister(instr->function());
3303 // If the receiver is null or undefined, we have to pass the global
3304 // object as a receiver to normal functions. Values have to be
3305 // passed unchanged to builtins and strict-mode functions.
3306 Label receiver_ok, global_object;
3307 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3308 Register scratch = ToRegister(instr->temp());
3310 if (!instr->hydrogen()->known_function()) {
3311 // Do not transform the receiver to object for strict mode
3314 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3315 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3316 1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3317 __ j(not_equal, &receiver_ok, dist);
3319 // Do not transform the receiver to object for builtins.
3320 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3321 1 << SharedFunctionInfo::kNativeBitWithinByte);
3322 __ j(not_equal, &receiver_ok, dist);
3325 // Normal function. Replace undefined or null with global receiver.
3326 __ cmp(receiver, factory()->null_value());
3327 __ j(equal, &global_object, Label::kNear);
3328 __ cmp(receiver, factory()->undefined_value());
3329 __ j(equal, &global_object, Label::kNear);
3331 // The receiver should be a JS object.
3332 __ test(receiver, Immediate(kSmiTagMask));
3333 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3334 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3335 DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3337 __ jmp(&receiver_ok, Label::kNear);
3338 __ bind(&global_object);
3339 __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3340 const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3341 __ mov(receiver, Operand(receiver, global_offset));
3342 const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3343 __ mov(receiver, FieldOperand(receiver, proxy_offset));
3344 __ bind(&receiver_ok);
3348 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3349 Register receiver = ToRegister(instr->receiver());
3350 Register function = ToRegister(instr->function());
3351 Register length = ToRegister(instr->length());
3352 Register elements = ToRegister(instr->elements());
3353 DCHECK(receiver.is(eax)); // Used for parameter count.
3354 DCHECK(function.is(edi)); // Required by InvokeFunction.
3355 DCHECK(ToRegister(instr->result()).is(eax));
3357 // Copy the arguments to this function possibly from the
3358 // adaptor frame below it.
3359 const uint32_t kArgumentsLimit = 1 * KB;
3360 __ cmp(length, kArgumentsLimit);
3361 DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3364 __ mov(receiver, length);
3366 // Loop through the arguments pushing them onto the execution
3369 // length is a small non-negative integer, due to the test above.
3370 __ test(length, Operand(length));
3371 __ j(zero, &invoke, Label::kNear);
3373 __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3375 __ j(not_zero, &loop);
3377 // Invoke the function.
3379 DCHECK(instr->HasPointerMap());
3380 LPointerMap* pointers = instr->pointer_map();
3381 SafepointGenerator safepoint_generator(
3382 this, pointers, Safepoint::kLazyDeopt);
3383 ParameterCount actual(eax);
3384 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3388 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3393 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3394 LOperand* argument = instr->value();
3395 EmitPushTaggedOperand(argument);
3399 void LCodeGen::DoDrop(LDrop* instr) {
3400 __ Drop(instr->count());
3404 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3405 Register result = ToRegister(instr->result());
3406 __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3410 void LCodeGen::DoContext(LContext* instr) {
3411 Register result = ToRegister(instr->result());
3412 if (info()->IsOptimizing()) {
3413 __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3415 // If there is no frame, the context must be in esi.
3416 DCHECK(result.is(esi));
3421 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3422 DCHECK(ToRegister(instr->context()).is(esi));
3423 __ push(esi); // The context is the first argument.
3424 __ push(Immediate(instr->hydrogen()->pairs()));
3425 __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3426 CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3430 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3431 int formal_parameter_count, int arity,
3432 LInstruction* instr) {
3433 bool dont_adapt_arguments =
3434 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3435 bool can_invoke_directly =
3436 dont_adapt_arguments || formal_parameter_count == arity;
3438 Register function_reg = edi;
3440 if (can_invoke_directly) {
3442 __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3444 // Set eax to arguments count if adaption is not needed. Assumes that eax
3445 // is available to write to at this point.
3446 if (dont_adapt_arguments) {
3450 // Invoke function directly.
3451 if (function.is_identical_to(info()->closure())) {
3454 __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3456 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3458 // We need to adapt arguments.
3459 LPointerMap* pointers = instr->pointer_map();
3460 SafepointGenerator generator(
3461 this, pointers, Safepoint::kLazyDeopt);
3462 ParameterCount count(arity);
3463 ParameterCount expected(formal_parameter_count);
3464 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3469 void LCodeGen::DoTailCallThroughMegamorphicCache(
3470 LTailCallThroughMegamorphicCache* instr) {
3471 Register receiver = ToRegister(instr->receiver());
3472 Register name = ToRegister(instr->name());
3473 DCHECK(receiver.is(LoadDescriptor::ReceiverRegister()));
3474 DCHECK(name.is(LoadDescriptor::NameRegister()));
3475 Register slot = FLAG_vector_ics ? ToRegister(instr->slot()) : no_reg;
3476 Register vector = FLAG_vector_ics ? ToRegister(instr->vector()) : no_reg;
3478 Register scratch = ebx;
3479 Register extra = edi;
3480 DCHECK(!extra.is(slot) && !extra.is(vector));
3481 DCHECK(!scratch.is(receiver) && !scratch.is(name));
3482 DCHECK(!extra.is(receiver) && !extra.is(name));
3484 // Important for the tail-call.
3485 bool must_teardown_frame = NeedsEagerFrame();
3487 if (!instr->hydrogen()->is_just_miss()) {
3488 if (FLAG_vector_ics) {
3493 // The probe will tail call to a handler if found.
3494 // If --vector-ics is on, then it knows to pop the two args first.
3495 DCHECK(!instr->hydrogen()->is_keyed_load());
3496 isolate()->stub_cache()->GenerateProbe(
3497 masm(), Code::LOAD_IC, instr->hydrogen()->flags(), must_teardown_frame,
3498 receiver, name, scratch, extra);
3500 if (FLAG_vector_ics) {
3506 // Tail call to miss if we ended up here.
3507 if (must_teardown_frame) __ leave();
3508 if (instr->hydrogen()->is_keyed_load()) {
3509 KeyedLoadIC::GenerateMiss(masm());
3511 LoadIC::GenerateMiss(masm());
3516 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3517 DCHECK(ToRegister(instr->result()).is(eax));
3519 if (instr->hydrogen()->IsTailCall()) {
3520 if (NeedsEagerFrame()) __ leave();
3522 if (instr->target()->IsConstantOperand()) {
3523 LConstantOperand* target = LConstantOperand::cast(instr->target());
3524 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3525 __ jmp(code, RelocInfo::CODE_TARGET);
3527 DCHECK(instr->target()->IsRegister());
3528 Register target = ToRegister(instr->target());
3529 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3533 LPointerMap* pointers = instr->pointer_map();
3534 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3536 if (instr->target()->IsConstantOperand()) {
3537 LConstantOperand* target = LConstantOperand::cast(instr->target());
3538 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3539 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3540 __ call(code, RelocInfo::CODE_TARGET);
3542 DCHECK(instr->target()->IsRegister());
3543 Register target = ToRegister(instr->target());
3544 generator.BeforeCall(__ CallSize(Operand(target)));
3545 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3548 generator.AfterCall();
3553 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3554 DCHECK(ToRegister(instr->function()).is(edi));
3555 DCHECK(ToRegister(instr->result()).is(eax));
3557 if (instr->hydrogen()->pass_argument_count()) {
3558 __ mov(eax, instr->arity());
3562 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3564 bool is_self_call = false;
3565 if (instr->hydrogen()->function()->IsConstant()) {
3566 HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3567 Handle<JSFunction> jsfun =
3568 Handle<JSFunction>::cast(fun_const->handle(isolate()));
3569 is_self_call = jsfun.is_identical_to(info()->closure());
3575 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3578 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3582 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3583 Register input_reg = ToRegister(instr->value());
3584 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3585 factory()->heap_number_map());
3586 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3588 Label slow, allocated, done;
3589 Register tmp = input_reg.is(eax) ? ecx : eax;
3590 Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3592 // Preserve the value of all registers.
3593 PushSafepointRegistersScope scope(this);
3595 __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3596 // Check the sign of the argument. If the argument is positive, just
3597 // return it. We do not need to patch the stack since |input| and
3598 // |result| are the same register and |input| will be restored
3599 // unchanged by popping safepoint registers.
3600 __ test(tmp, Immediate(HeapNumber::kSignMask));
3601 __ j(zero, &done, Label::kNear);
3603 __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3604 __ jmp(&allocated, Label::kNear);
3606 // Slow case: Call the runtime system to do the number allocation.
3608 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3609 instr, instr->context());
3610 // Set the pointer to the new heap number in tmp.
3611 if (!tmp.is(eax)) __ mov(tmp, eax);
3612 // Restore input_reg after call to runtime.
3613 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3615 __ bind(&allocated);
3616 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3617 __ and_(tmp2, ~HeapNumber::kSignMask);
3618 __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3619 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3620 __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3621 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3627 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3628 Register input_reg = ToRegister(instr->value());
3629 __ test(input_reg, Operand(input_reg));
3631 __ j(not_sign, &is_positive, Label::kNear);
3632 __ neg(input_reg); // Sets flags.
3633 DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3634 __ bind(&is_positive);
3638 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3639 // Class for deferred case.
3640 class DeferredMathAbsTaggedHeapNumber FINAL : public LDeferredCode {
3642 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3644 : LDeferredCode(codegen), instr_(instr) { }
3645 void Generate() OVERRIDE {
3646 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3648 LInstruction* instr() OVERRIDE { return instr_; }
3654 DCHECK(instr->value()->Equals(instr->result()));
3655 Representation r = instr->hydrogen()->value()->representation();
3658 XMMRegister scratch = double_scratch0();
3659 XMMRegister input_reg = ToDoubleRegister(instr->value());
3660 __ xorps(scratch, scratch);
3661 __ subsd(scratch, input_reg);
3662 __ andps(input_reg, scratch);
3663 } else if (r.IsSmiOrInteger32()) {
3664 EmitIntegerMathAbs(instr);
3665 } else { // Tagged case.
3666 DeferredMathAbsTaggedHeapNumber* deferred =
3667 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
3668 Register input_reg = ToRegister(instr->value());
3670 __ JumpIfNotSmi(input_reg, deferred->entry());
3671 EmitIntegerMathAbs(instr);
3672 __ bind(deferred->exit());
3677 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3678 XMMRegister xmm_scratch = double_scratch0();
3679 Register output_reg = ToRegister(instr->result());
3680 XMMRegister input_reg = ToDoubleRegister(instr->value());
3682 if (CpuFeatures::IsSupported(SSE4_1)) {
3683 CpuFeatureScope scope(masm(), SSE4_1);
3684 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3685 // Deoptimize on negative zero.
3687 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3688 __ ucomisd(input_reg, xmm_scratch);
3689 __ j(not_equal, &non_zero, Label::kNear);
3690 __ movmskpd(output_reg, input_reg);
3691 __ test(output_reg, Immediate(1));
3692 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3695 __ roundsd(xmm_scratch, input_reg, kRoundDown);
3696 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3697 // Overflow is signalled with minint.
3698 __ cmp(output_reg, 0x1);
3699 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3701 Label negative_sign, done;
3702 // Deoptimize on unordered.
3703 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3704 __ ucomisd(input_reg, xmm_scratch);
3705 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3706 __ j(below, &negative_sign, Label::kNear);
3708 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3709 // Check for negative zero.
3710 Label positive_sign;
3711 __ j(above, &positive_sign, Label::kNear);
3712 __ movmskpd(output_reg, input_reg);
3713 __ test(output_reg, Immediate(1));
3714 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3715 __ Move(output_reg, Immediate(0));
3716 __ jmp(&done, Label::kNear);
3717 __ bind(&positive_sign);
3720 // Use truncating instruction (OK because input is positive).
3721 __ cvttsd2si(output_reg, Operand(input_reg));
3722 // Overflow is signalled with minint.
3723 __ cmp(output_reg, 0x1);
3724 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3725 __ jmp(&done, Label::kNear);
3727 // Non-zero negative reaches here.
3728 __ bind(&negative_sign);
3729 // Truncate, then compare and compensate.
3730 __ cvttsd2si(output_reg, Operand(input_reg));
3731 __ Cvtsi2sd(xmm_scratch, output_reg);
3732 __ ucomisd(input_reg, xmm_scratch);
3733 __ j(equal, &done, Label::kNear);
3734 __ sub(output_reg, Immediate(1));
3735 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3742 void LCodeGen::DoMathRound(LMathRound* instr) {
3743 Register output_reg = ToRegister(instr->result());
3744 XMMRegister input_reg = ToDoubleRegister(instr->value());
3745 XMMRegister xmm_scratch = double_scratch0();
3746 XMMRegister input_temp = ToDoubleRegister(instr->temp());
3747 ExternalReference one_half = ExternalReference::address_of_one_half();
3748 ExternalReference minus_one_half =
3749 ExternalReference::address_of_minus_one_half();
3751 Label done, round_to_zero, below_one_half, do_not_compensate;
3752 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3754 __ movsd(xmm_scratch, Operand::StaticVariable(one_half));
3755 __ ucomisd(xmm_scratch, input_reg);
3756 __ j(above, &below_one_half, Label::kNear);
3758 // CVTTSD2SI rounds towards zero, since 0.5 <= x, we use floor(0.5 + x).
3759 __ addsd(xmm_scratch, input_reg);
3760 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3761 // Overflow is signalled with minint.
3762 __ cmp(output_reg, 0x1);
3763 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3764 __ jmp(&done, dist);
3766 __ bind(&below_one_half);
3767 __ movsd(xmm_scratch, Operand::StaticVariable(minus_one_half));
3768 __ ucomisd(xmm_scratch, input_reg);
3769 __ j(below_equal, &round_to_zero, Label::kNear);
3771 // CVTTSD2SI rounds towards zero, we use ceil(x - (-0.5)) and then
3772 // compare and compensate.
3773 __ movaps(input_temp, input_reg); // Do not alter input_reg.
3774 __ subsd(input_temp, xmm_scratch);
3775 __ cvttsd2si(output_reg, Operand(input_temp));
3776 // Catch minint due to overflow, and to prevent overflow when compensating.
3777 __ cmp(output_reg, 0x1);
3778 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3780 __ Cvtsi2sd(xmm_scratch, output_reg);
3781 __ ucomisd(xmm_scratch, input_temp);
3782 __ j(equal, &done, dist);
3783 __ sub(output_reg, Immediate(1));
3784 // No overflow because we already ruled out minint.
3785 __ jmp(&done, dist);
3787 __ bind(&round_to_zero);
3788 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3789 // we can ignore the difference between a result of -0 and +0.
3790 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3791 // If the sign is positive, we return +0.
3792 __ movmskpd(output_reg, input_reg);
3793 __ test(output_reg, Immediate(1));
3794 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3796 __ Move(output_reg, Immediate(0));
3801 void LCodeGen::DoMathFround(LMathFround* instr) {
3802 XMMRegister input_reg = ToDoubleRegister(instr->value());
3803 XMMRegister output_reg = ToDoubleRegister(instr->result());
3804 __ cvtsd2ss(output_reg, input_reg);
3805 __ cvtss2sd(output_reg, output_reg);
3809 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3810 Operand input = ToOperand(instr->value());
3811 XMMRegister output = ToDoubleRegister(instr->result());
3812 __ sqrtsd(output, input);
3816 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3817 XMMRegister xmm_scratch = double_scratch0();
3818 XMMRegister input_reg = ToDoubleRegister(instr->value());
3819 Register scratch = ToRegister(instr->temp());
3820 DCHECK(ToDoubleRegister(instr->result()).is(input_reg));
3822 // Note that according to ECMA-262 15.8.2.13:
3823 // Math.pow(-Infinity, 0.5) == Infinity
3824 // Math.sqrt(-Infinity) == NaN
3826 // Check base for -Infinity. According to IEEE-754, single-precision
3827 // -Infinity has the highest 9 bits set and the lowest 23 bits cleared.
3828 __ mov(scratch, 0xFF800000);
3829 __ movd(xmm_scratch, scratch);
3830 __ cvtss2sd(xmm_scratch, xmm_scratch);
3831 __ ucomisd(input_reg, xmm_scratch);
3832 // Comparing -Infinity with NaN results in "unordered", which sets the
3833 // zero flag as if both were equal. However, it also sets the carry flag.
3834 __ j(not_equal, &sqrt, Label::kNear);
3835 __ j(carry, &sqrt, Label::kNear);
3836 // If input is -Infinity, return Infinity.
3837 __ xorps(input_reg, input_reg);
3838 __ subsd(input_reg, xmm_scratch);
3839 __ jmp(&done, Label::kNear);
3843 __ xorps(xmm_scratch, xmm_scratch);
3844 __ addsd(input_reg, xmm_scratch); // Convert -0 to +0.
3845 __ sqrtsd(input_reg, input_reg);
3850 void LCodeGen::DoPower(LPower* instr) {
3851 Representation exponent_type = instr->hydrogen()->right()->representation();
3852 // Having marked this as a call, we can use any registers.
3853 // Just make sure that the input/output registers are the expected ones.
3854 Register tagged_exponent = MathPowTaggedDescriptor::exponent();
3855 DCHECK(!instr->right()->IsDoubleRegister() ||
3856 ToDoubleRegister(instr->right()).is(xmm1));
3857 DCHECK(!instr->right()->IsRegister() ||
3858 ToRegister(instr->right()).is(tagged_exponent));
3859 DCHECK(ToDoubleRegister(instr->left()).is(xmm2));
3860 DCHECK(ToDoubleRegister(instr->result()).is(xmm3));
3862 if (exponent_type.IsSmi()) {
3863 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3865 } else if (exponent_type.IsTagged()) {
3867 __ JumpIfSmi(tagged_exponent, &no_deopt);
3868 DCHECK(!ecx.is(tagged_exponent));
3869 __ CmpObjectType(tagged_exponent, HEAP_NUMBER_TYPE, ecx);
3870 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3872 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3874 } else if (exponent_type.IsInteger32()) {
3875 MathPowStub stub(isolate(), MathPowStub::INTEGER);
3878 DCHECK(exponent_type.IsDouble());
3879 MathPowStub stub(isolate(), MathPowStub::DOUBLE);
3885 void LCodeGen::DoMathLog(LMathLog* instr) {
3886 DCHECK(instr->value()->Equals(instr->result()));
3887 XMMRegister input_reg = ToDoubleRegister(instr->value());
3888 XMMRegister xmm_scratch = double_scratch0();
3889 Label positive, done, zero;
3890 __ xorps(xmm_scratch, xmm_scratch);
3891 __ ucomisd(input_reg, xmm_scratch);
3892 __ j(above, &positive, Label::kNear);
3893 __ j(not_carry, &zero, Label::kNear);
3894 __ pcmpeqd(input_reg, input_reg);
3895 __ jmp(&done, Label::kNear);
3897 ExternalReference ninf =
3898 ExternalReference::address_of_negative_infinity();
3899 __ movsd(input_reg, Operand::StaticVariable(ninf));
3900 __ jmp(&done, Label::kNear);
3903 __ sub(Operand(esp), Immediate(kDoubleSize));
3904 __ movsd(Operand(esp, 0), input_reg);
3905 __ fld_d(Operand(esp, 0));
3907 __ fstp_d(Operand(esp, 0));
3908 __ movsd(input_reg, Operand(esp, 0));
3909 __ add(Operand(esp), Immediate(kDoubleSize));
3914 void LCodeGen::DoMathClz32(LMathClz32* instr) {
3915 Register input = ToRegister(instr->value());
3916 Register result = ToRegister(instr->result());
3918 __ Lzcnt(result, input);
3922 void LCodeGen::DoMathExp(LMathExp* instr) {
3923 XMMRegister input = ToDoubleRegister(instr->value());
3924 XMMRegister result = ToDoubleRegister(instr->result());
3925 XMMRegister temp0 = double_scratch0();
3926 Register temp1 = ToRegister(instr->temp1());
3927 Register temp2 = ToRegister(instr->temp2());
3929 MathExpGenerator::EmitMathExp(masm(), input, result, temp0, temp1, temp2);
3933 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
3934 DCHECK(ToRegister(instr->context()).is(esi));
3935 DCHECK(ToRegister(instr->function()).is(edi));
3936 DCHECK(instr->HasPointerMap());
3938 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
3939 if (known_function.is_null()) {
3940 LPointerMap* pointers = instr->pointer_map();
3941 SafepointGenerator generator(
3942 this, pointers, Safepoint::kLazyDeopt);
3943 ParameterCount count(instr->arity());
3944 __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
3946 CallKnownFunction(known_function,
3947 instr->hydrogen()->formal_parameter_count(),
3948 instr->arity(), instr);
3953 void LCodeGen::DoCallFunction(LCallFunction* instr) {
3954 DCHECK(ToRegister(instr->context()).is(esi));
3955 DCHECK(ToRegister(instr->function()).is(edi));
3956 DCHECK(ToRegister(instr->result()).is(eax));
3958 int arity = instr->arity();
3959 CallFunctionFlags flags = instr->hydrogen()->function_flags();
3960 if (instr->hydrogen()->HasVectorAndSlot()) {
3961 Register slot_register = ToRegister(instr->temp_slot());
3962 Register vector_register = ToRegister(instr->temp_vector());
3963 DCHECK(slot_register.is(edx));
3964 DCHECK(vector_register.is(ebx));
3966 AllowDeferredHandleDereference vector_structure_check;
3967 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3968 int index = vector->GetIndex(instr->hydrogen()->slot());
3970 __ mov(vector_register, vector);
3971 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3973 CallICState::CallType call_type =
3974 (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
3977 CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
3978 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3980 CallFunctionStub stub(isolate(), arity, flags);
3981 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3986 void LCodeGen::DoCallNew(LCallNew* instr) {
3987 DCHECK(ToRegister(instr->context()).is(esi));
3988 DCHECK(ToRegister(instr->constructor()).is(edi));
3989 DCHECK(ToRegister(instr->result()).is(eax));
3991 // No cell in ebx for construct type feedback in optimized code
3992 __ mov(ebx, isolate()->factory()->undefined_value());
3993 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
3994 __ Move(eax, Immediate(instr->arity()));
3995 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3999 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
4000 DCHECK(ToRegister(instr->context()).is(esi));
4001 DCHECK(ToRegister(instr->constructor()).is(edi));
4002 DCHECK(ToRegister(instr->result()).is(eax));
4004 __ Move(eax, Immediate(instr->arity()));
4005 __ mov(ebx, isolate()->factory()->undefined_value());
4006 ElementsKind kind = instr->hydrogen()->elements_kind();
4007 AllocationSiteOverrideMode override_mode =
4008 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
4009 ? DISABLE_ALLOCATION_SITES
4012 if (instr->arity() == 0) {
4013 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
4014 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4015 } else if (instr->arity() == 1) {
4017 if (IsFastPackedElementsKind(kind)) {
4019 // We might need a change here
4020 // look at the first argument
4021 __ mov(ecx, Operand(esp, 0));
4023 __ j(zero, &packed_case, Label::kNear);
4025 ElementsKind holey_kind = GetHoleyElementsKind(kind);
4026 ArraySingleArgumentConstructorStub stub(isolate(),
4029 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4030 __ jmp(&done, Label::kNear);
4031 __ bind(&packed_case);
4034 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
4035 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4038 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
4039 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4044 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4045 DCHECK(ToRegister(instr->context()).is(esi));
4046 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
4050 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4051 Register function = ToRegister(instr->function());
4052 Register code_object = ToRegister(instr->code_object());
4053 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4054 __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4058 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4059 Register result = ToRegister(instr->result());
4060 Register base = ToRegister(instr->base_object());
4061 if (instr->offset()->IsConstantOperand()) {
4062 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4063 __ lea(result, Operand(base, ToInteger32(offset)));
4065 Register offset = ToRegister(instr->offset());
4066 __ lea(result, Operand(base, offset, times_1, 0));
4071 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4072 Representation representation = instr->hydrogen()->field_representation();
4074 HObjectAccess access = instr->hydrogen()->access();
4075 int offset = access.offset();
4077 if (access.IsExternalMemory()) {
4078 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4079 MemOperand operand = instr->object()->IsConstantOperand()
4080 ? MemOperand::StaticVariable(
4081 ToExternalReference(LConstantOperand::cast(instr->object())))
4082 : MemOperand(ToRegister(instr->object()), offset);
4083 if (instr->value()->IsConstantOperand()) {
4084 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4085 __ mov(operand, Immediate(ToInteger32(operand_value)));
4087 Register value = ToRegister(instr->value());
4088 __ Store(value, operand, representation);
4093 Register object = ToRegister(instr->object());
4094 __ AssertNotSmi(object);
4096 DCHECK(!representation.IsSmi() ||
4097 !instr->value()->IsConstantOperand() ||
4098 IsSmi(LConstantOperand::cast(instr->value())));
4099 if (representation.IsDouble()) {
4100 DCHECK(access.IsInobject());
4101 DCHECK(!instr->hydrogen()->has_transition());
4102 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4103 XMMRegister value = ToDoubleRegister(instr->value());
4104 __ movsd(FieldOperand(object, offset), value);
4108 if (instr->hydrogen()->has_transition()) {
4109 Handle<Map> transition = instr->hydrogen()->transition_map();
4110 AddDeprecationDependency(transition);
4111 __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4112 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4113 Register temp = ToRegister(instr->temp());
4114 Register temp_map = ToRegister(instr->temp_map());
4115 // Update the write barrier for the map field.
4116 __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4121 Register write_register = object;
4122 if (!access.IsInobject()) {
4123 write_register = ToRegister(instr->temp());
4124 __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4127 MemOperand operand = FieldOperand(write_register, offset);
4128 if (instr->value()->IsConstantOperand()) {
4129 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4130 if (operand_value->IsRegister()) {
4131 Register value = ToRegister(operand_value);
4132 __ Store(value, operand, representation);
4133 } else if (representation.IsInteger32()) {
4134 Immediate immediate = ToImmediate(operand_value, representation);
4135 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4136 __ mov(operand, immediate);
4138 Handle<Object> handle_value = ToHandle(operand_value);
4139 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4140 __ mov(operand, handle_value);
4143 Register value = ToRegister(instr->value());
4144 __ Store(value, operand, representation);
4147 if (instr->hydrogen()->NeedsWriteBarrier()) {
4148 Register value = ToRegister(instr->value());
4149 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4150 // Update the write barrier for the object for in-object properties.
4151 __ RecordWriteField(write_register,
4156 EMIT_REMEMBERED_SET,
4157 instr->hydrogen()->SmiCheckForWriteBarrier(),
4158 instr->hydrogen()->PointersToHereCheckForValue());
4163 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4164 DCHECK(ToRegister(instr->context()).is(esi));
4165 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4166 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4168 __ mov(StoreDescriptor::NameRegister(), instr->name());
4170 StoreIC::initialize_stub(isolate(), instr->language_mode(),
4171 instr->hydrogen()->initialization_state());
4172 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4176 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4177 Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4178 if (instr->index()->IsConstantOperand()) {
4179 __ cmp(ToOperand(instr->length()),
4180 ToImmediate(LConstantOperand::cast(instr->index()),
4181 instr->hydrogen()->length()->representation()));
4182 cc = CommuteCondition(cc);
4183 } else if (instr->length()->IsConstantOperand()) {
4184 __ cmp(ToOperand(instr->index()),
4185 ToImmediate(LConstantOperand::cast(instr->length()),
4186 instr->hydrogen()->index()->representation()));
4188 __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4190 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4192 __ j(NegateCondition(cc), &done, Label::kNear);
4196 DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4201 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4202 ElementsKind elements_kind = instr->elements_kind();
4203 LOperand* key = instr->key();
4204 if (!key->IsConstantOperand() &&
4205 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4207 __ SmiUntag(ToRegister(key));
4209 Operand operand(BuildFastArrayOperand(
4212 instr->hydrogen()->key()->representation(),
4214 instr->base_offset()));
4215 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
4216 elements_kind == FLOAT32_ELEMENTS) {
4217 XMMRegister xmm_scratch = double_scratch0();
4218 __ cvtsd2ss(xmm_scratch, ToDoubleRegister(instr->value()));
4219 __ movss(operand, xmm_scratch);
4220 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
4221 elements_kind == FLOAT64_ELEMENTS) {
4222 __ movsd(operand, ToDoubleRegister(instr->value()));
4224 Register value = ToRegister(instr->value());
4225 switch (elements_kind) {
4226 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
4227 case EXTERNAL_UINT8_ELEMENTS:
4228 case EXTERNAL_INT8_ELEMENTS:
4229 case UINT8_ELEMENTS:
4231 case UINT8_CLAMPED_ELEMENTS:
4232 __ mov_b(operand, value);
4234 case EXTERNAL_INT16_ELEMENTS:
4235 case EXTERNAL_UINT16_ELEMENTS:
4236 case UINT16_ELEMENTS:
4237 case INT16_ELEMENTS:
4238 __ mov_w(operand, value);
4240 case EXTERNAL_INT32_ELEMENTS:
4241 case EXTERNAL_UINT32_ELEMENTS:
4242 case UINT32_ELEMENTS:
4243 case INT32_ELEMENTS:
4244 __ mov(operand, value);
4246 case EXTERNAL_FLOAT32_ELEMENTS:
4247 case EXTERNAL_FLOAT64_ELEMENTS:
4248 case FLOAT32_ELEMENTS:
4249 case FLOAT64_ELEMENTS:
4250 case FAST_SMI_ELEMENTS:
4252 case FAST_DOUBLE_ELEMENTS:
4253 case FAST_HOLEY_SMI_ELEMENTS:
4254 case FAST_HOLEY_ELEMENTS:
4255 case FAST_HOLEY_DOUBLE_ELEMENTS:
4256 case DICTIONARY_ELEMENTS:
4257 case SLOPPY_ARGUMENTS_ELEMENTS:
4265 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4266 Operand double_store_operand = BuildFastArrayOperand(
4269 instr->hydrogen()->key()->representation(),
4270 FAST_DOUBLE_ELEMENTS,
4271 instr->base_offset());
4273 XMMRegister value = ToDoubleRegister(instr->value());
4275 if (instr->NeedsCanonicalization()) {
4276 XMMRegister xmm_scratch = double_scratch0();
4277 // Turn potential sNaN value into qNaN.
4278 __ xorps(xmm_scratch, xmm_scratch);
4279 __ subsd(value, xmm_scratch);
4282 __ movsd(double_store_operand, value);
4286 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4287 Register elements = ToRegister(instr->elements());
4288 Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4290 Operand operand = BuildFastArrayOperand(
4293 instr->hydrogen()->key()->representation(),
4295 instr->base_offset());
4296 if (instr->value()->IsRegister()) {
4297 __ mov(operand, ToRegister(instr->value()));
4299 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4300 if (IsSmi(operand_value)) {
4301 Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4302 __ mov(operand, immediate);
4304 DCHECK(!IsInteger32(operand_value));
4305 Handle<Object> handle_value = ToHandle(operand_value);
4306 __ mov(operand, handle_value);
4310 if (instr->hydrogen()->NeedsWriteBarrier()) {
4311 DCHECK(instr->value()->IsRegister());
4312 Register value = ToRegister(instr->value());
4313 DCHECK(!instr->key()->IsConstantOperand());
4314 SmiCheck check_needed =
4315 instr->hydrogen()->value()->type().IsHeapObject()
4316 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4317 // Compute address of modified element and store it into key register.
4318 __ lea(key, operand);
4319 __ RecordWrite(elements,
4323 EMIT_REMEMBERED_SET,
4325 instr->hydrogen()->PointersToHereCheckForValue());
4330 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4331 // By cases...external, fast-double, fast
4332 if (instr->is_typed_elements()) {
4333 DoStoreKeyedExternalArray(instr);
4334 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4335 DoStoreKeyedFixedDoubleArray(instr);
4337 DoStoreKeyedFixedArray(instr);
4342 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4343 DCHECK(ToRegister(instr->context()).is(esi));
4344 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4345 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4346 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4348 Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4349 isolate(), instr->language_mode(),
4350 instr->hydrogen()->initialization_state()).code();
4351 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4355 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4356 Register object = ToRegister(instr->object());
4357 Register temp = ToRegister(instr->temp());
4358 Label no_memento_found;
4359 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4360 DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4361 __ bind(&no_memento_found);
4365 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4366 Register object_reg = ToRegister(instr->object());
4368 Handle<Map> from_map = instr->original_map();
4369 Handle<Map> to_map = instr->transitioned_map();
4370 ElementsKind from_kind = instr->from_kind();
4371 ElementsKind to_kind = instr->to_kind();
4373 Label not_applicable;
4374 bool is_simple_map_transition =
4375 IsSimpleMapChangeTransition(from_kind, to_kind);
4376 Label::Distance branch_distance =
4377 is_simple_map_transition ? Label::kNear : Label::kFar;
4378 __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4379 __ j(not_equal, ¬_applicable, branch_distance);
4380 if (is_simple_map_transition) {
4381 Register new_map_reg = ToRegister(instr->new_map_temp());
4382 __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4385 DCHECK_NOT_NULL(instr->temp());
4386 __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4387 ToRegister(instr->temp()),
4390 DCHECK(ToRegister(instr->context()).is(esi));
4391 DCHECK(object_reg.is(eax));
4392 PushSafepointRegistersScope scope(this);
4393 __ mov(ebx, to_map);
4394 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4395 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4397 RecordSafepointWithLazyDeopt(instr,
4398 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4400 __ bind(¬_applicable);
4404 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4405 class DeferredStringCharCodeAt FINAL : public LDeferredCode {
4407 DeferredStringCharCodeAt(LCodeGen* codegen,
4408 LStringCharCodeAt* instr)
4409 : LDeferredCode(codegen), instr_(instr) { }
4410 void Generate() OVERRIDE { codegen()->DoDeferredStringCharCodeAt(instr_); }
4411 LInstruction* instr() OVERRIDE { return instr_; }
4414 LStringCharCodeAt* instr_;
4417 DeferredStringCharCodeAt* deferred =
4418 new(zone()) DeferredStringCharCodeAt(this, instr);
4420 StringCharLoadGenerator::Generate(masm(),
4422 ToRegister(instr->string()),
4423 ToRegister(instr->index()),
4424 ToRegister(instr->result()),
4426 __ bind(deferred->exit());
4430 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4431 Register string = ToRegister(instr->string());
4432 Register result = ToRegister(instr->result());
4434 // TODO(3095996): Get rid of this. For now, we need to make the
4435 // result register contain a valid pointer because it is already
4436 // contained in the register pointer map.
4437 __ Move(result, Immediate(0));
4439 PushSafepointRegistersScope scope(this);
4441 // Push the index as a smi. This is safe because of the checks in
4442 // DoStringCharCodeAt above.
4443 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4444 if (instr->index()->IsConstantOperand()) {
4445 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4446 Representation::Smi());
4449 Register index = ToRegister(instr->index());
4453 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4454 instr, instr->context());
4457 __ StoreToSafepointRegisterSlot(result, eax);
4461 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4462 class DeferredStringCharFromCode FINAL : public LDeferredCode {
4464 DeferredStringCharFromCode(LCodeGen* codegen,
4465 LStringCharFromCode* instr)
4466 : LDeferredCode(codegen), instr_(instr) { }
4467 void Generate() OVERRIDE {
4468 codegen()->DoDeferredStringCharFromCode(instr_);
4470 LInstruction* instr() OVERRIDE { return instr_; }
4473 LStringCharFromCode* instr_;
4476 DeferredStringCharFromCode* deferred =
4477 new(zone()) DeferredStringCharFromCode(this, instr);
4479 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4480 Register char_code = ToRegister(instr->char_code());
4481 Register result = ToRegister(instr->result());
4482 DCHECK(!char_code.is(result));
4484 __ cmp(char_code, String::kMaxOneByteCharCode);
4485 __ j(above, deferred->entry());
4486 __ Move(result, Immediate(factory()->single_character_string_cache()));
4487 __ mov(result, FieldOperand(result,
4488 char_code, times_pointer_size,
4489 FixedArray::kHeaderSize));
4490 __ cmp(result, factory()->undefined_value());
4491 __ j(equal, deferred->entry());
4492 __ bind(deferred->exit());
4496 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4497 Register char_code = ToRegister(instr->char_code());
4498 Register result = ToRegister(instr->result());
4500 // TODO(3095996): Get rid of this. For now, we need to make the
4501 // result register contain a valid pointer because it is already
4502 // contained in the register pointer map.
4503 __ Move(result, Immediate(0));
4505 PushSafepointRegistersScope scope(this);
4506 __ SmiTag(char_code);
4508 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4509 __ StoreToSafepointRegisterSlot(result, eax);
4513 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4514 DCHECK(ToRegister(instr->context()).is(esi));
4515 DCHECK(ToRegister(instr->left()).is(edx));
4516 DCHECK(ToRegister(instr->right()).is(eax));
4517 StringAddStub stub(isolate(),
4518 instr->hydrogen()->flags(),
4519 instr->hydrogen()->pretenure_flag());
4520 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4524 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4525 LOperand* input = instr->value();
4526 LOperand* output = instr->result();
4527 DCHECK(input->IsRegister() || input->IsStackSlot());
4528 DCHECK(output->IsDoubleRegister());
4529 __ Cvtsi2sd(ToDoubleRegister(output), ToOperand(input));
4533 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4534 LOperand* input = instr->value();
4535 LOperand* output = instr->result();
4536 __ LoadUint32(ToDoubleRegister(output), ToRegister(input));
4540 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4541 class DeferredNumberTagI FINAL : public LDeferredCode {
4543 DeferredNumberTagI(LCodeGen* codegen,
4545 : LDeferredCode(codegen), instr_(instr) { }
4546 void Generate() OVERRIDE {
4547 codegen()->DoDeferredNumberTagIU(
4548 instr_, instr_->value(), instr_->temp(), SIGNED_INT32);
4550 LInstruction* instr() OVERRIDE { return instr_; }
4553 LNumberTagI* instr_;
4556 LOperand* input = instr->value();
4557 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4558 Register reg = ToRegister(input);
4560 DeferredNumberTagI* deferred =
4561 new(zone()) DeferredNumberTagI(this, instr);
4563 __ j(overflow, deferred->entry());
4564 __ bind(deferred->exit());
4568 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4569 class DeferredNumberTagU FINAL : public LDeferredCode {
4571 DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4572 : LDeferredCode(codegen), instr_(instr) { }
4573 void Generate() OVERRIDE {
4574 codegen()->DoDeferredNumberTagIU(
4575 instr_, instr_->value(), instr_->temp(), UNSIGNED_INT32);
4577 LInstruction* instr() OVERRIDE { return instr_; }
4580 LNumberTagU* instr_;
4583 LOperand* input = instr->value();
4584 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4585 Register reg = ToRegister(input);
4587 DeferredNumberTagU* deferred =
4588 new(zone()) DeferredNumberTagU(this, instr);
4589 __ cmp(reg, Immediate(Smi::kMaxValue));
4590 __ j(above, deferred->entry());
4592 __ bind(deferred->exit());
4596 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
4599 IntegerSignedness signedness) {
4601 Register reg = ToRegister(value);
4602 Register tmp = ToRegister(temp);
4603 XMMRegister xmm_scratch = double_scratch0();
4605 if (signedness == SIGNED_INT32) {
4606 // There was overflow, so bits 30 and 31 of the original integer
4607 // disagree. Try to allocate a heap number in new space and store
4608 // the value in there. If that fails, call the runtime system.
4610 __ xor_(reg, 0x80000000);
4611 __ Cvtsi2sd(xmm_scratch, Operand(reg));
4613 __ LoadUint32(xmm_scratch, reg);
4616 if (FLAG_inline_new) {
4617 __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
4618 __ jmp(&done, Label::kNear);
4621 // Slow case: Call the runtime system to do the number allocation.
4624 // TODO(3095996): Put a valid pointer value in the stack slot where the
4625 // result register is stored, as this register is in the pointer map, but
4626 // contains an integer value.
4627 __ Move(reg, Immediate(0));
4629 // Preserve the value of all registers.
4630 PushSafepointRegistersScope scope(this);
4632 // NumberTagI and NumberTagD use the context from the frame, rather than
4633 // the environment's HContext or HInlinedContext value.
4634 // They only call Runtime::kAllocateHeapNumber.
4635 // The corresponding HChange instructions are added in a phase that does
4636 // not have easy access to the local context.
4637 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4638 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4639 RecordSafepointWithRegisters(
4640 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4641 __ StoreToSafepointRegisterSlot(reg, eax);
4644 // Done. Put the value in xmm_scratch into the value of the allocated heap
4647 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), xmm_scratch);
4651 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4652 class DeferredNumberTagD FINAL : public LDeferredCode {
4654 DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4655 : LDeferredCode(codegen), instr_(instr) { }
4656 void Generate() OVERRIDE { codegen()->DoDeferredNumberTagD(instr_); }
4657 LInstruction* instr() OVERRIDE { return instr_; }
4660 LNumberTagD* instr_;
4663 Register reg = ToRegister(instr->result());
4665 DeferredNumberTagD* deferred =
4666 new(zone()) DeferredNumberTagD(this, instr);
4667 if (FLAG_inline_new) {
4668 Register tmp = ToRegister(instr->temp());
4669 __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
4671 __ jmp(deferred->entry());
4673 __ bind(deferred->exit());
4674 XMMRegister input_reg = ToDoubleRegister(instr->value());
4675 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg);
4679 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4680 // TODO(3095996): Get rid of this. For now, we need to make the
4681 // result register contain a valid pointer because it is already
4682 // contained in the register pointer map.
4683 Register reg = ToRegister(instr->result());
4684 __ Move(reg, Immediate(0));
4686 PushSafepointRegistersScope scope(this);
4687 // NumberTagI and NumberTagD use the context from the frame, rather than
4688 // the environment's HContext or HInlinedContext value.
4689 // They only call Runtime::kAllocateHeapNumber.
4690 // The corresponding HChange instructions are added in a phase that does
4691 // not have easy access to the local context.
4692 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4693 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4694 RecordSafepointWithRegisters(
4695 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4696 __ StoreToSafepointRegisterSlot(reg, eax);
4700 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4701 HChange* hchange = instr->hydrogen();
4702 Register input = ToRegister(instr->value());
4703 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4704 hchange->value()->CheckFlag(HValue::kUint32)) {
4705 __ test(input, Immediate(0xc0000000));
4706 DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
4709 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4710 !hchange->value()->CheckFlag(HValue::kUint32)) {
4711 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4716 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4717 LOperand* input = instr->value();
4718 Register result = ToRegister(input);
4719 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4720 if (instr->needs_check()) {
4721 __ test(result, Immediate(kSmiTagMask));
4722 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4724 __ AssertSmi(result);
4726 __ SmiUntag(result);
4730 void LCodeGen::EmitNumberUntagD(LNumberUntagD* instr, Register input_reg,
4731 Register temp_reg, XMMRegister result_reg,
4732 NumberUntagDMode mode) {
4733 bool can_convert_undefined_to_nan =
4734 instr->hydrogen()->can_convert_undefined_to_nan();
4735 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
4737 Label convert, load_smi, done;
4739 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4741 __ JumpIfSmi(input_reg, &load_smi, Label::kNear);
4743 // Heap number map check.
4744 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4745 factory()->heap_number_map());
4746 if (can_convert_undefined_to_nan) {
4747 __ j(not_equal, &convert, Label::kNear);
4749 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4752 // Heap number to XMM conversion.
4753 __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset));
4755 if (deoptimize_on_minus_zero) {
4756 XMMRegister xmm_scratch = double_scratch0();
4757 __ xorps(xmm_scratch, xmm_scratch);
4758 __ ucomisd(result_reg, xmm_scratch);
4759 __ j(not_zero, &done, Label::kNear);
4760 __ movmskpd(temp_reg, result_reg);
4761 __ test_b(temp_reg, 1);
4762 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4764 __ jmp(&done, Label::kNear);
4766 if (can_convert_undefined_to_nan) {
4769 // Convert undefined to NaN.
4770 __ cmp(input_reg, factory()->undefined_value());
4771 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
4773 __ pcmpeqd(result_reg, result_reg);
4774 __ jmp(&done, Label::kNear);
4777 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4781 // Smi to XMM conversion. Clobbering a temp is faster than re-tagging the
4782 // input register since we avoid dependencies.
4783 __ mov(temp_reg, input_reg);
4784 __ SmiUntag(temp_reg); // Untag smi before converting to float.
4785 __ Cvtsi2sd(result_reg, Operand(temp_reg));
4790 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
4791 Register input_reg = ToRegister(instr->value());
4793 // The input was optimistically untagged; revert it.
4794 STATIC_ASSERT(kSmiTagSize == 1);
4795 __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
4797 if (instr->truncating()) {
4798 Label no_heap_number, check_bools, check_false;
4800 // Heap number map check.
4801 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4802 factory()->heap_number_map());
4803 __ j(not_equal, &no_heap_number, Label::kNear);
4804 __ TruncateHeapNumberToI(input_reg, input_reg);
4807 __ bind(&no_heap_number);
4808 // Check for Oddballs. Undefined/False is converted to zero and True to one
4809 // for truncating conversions.
4810 __ cmp(input_reg, factory()->undefined_value());
4811 __ j(not_equal, &check_bools, Label::kNear);
4812 __ Move(input_reg, Immediate(0));
4815 __ bind(&check_bools);
4816 __ cmp(input_reg, factory()->true_value());
4817 __ j(not_equal, &check_false, Label::kNear);
4818 __ Move(input_reg, Immediate(1));
4821 __ bind(&check_false);
4822 __ cmp(input_reg, factory()->false_value());
4823 DeoptimizeIf(not_equal, instr,
4824 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
4825 __ Move(input_reg, Immediate(0));
4827 XMMRegister scratch = ToDoubleRegister(instr->temp());
4828 DCHECK(!scratch.is(xmm0));
4829 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4830 isolate()->factory()->heap_number_map());
4831 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4832 __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
4833 __ cvttsd2si(input_reg, Operand(xmm0));
4834 __ Cvtsi2sd(scratch, Operand(input_reg));
4835 __ ucomisd(xmm0, scratch);
4836 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
4837 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
4838 if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
4839 __ test(input_reg, Operand(input_reg));
4840 __ j(not_zero, done);
4841 __ movmskpd(input_reg, xmm0);
4842 __ and_(input_reg, 1);
4843 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4849 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
4850 class DeferredTaggedToI FINAL : public LDeferredCode {
4852 DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
4853 : LDeferredCode(codegen), instr_(instr) { }
4854 void Generate() OVERRIDE { codegen()->DoDeferredTaggedToI(instr_, done()); }
4855 LInstruction* instr() OVERRIDE { return instr_; }
4861 LOperand* input = instr->value();
4862 DCHECK(input->IsRegister());
4863 Register input_reg = ToRegister(input);
4864 DCHECK(input_reg.is(ToRegister(instr->result())));
4866 if (instr->hydrogen()->value()->representation().IsSmi()) {
4867 __ SmiUntag(input_reg);
4869 DeferredTaggedToI* deferred =
4870 new(zone()) DeferredTaggedToI(this, instr);
4871 // Optimistically untag the input.
4872 // If the input is a HeapObject, SmiUntag will set the carry flag.
4873 STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
4874 __ SmiUntag(input_reg);
4875 // Branch to deferred code if the input was tagged.
4876 // The deferred code will take care of restoring the tag.
4877 __ j(carry, deferred->entry());
4878 __ bind(deferred->exit());
4883 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4884 LOperand* input = instr->value();
4885 DCHECK(input->IsRegister());
4886 LOperand* temp = instr->temp();
4887 DCHECK(temp->IsRegister());
4888 LOperand* result = instr->result();
4889 DCHECK(result->IsDoubleRegister());
4891 Register input_reg = ToRegister(input);
4892 Register temp_reg = ToRegister(temp);
4894 HValue* value = instr->hydrogen()->value();
4895 NumberUntagDMode mode = value->representation().IsSmi()
4896 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4898 XMMRegister result_reg = ToDoubleRegister(result);
4899 EmitNumberUntagD(instr, input_reg, temp_reg, result_reg, mode);
4903 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
4904 LOperand* input = instr->value();
4905 DCHECK(input->IsDoubleRegister());
4906 LOperand* result = instr->result();
4907 DCHECK(result->IsRegister());
4908 Register result_reg = ToRegister(result);
4910 if (instr->truncating()) {
4911 XMMRegister input_reg = ToDoubleRegister(input);
4912 __ TruncateDoubleToI(result_reg, input_reg);
4914 Label lost_precision, is_nan, minus_zero, done;
4915 XMMRegister input_reg = ToDoubleRegister(input);
4916 XMMRegister xmm_scratch = double_scratch0();
4917 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4918 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4919 instr->hydrogen()->GetMinusZeroMode(), &lost_precision,
4920 &is_nan, &minus_zero, dist);
4921 __ jmp(&done, dist);
4922 __ bind(&lost_precision);
4923 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4925 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4926 __ bind(&minus_zero);
4927 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4933 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
4934 LOperand* input = instr->value();
4935 DCHECK(input->IsDoubleRegister());
4936 LOperand* result = instr->result();
4937 DCHECK(result->IsRegister());
4938 Register result_reg = ToRegister(result);
4940 Label lost_precision, is_nan, minus_zero, done;
4941 XMMRegister input_reg = ToDoubleRegister(input);
4942 XMMRegister xmm_scratch = double_scratch0();
4943 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4944 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4945 instr->hydrogen()->GetMinusZeroMode(), &lost_precision, &is_nan,
4947 __ jmp(&done, dist);
4948 __ bind(&lost_precision);
4949 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4951 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4952 __ bind(&minus_zero);
4953 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4955 __ SmiTag(result_reg);
4956 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4960 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
4961 LOperand* input = instr->value();
4962 __ test(ToOperand(input), Immediate(kSmiTagMask));
4963 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4967 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
4968 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
4969 LOperand* input = instr->value();
4970 __ test(ToOperand(input), Immediate(kSmiTagMask));
4971 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
4976 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
4977 Register input = ToRegister(instr->value());
4978 Register temp = ToRegister(instr->temp());
4980 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
4982 if (instr->hydrogen()->is_interval_check()) {
4985 instr->hydrogen()->GetCheckInterval(&first, &last);
4987 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
4988 static_cast<int8_t>(first));
4990 // If there is only one type in the interval check for equality.
4991 if (first == last) {
4992 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
4994 DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
4995 // Omit check for the last type.
4996 if (last != LAST_TYPE) {
4997 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
4998 static_cast<int8_t>(last));
4999 DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5005 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5007 if (base::bits::IsPowerOfTwo32(mask)) {
5008 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5009 __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5010 DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5011 Deoptimizer::kWrongInstanceType);
5013 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5014 __ and_(temp, mask);
5016 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5022 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5023 Handle<HeapObject> object = instr->hydrogen()->object().handle();
5024 if (instr->hydrogen()->object_in_new_space()) {
5025 Register reg = ToRegister(instr->value());
5026 Handle<Cell> cell = isolate()->factory()->NewCell(object);
5027 __ cmp(reg, Operand::ForCell(cell));
5029 Operand operand = ToOperand(instr->value());
5030 __ cmp(operand, object);
5032 DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5036 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5038 PushSafepointRegistersScope scope(this);
5041 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5042 RecordSafepointWithRegisters(
5043 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5045 __ test(eax, Immediate(kSmiTagMask));
5047 DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5051 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5052 class DeferredCheckMaps FINAL : public LDeferredCode {
5054 DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr, Register object)
5055 : LDeferredCode(codegen), instr_(instr), object_(object) {
5056 SetExit(check_maps());
5058 void Generate() OVERRIDE {
5059 codegen()->DoDeferredInstanceMigration(instr_, object_);
5061 Label* check_maps() { return &check_maps_; }
5062 LInstruction* instr() OVERRIDE { return instr_; }
5070 if (instr->hydrogen()->IsStabilityCheck()) {
5071 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5072 for (int i = 0; i < maps->size(); ++i) {
5073 AddStabilityDependency(maps->at(i).handle());
5078 LOperand* input = instr->value();
5079 DCHECK(input->IsRegister());
5080 Register reg = ToRegister(input);
5082 DeferredCheckMaps* deferred = NULL;
5083 if (instr->hydrogen()->HasMigrationTarget()) {
5084 deferred = new(zone()) DeferredCheckMaps(this, instr, reg);
5085 __ bind(deferred->check_maps());
5088 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5090 for (int i = 0; i < maps->size() - 1; i++) {
5091 Handle<Map> map = maps->at(i).handle();
5092 __ CompareMap(reg, map);
5093 __ j(equal, &success, Label::kNear);
5096 Handle<Map> map = maps->at(maps->size() - 1).handle();
5097 __ CompareMap(reg, map);
5098 if (instr->hydrogen()->HasMigrationTarget()) {
5099 __ j(not_equal, deferred->entry());
5101 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5108 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5109 XMMRegister value_reg = ToDoubleRegister(instr->unclamped());
5110 XMMRegister xmm_scratch = double_scratch0();
5111 Register result_reg = ToRegister(instr->result());
5112 __ ClampDoubleToUint8(value_reg, xmm_scratch, result_reg);
5116 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5117 DCHECK(instr->unclamped()->Equals(instr->result()));
5118 Register value_reg = ToRegister(instr->result());
5119 __ ClampUint8(value_reg);
5123 void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
5124 DCHECK(instr->unclamped()->Equals(instr->result()));
5125 Register input_reg = ToRegister(instr->unclamped());
5126 XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm());
5127 XMMRegister xmm_scratch = double_scratch0();
5128 Label is_smi, done, heap_number;
5130 __ JumpIfSmi(input_reg, &is_smi);
5132 // Check for heap number
5133 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5134 factory()->heap_number_map());
5135 __ j(equal, &heap_number, Label::kNear);
5137 // Check for undefined. Undefined is converted to zero for clamping
5139 __ cmp(input_reg, factory()->undefined_value());
5140 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5141 __ mov(input_reg, 0);
5142 __ jmp(&done, Label::kNear);
5145 __ bind(&heap_number);
5146 __ movsd(xmm_scratch, FieldOperand(input_reg, HeapNumber::kValueOffset));
5147 __ ClampDoubleToUint8(xmm_scratch, temp_xmm_reg, input_reg);
5148 __ jmp(&done, Label::kNear);
5152 __ SmiUntag(input_reg);
5153 __ ClampUint8(input_reg);
5158 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5159 XMMRegister value_reg = ToDoubleRegister(instr->value());
5160 Register result_reg = ToRegister(instr->result());
5161 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5162 if (CpuFeatures::IsSupported(SSE4_1)) {
5163 CpuFeatureScope scope2(masm(), SSE4_1);
5164 __ pextrd(result_reg, value_reg, 1);
5166 XMMRegister xmm_scratch = double_scratch0();
5167 __ pshufd(xmm_scratch, value_reg, 1);
5168 __ movd(result_reg, xmm_scratch);
5171 __ movd(result_reg, value_reg);
5176 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5177 Register hi_reg = ToRegister(instr->hi());
5178 Register lo_reg = ToRegister(instr->lo());
5179 XMMRegister result_reg = ToDoubleRegister(instr->result());
5181 if (CpuFeatures::IsSupported(SSE4_1)) {
5182 CpuFeatureScope scope2(masm(), SSE4_1);
5183 __ movd(result_reg, lo_reg);
5184 __ pinsrd(result_reg, hi_reg, 1);
5186 XMMRegister xmm_scratch = double_scratch0();
5187 __ movd(result_reg, hi_reg);
5188 __ psllq(result_reg, 32);
5189 __ movd(xmm_scratch, lo_reg);
5190 __ orps(result_reg, xmm_scratch);
5195 void LCodeGen::DoAllocate(LAllocate* instr) {
5196 class DeferredAllocate FINAL : public LDeferredCode {
5198 DeferredAllocate(LCodeGen* codegen, LAllocate* instr)
5199 : LDeferredCode(codegen), instr_(instr) { }
5200 void Generate() OVERRIDE { codegen()->DoDeferredAllocate(instr_); }
5201 LInstruction* instr() OVERRIDE { return instr_; }
5207 DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr);
5209 Register result = ToRegister(instr->result());
5210 Register temp = ToRegister(instr->temp());
5212 // Allocate memory for the object.
5213 AllocationFlags flags = TAG_OBJECT;
5214 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5215 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5217 if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5218 DCHECK(!instr->hydrogen()->IsOldDataSpaceAllocation());
5219 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5220 flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_POINTER_SPACE);
5221 } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5222 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5223 flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_DATA_SPACE);
5226 if (instr->size()->IsConstantOperand()) {
5227 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5228 if (size <= Page::kMaxRegularHeapObjectSize) {
5229 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5231 __ jmp(deferred->entry());
5234 Register size = ToRegister(instr->size());
5235 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5238 __ bind(deferred->exit());
5240 if (instr->hydrogen()->MustPrefillWithFiller()) {
5241 if (instr->size()->IsConstantOperand()) {
5242 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5243 __ mov(temp, (size / kPointerSize) - 1);
5245 temp = ToRegister(instr->size());
5246 __ shr(temp, kPointerSizeLog2);
5251 __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5252 isolate()->factory()->one_pointer_filler_map());
5254 __ j(not_zero, &loop);
5259 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5260 Register result = ToRegister(instr->result());
5262 // TODO(3095996): Get rid of this. For now, we need to make the
5263 // result register contain a valid pointer because it is already
5264 // contained in the register pointer map.
5265 __ Move(result, Immediate(Smi::FromInt(0)));
5267 PushSafepointRegistersScope scope(this);
5268 if (instr->size()->IsRegister()) {
5269 Register size = ToRegister(instr->size());
5270 DCHECK(!size.is(result));
5271 __ SmiTag(ToRegister(instr->size()));
5274 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5275 if (size >= 0 && size <= Smi::kMaxValue) {
5276 __ push(Immediate(Smi::FromInt(size)));
5278 // We should never get here at runtime => abort
5284 int flags = AllocateDoubleAlignFlag::encode(
5285 instr->hydrogen()->MustAllocateDoubleAligned());
5286 if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5287 DCHECK(!instr->hydrogen()->IsOldDataSpaceAllocation());
5288 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5289 flags = AllocateTargetSpace::update(flags, OLD_POINTER_SPACE);
5290 } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5291 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5292 flags = AllocateTargetSpace::update(flags, OLD_DATA_SPACE);
5294 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5296 __ push(Immediate(Smi::FromInt(flags)));
5298 CallRuntimeFromDeferred(
5299 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5300 __ StoreToSafepointRegisterSlot(result, eax);
5304 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5305 DCHECK(ToRegister(instr->value()).is(eax));
5307 CallRuntime(Runtime::kToFastProperties, 1, instr);
5311 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5312 DCHECK(ToRegister(instr->context()).is(esi));
5314 // Registers will be used as follows:
5315 // ecx = literals array.
5316 // ebx = regexp literal.
5317 // eax = regexp literal clone.
5319 int literal_offset =
5320 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5321 __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5322 __ mov(ebx, FieldOperand(ecx, literal_offset));
5323 __ cmp(ebx, factory()->undefined_value());
5324 __ j(not_equal, &materialized, Label::kNear);
5326 // Create regexp literal using runtime function
5327 // Result will be in eax.
5329 __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5330 __ push(Immediate(instr->hydrogen()->pattern()));
5331 __ push(Immediate(instr->hydrogen()->flags()));
5332 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5335 __ bind(&materialized);
5336 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5337 Label allocated, runtime_allocate;
5338 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5339 __ jmp(&allocated, Label::kNear);
5341 __ bind(&runtime_allocate);
5343 __ push(Immediate(Smi::FromInt(size)));
5344 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5347 __ bind(&allocated);
5348 // Copy the content into the newly allocated memory.
5349 // (Unroll copy loop once for better throughput).
5350 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5351 __ mov(edx, FieldOperand(ebx, i));
5352 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5353 __ mov(FieldOperand(eax, i), edx);
5354 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5356 if ((size % (2 * kPointerSize)) != 0) {
5357 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5358 __ mov(FieldOperand(eax, size - kPointerSize), edx);
5363 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5364 DCHECK(ToRegister(instr->context()).is(esi));
5365 // Use the fast case closure allocation code that allocates in new
5366 // space for nested functions that don't need literals cloning.
5367 bool pretenure = instr->hydrogen()->pretenure();
5368 if (!pretenure && instr->hydrogen()->has_no_literals()) {
5369 FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
5370 instr->hydrogen()->kind());
5371 __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
5372 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5375 __ push(Immediate(instr->hydrogen()->shared_info()));
5376 __ push(Immediate(pretenure ? factory()->true_value()
5377 : factory()->false_value()));
5378 CallRuntime(Runtime::kNewClosure, 3, instr);
5383 void LCodeGen::DoTypeof(LTypeof* instr) {
5384 DCHECK(ToRegister(instr->context()).is(esi));
5385 LOperand* input = instr->value();
5386 EmitPushTaggedOperand(input);
5387 CallRuntime(Runtime::kTypeof, 1, instr);
5391 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5392 Register input = ToRegister(instr->value());
5393 Condition final_branch_condition = EmitTypeofIs(instr, input);
5394 if (final_branch_condition != no_condition) {
5395 EmitBranch(instr, final_branch_condition);
5400 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
5401 Label* true_label = instr->TrueLabel(chunk_);
5402 Label* false_label = instr->FalseLabel(chunk_);
5403 Handle<String> type_name = instr->type_literal();
5404 int left_block = instr->TrueDestination(chunk_);
5405 int right_block = instr->FalseDestination(chunk_);
5406 int next_block = GetNextEmittedBlock();
5408 Label::Distance true_distance = left_block == next_block ? Label::kNear
5410 Label::Distance false_distance = right_block == next_block ? Label::kNear
5412 Condition final_branch_condition = no_condition;
5413 if (String::Equals(type_name, factory()->number_string())) {
5414 __ JumpIfSmi(input, true_label, true_distance);
5415 __ cmp(FieldOperand(input, HeapObject::kMapOffset),
5416 factory()->heap_number_map());
5417 final_branch_condition = equal;
5419 } else if (String::Equals(type_name, factory()->string_string())) {
5420 __ JumpIfSmi(input, false_label, false_distance);
5421 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
5422 __ j(above_equal, false_label, false_distance);
5423 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5424 1 << Map::kIsUndetectable);
5425 final_branch_condition = zero;
5427 } else if (String::Equals(type_name, factory()->symbol_string())) {
5428 __ JumpIfSmi(input, false_label, false_distance);
5429 __ CmpObjectType(input, SYMBOL_TYPE, input);
5430 final_branch_condition = equal;
5432 } else if (String::Equals(type_name, factory()->boolean_string())) {
5433 __ cmp(input, factory()->true_value());
5434 __ j(equal, true_label, true_distance);
5435 __ cmp(input, factory()->false_value());
5436 final_branch_condition = equal;
5438 } else if (String::Equals(type_name, factory()->undefined_string())) {
5439 __ cmp(input, factory()->undefined_value());
5440 __ j(equal, true_label, true_distance);
5441 __ JumpIfSmi(input, false_label, false_distance);
5442 // Check for undetectable objects => true.
5443 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
5444 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5445 1 << Map::kIsUndetectable);
5446 final_branch_condition = not_zero;
5448 } else if (String::Equals(type_name, factory()->function_string())) {
5449 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5450 __ JumpIfSmi(input, false_label, false_distance);
5451 __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
5452 __ j(equal, true_label, true_distance);
5453 __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
5454 final_branch_condition = equal;
5456 } else if (String::Equals(type_name, factory()->object_string())) {
5457 __ JumpIfSmi(input, false_label, false_distance);
5458 __ cmp(input, factory()->null_value());
5459 __ j(equal, true_label, true_distance);
5460 __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
5461 __ j(below, false_label, false_distance);
5462 __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5463 __ j(above, false_label, false_distance);
5464 // Check for undetectable objects => false.
5465 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5466 1 << Map::kIsUndetectable);
5467 final_branch_condition = zero;
5470 __ jmp(false_label, false_distance);
5472 return final_branch_condition;
5476 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
5477 Register temp = ToRegister(instr->temp());
5479 EmitIsConstructCall(temp);
5480 EmitBranch(instr, equal);
5484 void LCodeGen::EmitIsConstructCall(Register temp) {
5485 // Get the frame pointer for the calling frame.
5486 __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
5488 // Skip the arguments adaptor frame if it exists.
5489 Label check_frame_marker;
5490 __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
5491 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
5492 __ j(not_equal, &check_frame_marker, Label::kNear);
5493 __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
5495 // Check the marker in the calling frame.
5496 __ bind(&check_frame_marker);
5497 __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
5498 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
5502 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
5503 if (!info()->IsStub()) {
5504 // Ensure that we have enough space after the previous lazy-bailout
5505 // instruction for patching the code here.
5506 int current_pc = masm()->pc_offset();
5507 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
5508 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
5509 __ Nop(padding_size);
5512 last_lazy_deopt_pc_ = masm()->pc_offset();
5516 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
5517 last_lazy_deopt_pc_ = masm()->pc_offset();
5518 DCHECK(instr->HasEnvironment());
5519 LEnvironment* env = instr->environment();
5520 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5521 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5525 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
5526 Deoptimizer::BailoutType type = instr->hydrogen()->type();
5527 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
5528 // needed return address), even though the implementation of LAZY and EAGER is
5529 // now identical. When LAZY is eventually completely folded into EAGER, remove
5530 // the special case below.
5531 if (info()->IsStub() && type == Deoptimizer::EAGER) {
5532 type = Deoptimizer::LAZY;
5534 DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
5538 void LCodeGen::DoDummy(LDummy* instr) {
5539 // Nothing to see here, move on!
5543 void LCodeGen::DoDummyUse(LDummyUse* instr) {
5544 // Nothing to see here, move on!
5548 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5549 PushSafepointRegistersScope scope(this);
5550 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5551 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5552 RecordSafepointWithLazyDeopt(
5553 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5554 DCHECK(instr->HasEnvironment());
5555 LEnvironment* env = instr->environment();
5556 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5560 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5561 class DeferredStackCheck FINAL : public LDeferredCode {
5563 DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5564 : LDeferredCode(codegen), instr_(instr) { }
5565 void Generate() OVERRIDE { codegen()->DoDeferredStackCheck(instr_); }
5566 LInstruction* instr() OVERRIDE { return instr_; }
5569 LStackCheck* instr_;
5572 DCHECK(instr->HasEnvironment());
5573 LEnvironment* env = instr->environment();
5574 // There is no LLazyBailout instruction for stack-checks. We have to
5575 // prepare for lazy deoptimization explicitly here.
5576 if (instr->hydrogen()->is_function_entry()) {
5577 // Perform stack overflow check.
5579 ExternalReference stack_limit =
5580 ExternalReference::address_of_stack_limit(isolate());
5581 __ cmp(esp, Operand::StaticVariable(stack_limit));
5582 __ j(above_equal, &done, Label::kNear);
5584 DCHECK(instr->context()->IsRegister());
5585 DCHECK(ToRegister(instr->context()).is(esi));
5586 CallCode(isolate()->builtins()->StackCheck(),
5587 RelocInfo::CODE_TARGET,
5591 DCHECK(instr->hydrogen()->is_backwards_branch());
5592 // Perform stack overflow check if this goto needs it before jumping.
5593 DeferredStackCheck* deferred_stack_check =
5594 new(zone()) DeferredStackCheck(this, instr);
5595 ExternalReference stack_limit =
5596 ExternalReference::address_of_stack_limit(isolate());
5597 __ cmp(esp, Operand::StaticVariable(stack_limit));
5598 __ j(below, deferred_stack_check->entry());
5599 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5600 __ bind(instr->done_label());
5601 deferred_stack_check->SetExit(instr->done_label());
5602 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5603 // Don't record a deoptimization index for the safepoint here.
5604 // This will be done explicitly when emitting call and the safepoint in
5605 // the deferred code.
5610 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
5611 // This is a pseudo-instruction that ensures that the environment here is
5612 // properly registered for deoptimization and records the assembler's PC
5614 LEnvironment* environment = instr->environment();
5616 // If the environment were already registered, we would have no way of
5617 // backpatching it with the spill slot operands.
5618 DCHECK(!environment->HasBeenRegistered());
5619 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
5621 GenerateOsrPrologue();
5625 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
5626 DCHECK(ToRegister(instr->context()).is(esi));
5627 __ cmp(eax, isolate()->factory()->undefined_value());
5628 DeoptimizeIf(equal, instr, Deoptimizer::kUndefined);
5630 __ cmp(eax, isolate()->factory()->null_value());
5631 DeoptimizeIf(equal, instr, Deoptimizer::kNull);
5633 __ test(eax, Immediate(kSmiTagMask));
5634 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5636 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
5637 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
5638 DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
5640 Label use_cache, call_runtime;
5641 __ CheckEnumCache(&call_runtime);
5643 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
5644 __ jmp(&use_cache, Label::kNear);
5646 // Get the set of properties to enumerate.
5647 __ bind(&call_runtime);
5649 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
5651 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
5652 isolate()->factory()->meta_map());
5653 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5654 __ bind(&use_cache);
5658 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
5659 Register map = ToRegister(instr->map());
5660 Register result = ToRegister(instr->result());
5661 Label load_cache, done;
5662 __ EnumLength(result, map);
5663 __ cmp(result, Immediate(Smi::FromInt(0)));
5664 __ j(not_equal, &load_cache, Label::kNear);
5665 __ mov(result, isolate()->factory()->empty_fixed_array());
5666 __ jmp(&done, Label::kNear);
5668 __ bind(&load_cache);
5669 __ LoadInstanceDescriptors(map, result);
5671 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
5673 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
5675 __ test(result, result);
5676 DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
5680 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
5681 Register object = ToRegister(instr->value());
5682 __ cmp(ToRegister(instr->map()),
5683 FieldOperand(object, HeapObject::kMapOffset));
5684 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5688 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
5691 PushSafepointRegistersScope scope(this);
5695 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
5696 RecordSafepointWithRegisters(
5697 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
5698 __ StoreToSafepointRegisterSlot(object, eax);
5702 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
5703 class DeferredLoadMutableDouble FINAL : public LDeferredCode {
5705 DeferredLoadMutableDouble(LCodeGen* codegen,
5706 LLoadFieldByIndex* instr,
5709 : LDeferredCode(codegen),
5714 void Generate() OVERRIDE {
5715 codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
5717 LInstruction* instr() OVERRIDE { return instr_; }
5720 LLoadFieldByIndex* instr_;
5725 Register object = ToRegister(instr->object());
5726 Register index = ToRegister(instr->index());
5728 DeferredLoadMutableDouble* deferred;
5729 deferred = new(zone()) DeferredLoadMutableDouble(
5730 this, instr, object, index);
5732 Label out_of_object, done;
5733 __ test(index, Immediate(Smi::FromInt(1)));
5734 __ j(not_zero, deferred->entry());
5738 __ cmp(index, Immediate(0));
5739 __ j(less, &out_of_object, Label::kNear);
5740 __ mov(object, FieldOperand(object,
5742 times_half_pointer_size,
5743 JSObject::kHeaderSize));
5744 __ jmp(&done, Label::kNear);
5746 __ bind(&out_of_object);
5747 __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
5749 // Index is now equal to out of object property index plus 1.
5750 __ mov(object, FieldOperand(object,
5752 times_half_pointer_size,
5753 FixedArray::kHeaderSize - kPointerSize));
5754 __ bind(deferred->exit());
5759 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
5760 Register context = ToRegister(instr->context());
5761 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
5765 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
5766 Handle<ScopeInfo> scope_info = instr->scope_info();
5767 __ Push(scope_info);
5768 __ push(ToRegister(instr->function()));
5769 CallRuntime(Runtime::kPushBlockContext, 2, instr);
5770 RecordSafepoint(Safepoint::kNoLazyDeopt);
5776 } } // namespace v8::internal
5778 #endif // V8_TARGET_ARCH_IA32