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.
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/ic/ic.h"
17 #include "src/ic/stub-cache.h"
18 #include "src/x87/lithium-codegen-x87.h"
24 // When invoking builtins, we need to record the safepoint in the middle of
25 // the invoke instruction sequence generated by the macro assembler.
26 class SafepointGenerator FINAL : public CallWrapper {
28 SafepointGenerator(LCodeGen* codegen,
29 LPointerMap* pointers,
30 Safepoint::DeoptMode mode)
34 virtual ~SafepointGenerator() {}
36 void BeforeCall(int call_size) const OVERRIDE {}
38 void AfterCall() const OVERRIDE {
39 codegen_->RecordSafepoint(pointers_, deopt_mode_);
44 LPointerMap* pointers_;
45 Safepoint::DeoptMode deopt_mode_;
51 bool LCodeGen::GenerateCode() {
52 LPhase phase("Z_Code generation", chunk());
56 // Open a frame scope to indicate that there is a frame on the stack. The
57 // MANUAL indicates that the scope shouldn't actually generate code to set up
58 // the frame (that is done in GeneratePrologue).
59 FrameScope frame_scope(masm_, StackFrame::MANUAL);
61 support_aligned_spilled_doubles_ = info()->IsOptimizing();
63 dynamic_frame_alignment_ = info()->IsOptimizing() &&
64 ((chunk()->num_double_slots() > 2 &&
65 !chunk()->graph()->is_recursive()) ||
66 !info()->osr_ast_id().IsNone());
68 return GeneratePrologue() &&
70 GenerateDeferredCode() &&
71 GenerateJumpTable() &&
72 GenerateSafepointTable();
76 void LCodeGen::FinishCode(Handle<Code> code) {
78 code->set_stack_slots(GetStackSlotCount());
79 code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
80 PopulateDeoptimizationData(code);
81 if (!info()->IsStub()) {
82 Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(code);
88 void LCodeGen::MakeSureStackPagesMapped(int offset) {
89 const int kPageSize = 4 * KB;
90 for (offset -= kPageSize; offset > 0; offset -= kPageSize) {
91 __ mov(Operand(esp, offset), eax);
97 bool LCodeGen::GeneratePrologue() {
98 DCHECK(is_generating());
100 if (info()->IsOptimizing()) {
101 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
104 if (strlen(FLAG_stop_at) > 0 &&
105 info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
110 // Sloppy mode functions and builtins need to replace the receiver with the
111 // global proxy when called as functions (without an explicit receiver
113 if (graph()->this_has_uses() && is_sloppy(info_->language_mode()) &&
114 !info_->is_native()) {
116 // +1 for return address.
117 int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
118 __ mov(ecx, Operand(esp, receiver_offset));
120 __ cmp(ecx, isolate()->factory()->undefined_value());
121 __ j(not_equal, &ok, Label::kNear);
123 __ mov(ecx, GlobalObjectOperand());
124 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
126 __ mov(Operand(esp, receiver_offset), ecx);
131 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
132 // Move state of dynamic frame alignment into edx.
133 __ Move(edx, Immediate(kNoAlignmentPadding));
135 Label do_not_pad, align_loop;
136 STATIC_ASSERT(kDoubleSize == 2 * kPointerSize);
137 // Align esp + 4 to a multiple of 2 * kPointerSize.
138 __ test(esp, Immediate(kPointerSize));
139 __ j(not_zero, &do_not_pad, Label::kNear);
140 __ push(Immediate(0));
142 __ mov(edx, Immediate(kAlignmentPaddingPushed));
143 // Copy arguments, receiver, and return address.
144 __ mov(ecx, Immediate(scope()->num_parameters() + 2));
146 __ bind(&align_loop);
147 __ mov(eax, Operand(ebx, 1 * kPointerSize));
148 __ mov(Operand(ebx, 0), eax);
149 __ add(Operand(ebx), Immediate(kPointerSize));
151 __ j(not_zero, &align_loop, Label::kNear);
152 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
153 __ bind(&do_not_pad);
157 info()->set_prologue_offset(masm_->pc_offset());
158 if (NeedsEagerFrame()) {
159 DCHECK(!frame_is_built_);
160 frame_is_built_ = true;
161 if (info()->IsStub()) {
164 __ Prologue(info()->IsCodePreAgingActive());
166 info()->AddNoFrameRange(0, masm_->pc_offset());
169 if (info()->IsOptimizing() &&
170 dynamic_frame_alignment_ &&
172 __ test(esp, Immediate(kPointerSize));
173 __ Assert(zero, kFrameIsExpectedToBeAligned);
176 // Reserve space for the stack slots needed by the code.
177 int slots = GetStackSlotCount();
178 DCHECK(slots != 0 || !info()->IsOptimizing());
181 if (dynamic_frame_alignment_) {
184 __ push(Immediate(kNoAlignmentPadding));
187 if (FLAG_debug_code) {
188 __ sub(Operand(esp), Immediate(slots * kPointerSize));
190 MakeSureStackPagesMapped(slots * kPointerSize);
193 __ mov(Operand(eax), Immediate(slots));
196 __ mov(MemOperand(esp, eax, times_4, 0),
197 Immediate(kSlotsZapValue));
199 __ j(not_zero, &loop);
202 __ sub(Operand(esp), Immediate(slots * kPointerSize));
204 MakeSureStackPagesMapped(slots * kPointerSize);
208 if (support_aligned_spilled_doubles_) {
209 Comment(";;; Store dynamic frame alignment tag for spilled doubles");
210 // Store dynamic frame alignment state in the first local.
211 int offset = JavaScriptFrameConstants::kDynamicAlignmentStateOffset;
212 if (dynamic_frame_alignment_) {
213 __ mov(Operand(ebp, offset), edx);
215 __ mov(Operand(ebp, offset), Immediate(kNoAlignmentPadding));
221 // Possibly allocate a local context.
222 int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
223 if (heap_slots > 0) {
224 Comment(";;; Allocate local context");
225 bool need_write_barrier = true;
226 // Argument to NewContext is the function, which is still in edi.
227 if (heap_slots <= FastNewContextStub::kMaximumSlots) {
228 FastNewContextStub stub(isolate(), heap_slots);
230 // Result of FastNewContextStub is always in new space.
231 need_write_barrier = false;
234 __ CallRuntime(Runtime::kNewFunctionContext, 1);
236 RecordSafepoint(Safepoint::kNoLazyDeopt);
237 // Context is returned in eax. It replaces the context passed to us.
238 // It's saved in the stack and kept live in esi.
240 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
242 // Copy parameters into context if necessary.
243 int num_parameters = scope()->num_parameters();
244 for (int i = 0; i < num_parameters; i++) {
245 Variable* var = scope()->parameter(i);
246 if (var->IsContextSlot()) {
247 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
248 (num_parameters - 1 - i) * kPointerSize;
249 // Load parameter from stack.
250 __ mov(eax, Operand(ebp, parameter_offset));
251 // Store it in the context.
252 int context_offset = Context::SlotOffset(var->index());
253 __ mov(Operand(esi, context_offset), eax);
254 // Update the write barrier. This clobbers eax and ebx.
255 if (need_write_barrier) {
256 __ RecordWriteContextSlot(esi, context_offset, eax, ebx,
258 } else if (FLAG_debug_code) {
260 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
261 __ Abort(kExpectedNewSpaceObject);
266 Comment(";;; End allocate local context");
269 // Initailize FPU state.
272 if (FLAG_trace && info()->IsOptimizing()) {
273 // We have not executed any compiled code yet, so esi still holds the
275 __ CallRuntime(Runtime::kTraceEnter, 0);
277 return !is_aborted();
281 void LCodeGen::GenerateOsrPrologue() {
282 // Generate the OSR entry prologue at the first unknown OSR value, or if there
283 // are none, at the OSR entrypoint instruction.
284 if (osr_pc_offset_ >= 0) return;
286 osr_pc_offset_ = masm()->pc_offset();
288 // Move state of dynamic frame alignment into edx.
289 __ Move(edx, Immediate(kNoAlignmentPadding));
291 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
292 Label do_not_pad, align_loop;
293 // Align ebp + 4 to a multiple of 2 * kPointerSize.
294 __ test(ebp, Immediate(kPointerSize));
295 __ j(zero, &do_not_pad, Label::kNear);
296 __ push(Immediate(0));
298 __ mov(edx, Immediate(kAlignmentPaddingPushed));
300 // Move all parts of the frame over one word. The frame consists of:
301 // unoptimized frame slots, alignment state, context, frame pointer, return
302 // address, receiver, and the arguments.
303 __ mov(ecx, Immediate(scope()->num_parameters() +
304 5 + graph()->osr()->UnoptimizedFrameSlots()));
306 __ bind(&align_loop);
307 __ mov(eax, Operand(ebx, 1 * kPointerSize));
308 __ mov(Operand(ebx, 0), eax);
309 __ add(Operand(ebx), Immediate(kPointerSize));
311 __ j(not_zero, &align_loop, Label::kNear);
312 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
313 __ sub(Operand(ebp), Immediate(kPointerSize));
314 __ bind(&do_not_pad);
317 // Save the first local, which is overwritten by the alignment state.
318 Operand alignment_loc = MemOperand(ebp, -3 * kPointerSize);
319 __ push(alignment_loc);
321 // Set the dynamic frame alignment state.
322 __ mov(alignment_loc, edx);
324 // Adjust the frame size, subsuming the unoptimized frame into the
326 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
328 __ sub(esp, Immediate((slots - 1) * kPointerSize));
330 // Initailize FPU state.
335 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
336 if (instr->IsCall()) {
337 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
339 if (!instr->IsLazyBailout() && !instr->IsGap()) {
340 safepoints_.BumpLastLazySafepointIndex();
342 FlushX87StackIfNecessary(instr);
346 void LCodeGen::GenerateBodyInstructionPost(LInstruction* instr) {
347 // When return from function call, FPU should be initialized again.
348 if (instr->IsCall() && instr->ClobbersDoubleRegisters(isolate())) {
349 bool double_result = instr->HasDoubleRegisterResult();
351 __ lea(esp, Operand(esp, -kDoubleSize));
352 __ fstp_d(Operand(esp, 0));
356 __ fld_d(Operand(esp, 0));
357 __ lea(esp, Operand(esp, kDoubleSize));
360 if (instr->IsGoto()) {
361 x87_stack_.LeavingBlock(current_block_, LGoto::cast(instr), this);
362 } else if (FLAG_debug_code && FLAG_enable_slow_asserts &&
363 !instr->IsGap() && !instr->IsReturn()) {
364 if (instr->ClobbersDoubleRegisters(isolate())) {
365 if (instr->HasDoubleRegisterResult()) {
366 DCHECK_EQ(1, x87_stack_.depth());
368 DCHECK_EQ(0, x87_stack_.depth());
371 __ VerifyX87StackDepth(x87_stack_.depth());
376 bool LCodeGen::GenerateJumpTable() {
377 if (!jump_table_.length()) return !is_aborted();
380 Comment(";;; -------------------- Jump table --------------------");
382 for (int i = 0; i < jump_table_.length(); i++) {
383 Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
384 __ bind(&table_entry->label);
385 Address entry = table_entry->address;
386 DeoptComment(table_entry->deopt_info);
387 if (table_entry->needs_frame) {
388 DCHECK(!info()->saves_caller_doubles());
389 __ push(Immediate(ExternalReference::ForDeoptEntry(entry)));
390 __ call(&needs_frame);
392 __ call(entry, RelocInfo::RUNTIME_ENTRY);
394 info()->LogDeoptCallPosition(masm()->pc_offset(),
395 table_entry->deopt_info.inlining_id);
397 if (needs_frame.is_linked()) {
398 __ bind(&needs_frame);
402 3: return address <-- esp
407 __ sub(esp, Immediate(kPointerSize)); // Reserve space for stub marker.
408 __ push(MemOperand(esp, kPointerSize)); // Copy return address.
409 __ push(MemOperand(esp, 3 * kPointerSize)); // Copy entry address.
416 0: entry address <-- esp
418 __ mov(MemOperand(esp, 4 * kPointerSize), ebp); // Save ebp.
421 __ mov(ebp, MemOperand(ebp, StandardFrameConstants::kContextOffset));
422 __ mov(MemOperand(esp, 3 * kPointerSize), ebp);
423 // Fill ebp with the right stack frame address.
424 __ lea(ebp, MemOperand(esp, 4 * kPointerSize));
426 // This variant of deopt can only be used with stubs. Since we don't
427 // have a function pointer to install in the stack frame that we're
428 // building, install a special marker there instead.
429 DCHECK(info()->IsStub());
430 __ mov(MemOperand(esp, 2 * kPointerSize),
431 Immediate(Smi::FromInt(StackFrame::STUB)));
438 0: entry address <-- esp
440 __ ret(0); // Call the continuation without clobbering registers.
442 return !is_aborted();
446 bool LCodeGen::GenerateDeferredCode() {
447 DCHECK(is_generating());
448 if (deferred_.length() > 0) {
449 for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
450 LDeferredCode* code = deferred_[i];
451 X87Stack copy(code->x87_stack());
455 instructions_->at(code->instruction_index())->hydrogen_value();
456 RecordAndWritePosition(
457 chunk()->graph()->SourcePositionToScriptPosition(value->position()));
459 Comment(";;; <@%d,#%d> "
460 "-------------------- Deferred %s --------------------",
461 code->instruction_index(),
462 code->instr()->hydrogen_value()->id(),
463 code->instr()->Mnemonic());
464 __ bind(code->entry());
465 if (NeedsDeferredFrame()) {
466 Comment(";;; Build frame");
467 DCHECK(!frame_is_built_);
468 DCHECK(info()->IsStub());
469 frame_is_built_ = true;
470 // Build the frame in such a way that esi isn't trashed.
471 __ push(ebp); // Caller's frame pointer.
472 __ push(Operand(ebp, StandardFrameConstants::kContextOffset));
473 __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
474 __ lea(ebp, Operand(esp, 2 * kPointerSize));
475 Comment(";;; Deferred code");
478 if (NeedsDeferredFrame()) {
479 __ bind(code->done());
480 Comment(";;; Destroy frame");
481 DCHECK(frame_is_built_);
482 frame_is_built_ = false;
486 __ jmp(code->exit());
490 // Deferred code is the last part of the instruction sequence. Mark
491 // the generated code as done unless we bailed out.
492 if (!is_aborted()) status_ = DONE;
493 return !is_aborted();
497 bool LCodeGen::GenerateSafepointTable() {
499 if (!info()->IsStub()) {
500 // For lazy deoptimization we need space to patch a call after every call.
501 // Ensure there is always space for such patching, even if the code ends
503 int target_offset = masm()->pc_offset() + Deoptimizer::patch_size();
504 while (masm()->pc_offset() < target_offset) {
508 safepoints_.Emit(masm(), GetStackSlotCount());
509 return !is_aborted();
513 Register LCodeGen::ToRegister(int index) const {
514 return Register::FromAllocationIndex(index);
518 X87Register LCodeGen::ToX87Register(int index) const {
519 return X87Register::FromAllocationIndex(index);
523 void LCodeGen::X87LoadForUsage(X87Register reg) {
524 DCHECK(x87_stack_.Contains(reg));
525 x87_stack_.Fxch(reg);
530 void LCodeGen::X87LoadForUsage(X87Register reg1, X87Register reg2) {
531 DCHECK(x87_stack_.Contains(reg1));
532 DCHECK(x87_stack_.Contains(reg2));
533 if (reg1.is(reg2) && x87_stack_.depth() == 1) {
534 __ fld(x87_stack_.st(reg1));
535 x87_stack_.push(reg1);
539 x87_stack_.Fxch(reg1, 1);
540 x87_stack_.Fxch(reg2);
547 int LCodeGen::X87Stack::GetLayout() {
548 int layout = stack_depth_;
549 for (int i = 0; i < stack_depth_; i++) {
550 layout |= (stack_[stack_depth_ - 1 - i].code() << ((i + 1) * 3));
557 void LCodeGen::X87Stack::Fxch(X87Register reg, int other_slot) {
559 DCHECK(Contains(reg) && stack_depth_ > other_slot);
560 int i = ArrayIndex(reg);
562 if (st != other_slot) {
563 int other_i = st2idx(other_slot);
564 X87Register other = stack_[other_i];
565 stack_[other_i] = reg;
569 } else if (other_slot == 0) {
580 int LCodeGen::X87Stack::st2idx(int pos) {
581 return stack_depth_ - pos - 1;
585 int LCodeGen::X87Stack::ArrayIndex(X87Register reg) {
586 for (int i = 0; i < stack_depth_; i++) {
587 if (stack_[i].is(reg)) return i;
594 bool LCodeGen::X87Stack::Contains(X87Register reg) {
595 for (int i = 0; i < stack_depth_; i++) {
596 if (stack_[i].is(reg)) return true;
602 void LCodeGen::X87Stack::Free(X87Register reg) {
604 DCHECK(Contains(reg));
605 int i = ArrayIndex(reg);
608 // keep track of how fstp(i) changes the order of elements
609 int tos_i = st2idx(0);
610 stack_[i] = stack_[tos_i];
617 void LCodeGen::X87Mov(X87Register dst, Operand src, X87OperandType opts) {
618 if (x87_stack_.Contains(dst)) {
619 x87_stack_.Fxch(dst);
622 x87_stack_.push(dst);
628 void LCodeGen::X87Mov(X87Register dst, X87Register src, X87OperandType opts) {
629 if (x87_stack_.Contains(dst)) {
630 x87_stack_.Fxch(dst);
633 // Push ST(i) onto the FPU register stack
634 __ fld(x87_stack_.st(src));
635 x87_stack_.push(dst);
637 // Push ST(i) onto the FPU register stack
638 __ fld(x87_stack_.st(src));
639 x87_stack_.push(dst);
644 void LCodeGen::X87Fld(Operand src, X87OperandType opts) {
645 DCHECK(!src.is_reg_only());
647 case kX87DoubleOperand:
650 case kX87FloatOperand:
662 void LCodeGen::X87Mov(Operand dst, X87Register src, X87OperandType opts) {
663 DCHECK(!dst.is_reg_only());
664 x87_stack_.Fxch(src);
666 case kX87DoubleOperand:
669 case kX87FloatOperand:
681 void LCodeGen::X87Stack::PrepareToWrite(X87Register reg) {
686 // Mark this register as the next register to write to
687 stack_[stack_depth_] = reg;
691 void LCodeGen::X87Stack::CommitWrite(X87Register reg) {
693 // Assert the reg is prepared to write, but not on the virtual stack yet
694 DCHECK(!Contains(reg) && stack_[stack_depth_].is(reg) &&
695 stack_depth_ < X87Register::kMaxNumAllocatableRegisters);
700 void LCodeGen::X87PrepareBinaryOp(
701 X87Register left, X87Register right, X87Register result) {
702 // You need to use DefineSameAsFirst for x87 instructions
703 DCHECK(result.is(left));
704 x87_stack_.Fxch(right, 1);
705 x87_stack_.Fxch(left);
709 void LCodeGen::X87Stack::FlushIfNecessary(LInstruction* instr, LCodeGen* cgen) {
710 if (stack_depth_ > 0 && instr->ClobbersDoubleRegisters(isolate())) {
711 bool double_inputs = instr->HasDoubleRegisterInput();
713 // Flush stack from tos down, since FreeX87() will mess with tos
714 for (int i = stack_depth_-1; i >= 0; i--) {
715 X87Register reg = stack_[i];
716 // Skip registers which contain the inputs for the next instruction
717 // when flushing the stack
718 if (double_inputs && instr->IsDoubleInput(reg, cgen)) {
722 if (i < stack_depth_-1) i++;
725 if (instr->IsReturn()) {
726 while (stack_depth_ > 0) {
730 if (FLAG_debug_code && FLAG_enable_slow_asserts) __ VerifyX87StackDepth(0);
735 void LCodeGen::X87Stack::LeavingBlock(int current_block_id, LGoto* goto_instr,
737 // For going to a joined block, an explicit LClobberDoubles is inserted before
738 // LGoto. Because all used x87 registers are spilled to stack slots. The
739 // ResolvePhis phase of register allocator could guarantee the two input's x87
740 // stacks have the same layout. So don't check stack_depth_ <= 1 here.
741 int goto_block_id = goto_instr->block_id();
742 if (current_block_id + 1 != goto_block_id) {
743 // If we have a value on the x87 stack on leaving a block, it must be a
744 // phi input. If the next block we compile is not the join block, we have
745 // to discard the stack state.
746 // Before discarding the stack state, we need to save it if the "goto block"
747 // has unreachable last predecessor when FLAG_unreachable_code_elimination.
748 if (FLAG_unreachable_code_elimination) {
749 int length = goto_instr->block()->predecessors()->length();
750 bool has_unreachable_last_predecessor = false;
751 for (int i = 0; i < length; i++) {
752 HBasicBlock* block = goto_instr->block()->predecessors()->at(i);
753 if (block->IsUnreachable() &&
754 (block->block_id() + 1) == goto_block_id) {
755 has_unreachable_last_predecessor = true;
758 if (has_unreachable_last_predecessor) {
759 if (cgen->x87_stack_map_.find(goto_block_id) ==
760 cgen->x87_stack_map_.end()) {
761 X87Stack* stack = new (cgen->zone()) X87Stack(*this);
762 cgen->x87_stack_map_.insert(std::make_pair(goto_block_id, stack));
767 // Discard the stack state.
773 void LCodeGen::EmitFlushX87ForDeopt() {
774 // The deoptimizer does not support X87 Registers. But as long as we
775 // deopt from a stub its not a problem, since we will re-materialize the
776 // original stub inputs, which can't be double registers.
777 // DCHECK(info()->IsStub());
778 if (FLAG_debug_code && FLAG_enable_slow_asserts) {
780 __ VerifyX87StackDepth(x87_stack_.depth());
784 // Flush X87 stack in the deoptimizer entry.
788 Register LCodeGen::ToRegister(LOperand* op) const {
789 DCHECK(op->IsRegister());
790 return ToRegister(op->index());
794 X87Register LCodeGen::ToX87Register(LOperand* op) const {
795 DCHECK(op->IsDoubleRegister());
796 return ToX87Register(op->index());
800 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
801 return ToRepresentation(op, Representation::Integer32());
805 int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
806 const Representation& r) const {
807 HConstant* constant = chunk_->LookupConstant(op);
808 int32_t value = constant->Integer32Value();
809 if (r.IsInteger32()) return value;
810 DCHECK(r.IsSmiOrTagged());
811 return reinterpret_cast<int32_t>(Smi::FromInt(value));
815 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
816 HConstant* constant = chunk_->LookupConstant(op);
817 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
818 return constant->handle(isolate());
822 double LCodeGen::ToDouble(LConstantOperand* op) const {
823 HConstant* constant = chunk_->LookupConstant(op);
824 DCHECK(constant->HasDoubleValue());
825 return constant->DoubleValue();
829 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
830 HConstant* constant = chunk_->LookupConstant(op);
831 DCHECK(constant->HasExternalReferenceValue());
832 return constant->ExternalReferenceValue();
836 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
837 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
841 bool LCodeGen::IsSmi(LConstantOperand* op) const {
842 return chunk_->LookupLiteralRepresentation(op).IsSmi();
846 static int ArgumentsOffsetWithoutFrame(int index) {
848 return -(index + 1) * kPointerSize + kPCOnStackSize;
852 Operand LCodeGen::ToOperand(LOperand* op) const {
853 if (op->IsRegister()) return Operand(ToRegister(op));
854 DCHECK(!op->IsDoubleRegister());
855 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
856 if (NeedsEagerFrame()) {
857 return Operand(ebp, StackSlotOffset(op->index()));
859 // Retrieve parameter without eager stack-frame relative to the
861 return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
866 Operand LCodeGen::HighOperand(LOperand* op) {
867 DCHECK(op->IsDoubleStackSlot());
868 if (NeedsEagerFrame()) {
869 return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
871 // Retrieve parameter without eager stack-frame relative to the
874 esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
879 void LCodeGen::WriteTranslation(LEnvironment* environment,
880 Translation* translation) {
881 if (environment == NULL) return;
883 // The translation includes one command per value in the environment.
884 int translation_size = environment->translation_size();
885 // The output frame height does not include the parameters.
886 int height = translation_size - environment->parameter_count();
888 WriteTranslation(environment->outer(), translation);
889 bool has_closure_id = !info()->closure().is_null() &&
890 !info()->closure().is_identical_to(environment->closure());
891 int closure_id = has_closure_id
892 ? DefineDeoptimizationLiteral(environment->closure())
893 : Translation::kSelfLiteralId;
894 switch (environment->frame_type()) {
896 translation->BeginJSFrame(environment->ast_id(), closure_id, height);
899 translation->BeginConstructStubFrame(closure_id, translation_size);
902 DCHECK(translation_size == 1);
904 translation->BeginGetterStubFrame(closure_id);
907 DCHECK(translation_size == 2);
909 translation->BeginSetterStubFrame(closure_id);
911 case ARGUMENTS_ADAPTOR:
912 translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
915 translation->BeginCompiledStubFrame();
921 int object_index = 0;
922 int dematerialized_index = 0;
923 for (int i = 0; i < translation_size; ++i) {
924 LOperand* value = environment->values()->at(i);
925 AddToTranslation(environment,
928 environment->HasTaggedValueAt(i),
929 environment->HasUint32ValueAt(i),
931 &dematerialized_index);
936 void LCodeGen::AddToTranslation(LEnvironment* environment,
937 Translation* translation,
941 int* object_index_pointer,
942 int* dematerialized_index_pointer) {
943 if (op == LEnvironment::materialization_marker()) {
944 int object_index = (*object_index_pointer)++;
945 if (environment->ObjectIsDuplicateAt(object_index)) {
946 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
947 translation->DuplicateObject(dupe_of);
950 int object_length = environment->ObjectLengthAt(object_index);
951 if (environment->ObjectIsArgumentsAt(object_index)) {
952 translation->BeginArgumentsObject(object_length);
954 translation->BeginCapturedObject(object_length);
956 int dematerialized_index = *dematerialized_index_pointer;
957 int env_offset = environment->translation_size() + dematerialized_index;
958 *dematerialized_index_pointer += object_length;
959 for (int i = 0; i < object_length; ++i) {
960 LOperand* value = environment->values()->at(env_offset + i);
961 AddToTranslation(environment,
964 environment->HasTaggedValueAt(env_offset + i),
965 environment->HasUint32ValueAt(env_offset + i),
966 object_index_pointer,
967 dematerialized_index_pointer);
972 if (op->IsStackSlot()) {
974 translation->StoreStackSlot(op->index());
975 } else if (is_uint32) {
976 translation->StoreUint32StackSlot(op->index());
978 translation->StoreInt32StackSlot(op->index());
980 } else if (op->IsDoubleStackSlot()) {
981 translation->StoreDoubleStackSlot(op->index());
982 } else if (op->IsRegister()) {
983 Register reg = ToRegister(op);
985 translation->StoreRegister(reg);
986 } else if (is_uint32) {
987 translation->StoreUint32Register(reg);
989 translation->StoreInt32Register(reg);
991 } else if (op->IsDoubleRegister()) {
992 X87Register reg = ToX87Register(op);
993 translation->StoreDoubleRegister(reg);
994 } else if (op->IsConstantOperand()) {
995 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
996 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
997 translation->StoreLiteral(src_index);
1004 void LCodeGen::CallCodeGeneric(Handle<Code> code,
1005 RelocInfo::Mode mode,
1006 LInstruction* instr,
1007 SafepointMode safepoint_mode) {
1008 DCHECK(instr != NULL);
1009 __ call(code, mode);
1010 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
1012 // Signal that we don't inline smi code before these stubs in the
1013 // optimizing code generator.
1014 if (code->kind() == Code::BINARY_OP_IC ||
1015 code->kind() == Code::COMPARE_IC) {
1021 void LCodeGen::CallCode(Handle<Code> code,
1022 RelocInfo::Mode mode,
1023 LInstruction* instr) {
1024 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
1028 void LCodeGen::CallRuntime(const Runtime::Function* fun, int argc,
1029 LInstruction* instr, SaveFPRegsMode save_doubles) {
1030 DCHECK(instr != NULL);
1031 DCHECK(instr->HasPointerMap());
1033 __ CallRuntime(fun, argc, save_doubles);
1035 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
1037 DCHECK(info()->is_calling());
1041 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
1042 if (context->IsRegister()) {
1043 if (!ToRegister(context).is(esi)) {
1044 __ mov(esi, ToRegister(context));
1046 } else if (context->IsStackSlot()) {
1047 __ mov(esi, ToOperand(context));
1048 } else if (context->IsConstantOperand()) {
1049 HConstant* constant =
1050 chunk_->LookupConstant(LConstantOperand::cast(context));
1051 __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
1057 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
1059 LInstruction* instr,
1060 LOperand* context) {
1061 LoadContextFromDeferred(context);
1063 __ CallRuntimeSaveDoubles(id);
1064 RecordSafepointWithRegisters(
1065 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
1067 DCHECK(info()->is_calling());
1071 void LCodeGen::RegisterEnvironmentForDeoptimization(
1072 LEnvironment* environment, Safepoint::DeoptMode mode) {
1073 environment->set_has_been_used();
1074 if (!environment->HasBeenRegistered()) {
1075 // Physical stack frame layout:
1076 // -x ............. -4 0 ..................................... y
1077 // [incoming arguments] [spill slots] [pushed outgoing arguments]
1079 // Layout of the environment:
1080 // 0 ..................................................... size-1
1081 // [parameters] [locals] [expression stack including arguments]
1083 // Layout of the translation:
1084 // 0 ........................................................ size - 1 + 4
1085 // [expression stack including arguments] [locals] [4 words] [parameters]
1086 // |>------------ translation_size ------------<|
1088 int frame_count = 0;
1089 int jsframe_count = 0;
1090 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
1092 if (e->frame_type() == JS_FUNCTION) {
1096 Translation translation(&translations_, frame_count, jsframe_count, zone());
1097 WriteTranslation(environment, &translation);
1098 int deoptimization_index = deoptimizations_.length();
1099 int pc_offset = masm()->pc_offset();
1100 environment->Register(deoptimization_index,
1101 translation.index(),
1102 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
1103 deoptimizations_.Add(environment, zone());
1108 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1109 Deoptimizer::DeoptReason deopt_reason,
1110 Deoptimizer::BailoutType bailout_type) {
1111 LEnvironment* environment = instr->environment();
1112 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
1113 DCHECK(environment->HasBeenRegistered());
1114 int id = environment->deoptimization_index();
1115 DCHECK(info()->IsOptimizing() || info()->IsStub());
1117 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
1118 if (entry == NULL) {
1119 Abort(kBailoutWasNotPrepared);
1123 if (DeoptEveryNTimes()) {
1124 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
1128 __ mov(eax, Operand::StaticVariable(count));
1129 __ sub(eax, Immediate(1));
1130 __ j(not_zero, &no_deopt, Label::kNear);
1131 if (FLAG_trap_on_deopt) __ int3();
1132 __ mov(eax, Immediate(FLAG_deopt_every_n_times));
1133 __ mov(Operand::StaticVariable(count), eax);
1136 DCHECK(frame_is_built_);
1137 // Put the x87 stack layout in TOS.
1138 if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1139 __ push(Immediate(x87_stack_.GetLayout()));
1140 __ fild_s(MemOperand(esp, 0));
1141 // Don't touch eflags.
1142 __ lea(esp, Operand(esp, kPointerSize));
1143 __ call(entry, RelocInfo::RUNTIME_ENTRY);
1145 __ mov(Operand::StaticVariable(count), eax);
1150 // Put the x87 stack layout in TOS, so that we can save x87 fp registers in
1151 // the correct location.
1154 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1155 if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1157 int x87_stack_layout = x87_stack_.GetLayout();
1158 __ push(Immediate(x87_stack_layout));
1159 __ fild_s(MemOperand(esp, 0));
1160 // Don't touch eflags.
1161 __ lea(esp, Operand(esp, kPointerSize));
1165 if (info()->ShouldTrapOnDeopt()) {
1167 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1172 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
1174 DCHECK(info()->IsStub() || frame_is_built_);
1175 if (cc == no_condition && frame_is_built_) {
1176 DeoptComment(deopt_info);
1177 __ call(entry, RelocInfo::RUNTIME_ENTRY);
1178 info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
1180 Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
1182 // We often have several deopts to the same entry, reuse the last
1183 // jump entry if this is the case.
1184 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
1185 jump_table_.is_empty() ||
1186 !table_entry.IsEquivalentTo(jump_table_.last())) {
1187 jump_table_.Add(table_entry, zone());
1189 if (cc == no_condition) {
1190 __ jmp(&jump_table_.last().label);
1192 __ j(cc, &jump_table_.last().label);
1198 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1199 Deoptimizer::DeoptReason deopt_reason) {
1200 Deoptimizer::BailoutType bailout_type = info()->IsStub()
1202 : Deoptimizer::EAGER;
1203 DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
1207 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
1208 int length = deoptimizations_.length();
1209 if (length == 0) return;
1210 Handle<DeoptimizationInputData> data =
1211 DeoptimizationInputData::New(isolate(), length, TENURED);
1213 Handle<ByteArray> translations =
1214 translations_.CreateByteArray(isolate()->factory());
1215 data->SetTranslationByteArray(*translations);
1216 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
1217 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
1218 if (info_->IsOptimizing()) {
1219 // Reference to shared function info does not change between phases.
1220 AllowDeferredHandleDereference allow_handle_dereference;
1221 data->SetSharedFunctionInfo(*info_->shared_info());
1223 data->SetSharedFunctionInfo(Smi::FromInt(0));
1225 data->SetWeakCellCache(Smi::FromInt(0));
1227 Handle<FixedArray> literals =
1228 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
1229 { AllowDeferredHandleDereference copy_handles;
1230 for (int i = 0; i < deoptimization_literals_.length(); i++) {
1231 literals->set(i, *deoptimization_literals_[i]);
1233 data->SetLiteralArray(*literals);
1236 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
1237 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
1239 // Populate the deoptimization entries.
1240 for (int i = 0; i < length; i++) {
1241 LEnvironment* env = deoptimizations_[i];
1242 data->SetAstId(i, env->ast_id());
1243 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
1244 data->SetArgumentsStackHeight(i,
1245 Smi::FromInt(env->arguments_stack_height()));
1246 data->SetPc(i, Smi::FromInt(env->pc_offset()));
1248 code->set_deoptimization_data(*data);
1252 int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
1253 int result = deoptimization_literals_.length();
1254 for (int i = 0; i < deoptimization_literals_.length(); ++i) {
1255 if (deoptimization_literals_[i].is_identical_to(literal)) return i;
1257 deoptimization_literals_.Add(literal, zone());
1262 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
1263 DCHECK(deoptimization_literals_.length() == 0);
1265 const ZoneList<Handle<JSFunction> >* inlined_closures =
1266 chunk()->inlined_closures();
1268 for (int i = 0, length = inlined_closures->length();
1271 DefineDeoptimizationLiteral(inlined_closures->at(i));
1274 inlined_function_count_ = deoptimization_literals_.length();
1278 void LCodeGen::RecordSafepointWithLazyDeopt(
1279 LInstruction* instr, SafepointMode safepoint_mode) {
1280 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
1281 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
1283 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
1284 RecordSafepointWithRegisters(
1285 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
1290 void LCodeGen::RecordSafepoint(
1291 LPointerMap* pointers,
1292 Safepoint::Kind kind,
1294 Safepoint::DeoptMode deopt_mode) {
1295 DCHECK(kind == expected_safepoint_kind_);
1296 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
1297 Safepoint safepoint =
1298 safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
1299 for (int i = 0; i < operands->length(); i++) {
1300 LOperand* pointer = operands->at(i);
1301 if (pointer->IsStackSlot()) {
1302 safepoint.DefinePointerSlot(pointer->index(), zone());
1303 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
1304 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
1310 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
1311 Safepoint::DeoptMode mode) {
1312 RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
1316 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
1317 LPointerMap empty_pointers(zone());
1318 RecordSafepoint(&empty_pointers, mode);
1322 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
1324 Safepoint::DeoptMode mode) {
1325 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1329 void LCodeGen::RecordAndWritePosition(int position) {
1330 if (position == RelocInfo::kNoPosition) return;
1331 masm()->positions_recorder()->RecordPosition(position);
1332 masm()->positions_recorder()->WriteRecordedPositions();
1336 static const char* LabelType(LLabel* label) {
1337 if (label->is_loop_header()) return " (loop header)";
1338 if (label->is_osr_entry()) return " (OSR entry)";
1343 void LCodeGen::DoLabel(LLabel* label) {
1344 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1345 current_instruction_,
1346 label->hydrogen_value()->id(),
1349 __ bind(label->label());
1350 current_block_ = label->block_id();
1351 if (label->block()->predecessors()->length() > 1) {
1352 // A join block's x87 stack is that of its last visited predecessor.
1353 // If the last visited predecessor block is unreachable, the stack state
1354 // will be wrong. In such case, use the x87 stack of reachable predecessor.
1355 X87StackMap::const_iterator it = x87_stack_map_.find(current_block_);
1356 // Restore x87 stack.
1357 if (it != x87_stack_map_.end()) {
1358 x87_stack_ = *(it->second);
1365 void LCodeGen::DoParallelMove(LParallelMove* move) {
1366 resolver_.Resolve(move);
1370 void LCodeGen::DoGap(LGap* gap) {
1371 for (int i = LGap::FIRST_INNER_POSITION;
1372 i <= LGap::LAST_INNER_POSITION;
1374 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1375 LParallelMove* move = gap->GetParallelMove(inner_pos);
1376 if (move != NULL) DoParallelMove(move);
1381 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1386 void LCodeGen::DoParameter(LParameter* instr) {
1391 void LCodeGen::DoCallStub(LCallStub* instr) {
1392 DCHECK(ToRegister(instr->context()).is(esi));
1393 DCHECK(ToRegister(instr->result()).is(eax));
1394 switch (instr->hydrogen()->major_key()) {
1395 case CodeStub::RegExpExec: {
1396 RegExpExecStub stub(isolate());
1397 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1400 case CodeStub::SubString: {
1401 SubStringStub stub(isolate());
1402 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1405 case CodeStub::StringCompare: {
1406 StringCompareStub stub(isolate());
1407 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1416 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1417 GenerateOsrPrologue();
1421 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1422 Register dividend = ToRegister(instr->dividend());
1423 int32_t divisor = instr->divisor();
1424 DCHECK(dividend.is(ToRegister(instr->result())));
1426 // Theoretically, a variation of the branch-free code for integer division by
1427 // a power of 2 (calculating the remainder via an additional multiplication
1428 // (which gets simplified to an 'and') and subtraction) should be faster, and
1429 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1430 // indicate that positive dividends are heavily favored, so the branching
1431 // version performs better.
1432 HMod* hmod = instr->hydrogen();
1433 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1434 Label dividend_is_not_negative, done;
1435 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1436 __ test(dividend, dividend);
1437 __ j(not_sign, ÷nd_is_not_negative, Label::kNear);
1438 // Note that this is correct even for kMinInt operands.
1440 __ and_(dividend, mask);
1442 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1443 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1445 __ jmp(&done, Label::kNear);
1448 __ bind(÷nd_is_not_negative);
1449 __ and_(dividend, mask);
1454 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1455 Register dividend = ToRegister(instr->dividend());
1456 int32_t divisor = instr->divisor();
1457 DCHECK(ToRegister(instr->result()).is(eax));
1460 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1464 __ TruncatingDiv(dividend, Abs(divisor));
1465 __ imul(edx, edx, Abs(divisor));
1466 __ mov(eax, dividend);
1469 // Check for negative zero.
1470 HMod* hmod = instr->hydrogen();
1471 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1472 Label remainder_not_zero;
1473 __ j(not_zero, &remainder_not_zero, Label::kNear);
1474 __ cmp(dividend, Immediate(0));
1475 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1476 __ bind(&remainder_not_zero);
1481 void LCodeGen::DoModI(LModI* instr) {
1482 HMod* hmod = instr->hydrogen();
1484 Register left_reg = ToRegister(instr->left());
1485 DCHECK(left_reg.is(eax));
1486 Register right_reg = ToRegister(instr->right());
1487 DCHECK(!right_reg.is(eax));
1488 DCHECK(!right_reg.is(edx));
1489 Register result_reg = ToRegister(instr->result());
1490 DCHECK(result_reg.is(edx));
1493 // Check for x % 0, idiv would signal a divide error. We have to
1494 // deopt in this case because we can't return a NaN.
1495 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1496 __ test(right_reg, Operand(right_reg));
1497 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1500 // Check for kMinInt % -1, idiv would signal a divide error. We
1501 // have to deopt if we care about -0, because we can't return that.
1502 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1503 Label no_overflow_possible;
1504 __ cmp(left_reg, kMinInt);
1505 __ j(not_equal, &no_overflow_possible, Label::kNear);
1506 __ cmp(right_reg, -1);
1507 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1508 DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1510 __ j(not_equal, &no_overflow_possible, Label::kNear);
1511 __ Move(result_reg, Immediate(0));
1512 __ jmp(&done, Label::kNear);
1514 __ bind(&no_overflow_possible);
1517 // Sign extend dividend in eax into edx:eax.
1520 // If we care about -0, test if the dividend is <0 and the result is 0.
1521 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1522 Label positive_left;
1523 __ test(left_reg, Operand(left_reg));
1524 __ j(not_sign, &positive_left, Label::kNear);
1526 __ test(result_reg, Operand(result_reg));
1527 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1528 __ jmp(&done, Label::kNear);
1529 __ bind(&positive_left);
1536 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1537 Register dividend = ToRegister(instr->dividend());
1538 int32_t divisor = instr->divisor();
1539 Register result = ToRegister(instr->result());
1540 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1541 DCHECK(!result.is(dividend));
1543 // Check for (0 / -x) that will produce negative zero.
1544 HDiv* hdiv = instr->hydrogen();
1545 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1546 __ test(dividend, dividend);
1547 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1549 // Check for (kMinInt / -1).
1550 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1551 __ cmp(dividend, kMinInt);
1552 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1554 // Deoptimize if remainder will not be 0.
1555 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1556 divisor != 1 && divisor != -1) {
1557 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1558 __ test(dividend, Immediate(mask));
1559 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1561 __ Move(result, dividend);
1562 int32_t shift = WhichPowerOf2Abs(divisor);
1564 // The arithmetic shift is always OK, the 'if' is an optimization only.
1565 if (shift > 1) __ sar(result, 31);
1566 __ shr(result, 32 - shift);
1567 __ add(result, dividend);
1568 __ sar(result, shift);
1570 if (divisor < 0) __ neg(result);
1574 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1575 Register dividend = ToRegister(instr->dividend());
1576 int32_t divisor = instr->divisor();
1577 DCHECK(ToRegister(instr->result()).is(edx));
1580 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1584 // Check for (0 / -x) that will produce negative zero.
1585 HDiv* hdiv = instr->hydrogen();
1586 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1587 __ test(dividend, dividend);
1588 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1591 __ TruncatingDiv(dividend, Abs(divisor));
1592 if (divisor < 0) __ neg(edx);
1594 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1596 __ imul(eax, eax, divisor);
1597 __ sub(eax, dividend);
1598 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1603 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1604 void LCodeGen::DoDivI(LDivI* instr) {
1605 HBinaryOperation* hdiv = instr->hydrogen();
1606 Register dividend = ToRegister(instr->dividend());
1607 Register divisor = ToRegister(instr->divisor());
1608 Register remainder = ToRegister(instr->temp());
1609 DCHECK(dividend.is(eax));
1610 DCHECK(remainder.is(edx));
1611 DCHECK(ToRegister(instr->result()).is(eax));
1612 DCHECK(!divisor.is(eax));
1613 DCHECK(!divisor.is(edx));
1616 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1617 __ test(divisor, divisor);
1618 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1621 // Check for (0 / -x) that will produce negative zero.
1622 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1623 Label dividend_not_zero;
1624 __ test(dividend, dividend);
1625 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1626 __ test(divisor, divisor);
1627 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1628 __ bind(÷nd_not_zero);
1631 // Check for (kMinInt / -1).
1632 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1633 Label dividend_not_min_int;
1634 __ cmp(dividend, kMinInt);
1635 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1636 __ cmp(divisor, -1);
1637 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1638 __ bind(÷nd_not_min_int);
1641 // Sign extend to edx (= remainder).
1645 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1646 // Deoptimize if remainder is not 0.
1647 __ test(remainder, remainder);
1648 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1653 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1654 Register dividend = ToRegister(instr->dividend());
1655 int32_t divisor = instr->divisor();
1656 DCHECK(dividend.is(ToRegister(instr->result())));
1658 // If the divisor is positive, things are easy: There can be no deopts and we
1659 // can simply do an arithmetic right shift.
1660 if (divisor == 1) return;
1661 int32_t shift = WhichPowerOf2Abs(divisor);
1663 __ sar(dividend, shift);
1667 // If the divisor is negative, we have to negate and handle edge cases.
1669 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1670 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1673 // Dividing by -1 is basically negation, unless we overflow.
1674 if (divisor == -1) {
1675 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1676 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1681 // If the negation could not overflow, simply shifting is OK.
1682 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1683 __ sar(dividend, shift);
1687 Label not_kmin_int, done;
1688 __ j(no_overflow, ¬_kmin_int, Label::kNear);
1689 __ mov(dividend, Immediate(kMinInt / divisor));
1690 __ jmp(&done, Label::kNear);
1691 __ bind(¬_kmin_int);
1692 __ sar(dividend, shift);
1697 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1698 Register dividend = ToRegister(instr->dividend());
1699 int32_t divisor = instr->divisor();
1700 DCHECK(ToRegister(instr->result()).is(edx));
1703 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1707 // Check for (0 / -x) that will produce negative zero.
1708 HMathFloorOfDiv* hdiv = instr->hydrogen();
1709 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1710 __ test(dividend, dividend);
1711 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1714 // Easy case: We need no dynamic check for the dividend and the flooring
1715 // division is the same as the truncating division.
1716 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1717 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1718 __ TruncatingDiv(dividend, Abs(divisor));
1719 if (divisor < 0) __ neg(edx);
1723 // In the general case we may need to adjust before and after the truncating
1724 // division to get a flooring division.
1725 Register temp = ToRegister(instr->temp3());
1726 DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1727 Label needs_adjustment, done;
1728 __ cmp(dividend, Immediate(0));
1729 __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1730 __ TruncatingDiv(dividend, Abs(divisor));
1731 if (divisor < 0) __ neg(edx);
1732 __ jmp(&done, Label::kNear);
1733 __ bind(&needs_adjustment);
1734 __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1735 __ TruncatingDiv(temp, Abs(divisor));
1736 if (divisor < 0) __ neg(edx);
1742 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1743 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1744 HBinaryOperation* hdiv = instr->hydrogen();
1745 Register dividend = ToRegister(instr->dividend());
1746 Register divisor = ToRegister(instr->divisor());
1747 Register remainder = ToRegister(instr->temp());
1748 Register result = ToRegister(instr->result());
1749 DCHECK(dividend.is(eax));
1750 DCHECK(remainder.is(edx));
1751 DCHECK(result.is(eax));
1752 DCHECK(!divisor.is(eax));
1753 DCHECK(!divisor.is(edx));
1756 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1757 __ test(divisor, divisor);
1758 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1761 // Check for (0 / -x) that will produce negative zero.
1762 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1763 Label dividend_not_zero;
1764 __ test(dividend, dividend);
1765 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1766 __ test(divisor, divisor);
1767 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1768 __ bind(÷nd_not_zero);
1771 // Check for (kMinInt / -1).
1772 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1773 Label dividend_not_min_int;
1774 __ cmp(dividend, kMinInt);
1775 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1776 __ cmp(divisor, -1);
1777 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1778 __ bind(÷nd_not_min_int);
1781 // Sign extend to edx (= remainder).
1786 __ test(remainder, remainder);
1787 __ j(zero, &done, Label::kNear);
1788 __ xor_(remainder, divisor);
1789 __ sar(remainder, 31);
1790 __ add(result, remainder);
1795 void LCodeGen::DoMulI(LMulI* instr) {
1796 Register left = ToRegister(instr->left());
1797 LOperand* right = instr->right();
1799 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1800 __ mov(ToRegister(instr->temp()), left);
1803 if (right->IsConstantOperand()) {
1804 // Try strength reductions on the multiplication.
1805 // All replacement instructions are at most as long as the imul
1806 // and have better latency.
1807 int constant = ToInteger32(LConstantOperand::cast(right));
1808 if (constant == -1) {
1810 } else if (constant == 0) {
1811 __ xor_(left, Operand(left));
1812 } else if (constant == 2) {
1813 __ add(left, Operand(left));
1814 } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1815 // If we know that the multiplication can't overflow, it's safe to
1816 // use instructions that don't set the overflow flag for the
1823 __ lea(left, Operand(left, left, times_2, 0));
1829 __ lea(left, Operand(left, left, times_4, 0));
1835 __ lea(left, Operand(left, left, times_8, 0));
1841 __ imul(left, left, constant);
1845 __ imul(left, left, constant);
1848 if (instr->hydrogen()->representation().IsSmi()) {
1851 __ imul(left, ToOperand(right));
1854 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1855 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1858 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1859 // Bail out if the result is supposed to be negative zero.
1861 __ test(left, Operand(left));
1862 __ j(not_zero, &done);
1863 if (right->IsConstantOperand()) {
1864 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1865 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1866 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1867 __ cmp(ToRegister(instr->temp()), Immediate(0));
1868 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1871 // Test the non-zero operand for negative sign.
1872 __ or_(ToRegister(instr->temp()), ToOperand(right));
1873 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1880 void LCodeGen::DoBitI(LBitI* instr) {
1881 LOperand* left = instr->left();
1882 LOperand* right = instr->right();
1883 DCHECK(left->Equals(instr->result()));
1884 DCHECK(left->IsRegister());
1886 if (right->IsConstantOperand()) {
1887 int32_t right_operand =
1888 ToRepresentation(LConstantOperand::cast(right),
1889 instr->hydrogen()->representation());
1890 switch (instr->op()) {
1891 case Token::BIT_AND:
1892 __ and_(ToRegister(left), right_operand);
1895 __ or_(ToRegister(left), right_operand);
1897 case Token::BIT_XOR:
1898 if (right_operand == int32_t(~0)) {
1899 __ not_(ToRegister(left));
1901 __ xor_(ToRegister(left), right_operand);
1909 switch (instr->op()) {
1910 case Token::BIT_AND:
1911 __ and_(ToRegister(left), ToOperand(right));
1914 __ or_(ToRegister(left), ToOperand(right));
1916 case Token::BIT_XOR:
1917 __ xor_(ToRegister(left), ToOperand(right));
1927 void LCodeGen::DoShiftI(LShiftI* instr) {
1928 LOperand* left = instr->left();
1929 LOperand* right = instr->right();
1930 DCHECK(left->Equals(instr->result()));
1931 DCHECK(left->IsRegister());
1932 if (right->IsRegister()) {
1933 DCHECK(ToRegister(right).is(ecx));
1935 switch (instr->op()) {
1937 __ ror_cl(ToRegister(left));
1940 __ sar_cl(ToRegister(left));
1943 __ shr_cl(ToRegister(left));
1944 if (instr->can_deopt()) {
1945 __ test(ToRegister(left), ToRegister(left));
1946 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1950 __ shl_cl(ToRegister(left));
1957 int value = ToInteger32(LConstantOperand::cast(right));
1958 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1959 switch (instr->op()) {
1961 if (shift_count == 0 && instr->can_deopt()) {
1962 __ test(ToRegister(left), ToRegister(left));
1963 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1965 __ ror(ToRegister(left), shift_count);
1969 if (shift_count != 0) {
1970 __ sar(ToRegister(left), shift_count);
1974 if (shift_count != 0) {
1975 __ shr(ToRegister(left), shift_count);
1976 } else if (instr->can_deopt()) {
1977 __ test(ToRegister(left), ToRegister(left));
1978 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1982 if (shift_count != 0) {
1983 if (instr->hydrogen_value()->representation().IsSmi() &&
1984 instr->can_deopt()) {
1985 if (shift_count != 1) {
1986 __ shl(ToRegister(left), shift_count - 1);
1988 __ SmiTag(ToRegister(left));
1989 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1991 __ shl(ToRegister(left), shift_count);
2003 void LCodeGen::DoSubI(LSubI* instr) {
2004 LOperand* left = instr->left();
2005 LOperand* right = instr->right();
2006 DCHECK(left->Equals(instr->result()));
2008 if (right->IsConstantOperand()) {
2009 __ sub(ToOperand(left),
2010 ToImmediate(right, instr->hydrogen()->representation()));
2012 __ sub(ToRegister(left), ToOperand(right));
2014 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
2015 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
2020 void LCodeGen::DoConstantI(LConstantI* instr) {
2021 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
2025 void LCodeGen::DoConstantS(LConstantS* instr) {
2026 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
2030 void LCodeGen::DoConstantD(LConstantD* instr) {
2031 uint64_t const bits = instr->bits();
2032 uint32_t const lower = static_cast<uint32_t>(bits);
2033 uint32_t const upper = static_cast<uint32_t>(bits >> 32);
2034 DCHECK(instr->result()->IsDoubleRegister());
2036 __ push(Immediate(upper));
2037 __ push(Immediate(lower));
2038 X87Register reg = ToX87Register(instr->result());
2039 X87Mov(reg, Operand(esp, 0));
2040 __ add(Operand(esp), Immediate(kDoubleSize));
2044 void LCodeGen::DoConstantE(LConstantE* instr) {
2045 __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
2049 void LCodeGen::DoConstantT(LConstantT* instr) {
2050 Register reg = ToRegister(instr->result());
2051 Handle<Object> object = instr->value(isolate());
2052 AllowDeferredHandleDereference smi_check;
2053 __ LoadObject(reg, object);
2057 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
2058 Register result = ToRegister(instr->result());
2059 Register map = ToRegister(instr->value());
2060 __ EnumLength(result, map);
2064 void LCodeGen::DoDateField(LDateField* instr) {
2065 Register object = ToRegister(instr->date());
2066 Register result = ToRegister(instr->result());
2067 Register scratch = ToRegister(instr->temp());
2068 Smi* index = instr->index();
2069 Label runtime, done;
2070 DCHECK(object.is(result));
2071 DCHECK(object.is(eax));
2073 __ test(object, Immediate(kSmiTagMask));
2074 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2075 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
2076 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotADateObject);
2078 if (index->value() == 0) {
2079 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
2081 if (index->value() < JSDate::kFirstUncachedField) {
2082 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
2083 __ mov(scratch, Operand::StaticVariable(stamp));
2084 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
2085 __ j(not_equal, &runtime, Label::kNear);
2086 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
2087 kPointerSize * index->value()));
2088 __ jmp(&done, Label::kNear);
2091 __ PrepareCallCFunction(2, scratch);
2092 __ mov(Operand(esp, 0), object);
2093 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
2094 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
2100 Operand LCodeGen::BuildSeqStringOperand(Register string,
2102 String::Encoding encoding) {
2103 if (index->IsConstantOperand()) {
2104 int offset = ToRepresentation(LConstantOperand::cast(index),
2105 Representation::Integer32());
2106 if (encoding == String::TWO_BYTE_ENCODING) {
2107 offset *= kUC16Size;
2109 STATIC_ASSERT(kCharSize == 1);
2110 return FieldOperand(string, SeqString::kHeaderSize + offset);
2112 return FieldOperand(
2113 string, ToRegister(index),
2114 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
2115 SeqString::kHeaderSize);
2119 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
2120 String::Encoding encoding = instr->hydrogen()->encoding();
2121 Register result = ToRegister(instr->result());
2122 Register string = ToRegister(instr->string());
2124 if (FLAG_debug_code) {
2126 __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
2127 __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
2129 __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
2130 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2131 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2132 __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
2133 ? one_byte_seq_type : two_byte_seq_type));
2134 __ Check(equal, kUnexpectedStringType);
2138 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2139 if (encoding == String::ONE_BYTE_ENCODING) {
2140 __ movzx_b(result, operand);
2142 __ movzx_w(result, operand);
2147 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
2148 String::Encoding encoding = instr->hydrogen()->encoding();
2149 Register string = ToRegister(instr->string());
2151 if (FLAG_debug_code) {
2152 Register value = ToRegister(instr->value());
2153 Register index = ToRegister(instr->index());
2154 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2155 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2157 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
2158 ? one_byte_seq_type : two_byte_seq_type;
2159 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
2162 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2163 if (instr->value()->IsConstantOperand()) {
2164 int value = ToRepresentation(LConstantOperand::cast(instr->value()),
2165 Representation::Integer32());
2166 DCHECK_LE(0, value);
2167 if (encoding == String::ONE_BYTE_ENCODING) {
2168 DCHECK_LE(value, String::kMaxOneByteCharCode);
2169 __ mov_b(operand, static_cast<int8_t>(value));
2171 DCHECK_LE(value, String::kMaxUtf16CodeUnit);
2172 __ mov_w(operand, static_cast<int16_t>(value));
2175 Register value = ToRegister(instr->value());
2176 if (encoding == String::ONE_BYTE_ENCODING) {
2177 __ mov_b(operand, value);
2179 __ mov_w(operand, value);
2185 void LCodeGen::DoAddI(LAddI* instr) {
2186 LOperand* left = instr->left();
2187 LOperand* right = instr->right();
2189 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
2190 if (right->IsConstantOperand()) {
2191 int32_t offset = ToRepresentation(LConstantOperand::cast(right),
2192 instr->hydrogen()->representation());
2193 __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
2195 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
2196 __ lea(ToRegister(instr->result()), address);
2199 if (right->IsConstantOperand()) {
2200 __ add(ToOperand(left),
2201 ToImmediate(right, instr->hydrogen()->representation()));
2203 __ add(ToRegister(left), ToOperand(right));
2205 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
2206 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
2212 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
2213 LOperand* left = instr->left();
2214 LOperand* right = instr->right();
2215 DCHECK(left->Equals(instr->result()));
2216 HMathMinMax::Operation operation = instr->hydrogen()->operation();
2217 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
2219 Condition condition = (operation == HMathMinMax::kMathMin)
2222 if (right->IsConstantOperand()) {
2223 Operand left_op = ToOperand(left);
2224 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
2225 instr->hydrogen()->representation());
2226 __ cmp(left_op, immediate);
2227 __ j(condition, &return_left, Label::kNear);
2228 __ mov(left_op, immediate);
2230 Register left_reg = ToRegister(left);
2231 Operand right_op = ToOperand(right);
2232 __ cmp(left_reg, right_op);
2233 __ j(condition, &return_left, Label::kNear);
2234 __ mov(left_reg, right_op);
2236 __ bind(&return_left);
2238 DCHECK(instr->hydrogen()->representation().IsDouble());
2239 Label check_nan_left, check_zero, return_left, return_right;
2240 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
2241 X87Register left_reg = ToX87Register(left);
2242 X87Register right_reg = ToX87Register(right);
2244 X87PrepareBinaryOp(left_reg, right_reg, ToX87Register(instr->result()));
2248 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
2249 __ j(equal, &check_zero, Label::kNear); // left == right.
2250 __ j(condition, &return_left, Label::kNear);
2251 __ jmp(&return_right, Label::kNear);
2253 __ bind(&check_zero);
2257 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
2258 // At this point, both left and right are either 0 or -0.
2259 if (operation == HMathMinMax::kMathMin) {
2260 // Push st0 and st1 to stack, then pop them to temp registers and OR them,
2262 Register scratch_reg = ToRegister(instr->temp());
2265 __ sub(esp, Immediate(2 * kPointerSize));
2266 __ fstp_s(MemOperand(esp, 0));
2267 __ fstp_s(MemOperand(esp, kPointerSize));
2268 __ pop(scratch_reg);
2269 __ xor_(MemOperand(esp, 0), scratch_reg);
2270 X87Mov(left_reg, MemOperand(esp, 0), kX87FloatOperand);
2271 __ pop(scratch_reg); // restore esp
2273 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
2277 __ jmp(&return_left, Label::kNear);
2279 __ bind(&check_nan_left);
2282 __ FCmp(); // NaN check.
2283 __ j(parity_even, &return_left, Label::kNear); // left == NaN.
2285 __ bind(&return_right);
2287 X87Mov(left_reg, right_reg);
2289 __ bind(&return_left);
2294 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
2295 X87Register left = ToX87Register(instr->left());
2296 X87Register right = ToX87Register(instr->right());
2297 X87Register result = ToX87Register(instr->result());
2298 if (instr->op() != Token::MOD) {
2299 X87PrepareBinaryOp(left, right, result);
2301 // Set the precision control to double-precision.
2302 __ X87SetFPUCW(0x027F);
2303 switch (instr->op()) {
2317 // Pass two doubles as arguments on the stack.
2318 __ PrepareCallCFunction(4, eax);
2319 X87Mov(Operand(esp, 1 * kDoubleSize), right);
2320 X87Mov(Operand(esp, 0), left);
2322 DCHECK(left.is(result));
2323 X87PrepareToWrite(result);
2325 ExternalReference::mod_two_doubles_operation(isolate()),
2328 // Return value is in st(0) on ia32.
2329 X87CommitWrite(result);
2337 // Restore the default value of control word.
2338 __ X87SetFPUCW(0x037F);
2342 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2343 DCHECK(ToRegister(instr->context()).is(esi));
2344 DCHECK(ToRegister(instr->left()).is(edx));
2345 DCHECK(ToRegister(instr->right()).is(eax));
2346 DCHECK(ToRegister(instr->result()).is(eax));
2348 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), instr->op()).code();
2349 CallCode(code, RelocInfo::CODE_TARGET, instr);
2353 template<class InstrType>
2354 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2355 int left_block = instr->TrueDestination(chunk_);
2356 int right_block = instr->FalseDestination(chunk_);
2358 int next_block = GetNextEmittedBlock();
2360 if (right_block == left_block || cc == no_condition) {
2361 EmitGoto(left_block);
2362 } else if (left_block == next_block) {
2363 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2364 } else if (right_block == next_block) {
2365 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2367 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2368 __ jmp(chunk_->GetAssemblyLabel(right_block));
2373 template<class InstrType>
2374 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2375 int false_block = instr->FalseDestination(chunk_);
2376 if (cc == no_condition) {
2377 __ jmp(chunk_->GetAssemblyLabel(false_block));
2379 __ j(cc, chunk_->GetAssemblyLabel(false_block));
2384 void LCodeGen::DoBranch(LBranch* instr) {
2385 Representation r = instr->hydrogen()->value()->representation();
2386 if (r.IsSmiOrInteger32()) {
2387 Register reg = ToRegister(instr->value());
2388 __ test(reg, Operand(reg));
2389 EmitBranch(instr, not_zero);
2390 } else if (r.IsDouble()) {
2391 X87Register reg = ToX87Register(instr->value());
2392 X87LoadForUsage(reg);
2395 EmitBranch(instr, not_zero);
2397 DCHECK(r.IsTagged());
2398 Register reg = ToRegister(instr->value());
2399 HType type = instr->hydrogen()->value()->type();
2400 if (type.IsBoolean()) {
2401 DCHECK(!info()->IsStub());
2402 __ cmp(reg, factory()->true_value());
2403 EmitBranch(instr, equal);
2404 } else if (type.IsSmi()) {
2405 DCHECK(!info()->IsStub());
2406 __ test(reg, Operand(reg));
2407 EmitBranch(instr, not_equal);
2408 } else if (type.IsJSArray()) {
2409 DCHECK(!info()->IsStub());
2410 EmitBranch(instr, no_condition);
2411 } else if (type.IsHeapNumber()) {
2413 } else if (type.IsString()) {
2414 DCHECK(!info()->IsStub());
2415 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2416 EmitBranch(instr, not_equal);
2418 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2419 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2421 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2422 // undefined -> false.
2423 __ cmp(reg, factory()->undefined_value());
2424 __ j(equal, instr->FalseLabel(chunk_));
2426 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2428 __ cmp(reg, factory()->true_value());
2429 __ j(equal, instr->TrueLabel(chunk_));
2431 __ cmp(reg, factory()->false_value());
2432 __ j(equal, instr->FalseLabel(chunk_));
2434 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2436 __ cmp(reg, factory()->null_value());
2437 __ j(equal, instr->FalseLabel(chunk_));
2440 if (expected.Contains(ToBooleanStub::SMI)) {
2441 // Smis: 0 -> false, all other -> true.
2442 __ test(reg, Operand(reg));
2443 __ j(equal, instr->FalseLabel(chunk_));
2444 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2445 } else if (expected.NeedsMap()) {
2446 // If we need a map later and have a Smi -> deopt.
2447 __ test(reg, Immediate(kSmiTagMask));
2448 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2451 Register map = no_reg; // Keep the compiler happy.
2452 if (expected.NeedsMap()) {
2453 map = ToRegister(instr->temp());
2454 DCHECK(!map.is(reg));
2455 __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2457 if (expected.CanBeUndetectable()) {
2458 // Undetectable -> false.
2459 __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2460 1 << Map::kIsUndetectable);
2461 __ j(not_zero, instr->FalseLabel(chunk_));
2465 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2466 // spec object -> true.
2467 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2468 __ j(above_equal, instr->TrueLabel(chunk_));
2471 if (expected.Contains(ToBooleanStub::STRING)) {
2472 // String value -> false iff empty.
2474 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2475 __ j(above_equal, ¬_string, Label::kNear);
2476 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2477 __ j(not_zero, instr->TrueLabel(chunk_));
2478 __ jmp(instr->FalseLabel(chunk_));
2479 __ bind(¬_string);
2482 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2483 // Symbol value -> true.
2484 __ CmpInstanceType(map, SYMBOL_TYPE);
2485 __ j(equal, instr->TrueLabel(chunk_));
2488 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2489 // heap number -> false iff +0, -0, or NaN.
2490 Label not_heap_number;
2491 __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2492 factory()->heap_number_map());
2493 __ j(not_equal, ¬_heap_number, Label::kNear);
2495 __ fld_d(FieldOperand(reg, HeapNumber::kValueOffset));
2497 __ j(zero, instr->FalseLabel(chunk_));
2498 __ jmp(instr->TrueLabel(chunk_));
2499 __ bind(¬_heap_number);
2502 if (!expected.IsGeneric()) {
2503 // We've seen something for the first time -> deopt.
2504 // This can only happen if we are not generic already.
2505 DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2512 void LCodeGen::EmitGoto(int block) {
2513 if (!IsNextEmittedBlock(block)) {
2514 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2519 void LCodeGen::DoClobberDoubles(LClobberDoubles* instr) {
2523 void LCodeGen::DoGoto(LGoto* instr) {
2524 EmitGoto(instr->block_id());
2528 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2529 Condition cond = no_condition;
2532 case Token::EQ_STRICT:
2536 case Token::NE_STRICT:
2540 cond = is_unsigned ? below : less;
2543 cond = is_unsigned ? above : greater;
2546 cond = is_unsigned ? below_equal : less_equal;
2549 cond = is_unsigned ? above_equal : greater_equal;
2552 case Token::INSTANCEOF:
2560 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2561 LOperand* left = instr->left();
2562 LOperand* right = instr->right();
2564 instr->is_double() ||
2565 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2566 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2567 Condition cc = TokenToCondition(instr->op(), is_unsigned);
2569 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2570 // We can statically evaluate the comparison.
2571 double left_val = ToDouble(LConstantOperand::cast(left));
2572 double right_val = ToDouble(LConstantOperand::cast(right));
2573 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2574 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2575 EmitGoto(next_block);
2577 if (instr->is_double()) {
2578 X87LoadForUsage(ToX87Register(right), ToX87Register(left));
2580 // Don't base result on EFLAGS when a NaN is involved. Instead
2581 // jump to the false block.
2582 __ j(parity_even, instr->FalseLabel(chunk_));
2584 if (right->IsConstantOperand()) {
2585 __ cmp(ToOperand(left),
2586 ToImmediate(right, instr->hydrogen()->representation()));
2587 } else if (left->IsConstantOperand()) {
2588 __ cmp(ToOperand(right),
2589 ToImmediate(left, instr->hydrogen()->representation()));
2590 // We commuted the operands, so commute the condition.
2591 cc = CommuteCondition(cc);
2593 __ cmp(ToRegister(left), ToOperand(right));
2596 EmitBranch(instr, cc);
2601 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2602 Register left = ToRegister(instr->left());
2604 if (instr->right()->IsConstantOperand()) {
2605 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2606 __ CmpObject(left, right);
2608 Operand right = ToOperand(instr->right());
2609 __ cmp(left, right);
2611 EmitBranch(instr, equal);
2615 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2616 if (instr->hydrogen()->representation().IsTagged()) {
2617 Register input_reg = ToRegister(instr->object());
2618 __ cmp(input_reg, factory()->the_hole_value());
2619 EmitBranch(instr, equal);
2623 // Put the value to the top of stack
2624 X87Register src = ToX87Register(instr->object());
2625 X87LoadForUsage(src);
2630 __ j(parity_even, &ok, Label::kNear);
2632 EmitFalseBranch(instr, no_condition);
2636 __ sub(esp, Immediate(kDoubleSize));
2637 __ fstp_d(MemOperand(esp, 0));
2639 __ add(esp, Immediate(kDoubleSize));
2640 int offset = sizeof(kHoleNanUpper32);
2641 // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
2642 // so we check the upper with 0xffffffff for hole as a temporary fix.
2643 __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
2644 EmitBranch(instr, equal);
2648 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2649 Representation rep = instr->hydrogen()->value()->representation();
2650 DCHECK(!rep.IsInteger32());
2652 if (rep.IsDouble()) {
2653 X87Register input = ToX87Register(instr->value());
2654 X87LoadForUsage(input);
2656 EmitBranch(instr, equal);
2658 Register value = ToRegister(instr->value());
2659 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2660 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2661 __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2663 EmitFalseBranch(instr, no_overflow);
2664 __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2665 Immediate(0x00000000));
2666 EmitBranch(instr, equal);
2671 Condition LCodeGen::EmitIsObject(Register input,
2673 Label* is_not_object,
2675 __ JumpIfSmi(input, is_not_object);
2677 __ cmp(input, isolate()->factory()->null_value());
2678 __ j(equal, is_object);
2680 __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
2681 // Undetectable objects behave like undefined.
2682 __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
2683 1 << Map::kIsUndetectable);
2684 __ j(not_zero, is_not_object);
2686 __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
2687 __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2688 __ j(below, is_not_object);
2689 __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2694 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2695 Register reg = ToRegister(instr->value());
2696 Register temp = ToRegister(instr->temp());
2698 Condition true_cond = EmitIsObject(
2699 reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2701 EmitBranch(instr, true_cond);
2705 Condition LCodeGen::EmitIsString(Register input,
2707 Label* is_not_string,
2708 SmiCheck check_needed = INLINE_SMI_CHECK) {
2709 if (check_needed == INLINE_SMI_CHECK) {
2710 __ JumpIfSmi(input, is_not_string);
2713 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2719 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2720 Register reg = ToRegister(instr->value());
2721 Register temp = ToRegister(instr->temp());
2723 SmiCheck check_needed =
2724 instr->hydrogen()->value()->type().IsHeapObject()
2725 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2727 Condition true_cond = EmitIsString(
2728 reg, temp, instr->FalseLabel(chunk_), check_needed);
2730 EmitBranch(instr, true_cond);
2734 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2735 Operand input = ToOperand(instr->value());
2737 __ test(input, Immediate(kSmiTagMask));
2738 EmitBranch(instr, zero);
2742 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2743 Register input = ToRegister(instr->value());
2744 Register temp = ToRegister(instr->temp());
2746 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2747 STATIC_ASSERT(kSmiTag == 0);
2748 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2750 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2751 __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2752 1 << Map::kIsUndetectable);
2753 EmitBranch(instr, not_zero);
2757 static Condition ComputeCompareCondition(Token::Value op) {
2759 case Token::EQ_STRICT:
2769 return greater_equal;
2772 return no_condition;
2777 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2778 Token::Value op = instr->op();
2780 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
2781 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2783 Condition condition = ComputeCompareCondition(op);
2784 __ test(eax, Operand(eax));
2786 EmitBranch(instr, condition);
2790 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2791 InstanceType from = instr->from();
2792 InstanceType to = instr->to();
2793 if (from == FIRST_TYPE) return to;
2794 DCHECK(from == to || to == LAST_TYPE);
2799 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2800 InstanceType from = instr->from();
2801 InstanceType to = instr->to();
2802 if (from == to) return equal;
2803 if (to == LAST_TYPE) return above_equal;
2804 if (from == FIRST_TYPE) return below_equal;
2810 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2811 Register input = ToRegister(instr->value());
2812 Register temp = ToRegister(instr->temp());
2814 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2815 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2818 __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2819 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2823 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2824 Register input = ToRegister(instr->value());
2825 Register result = ToRegister(instr->result());
2827 __ AssertString(input);
2829 __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2830 __ IndexFromHash(result, result);
2834 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2835 LHasCachedArrayIndexAndBranch* instr) {
2836 Register input = ToRegister(instr->value());
2838 __ test(FieldOperand(input, String::kHashFieldOffset),
2839 Immediate(String::kContainsCachedArrayIndexMask));
2840 EmitBranch(instr, equal);
2844 // Branches to a label or falls through with the answer in the z flag. Trashes
2845 // the temp registers, but not the input.
2846 void LCodeGen::EmitClassOfTest(Label* is_true,
2848 Handle<String>class_name,
2852 DCHECK(!input.is(temp));
2853 DCHECK(!input.is(temp2));
2854 DCHECK(!temp.is(temp2));
2855 __ JumpIfSmi(input, is_false);
2857 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2858 // Assuming the following assertions, we can use the same compares to test
2859 // for both being a function type and being in the object type range.
2860 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2861 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2862 FIRST_SPEC_OBJECT_TYPE + 1);
2863 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2864 LAST_SPEC_OBJECT_TYPE - 1);
2865 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2866 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2867 __ j(below, is_false);
2868 __ j(equal, is_true);
2869 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2870 __ j(equal, is_true);
2872 // Faster code path to avoid two compares: subtract lower bound from the
2873 // actual type and do a signed compare with the width of the type range.
2874 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2875 __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2876 __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2877 __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2878 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2879 __ j(above, is_false);
2882 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2883 // Check if the constructor in the map is a function.
2884 __ GetMapConstructor(temp, temp, temp2);
2885 // Objects with a non-function constructor have class 'Object'.
2886 __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2887 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2888 __ j(not_equal, is_true);
2890 __ j(not_equal, is_false);
2893 // temp now contains the constructor function. Grab the
2894 // instance class name from there.
2895 __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2896 __ mov(temp, FieldOperand(temp,
2897 SharedFunctionInfo::kInstanceClassNameOffset));
2898 // The class name we are testing against is internalized since it's a literal.
2899 // The name in the constructor is internalized because of the way the context
2900 // is booted. This routine isn't expected to work for random API-created
2901 // classes and it doesn't have to because you can't access it with natives
2902 // syntax. Since both sides are internalized it is sufficient to use an
2903 // identity comparison.
2904 __ cmp(temp, class_name);
2905 // End with the answer in the z flag.
2909 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2910 Register input = ToRegister(instr->value());
2911 Register temp = ToRegister(instr->temp());
2912 Register temp2 = ToRegister(instr->temp2());
2914 Handle<String> class_name = instr->hydrogen()->class_name();
2916 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2917 class_name, input, temp, temp2);
2919 EmitBranch(instr, equal);
2923 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2924 Register reg = ToRegister(instr->value());
2925 __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2926 EmitBranch(instr, equal);
2930 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2931 // Object and function are in fixed registers defined by the stub.
2932 DCHECK(ToRegister(instr->context()).is(esi));
2933 InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2934 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2936 Label true_value, done;
2937 __ test(eax, Operand(eax));
2938 __ j(zero, &true_value, Label::kNear);
2939 __ mov(ToRegister(instr->result()), factory()->false_value());
2940 __ jmp(&done, Label::kNear);
2941 __ bind(&true_value);
2942 __ mov(ToRegister(instr->result()), factory()->true_value());
2947 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2948 class DeferredInstanceOfKnownGlobal FINAL : public LDeferredCode {
2950 DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2951 LInstanceOfKnownGlobal* instr,
2952 const X87Stack& x87_stack)
2953 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
2954 void Generate() OVERRIDE {
2955 codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2957 LInstruction* instr() OVERRIDE { return instr_; }
2958 Label* map_check() { return &map_check_; }
2960 LInstanceOfKnownGlobal* instr_;
2964 DeferredInstanceOfKnownGlobal* deferred;
2965 deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr, x87_stack_);
2967 Label done, false_result;
2968 Register object = ToRegister(instr->value());
2969 Register temp = ToRegister(instr->temp());
2971 // A Smi is not an instance of anything.
2972 __ JumpIfSmi(object, &false_result, Label::kNear);
2974 // This is the inlined call site instanceof cache. The two occurences of the
2975 // hole value will be patched to the last map/result pair generated by the
2978 Register map = ToRegister(instr->temp());
2979 __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2980 __ bind(deferred->map_check()); // Label for calculating code patching.
2981 Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2982 __ cmp(map, Operand::ForCell(cache_cell)); // Patched to cached map.
2983 __ j(not_equal, &cache_miss, Label::kNear);
2984 __ mov(eax, factory()->the_hole_value()); // Patched to either true or false.
2985 __ jmp(&done, Label::kNear);
2987 // The inlined call site cache did not match. Check for null and string
2988 // before calling the deferred code.
2989 __ bind(&cache_miss);
2990 // Null is not an instance of anything.
2991 __ cmp(object, factory()->null_value());
2992 __ j(equal, &false_result, Label::kNear);
2994 // String values are not instances of anything.
2995 Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2996 __ j(is_string, &false_result, Label::kNear);
2998 // Go to the deferred code.
2999 __ jmp(deferred->entry());
3001 __ bind(&false_result);
3002 __ mov(ToRegister(instr->result()), factory()->false_value());
3004 // Here result has either true or false. Deferred code also produces true or
3006 __ bind(deferred->exit());
3011 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
3013 PushSafepointRegistersScope scope(this);
3015 InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
3016 flags = static_cast<InstanceofStub::Flags>(
3017 flags | InstanceofStub::kArgsInRegisters);
3018 flags = static_cast<InstanceofStub::Flags>(
3019 flags | InstanceofStub::kCallSiteInlineCheck);
3020 flags = static_cast<InstanceofStub::Flags>(
3021 flags | InstanceofStub::kReturnTrueFalseObject);
3022 InstanceofStub stub(isolate(), flags);
3024 // Get the temp register reserved by the instruction. This needs to be a
3025 // register which is pushed last by PushSafepointRegisters as top of the
3026 // stack is used to pass the offset to the location of the map check to
3028 Register temp = ToRegister(instr->temp());
3029 DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
3030 __ LoadHeapObject(InstanceofStub::right(), instr->function());
3031 static const int kAdditionalDelta = 13;
3032 int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
3033 __ mov(temp, Immediate(delta));
3034 __ StoreToSafepointRegisterSlot(temp, temp);
3035 CallCodeGeneric(stub.GetCode(),
3036 RelocInfo::CODE_TARGET,
3038 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
3039 // Get the deoptimization index of the LLazyBailout-environment that
3040 // corresponds to this instruction.
3041 LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
3042 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
3044 // Put the result value into the eax slot and restore all registers.
3045 __ StoreToSafepointRegisterSlot(eax, eax);
3049 void LCodeGen::DoCmpT(LCmpT* instr) {
3050 Token::Value op = instr->op();
3052 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
3053 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3055 Condition condition = ComputeCompareCondition(op);
3056 Label true_value, done;
3057 __ test(eax, Operand(eax));
3058 __ j(condition, &true_value, Label::kNear);
3059 __ mov(ToRegister(instr->result()), factory()->false_value());
3060 __ jmp(&done, Label::kNear);
3061 __ bind(&true_value);
3062 __ mov(ToRegister(instr->result()), factory()->true_value());
3067 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
3068 int extra_value_count = dynamic_frame_alignment ? 2 : 1;
3070 if (instr->has_constant_parameter_count()) {
3071 int parameter_count = ToInteger32(instr->constant_parameter_count());
3072 if (dynamic_frame_alignment && FLAG_debug_code) {
3074 (parameter_count + extra_value_count) * kPointerSize),
3075 Immediate(kAlignmentZapValue));
3076 __ Assert(equal, kExpectedAlignmentMarker);
3078 __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
3080 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
3081 Register reg = ToRegister(instr->parameter_count());
3082 // The argument count parameter is a smi
3084 Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
3085 if (dynamic_frame_alignment && FLAG_debug_code) {
3086 DCHECK(extra_value_count == 2);
3087 __ cmp(Operand(esp, reg, times_pointer_size,
3088 extra_value_count * kPointerSize),
3089 Immediate(kAlignmentZapValue));
3090 __ Assert(equal, kExpectedAlignmentMarker);
3093 // emit code to restore stack based on instr->parameter_count()
3094 __ pop(return_addr_reg); // save return address
3095 if (dynamic_frame_alignment) {
3096 __ inc(reg); // 1 more for alignment
3098 __ shl(reg, kPointerSizeLog2);
3100 __ jmp(return_addr_reg);
3105 void LCodeGen::DoReturn(LReturn* instr) {
3106 if (FLAG_trace && info()->IsOptimizing()) {
3107 // Preserve the return value on the stack and rely on the runtime call
3108 // to return the value in the same register. We're leaving the code
3109 // managed by the register allocator and tearing down the frame, it's
3110 // safe to write to the context register.
3112 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3113 __ CallRuntime(Runtime::kTraceExit, 1);
3115 if (dynamic_frame_alignment_) {
3116 // Fetch the state of the dynamic frame alignment.
3117 __ mov(edx, Operand(ebp,
3118 JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
3120 int no_frame_start = -1;
3121 if (NeedsEagerFrame()) {
3124 no_frame_start = masm_->pc_offset();
3126 if (dynamic_frame_alignment_) {
3128 __ cmp(edx, Immediate(kNoAlignmentPadding));
3129 __ j(equal, &no_padding, Label::kNear);
3131 EmitReturn(instr, true);
3132 __ bind(&no_padding);
3135 EmitReturn(instr, false);
3136 if (no_frame_start != -1) {
3137 info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
3143 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
3144 DCHECK(FLAG_vector_ics);
3145 Register vector_register = ToRegister(instr->temp_vector());
3146 Register slot_register = VectorLoadICDescriptor::SlotRegister();
3147 DCHECK(vector_register.is(VectorLoadICDescriptor::VectorRegister()));
3148 DCHECK(slot_register.is(eax));
3150 AllowDeferredHandleDereference vector_structure_check;
3151 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3152 __ mov(vector_register, vector);
3153 // No need to allocate this register.
3154 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
3155 int index = vector->GetIndex(slot);
3156 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3160 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
3161 DCHECK(ToRegister(instr->context()).is(esi));
3162 DCHECK(ToRegister(instr->global_object())
3163 .is(LoadDescriptor::ReceiverRegister()));
3164 DCHECK(ToRegister(instr->result()).is(eax));
3166 __ mov(LoadDescriptor::NameRegister(), instr->name());
3167 if (FLAG_vector_ics) {
3168 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
3170 ContextualMode mode = instr->for_typeof() ? NOT_CONTEXTUAL : CONTEXTUAL;
3171 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(isolate(), mode,
3172 PREMONOMORPHIC).code();
3173 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3177 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
3178 Register context = ToRegister(instr->context());
3179 Register result = ToRegister(instr->result());
3180 __ mov(result, ContextOperand(context, instr->slot_index()));
3182 if (instr->hydrogen()->RequiresHoleCheck()) {
3183 __ cmp(result, factory()->the_hole_value());
3184 if (instr->hydrogen()->DeoptimizesOnHole()) {
3185 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3188 __ j(not_equal, &is_not_hole, Label::kNear);
3189 __ mov(result, factory()->undefined_value());
3190 __ bind(&is_not_hole);
3196 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
3197 Register context = ToRegister(instr->context());
3198 Register value = ToRegister(instr->value());
3200 Label skip_assignment;
3202 Operand target = ContextOperand(context, instr->slot_index());
3203 if (instr->hydrogen()->RequiresHoleCheck()) {
3204 __ cmp(target, factory()->the_hole_value());
3205 if (instr->hydrogen()->DeoptimizesOnHole()) {
3206 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3208 __ j(not_equal, &skip_assignment, Label::kNear);
3212 __ mov(target, value);
3213 if (instr->hydrogen()->NeedsWriteBarrier()) {
3214 SmiCheck check_needed =
3215 instr->hydrogen()->value()->type().IsHeapObject()
3216 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
3217 Register temp = ToRegister(instr->temp());
3218 int offset = Context::SlotOffset(instr->slot_index());
3219 __ RecordWriteContextSlot(context, offset, value, temp, kSaveFPRegs,
3220 EMIT_REMEMBERED_SET, check_needed);
3223 __ bind(&skip_assignment);
3227 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
3228 HObjectAccess access = instr->hydrogen()->access();
3229 int offset = access.offset();
3231 if (access.IsExternalMemory()) {
3232 Register result = ToRegister(instr->result());
3233 MemOperand operand = instr->object()->IsConstantOperand()
3234 ? MemOperand::StaticVariable(ToExternalReference(
3235 LConstantOperand::cast(instr->object())))
3236 : MemOperand(ToRegister(instr->object()), offset);
3237 __ Load(result, operand, access.representation());
3241 Register object = ToRegister(instr->object());
3242 if (instr->hydrogen()->representation().IsDouble()) {
3243 X87Mov(ToX87Register(instr->result()), FieldOperand(object, offset));
3247 Register result = ToRegister(instr->result());
3248 if (!access.IsInobject()) {
3249 __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
3252 __ Load(result, FieldOperand(object, offset), access.representation());
3256 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
3257 DCHECK(!operand->IsDoubleRegister());
3258 if (operand->IsConstantOperand()) {
3259 Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
3260 AllowDeferredHandleDereference smi_check;
3261 if (object->IsSmi()) {
3262 __ Push(Handle<Smi>::cast(object));
3264 __ PushHeapObject(Handle<HeapObject>::cast(object));
3266 } else if (operand->IsRegister()) {
3267 __ push(ToRegister(operand));
3269 __ push(ToOperand(operand));
3274 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3275 DCHECK(ToRegister(instr->context()).is(esi));
3276 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3277 DCHECK(ToRegister(instr->result()).is(eax));
3279 __ mov(LoadDescriptor::NameRegister(), instr->name());
3280 if (FLAG_vector_ics) {
3281 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3283 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(
3284 isolate(), NOT_CONTEXTUAL,
3285 instr->hydrogen()->initialization_state()).code();
3286 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3290 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3291 Register function = ToRegister(instr->function());
3292 Register temp = ToRegister(instr->temp());
3293 Register result = ToRegister(instr->result());
3295 // Get the prototype or initial map from the function.
3297 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
3299 // Check that the function has a prototype or an initial map.
3300 __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3301 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3303 // If the function does not have an initial map, we're done.
3305 __ CmpObjectType(result, MAP_TYPE, temp);
3306 __ j(not_equal, &done, Label::kNear);
3308 // Get the prototype from the initial map.
3309 __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3316 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3317 Register result = ToRegister(instr->result());
3318 __ LoadRoot(result, instr->index());
3322 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3323 Register arguments = ToRegister(instr->arguments());
3324 Register result = ToRegister(instr->result());
3325 if (instr->length()->IsConstantOperand() &&
3326 instr->index()->IsConstantOperand()) {
3327 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3328 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3329 int index = (const_length - const_index) + 1;
3330 __ mov(result, Operand(arguments, index * kPointerSize));
3332 Register length = ToRegister(instr->length());
3333 Operand index = ToOperand(instr->index());
3334 // There are two words between the frame pointer and the last argument.
3335 // Subtracting from length accounts for one of them add one more.
3336 __ sub(length, index);
3337 __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3342 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3343 ElementsKind elements_kind = instr->elements_kind();
3344 LOperand* key = instr->key();
3345 if (!key->IsConstantOperand() &&
3346 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3348 __ SmiUntag(ToRegister(key));
3350 Operand operand(BuildFastArrayOperand(
3353 instr->hydrogen()->key()->representation(),
3355 instr->base_offset()));
3356 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
3357 elements_kind == FLOAT32_ELEMENTS) {
3358 X87Mov(ToX87Register(instr->result()), operand, kX87FloatOperand);
3359 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
3360 elements_kind == FLOAT64_ELEMENTS) {
3361 X87Mov(ToX87Register(instr->result()), operand);
3363 Register result(ToRegister(instr->result()));
3364 switch (elements_kind) {
3365 case EXTERNAL_INT8_ELEMENTS:
3367 __ movsx_b(result, operand);
3369 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3370 case EXTERNAL_UINT8_ELEMENTS:
3371 case UINT8_ELEMENTS:
3372 case UINT8_CLAMPED_ELEMENTS:
3373 __ movzx_b(result, operand);
3375 case EXTERNAL_INT16_ELEMENTS:
3376 case INT16_ELEMENTS:
3377 __ movsx_w(result, operand);
3379 case EXTERNAL_UINT16_ELEMENTS:
3380 case UINT16_ELEMENTS:
3381 __ movzx_w(result, operand);
3383 case EXTERNAL_INT32_ELEMENTS:
3384 case INT32_ELEMENTS:
3385 __ mov(result, operand);
3387 case EXTERNAL_UINT32_ELEMENTS:
3388 case UINT32_ELEMENTS:
3389 __ mov(result, operand);
3390 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3391 __ test(result, Operand(result));
3392 DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3395 case EXTERNAL_FLOAT32_ELEMENTS:
3396 case EXTERNAL_FLOAT64_ELEMENTS:
3397 case FLOAT32_ELEMENTS:
3398 case FLOAT64_ELEMENTS:
3399 case FAST_SMI_ELEMENTS:
3401 case FAST_DOUBLE_ELEMENTS:
3402 case FAST_HOLEY_SMI_ELEMENTS:
3403 case FAST_HOLEY_ELEMENTS:
3404 case FAST_HOLEY_DOUBLE_ELEMENTS:
3405 case DICTIONARY_ELEMENTS:
3406 case SLOPPY_ARGUMENTS_ELEMENTS:
3414 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3415 if (instr->hydrogen()->RequiresHoleCheck()) {
3416 Operand hole_check_operand = BuildFastArrayOperand(
3417 instr->elements(), instr->key(),
3418 instr->hydrogen()->key()->representation(),
3419 FAST_DOUBLE_ELEMENTS,
3420 instr->base_offset() + sizeof(kHoleNanLower32));
3421 __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3422 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3425 Operand double_load_operand = BuildFastArrayOperand(
3428 instr->hydrogen()->key()->representation(),
3429 FAST_DOUBLE_ELEMENTS,
3430 instr->base_offset());
3431 X87Mov(ToX87Register(instr->result()), double_load_operand);
3435 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3436 Register result = ToRegister(instr->result());
3440 BuildFastArrayOperand(instr->elements(), instr->key(),
3441 instr->hydrogen()->key()->representation(),
3442 FAST_ELEMENTS, instr->base_offset()));
3444 // Check for the hole value.
3445 if (instr->hydrogen()->RequiresHoleCheck()) {
3446 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3447 __ test(result, Immediate(kSmiTagMask));
3448 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3450 __ cmp(result, factory()->the_hole_value());
3451 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3457 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3458 if (instr->is_typed_elements()) {
3459 DoLoadKeyedExternalArray(instr);
3460 } else if (instr->hydrogen()->representation().IsDouble()) {
3461 DoLoadKeyedFixedDoubleArray(instr);
3463 DoLoadKeyedFixedArray(instr);
3468 Operand LCodeGen::BuildFastArrayOperand(
3469 LOperand* elements_pointer,
3471 Representation key_representation,
3472 ElementsKind elements_kind,
3473 uint32_t base_offset) {
3474 Register elements_pointer_reg = ToRegister(elements_pointer);
3475 int element_shift_size = ElementsKindToShiftSize(elements_kind);
3476 int shift_size = element_shift_size;
3477 if (key->IsConstantOperand()) {
3478 int constant_value = ToInteger32(LConstantOperand::cast(key));
3479 if (constant_value & 0xF0000000) {
3480 Abort(kArrayIndexConstantValueTooBig);
3482 return Operand(elements_pointer_reg,
3483 ((constant_value) << shift_size)
3486 // Take the tag bit into account while computing the shift size.
3487 if (key_representation.IsSmi() && (shift_size >= 1)) {
3488 shift_size -= kSmiTagSize;
3490 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3491 return Operand(elements_pointer_reg,
3499 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3500 DCHECK(ToRegister(instr->context()).is(esi));
3501 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3502 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3504 if (FLAG_vector_ics) {
3505 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3509 CodeFactory::KeyedLoadICInOptimizedCode(
3510 isolate(), instr->hydrogen()->initialization_state()).code();
3511 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3515 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3516 Register result = ToRegister(instr->result());
3518 if (instr->hydrogen()->from_inlined()) {
3519 __ lea(result, Operand(esp, -2 * kPointerSize));
3521 // Check for arguments adapter frame.
3522 Label done, adapted;
3523 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3524 __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3525 __ cmp(Operand(result),
3526 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3527 __ j(equal, &adapted, Label::kNear);
3529 // No arguments adaptor frame.
3530 __ mov(result, Operand(ebp));
3531 __ jmp(&done, Label::kNear);
3533 // Arguments adaptor frame present.
3535 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3537 // Result is the frame pointer for the frame if not adapted and for the real
3538 // frame below the adaptor frame if adapted.
3544 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3545 Operand elem = ToOperand(instr->elements());
3546 Register result = ToRegister(instr->result());
3550 // If no arguments adaptor frame the number of arguments is fixed.
3552 __ mov(result, Immediate(scope()->num_parameters()));
3553 __ j(equal, &done, Label::kNear);
3555 // Arguments adaptor frame present. Get argument length from there.
3556 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3557 __ mov(result, Operand(result,
3558 ArgumentsAdaptorFrameConstants::kLengthOffset));
3559 __ SmiUntag(result);
3561 // Argument length is in result register.
3566 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3567 Register receiver = ToRegister(instr->receiver());
3568 Register function = ToRegister(instr->function());
3570 // If the receiver is null or undefined, we have to pass the global
3571 // object as a receiver to normal functions. Values have to be
3572 // passed unchanged to builtins and strict-mode functions.
3573 Label receiver_ok, global_object;
3574 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3575 Register scratch = ToRegister(instr->temp());
3577 if (!instr->hydrogen()->known_function()) {
3578 // Do not transform the receiver to object for strict mode
3581 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3582 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3583 1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3584 __ j(not_equal, &receiver_ok, dist);
3586 // Do not transform the receiver to object for builtins.
3587 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3588 1 << SharedFunctionInfo::kNativeBitWithinByte);
3589 __ j(not_equal, &receiver_ok, dist);
3592 // Normal function. Replace undefined or null with global receiver.
3593 __ cmp(receiver, factory()->null_value());
3594 __ j(equal, &global_object, Label::kNear);
3595 __ cmp(receiver, factory()->undefined_value());
3596 __ j(equal, &global_object, Label::kNear);
3598 // The receiver should be a JS object.
3599 __ test(receiver, Immediate(kSmiTagMask));
3600 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3601 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3602 DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3604 __ jmp(&receiver_ok, Label::kNear);
3605 __ bind(&global_object);
3606 __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3607 const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3608 __ mov(receiver, Operand(receiver, global_offset));
3609 const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3610 __ mov(receiver, FieldOperand(receiver, proxy_offset));
3611 __ bind(&receiver_ok);
3615 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3616 Register receiver = ToRegister(instr->receiver());
3617 Register function = ToRegister(instr->function());
3618 Register length = ToRegister(instr->length());
3619 Register elements = ToRegister(instr->elements());
3620 DCHECK(receiver.is(eax)); // Used for parameter count.
3621 DCHECK(function.is(edi)); // Required by InvokeFunction.
3622 DCHECK(ToRegister(instr->result()).is(eax));
3624 // Copy the arguments to this function possibly from the
3625 // adaptor frame below it.
3626 const uint32_t kArgumentsLimit = 1 * KB;
3627 __ cmp(length, kArgumentsLimit);
3628 DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3631 __ mov(receiver, length);
3633 // Loop through the arguments pushing them onto the execution
3636 // length is a small non-negative integer, due to the test above.
3637 __ test(length, Operand(length));
3638 __ j(zero, &invoke, Label::kNear);
3640 __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3642 __ j(not_zero, &loop);
3644 // Invoke the function.
3646 DCHECK(instr->HasPointerMap());
3647 LPointerMap* pointers = instr->pointer_map();
3648 SafepointGenerator safepoint_generator(
3649 this, pointers, Safepoint::kLazyDeopt);
3650 ParameterCount actual(eax);
3651 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3655 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3660 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3661 LOperand* argument = instr->value();
3662 EmitPushTaggedOperand(argument);
3666 void LCodeGen::DoDrop(LDrop* instr) {
3667 __ Drop(instr->count());
3671 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3672 Register result = ToRegister(instr->result());
3673 __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3677 void LCodeGen::DoContext(LContext* instr) {
3678 Register result = ToRegister(instr->result());
3679 if (info()->IsOptimizing()) {
3680 __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3682 // If there is no frame, the context must be in esi.
3683 DCHECK(result.is(esi));
3688 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3689 DCHECK(ToRegister(instr->context()).is(esi));
3690 __ push(esi); // The context is the first argument.
3691 __ push(Immediate(instr->hydrogen()->pairs()));
3692 __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3693 CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3697 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3698 int formal_parameter_count, int arity,
3699 LInstruction* instr) {
3700 bool dont_adapt_arguments =
3701 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3702 bool can_invoke_directly =
3703 dont_adapt_arguments || formal_parameter_count == arity;
3705 Register function_reg = edi;
3707 if (can_invoke_directly) {
3709 __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3711 // Set eax to arguments count if adaption is not needed. Assumes that eax
3712 // is available to write to at this point.
3713 if (dont_adapt_arguments) {
3717 // Invoke function directly.
3718 if (function.is_identical_to(info()->closure())) {
3721 __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3723 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3725 // We need to adapt arguments.
3726 LPointerMap* pointers = instr->pointer_map();
3727 SafepointGenerator generator(
3728 this, pointers, Safepoint::kLazyDeopt);
3729 ParameterCount count(arity);
3730 ParameterCount expected(formal_parameter_count);
3731 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3736 void LCodeGen::DoTailCallThroughMegamorphicCache(
3737 LTailCallThroughMegamorphicCache* instr) {
3738 Register receiver = ToRegister(instr->receiver());
3739 Register name = ToRegister(instr->name());
3740 DCHECK(receiver.is(LoadDescriptor::ReceiverRegister()));
3741 DCHECK(name.is(LoadDescriptor::NameRegister()));
3742 Register slot = FLAG_vector_ics ? ToRegister(instr->slot()) : no_reg;
3743 Register vector = FLAG_vector_ics ? ToRegister(instr->vector()) : no_reg;
3745 Register scratch = ebx;
3746 Register extra = edi;
3747 DCHECK(!extra.is(slot) && !extra.is(vector));
3748 DCHECK(!scratch.is(receiver) && !scratch.is(name));
3749 DCHECK(!extra.is(receiver) && !extra.is(name));
3751 // Important for the tail-call.
3752 bool must_teardown_frame = NeedsEagerFrame();
3754 if (!instr->hydrogen()->is_just_miss()) {
3755 if (FLAG_vector_ics) {
3760 // The probe will tail call to a handler if found.
3761 // If --vector-ics is on, then it knows to pop the two args first.
3762 DCHECK(!instr->hydrogen()->is_keyed_load());
3763 isolate()->stub_cache()->GenerateProbe(
3764 masm(), Code::LOAD_IC, instr->hydrogen()->flags(), must_teardown_frame,
3765 receiver, name, scratch, extra);
3767 if (FLAG_vector_ics) {
3773 // Tail call to miss if we ended up here.
3774 if (must_teardown_frame) __ leave();
3775 if (instr->hydrogen()->is_keyed_load()) {
3776 KeyedLoadIC::GenerateMiss(masm());
3778 LoadIC::GenerateMiss(masm());
3783 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3784 DCHECK(ToRegister(instr->result()).is(eax));
3786 if (instr->hydrogen()->IsTailCall()) {
3787 if (NeedsEagerFrame()) __ leave();
3789 if (instr->target()->IsConstantOperand()) {
3790 LConstantOperand* target = LConstantOperand::cast(instr->target());
3791 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3792 __ jmp(code, RelocInfo::CODE_TARGET);
3794 DCHECK(instr->target()->IsRegister());
3795 Register target = ToRegister(instr->target());
3796 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3800 LPointerMap* pointers = instr->pointer_map();
3801 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3803 if (instr->target()->IsConstantOperand()) {
3804 LConstantOperand* target = LConstantOperand::cast(instr->target());
3805 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3806 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3807 __ call(code, RelocInfo::CODE_TARGET);
3809 DCHECK(instr->target()->IsRegister());
3810 Register target = ToRegister(instr->target());
3811 generator.BeforeCall(__ CallSize(Operand(target)));
3812 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3815 generator.AfterCall();
3820 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3821 DCHECK(ToRegister(instr->function()).is(edi));
3822 DCHECK(ToRegister(instr->result()).is(eax));
3824 if (instr->hydrogen()->pass_argument_count()) {
3825 __ mov(eax, instr->arity());
3829 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3831 bool is_self_call = false;
3832 if (instr->hydrogen()->function()->IsConstant()) {
3833 HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3834 Handle<JSFunction> jsfun =
3835 Handle<JSFunction>::cast(fun_const->handle(isolate()));
3836 is_self_call = jsfun.is_identical_to(info()->closure());
3842 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3845 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3849 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3850 Register input_reg = ToRegister(instr->value());
3851 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3852 factory()->heap_number_map());
3853 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3855 Label slow, allocated, done;
3856 Register tmp = input_reg.is(eax) ? ecx : eax;
3857 Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3859 // Preserve the value of all registers.
3860 PushSafepointRegistersScope scope(this);
3862 __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3863 // Check the sign of the argument. If the argument is positive, just
3864 // return it. We do not need to patch the stack since |input| and
3865 // |result| are the same register and |input| will be restored
3866 // unchanged by popping safepoint registers.
3867 __ test(tmp, Immediate(HeapNumber::kSignMask));
3868 __ j(zero, &done, Label::kNear);
3870 __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3871 __ jmp(&allocated, Label::kNear);
3873 // Slow case: Call the runtime system to do the number allocation.
3875 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3876 instr, instr->context());
3877 // Set the pointer to the new heap number in tmp.
3878 if (!tmp.is(eax)) __ mov(tmp, eax);
3879 // Restore input_reg after call to runtime.
3880 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3882 __ bind(&allocated);
3883 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3884 __ and_(tmp2, ~HeapNumber::kSignMask);
3885 __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3886 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3887 __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3888 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3894 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3895 Register input_reg = ToRegister(instr->value());
3896 __ test(input_reg, Operand(input_reg));
3898 __ j(not_sign, &is_positive, Label::kNear);
3899 __ neg(input_reg); // Sets flags.
3900 DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3901 __ bind(&is_positive);
3905 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3906 // Class for deferred case.
3907 class DeferredMathAbsTaggedHeapNumber FINAL : public LDeferredCode {
3909 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3911 const X87Stack& x87_stack)
3912 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
3913 void Generate() OVERRIDE {
3914 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3916 LInstruction* instr() OVERRIDE { return instr_; }
3922 DCHECK(instr->value()->Equals(instr->result()));
3923 Representation r = instr->hydrogen()->value()->representation();
3926 X87Register value = ToX87Register(instr->value());
3929 } else if (r.IsSmiOrInteger32()) {
3930 EmitIntegerMathAbs(instr);
3931 } else { // Tagged case.
3932 DeferredMathAbsTaggedHeapNumber* deferred =
3933 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr, x87_stack_);
3934 Register input_reg = ToRegister(instr->value());
3936 __ JumpIfNotSmi(input_reg, deferred->entry());
3937 EmitIntegerMathAbs(instr);
3938 __ bind(deferred->exit());
3943 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3944 Register output_reg = ToRegister(instr->result());
3945 X87Register input_reg = ToX87Register(instr->value());
3948 Label not_minus_zero, done;
3949 // Deoptimize on unordered.
3953 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3954 __ j(below, ¬_minus_zero, Label::kNear);
3956 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3957 // Check for negative zero.
3958 __ j(not_equal, ¬_minus_zero, Label::kNear);
3962 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3963 __ Move(output_reg, Immediate(0));
3964 __ jmp(&done, Label::kFar);
3968 // rc=01B, round down.
3969 __ bind(¬_minus_zero);
3971 __ X87SetRC(0x0400);
3972 __ sub(esp, Immediate(kPointerSize));
3973 __ fist_s(Operand(esp, 0));
3976 DeoptimizeIf(equal, instr, Deoptimizer::kOverflow);
3978 __ X87SetRC(0x0000);
3983 void LCodeGen::DoMathRound(LMathRound* instr) {
3984 X87Register input_reg = ToX87Register(instr->value());
3985 Register result = ToRegister(instr->result());
3987 Label below_one_half, below_minus_one_half, done;
3989 ExternalReference one_half = ExternalReference::address_of_one_half();
3990 ExternalReference minus_one_half =
3991 ExternalReference::address_of_minus_one_half();
3993 __ fld_d(Operand::StaticVariable(one_half));
3996 __ j(carry, &below_one_half);
3998 // Use rounds towards zero, since 0.5 <= x, we use floor(0.5 + x)
4000 __ fadd_d(Operand::StaticVariable(one_half));
4001 // rc=11B, round toward zero.
4002 __ X87SetRC(0x0c00);
4003 __ sub(esp, Immediate(kPointerSize));
4004 // Clear exception bits.
4006 __ fistp_s(MemOperand(esp, 0));
4010 DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
4012 // Restore round mode.
4013 __ X87SetRC(0x0000);
4016 __ bind(&below_one_half);
4017 __ fld_d(Operand::StaticVariable(minus_one_half));
4020 __ j(carry, &below_minus_one_half);
4021 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
4022 // we can ignore the difference between a result of -0 and +0.
4023 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4024 // If the sign is positive, we return +0.
4027 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4029 __ Move(result, Immediate(0));
4032 __ bind(&below_minus_one_half);
4034 __ fadd_d(Operand::StaticVariable(one_half));
4035 // rc=01B, round down.
4036 __ X87SetRC(0x0400);
4037 __ sub(esp, Immediate(kPointerSize));
4038 // Clear exception bits.
4040 __ fistp_s(MemOperand(esp, 0));
4044 DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
4046 // Restore round mode.
4047 __ X87SetRC(0x0000);
4053 void LCodeGen::DoMathFround(LMathFround* instr) {
4054 X87Register input_reg = ToX87Register(instr->value());
4056 __ sub(esp, Immediate(kPointerSize));
4057 __ fstp_s(MemOperand(esp, 0));
4058 X87Fld(MemOperand(esp, 0), kX87FloatOperand);
4059 __ add(esp, Immediate(kPointerSize));
4063 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
4064 X87Register input = ToX87Register(instr->value());
4065 X87Register result_reg = ToX87Register(instr->result());
4066 Register temp_result = ToRegister(instr->temp1());
4067 Register temp = ToRegister(instr->temp2());
4068 Label slow, done, smi, finish;
4069 DCHECK(result_reg.is(input));
4071 // Store input into Heap number and call runtime function kMathExpRT.
4072 if (FLAG_inline_new) {
4073 __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4074 __ jmp(&done, Label::kNear);
4077 // Slow case: Call the runtime system to do the number allocation.
4080 // TODO(3095996): Put a valid pointer value in the stack slot where the
4081 // result register is stored, as this register is in the pointer map, but
4082 // contains an integer value.
4083 __ Move(temp_result, Immediate(0));
4085 // Preserve the value of all registers.
4086 PushSafepointRegistersScope scope(this);
4088 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4089 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4090 RecordSafepointWithRegisters(
4091 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4092 __ StoreToSafepointRegisterSlot(temp_result, eax);
4095 X87LoadForUsage(input);
4096 __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4099 // Preserve the value of all registers.
4100 PushSafepointRegistersScope scope(this);
4102 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4103 __ push(temp_result);
4104 __ CallRuntimeSaveDoubles(Runtime::kMathSqrt);
4105 RecordSafepointWithRegisters(instr->pointer_map(), 1,
4106 Safepoint::kNoLazyDeopt);
4107 __ StoreToSafepointRegisterSlot(temp_result, eax);
4109 X87PrepareToWrite(result_reg);
4110 // return value of MathExpRT is Smi or Heap Number.
4111 __ JumpIfSmi(temp_result, &smi);
4112 // Heap number(double)
4113 __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4117 __ SmiUntag(temp_result);
4118 __ push(temp_result);
4119 __ fild_s(MemOperand(esp, 0));
4120 __ pop(temp_result);
4122 X87CommitWrite(result_reg);
4126 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
4127 X87Register input_reg = ToX87Register(instr->value());
4128 DCHECK(ToX87Register(instr->result()).is(input_reg));
4130 // Note that according to ECMA-262 15.8.2.13:
4131 // Math.pow(-Infinity, 0.5) == Infinity
4132 // Math.sqrt(-Infinity) == NaN
4134 // Check base for -Infinity. C3 == 0, C2 == 1, C1 == 1 and C0 == 1
4138 __ and_(eax, Immediate(0x4700));
4139 __ cmp(eax, Immediate(0x0700));
4140 __ j(not_equal, &sqrt, Label::kNear);
4141 // If input is -Infinity, return Infinity.
4143 __ jmp(&done, Label::kNear);
4148 __ faddp(); // Convert -0 to +0.
4155 void LCodeGen::DoPower(LPower* instr) {
4156 Representation exponent_type = instr->hydrogen()->right()->representation();
4157 X87Register result = ToX87Register(instr->result());
4158 // Having marked this as a call, we can use any registers.
4159 X87Register base = ToX87Register(instr->left());
4160 ExternalReference one_half = ExternalReference::address_of_one_half();
4162 if (exponent_type.IsSmi()) {
4163 Register exponent = ToRegister(instr->right());
4164 X87LoadForUsage(base);
4165 __ SmiUntag(exponent);
4167 __ fild_s(MemOperand(esp, 0));
4169 } else if (exponent_type.IsTagged()) {
4170 Register exponent = ToRegister(instr->right());
4171 Register temp = exponent.is(ecx) ? eax : ecx;
4172 Label no_deopt, done;
4173 X87LoadForUsage(base);
4174 __ JumpIfSmi(exponent, &no_deopt);
4175 __ CmpObjectType(exponent, HEAP_NUMBER_TYPE, temp);
4176 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4177 // Heap number(double)
4178 __ fld_d(FieldOperand(exponent, HeapNumber::kValueOffset));
4182 __ SmiUntag(exponent);
4184 __ fild_s(MemOperand(esp, 0));
4187 } else if (exponent_type.IsInteger32()) {
4188 Register exponent = ToRegister(instr->right());
4189 X87LoadForUsage(base);
4191 __ fild_s(MemOperand(esp, 0));
4194 DCHECK(exponent_type.IsDouble());
4195 X87Register exponent_double = ToX87Register(instr->right());
4196 X87LoadForUsage(base, exponent_double);
4199 // FP data stack {base, exponent(TOS)}.
4200 // Handle (exponent==+-0.5 && base == -0).
4204 X87Fld(Operand::StaticVariable(one_half), kX87DoubleOperand);
4206 __ j(parity_even, ¬_plus_0, Label::kNear); // NaN.
4207 __ j(not_equal, ¬_plus_0, Label::kNear);
4209 // FP data stack {base, exponent(TOS), zero}.
4211 __ bind(¬_plus_0);
4214 __ PrepareCallCFunction(4, eax);
4215 __ fstp_d(MemOperand(esp, kDoubleSize)); // Exponent value.
4216 __ fstp_d(MemOperand(esp, 0)); // Base value.
4217 X87PrepareToWrite(result);
4218 __ CallCFunction(ExternalReference::power_double_double_function(isolate()),
4220 // Return value is in st(0) on ia32.
4221 X87CommitWrite(result);
4226 void LCodeGen::DoMathLog(LMathLog* instr) {
4227 DCHECK(instr->value()->Equals(instr->result()));
4228 X87Register input_reg = ToX87Register(instr->value());
4231 Label positive, done, zero, nan_result;
4235 __ j(below, &nan_result, Label::kNear);
4236 __ j(equal, &zero, Label::kNear);
4244 __ jmp(&done, Label::kNear);
4246 __ bind(&nan_result);
4247 X87PrepareToWrite(input_reg);
4248 __ push(Immediate(0xffffffff));
4249 __ push(Immediate(0x7fffffff));
4250 __ fld_d(MemOperand(esp, 0));
4251 __ lea(esp, Operand(esp, kDoubleSize));
4252 X87CommitWrite(input_reg);
4253 __ jmp(&done, Label::kNear);
4256 ExternalReference ninf = ExternalReference::address_of_negative_infinity();
4257 X87PrepareToWrite(input_reg);
4258 __ fld_d(Operand::StaticVariable(ninf));
4259 X87CommitWrite(input_reg);
4265 void LCodeGen::DoMathClz32(LMathClz32* instr) {
4266 Register input = ToRegister(instr->value());
4267 Register result = ToRegister(instr->result());
4269 __ Lzcnt(result, input);
4273 void LCodeGen::DoMathExp(LMathExp* instr) {
4274 X87Register input = ToX87Register(instr->value());
4275 X87Register result_reg = ToX87Register(instr->result());
4276 Register temp_result = ToRegister(instr->temp1());
4277 Register temp = ToRegister(instr->temp2());
4278 Label slow, done, smi, finish;
4279 DCHECK(result_reg.is(input));
4281 // Store input into Heap number and call runtime function kMathExpRT.
4282 if (FLAG_inline_new) {
4283 __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4284 __ jmp(&done, Label::kNear);
4287 // Slow case: Call the runtime system to do the number allocation.
4290 // TODO(3095996): Put a valid pointer value in the stack slot where the
4291 // result register is stored, as this register is in the pointer map, but
4292 // contains an integer value.
4293 __ Move(temp_result, Immediate(0));
4295 // Preserve the value of all registers.
4296 PushSafepointRegistersScope scope(this);
4298 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4299 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4300 RecordSafepointWithRegisters(instr->pointer_map(), 0,
4301 Safepoint::kNoLazyDeopt);
4302 __ StoreToSafepointRegisterSlot(temp_result, eax);
4305 X87LoadForUsage(input);
4306 __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4309 // Preserve the value of all registers.
4310 PushSafepointRegistersScope scope(this);
4312 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4313 __ push(temp_result);
4314 __ CallRuntimeSaveDoubles(Runtime::kMathExpRT);
4315 RecordSafepointWithRegisters(instr->pointer_map(), 1,
4316 Safepoint::kNoLazyDeopt);
4317 __ StoreToSafepointRegisterSlot(temp_result, eax);
4319 X87PrepareToWrite(result_reg);
4320 // return value of MathExpRT is Smi or Heap Number.
4321 __ JumpIfSmi(temp_result, &smi);
4322 // Heap number(double)
4323 __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4327 __ SmiUntag(temp_result);
4328 __ push(temp_result);
4329 __ fild_s(MemOperand(esp, 0));
4330 __ pop(temp_result);
4332 X87CommitWrite(result_reg);
4336 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
4337 DCHECK(ToRegister(instr->context()).is(esi));
4338 DCHECK(ToRegister(instr->function()).is(edi));
4339 DCHECK(instr->HasPointerMap());
4341 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
4342 if (known_function.is_null()) {
4343 LPointerMap* pointers = instr->pointer_map();
4344 SafepointGenerator generator(
4345 this, pointers, Safepoint::kLazyDeopt);
4346 ParameterCount count(instr->arity());
4347 __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
4349 CallKnownFunction(known_function,
4350 instr->hydrogen()->formal_parameter_count(),
4351 instr->arity(), instr);
4356 void LCodeGen::DoCallFunction(LCallFunction* instr) {
4357 DCHECK(ToRegister(instr->context()).is(esi));
4358 DCHECK(ToRegister(instr->function()).is(edi));
4359 DCHECK(ToRegister(instr->result()).is(eax));
4361 int arity = instr->arity();
4362 CallFunctionFlags flags = instr->hydrogen()->function_flags();
4363 if (instr->hydrogen()->HasVectorAndSlot()) {
4364 Register slot_register = ToRegister(instr->temp_slot());
4365 Register vector_register = ToRegister(instr->temp_vector());
4366 DCHECK(slot_register.is(edx));
4367 DCHECK(vector_register.is(ebx));
4369 AllowDeferredHandleDereference vector_structure_check;
4370 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
4371 int index = vector->GetIndex(instr->hydrogen()->slot());
4373 __ mov(vector_register, vector);
4374 __ mov(slot_register, Immediate(Smi::FromInt(index)));
4376 CallICState::CallType call_type =
4377 (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
4380 CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
4381 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4383 CallFunctionStub stub(isolate(), arity, flags);
4384 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4389 void LCodeGen::DoCallNew(LCallNew* instr) {
4390 DCHECK(ToRegister(instr->context()).is(esi));
4391 DCHECK(ToRegister(instr->constructor()).is(edi));
4392 DCHECK(ToRegister(instr->result()).is(eax));
4394 // No cell in ebx for construct type feedback in optimized code
4395 __ mov(ebx, isolate()->factory()->undefined_value());
4396 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
4397 __ Move(eax, Immediate(instr->arity()));
4398 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4402 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
4403 DCHECK(ToRegister(instr->context()).is(esi));
4404 DCHECK(ToRegister(instr->constructor()).is(edi));
4405 DCHECK(ToRegister(instr->result()).is(eax));
4407 __ Move(eax, Immediate(instr->arity()));
4408 __ mov(ebx, isolate()->factory()->undefined_value());
4409 ElementsKind kind = instr->hydrogen()->elements_kind();
4410 AllocationSiteOverrideMode override_mode =
4411 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
4412 ? DISABLE_ALLOCATION_SITES
4415 if (instr->arity() == 0) {
4416 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
4417 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4418 } else if (instr->arity() == 1) {
4420 if (IsFastPackedElementsKind(kind)) {
4422 // We might need a change here
4423 // look at the first argument
4424 __ mov(ecx, Operand(esp, 0));
4426 __ j(zero, &packed_case, Label::kNear);
4428 ElementsKind holey_kind = GetHoleyElementsKind(kind);
4429 ArraySingleArgumentConstructorStub stub(isolate(),
4432 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4433 __ jmp(&done, Label::kNear);
4434 __ bind(&packed_case);
4437 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
4438 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4441 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
4442 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4447 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4448 DCHECK(ToRegister(instr->context()).is(esi));
4449 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
4453 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4454 Register function = ToRegister(instr->function());
4455 Register code_object = ToRegister(instr->code_object());
4456 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4457 __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4461 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4462 Register result = ToRegister(instr->result());
4463 Register base = ToRegister(instr->base_object());
4464 if (instr->offset()->IsConstantOperand()) {
4465 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4466 __ lea(result, Operand(base, ToInteger32(offset)));
4468 Register offset = ToRegister(instr->offset());
4469 __ lea(result, Operand(base, offset, times_1, 0));
4474 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4475 Representation representation = instr->hydrogen()->field_representation();
4477 HObjectAccess access = instr->hydrogen()->access();
4478 int offset = access.offset();
4480 if (access.IsExternalMemory()) {
4481 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4482 MemOperand operand = instr->object()->IsConstantOperand()
4483 ? MemOperand::StaticVariable(
4484 ToExternalReference(LConstantOperand::cast(instr->object())))
4485 : MemOperand(ToRegister(instr->object()), offset);
4486 if (instr->value()->IsConstantOperand()) {
4487 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4488 __ mov(operand, Immediate(ToInteger32(operand_value)));
4490 Register value = ToRegister(instr->value());
4491 __ Store(value, operand, representation);
4496 Register object = ToRegister(instr->object());
4497 __ AssertNotSmi(object);
4498 DCHECK(!representation.IsSmi() ||
4499 !instr->value()->IsConstantOperand() ||
4500 IsSmi(LConstantOperand::cast(instr->value())));
4501 if (representation.IsDouble()) {
4502 DCHECK(access.IsInobject());
4503 DCHECK(!instr->hydrogen()->has_transition());
4504 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4505 X87Register value = ToX87Register(instr->value());
4506 X87Mov(FieldOperand(object, offset), value);
4510 if (instr->hydrogen()->has_transition()) {
4511 Handle<Map> transition = instr->hydrogen()->transition_map();
4512 AddDeprecationDependency(transition);
4513 __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4514 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4515 Register temp = ToRegister(instr->temp());
4516 Register temp_map = ToRegister(instr->temp_map());
4517 __ mov(temp_map, transition);
4518 __ mov(FieldOperand(object, HeapObject::kMapOffset), temp_map);
4519 // Update the write barrier for the map field.
4520 __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4525 Register write_register = object;
4526 if (!access.IsInobject()) {
4527 write_register = ToRegister(instr->temp());
4528 __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4531 MemOperand operand = FieldOperand(write_register, offset);
4532 if (instr->value()->IsConstantOperand()) {
4533 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4534 if (operand_value->IsRegister()) {
4535 Register value = ToRegister(operand_value);
4536 __ Store(value, operand, representation);
4537 } else if (representation.IsInteger32()) {
4538 Immediate immediate = ToImmediate(operand_value, representation);
4539 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4540 __ mov(operand, immediate);
4542 Handle<Object> handle_value = ToHandle(operand_value);
4543 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4544 __ mov(operand, handle_value);
4547 Register value = ToRegister(instr->value());
4548 __ Store(value, operand, representation);
4551 if (instr->hydrogen()->NeedsWriteBarrier()) {
4552 Register value = ToRegister(instr->value());
4553 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4554 // Update the write barrier for the object for in-object properties.
4555 __ RecordWriteField(write_register, offset, value, temp, kSaveFPRegs,
4556 EMIT_REMEMBERED_SET,
4557 instr->hydrogen()->SmiCheckForWriteBarrier(),
4558 instr->hydrogen()->PointersToHereCheckForValue());
4563 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4564 DCHECK(ToRegister(instr->context()).is(esi));
4565 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4566 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4568 __ mov(StoreDescriptor::NameRegister(), instr->name());
4570 StoreIC::initialize_stub(isolate(), instr->language_mode(),
4571 instr->hydrogen()->initialization_state());
4572 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4576 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4577 Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4578 if (instr->index()->IsConstantOperand()) {
4579 __ cmp(ToOperand(instr->length()),
4580 ToImmediate(LConstantOperand::cast(instr->index()),
4581 instr->hydrogen()->length()->representation()));
4582 cc = CommuteCondition(cc);
4583 } else if (instr->length()->IsConstantOperand()) {
4584 __ cmp(ToOperand(instr->index()),
4585 ToImmediate(LConstantOperand::cast(instr->length()),
4586 instr->hydrogen()->index()->representation()));
4588 __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4590 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4592 __ j(NegateCondition(cc), &done, Label::kNear);
4596 DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4601 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4602 ElementsKind elements_kind = instr->elements_kind();
4603 LOperand* key = instr->key();
4604 if (!key->IsConstantOperand() &&
4605 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4607 __ SmiUntag(ToRegister(key));
4609 Operand operand(BuildFastArrayOperand(
4612 instr->hydrogen()->key()->representation(),
4614 instr->base_offset()));
4615 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
4616 elements_kind == FLOAT32_ELEMENTS) {
4617 X87Mov(operand, ToX87Register(instr->value()), kX87FloatOperand);
4618 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
4619 elements_kind == FLOAT64_ELEMENTS) {
4620 uint64_t int_val = kHoleNanInt64;
4621 int32_t lower = static_cast<int32_t>(int_val);
4622 int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4623 Operand operand2 = BuildFastArrayOperand(
4624 instr->elements(), instr->key(),
4625 instr->hydrogen()->key()->representation(), elements_kind,
4626 instr->base_offset() + kPointerSize);
4628 Label no_special_nan_handling, done;
4629 X87Register value = ToX87Register(instr->value());
4631 __ lea(esp, Operand(esp, -kDoubleSize));
4632 __ fst_d(MemOperand(esp, 0));
4633 __ lea(esp, Operand(esp, kDoubleSize));
4634 int offset = sizeof(kHoleNanUpper32);
4635 // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
4636 // so we check the upper with 0xffffffff for hole as a temporary fix.
4637 __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
4638 __ j(not_equal, &no_special_nan_handling, Label::kNear);
4639 __ mov(operand, Immediate(lower));
4640 __ mov(operand2, Immediate(upper));
4641 __ jmp(&done, Label::kNear);
4643 __ bind(&no_special_nan_handling);
4647 Register value = ToRegister(instr->value());
4648 switch (elements_kind) {
4649 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
4650 case EXTERNAL_UINT8_ELEMENTS:
4651 case EXTERNAL_INT8_ELEMENTS:
4652 case UINT8_ELEMENTS:
4654 case UINT8_CLAMPED_ELEMENTS:
4655 __ mov_b(operand, value);
4657 case EXTERNAL_INT16_ELEMENTS:
4658 case EXTERNAL_UINT16_ELEMENTS:
4659 case UINT16_ELEMENTS:
4660 case INT16_ELEMENTS:
4661 __ mov_w(operand, value);
4663 case EXTERNAL_INT32_ELEMENTS:
4664 case EXTERNAL_UINT32_ELEMENTS:
4665 case UINT32_ELEMENTS:
4666 case INT32_ELEMENTS:
4667 __ mov(operand, value);
4669 case EXTERNAL_FLOAT32_ELEMENTS:
4670 case EXTERNAL_FLOAT64_ELEMENTS:
4671 case FLOAT32_ELEMENTS:
4672 case FLOAT64_ELEMENTS:
4673 case FAST_SMI_ELEMENTS:
4675 case FAST_DOUBLE_ELEMENTS:
4676 case FAST_HOLEY_SMI_ELEMENTS:
4677 case FAST_HOLEY_ELEMENTS:
4678 case FAST_HOLEY_DOUBLE_ELEMENTS:
4679 case DICTIONARY_ELEMENTS:
4680 case SLOPPY_ARGUMENTS_ELEMENTS:
4688 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4689 Operand double_store_operand = BuildFastArrayOperand(
4692 instr->hydrogen()->key()->representation(),
4693 FAST_DOUBLE_ELEMENTS,
4694 instr->base_offset());
4696 uint64_t int_val = kHoleNanInt64;
4697 int32_t lower = static_cast<int32_t>(int_val);
4698 int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4699 Operand double_store_operand2 = BuildFastArrayOperand(
4700 instr->elements(), instr->key(),
4701 instr->hydrogen()->key()->representation(), FAST_DOUBLE_ELEMENTS,
4702 instr->base_offset() + kPointerSize);
4704 if (instr->hydrogen()->IsConstantHoleStore()) {
4705 // This means we should store the (double) hole. No floating point
4706 // registers required.
4707 __ mov(double_store_operand, Immediate(lower));
4708 __ mov(double_store_operand2, Immediate(upper));
4710 Label no_special_nan_handling, done;
4711 X87Register value = ToX87Register(instr->value());
4714 if (instr->NeedsCanonicalization()) {
4718 __ j(parity_odd, &no_special_nan_handling, Label::kNear);
4719 // All NaNs are Canonicalized to 0x7fffffffffffffff
4720 __ mov(double_store_operand, Immediate(0xffffffff));
4721 __ mov(double_store_operand2, Immediate(0x7fffffff));
4722 __ jmp(&done, Label::kNear);
4724 __ lea(esp, Operand(esp, -kDoubleSize));
4725 __ fst_d(MemOperand(esp, 0));
4726 __ lea(esp, Operand(esp, kDoubleSize));
4727 int offset = sizeof(kHoleNanUpper32);
4728 // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
4729 // so we check the upper with 0xffffffff for hole as a temporary fix.
4730 __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
4731 __ j(not_equal, &no_special_nan_handling, Label::kNear);
4732 __ mov(double_store_operand, Immediate(lower));
4733 __ mov(double_store_operand2, Immediate(upper));
4734 __ jmp(&done, Label::kNear);
4736 __ bind(&no_special_nan_handling);
4737 __ fst_d(double_store_operand);
4743 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4744 Register elements = ToRegister(instr->elements());
4745 Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4747 Operand operand = BuildFastArrayOperand(
4750 instr->hydrogen()->key()->representation(),
4752 instr->base_offset());
4753 if (instr->value()->IsRegister()) {
4754 __ mov(operand, ToRegister(instr->value()));
4756 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4757 if (IsSmi(operand_value)) {
4758 Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4759 __ mov(operand, immediate);
4761 DCHECK(!IsInteger32(operand_value));
4762 Handle<Object> handle_value = ToHandle(operand_value);
4763 __ mov(operand, handle_value);
4767 if (instr->hydrogen()->NeedsWriteBarrier()) {
4768 DCHECK(instr->value()->IsRegister());
4769 Register value = ToRegister(instr->value());
4770 DCHECK(!instr->key()->IsConstantOperand());
4771 SmiCheck check_needed =
4772 instr->hydrogen()->value()->type().IsHeapObject()
4773 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4774 // Compute address of modified element and store it into key register.
4775 __ lea(key, operand);
4776 __ RecordWrite(elements, key, value, kSaveFPRegs, EMIT_REMEMBERED_SET,
4778 instr->hydrogen()->PointersToHereCheckForValue());
4783 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4784 // By cases...external, fast-double, fast
4785 if (instr->is_typed_elements()) {
4786 DoStoreKeyedExternalArray(instr);
4787 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4788 DoStoreKeyedFixedDoubleArray(instr);
4790 DoStoreKeyedFixedArray(instr);
4795 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4796 DCHECK(ToRegister(instr->context()).is(esi));
4797 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4798 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4799 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4801 Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4802 isolate(), instr->language_mode(),
4803 instr->hydrogen()->initialization_state()).code();
4804 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4808 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4809 Register object = ToRegister(instr->object());
4810 Register temp = ToRegister(instr->temp());
4811 Label no_memento_found;
4812 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4813 DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4814 __ bind(&no_memento_found);
4818 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4819 Register object_reg = ToRegister(instr->object());
4821 Handle<Map> from_map = instr->original_map();
4822 Handle<Map> to_map = instr->transitioned_map();
4823 ElementsKind from_kind = instr->from_kind();
4824 ElementsKind to_kind = instr->to_kind();
4826 Label not_applicable;
4827 bool is_simple_map_transition =
4828 IsSimpleMapChangeTransition(from_kind, to_kind);
4829 Label::Distance branch_distance =
4830 is_simple_map_transition ? Label::kNear : Label::kFar;
4831 __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4832 __ j(not_equal, ¬_applicable, branch_distance);
4833 if (is_simple_map_transition) {
4834 Register new_map_reg = ToRegister(instr->new_map_temp());
4835 __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4838 DCHECK_NOT_NULL(instr->temp());
4839 __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4840 ToRegister(instr->temp()), kDontSaveFPRegs);
4842 DCHECK(ToRegister(instr->context()).is(esi));
4843 DCHECK(object_reg.is(eax));
4844 PushSafepointRegistersScope scope(this);
4845 __ mov(ebx, to_map);
4846 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4847 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4849 RecordSafepointWithLazyDeopt(instr,
4850 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4852 __ bind(¬_applicable);
4856 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4857 class DeferredStringCharCodeAt FINAL : public LDeferredCode {
4859 DeferredStringCharCodeAt(LCodeGen* codegen,
4860 LStringCharCodeAt* instr,
4861 const X87Stack& x87_stack)
4862 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4863 void Generate() OVERRIDE { codegen()->DoDeferredStringCharCodeAt(instr_); }
4864 LInstruction* instr() OVERRIDE { return instr_; }
4867 LStringCharCodeAt* instr_;
4870 DeferredStringCharCodeAt* deferred =
4871 new(zone()) DeferredStringCharCodeAt(this, instr, x87_stack_);
4873 StringCharLoadGenerator::Generate(masm(),
4875 ToRegister(instr->string()),
4876 ToRegister(instr->index()),
4877 ToRegister(instr->result()),
4879 __ bind(deferred->exit());
4883 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4884 Register string = ToRegister(instr->string());
4885 Register result = ToRegister(instr->result());
4887 // TODO(3095996): Get rid of this. For now, we need to make the
4888 // result register contain a valid pointer because it is already
4889 // contained in the register pointer map.
4890 __ Move(result, Immediate(0));
4892 PushSafepointRegistersScope scope(this);
4894 // Push the index as a smi. This is safe because of the checks in
4895 // DoStringCharCodeAt above.
4896 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4897 if (instr->index()->IsConstantOperand()) {
4898 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4899 Representation::Smi());
4902 Register index = ToRegister(instr->index());
4906 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4907 instr, instr->context());
4910 __ StoreToSafepointRegisterSlot(result, eax);
4914 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4915 class DeferredStringCharFromCode FINAL : public LDeferredCode {
4917 DeferredStringCharFromCode(LCodeGen* codegen,
4918 LStringCharFromCode* instr,
4919 const X87Stack& x87_stack)
4920 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4921 void Generate() OVERRIDE {
4922 codegen()->DoDeferredStringCharFromCode(instr_);
4924 LInstruction* instr() OVERRIDE { return instr_; }
4927 LStringCharFromCode* instr_;
4930 DeferredStringCharFromCode* deferred =
4931 new(zone()) DeferredStringCharFromCode(this, instr, x87_stack_);
4933 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4934 Register char_code = ToRegister(instr->char_code());
4935 Register result = ToRegister(instr->result());
4936 DCHECK(!char_code.is(result));
4938 __ cmp(char_code, String::kMaxOneByteCharCode);
4939 __ j(above, deferred->entry());
4940 __ Move(result, Immediate(factory()->single_character_string_cache()));
4941 __ mov(result, FieldOperand(result,
4942 char_code, times_pointer_size,
4943 FixedArray::kHeaderSize));
4944 __ cmp(result, factory()->undefined_value());
4945 __ j(equal, deferred->entry());
4946 __ bind(deferred->exit());
4950 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4951 Register char_code = ToRegister(instr->char_code());
4952 Register result = ToRegister(instr->result());
4954 // TODO(3095996): Get rid of this. For now, we need to make the
4955 // result register contain a valid pointer because it is already
4956 // contained in the register pointer map.
4957 __ Move(result, Immediate(0));
4959 PushSafepointRegistersScope scope(this);
4960 __ SmiTag(char_code);
4962 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4963 __ StoreToSafepointRegisterSlot(result, eax);
4967 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4968 DCHECK(ToRegister(instr->context()).is(esi));
4969 DCHECK(ToRegister(instr->left()).is(edx));
4970 DCHECK(ToRegister(instr->right()).is(eax));
4971 StringAddStub stub(isolate(),
4972 instr->hydrogen()->flags(),
4973 instr->hydrogen()->pretenure_flag());
4974 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4978 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4979 LOperand* input = instr->value();
4980 LOperand* output = instr->result();
4981 DCHECK(input->IsRegister() || input->IsStackSlot());
4982 DCHECK(output->IsDoubleRegister());
4983 if (input->IsRegister()) {
4984 Register input_reg = ToRegister(input);
4986 X87Mov(ToX87Register(output), Operand(esp, 0), kX87IntOperand);
4989 X87Mov(ToX87Register(output), ToOperand(input), kX87IntOperand);
4994 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4995 LOperand* input = instr->value();
4996 LOperand* output = instr->result();
4997 X87Register res = ToX87Register(output);
4998 X87PrepareToWrite(res);
4999 __ LoadUint32NoSSE2(ToRegister(input));
5000 X87CommitWrite(res);
5004 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
5005 class DeferredNumberTagI FINAL : public LDeferredCode {
5007 DeferredNumberTagI(LCodeGen* codegen,
5009 const X87Stack& x87_stack)
5010 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5011 void Generate() OVERRIDE {
5012 codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
5015 LInstruction* instr() OVERRIDE { return instr_; }
5018 LNumberTagI* instr_;
5021 LOperand* input = instr->value();
5022 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5023 Register reg = ToRegister(input);
5025 DeferredNumberTagI* deferred =
5026 new(zone()) DeferredNumberTagI(this, instr, x87_stack_);
5028 __ j(overflow, deferred->entry());
5029 __ bind(deferred->exit());
5033 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
5034 class DeferredNumberTagU FINAL : public LDeferredCode {
5036 DeferredNumberTagU(LCodeGen* codegen,
5038 const X87Stack& x87_stack)
5039 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5040 void Generate() OVERRIDE {
5041 codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
5044 LInstruction* instr() OVERRIDE { return instr_; }
5047 LNumberTagU* instr_;
5050 LOperand* input = instr->value();
5051 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5052 Register reg = ToRegister(input);
5054 DeferredNumberTagU* deferred =
5055 new(zone()) DeferredNumberTagU(this, instr, x87_stack_);
5056 __ cmp(reg, Immediate(Smi::kMaxValue));
5057 __ j(above, deferred->entry());
5059 __ bind(deferred->exit());
5063 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
5066 IntegerSignedness signedness) {
5068 Register reg = ToRegister(value);
5069 Register tmp = ToRegister(temp);
5071 if (signedness == SIGNED_INT32) {
5072 // There was overflow, so bits 30 and 31 of the original integer
5073 // disagree. Try to allocate a heap number in new space and store
5074 // the value in there. If that fails, call the runtime system.
5076 __ xor_(reg, 0x80000000);
5078 __ fild_s(Operand(esp, 0));
5081 // There's no fild variant for unsigned values, so zero-extend to a 64-bit
5083 __ push(Immediate(0));
5085 __ fild_d(Operand(esp, 0));
5090 if (FLAG_inline_new) {
5091 __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
5092 __ jmp(&done, Label::kNear);
5095 // Slow case: Call the runtime system to do the number allocation.
5098 // TODO(3095996): Put a valid pointer value in the stack slot where the
5099 // result register is stored, as this register is in the pointer map, but
5100 // contains an integer value.
5101 __ Move(reg, Immediate(0));
5103 // Preserve the value of all registers.
5104 PushSafepointRegistersScope scope(this);
5106 // NumberTagI and NumberTagD use the context from the frame, rather than
5107 // the environment's HContext or HInlinedContext value.
5108 // They only call Runtime::kAllocateHeapNumber.
5109 // The corresponding HChange instructions are added in a phase that does
5110 // not have easy access to the local context.
5111 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5112 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5113 RecordSafepointWithRegisters(
5114 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5115 __ StoreToSafepointRegisterSlot(reg, eax);
5119 __ fstp_d(FieldOperand(reg, HeapNumber::kValueOffset));
5123 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
5124 class DeferredNumberTagD FINAL : public LDeferredCode {
5126 DeferredNumberTagD(LCodeGen* codegen,
5128 const X87Stack& x87_stack)
5129 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5130 void Generate() OVERRIDE { codegen()->DoDeferredNumberTagD(instr_); }
5131 LInstruction* instr() OVERRIDE { return instr_; }
5134 LNumberTagD* instr_;
5137 Register reg = ToRegister(instr->result());
5139 // Put the value to the top of stack
5140 X87Register src = ToX87Register(instr->value());
5141 // Don't use X87LoadForUsage here, which is only used by Instruction which
5142 // clobbers fp registers.
5143 x87_stack_.Fxch(src);
5145 DeferredNumberTagD* deferred =
5146 new(zone()) DeferredNumberTagD(this, instr, x87_stack_);
5147 if (FLAG_inline_new) {
5148 Register tmp = ToRegister(instr->temp());
5149 __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
5151 __ jmp(deferred->entry());
5153 __ bind(deferred->exit());
5154 __ fst_d(FieldOperand(reg, HeapNumber::kValueOffset));
5158 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
5159 // TODO(3095996): Get rid of this. For now, we need to make the
5160 // result register contain a valid pointer because it is already
5161 // contained in the register pointer map.
5162 Register reg = ToRegister(instr->result());
5163 __ Move(reg, Immediate(0));
5165 PushSafepointRegistersScope scope(this);
5166 // NumberTagI and NumberTagD use the context from the frame, rather than
5167 // the environment's HContext or HInlinedContext value.
5168 // They only call Runtime::kAllocateHeapNumber.
5169 // The corresponding HChange instructions are added in a phase that does
5170 // not have easy access to the local context.
5171 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5172 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5173 RecordSafepointWithRegisters(
5174 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5175 __ StoreToSafepointRegisterSlot(reg, eax);
5179 void LCodeGen::DoSmiTag(LSmiTag* instr) {
5180 HChange* hchange = instr->hydrogen();
5181 Register input = ToRegister(instr->value());
5182 if (hchange->CheckFlag(HValue::kCanOverflow) &&
5183 hchange->value()->CheckFlag(HValue::kUint32)) {
5184 __ test(input, Immediate(0xc0000000));
5185 DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
5188 if (hchange->CheckFlag(HValue::kCanOverflow) &&
5189 !hchange->value()->CheckFlag(HValue::kUint32)) {
5190 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5195 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
5196 LOperand* input = instr->value();
5197 Register result = ToRegister(input);
5198 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5199 if (instr->needs_check()) {
5200 __ test(result, Immediate(kSmiTagMask));
5201 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5203 __ AssertSmi(result);
5205 __ SmiUntag(result);
5209 void LCodeGen::EmitNumberUntagDNoSSE2(LNumberUntagD* instr, Register input_reg,
5210 Register temp_reg, X87Register res_reg,
5211 NumberUntagDMode mode) {
5212 bool can_convert_undefined_to_nan =
5213 instr->hydrogen()->can_convert_undefined_to_nan();
5214 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
5216 Label load_smi, done;
5218 X87PrepareToWrite(res_reg);
5219 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
5221 __ JumpIfSmi(input_reg, &load_smi);
5223 // Heap number map check.
5224 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5225 factory()->heap_number_map());
5226 if (!can_convert_undefined_to_nan) {
5227 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5229 Label heap_number, convert;
5230 __ j(equal, &heap_number);
5232 // Convert undefined (or hole) to NaN.
5233 __ cmp(input_reg, factory()->undefined_value());
5234 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5237 __ push(Immediate(0xffffffff));
5238 __ push(Immediate(0x7fffffff));
5239 __ fld_d(MemOperand(esp, 0));
5240 __ lea(esp, Operand(esp, kDoubleSize));
5241 __ jmp(&done, Label::kNear);
5243 __ bind(&heap_number);
5245 // Heap number to x87 conversion.
5246 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5247 if (deoptimize_on_minus_zero) {
5250 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5251 __ j(not_zero, &done, Label::kNear);
5253 // Use general purpose registers to check if we have -0.0
5254 __ mov(temp_reg, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5255 __ test(temp_reg, Immediate(HeapNumber::kSignMask));
5256 __ j(zero, &done, Label::kNear);
5258 // Pop FPU stack before deoptimizing.
5260 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5262 __ jmp(&done, Label::kNear);
5264 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
5268 // Clobbering a temp is faster than re-tagging the
5269 // input register since we avoid dependencies.
5270 __ mov(temp_reg, input_reg);
5271 __ SmiUntag(temp_reg); // Untag smi before converting to float.
5273 __ fild_s(Operand(esp, 0));
5274 __ add(esp, Immediate(kPointerSize));
5276 X87CommitWrite(res_reg);
5280 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
5281 Register input_reg = ToRegister(instr->value());
5283 // The input was optimistically untagged; revert it.
5284 STATIC_ASSERT(kSmiTagSize == 1);
5285 __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
5287 if (instr->truncating()) {
5288 Label no_heap_number, check_bools, check_false;
5290 // Heap number map check.
5291 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5292 factory()->heap_number_map());
5293 __ j(not_equal, &no_heap_number, Label::kNear);
5294 __ TruncateHeapNumberToI(input_reg, input_reg);
5297 __ bind(&no_heap_number);
5298 // Check for Oddballs. Undefined/False is converted to zero and True to one
5299 // for truncating conversions.
5300 __ cmp(input_reg, factory()->undefined_value());
5301 __ j(not_equal, &check_bools, Label::kNear);
5302 __ Move(input_reg, Immediate(0));
5305 __ bind(&check_bools);
5306 __ cmp(input_reg, factory()->true_value());
5307 __ j(not_equal, &check_false, Label::kNear);
5308 __ Move(input_reg, Immediate(1));
5311 __ bind(&check_false);
5312 __ cmp(input_reg, factory()->false_value());
5313 DeoptimizeIf(not_equal, instr,
5314 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
5315 __ Move(input_reg, Immediate(0));
5317 // TODO(olivf) Converting a number on the fpu is actually quite slow. We
5318 // should first try a fast conversion and then bailout to this slow case.
5319 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5320 isolate()->factory()->heap_number_map());
5321 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5323 __ sub(esp, Immediate(kPointerSize));
5324 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5326 if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
5327 Label no_precision_lost, not_nan, zero_check;
5330 __ fist_s(MemOperand(esp, 0));
5331 __ fild_s(MemOperand(esp, 0));
5335 __ j(equal, &no_precision_lost, Label::kNear);
5337 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5338 __ bind(&no_precision_lost);
5340 __ j(parity_odd, ¬_nan);
5342 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5345 __ test(input_reg, Operand(input_reg));
5346 __ j(zero, &zero_check, Label::kNear);
5350 __ bind(&zero_check);
5351 // To check for minus zero, we load the value again as float, and check
5352 // if that is still 0.
5353 __ sub(esp, Immediate(kPointerSize));
5354 __ fstp_s(Operand(esp, 0));
5356 __ test(input_reg, Operand(input_reg));
5357 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5359 __ fist_s(MemOperand(esp, 0));
5360 __ fild_s(MemOperand(esp, 0));
5363 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
5364 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
5370 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
5371 class DeferredTaggedToI FINAL : public LDeferredCode {
5373 DeferredTaggedToI(LCodeGen* codegen,
5375 const X87Stack& x87_stack)
5376 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5377 void Generate() OVERRIDE { codegen()->DoDeferredTaggedToI(instr_, done()); }
5378 LInstruction* instr() OVERRIDE { return instr_; }
5384 LOperand* input = instr->value();
5385 DCHECK(input->IsRegister());
5386 Register input_reg = ToRegister(input);
5387 DCHECK(input_reg.is(ToRegister(instr->result())));
5389 if (instr->hydrogen()->value()->representation().IsSmi()) {
5390 __ SmiUntag(input_reg);
5392 DeferredTaggedToI* deferred =
5393 new(zone()) DeferredTaggedToI(this, instr, x87_stack_);
5394 // Optimistically untag the input.
5395 // If the input is a HeapObject, SmiUntag will set the carry flag.
5396 STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
5397 __ SmiUntag(input_reg);
5398 // Branch to deferred code if the input was tagged.
5399 // The deferred code will take care of restoring the tag.
5400 __ j(carry, deferred->entry());
5401 __ bind(deferred->exit());
5406 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
5407 LOperand* input = instr->value();
5408 DCHECK(input->IsRegister());
5409 LOperand* temp = instr->temp();
5410 DCHECK(temp->IsRegister());
5411 LOperand* result = instr->result();
5412 DCHECK(result->IsDoubleRegister());
5414 Register input_reg = ToRegister(input);
5415 Register temp_reg = ToRegister(temp);
5417 HValue* value = instr->hydrogen()->value();
5418 NumberUntagDMode mode = value->representation().IsSmi()
5419 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
5421 EmitNumberUntagDNoSSE2(instr, input_reg, temp_reg, ToX87Register(result),
5426 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
5427 LOperand* input = instr->value();
5428 DCHECK(input->IsDoubleRegister());
5429 LOperand* result = instr->result();
5430 DCHECK(result->IsRegister());
5431 Register result_reg = ToRegister(result);
5433 if (instr->truncating()) {
5434 X87Register input_reg = ToX87Register(input);
5436 __ TruncateX87TOSToI(result_reg);
5438 Label lost_precision, is_nan, minus_zero, done;
5439 X87Register input_reg = ToX87Register(input);
5441 __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5442 &lost_precision, &is_nan, &minus_zero);
5444 __ bind(&lost_precision);
5445 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5447 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5448 __ bind(&minus_zero);
5449 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5455 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
5456 LOperand* input = instr->value();
5457 DCHECK(input->IsDoubleRegister());
5458 LOperand* result = instr->result();
5459 DCHECK(result->IsRegister());
5460 Register result_reg = ToRegister(result);
5462 Label lost_precision, is_nan, minus_zero, done;
5463 X87Register input_reg = ToX87Register(input);
5465 __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5466 &lost_precision, &is_nan, &minus_zero);
5468 __ bind(&lost_precision);
5469 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5471 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5472 __ bind(&minus_zero);
5473 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5475 __ SmiTag(result_reg);
5476 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5480 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
5481 LOperand* input = instr->value();
5482 __ test(ToOperand(input), Immediate(kSmiTagMask));
5483 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5487 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5488 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
5489 LOperand* input = instr->value();
5490 __ test(ToOperand(input), Immediate(kSmiTagMask));
5491 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5496 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
5497 Register input = ToRegister(instr->value());
5498 Register temp = ToRegister(instr->temp());
5500 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
5502 if (instr->hydrogen()->is_interval_check()) {
5505 instr->hydrogen()->GetCheckInterval(&first, &last);
5507 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5508 static_cast<int8_t>(first));
5510 // If there is only one type in the interval check for equality.
5511 if (first == last) {
5512 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5514 DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
5515 // Omit check for the last type.
5516 if (last != LAST_TYPE) {
5517 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5518 static_cast<int8_t>(last));
5519 DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5525 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5527 if (base::bits::IsPowerOfTwo32(mask)) {
5528 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5529 __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5530 DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5531 Deoptimizer::kWrongInstanceType);
5533 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5534 __ and_(temp, mask);
5536 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5542 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5543 Handle<HeapObject> object = instr->hydrogen()->object().handle();
5544 if (instr->hydrogen()->object_in_new_space()) {
5545 Register reg = ToRegister(instr->value());
5546 Handle<Cell> cell = isolate()->factory()->NewCell(object);
5547 __ cmp(reg, Operand::ForCell(cell));
5549 Operand operand = ToOperand(instr->value());
5550 __ cmp(operand, object);
5552 DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5556 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5558 PushSafepointRegistersScope scope(this);
5561 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5562 RecordSafepointWithRegisters(
5563 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5565 __ test(eax, Immediate(kSmiTagMask));
5567 DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5571 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5572 class DeferredCheckMaps FINAL : public LDeferredCode {
5574 DeferredCheckMaps(LCodeGen* codegen,
5577 const X87Stack& x87_stack)
5578 : LDeferredCode(codegen, x87_stack), instr_(instr), object_(object) {
5579 SetExit(check_maps());
5581 void Generate() OVERRIDE {
5582 codegen()->DoDeferredInstanceMigration(instr_, object_);
5584 Label* check_maps() { return &check_maps_; }
5585 LInstruction* instr() OVERRIDE { return instr_; }
5593 if (instr->hydrogen()->IsStabilityCheck()) {
5594 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5595 for (int i = 0; i < maps->size(); ++i) {
5596 AddStabilityDependency(maps->at(i).handle());
5601 LOperand* input = instr->value();
5602 DCHECK(input->IsRegister());
5603 Register reg = ToRegister(input);
5605 DeferredCheckMaps* deferred = NULL;
5606 if (instr->hydrogen()->HasMigrationTarget()) {
5607 deferred = new(zone()) DeferredCheckMaps(this, instr, reg, x87_stack_);
5608 __ bind(deferred->check_maps());
5611 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5613 for (int i = 0; i < maps->size() - 1; i++) {
5614 Handle<Map> map = maps->at(i).handle();
5615 __ CompareMap(reg, map);
5616 __ j(equal, &success, Label::kNear);
5619 Handle<Map> map = maps->at(maps->size() - 1).handle();
5620 __ CompareMap(reg, map);
5621 if (instr->hydrogen()->HasMigrationTarget()) {
5622 __ j(not_equal, deferred->entry());
5624 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5631 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5632 X87Register value_reg = ToX87Register(instr->unclamped());
5633 Register result_reg = ToRegister(instr->result());
5635 __ ClampTOSToUint8(result_reg);
5639 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5640 DCHECK(instr->unclamped()->Equals(instr->result()));
5641 Register value_reg = ToRegister(instr->result());
5642 __ ClampUint8(value_reg);
5646 void LCodeGen::DoClampTToUint8NoSSE2(LClampTToUint8NoSSE2* instr) {
5647 Register input_reg = ToRegister(instr->unclamped());
5648 Register result_reg = ToRegister(instr->result());
5649 Register scratch = ToRegister(instr->scratch());
5650 Register scratch2 = ToRegister(instr->scratch2());
5651 Register scratch3 = ToRegister(instr->scratch3());
5652 Label is_smi, done, heap_number, valid_exponent,
5653 largest_value, zero_result, maybe_nan_or_infinity;
5655 __ JumpIfSmi(input_reg, &is_smi);
5657 // Check for heap number
5658 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5659 factory()->heap_number_map());
5660 __ j(equal, &heap_number, Label::kNear);
5662 // Check for undefined. Undefined is converted to zero for clamping
5664 __ cmp(input_reg, factory()->undefined_value());
5665 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5666 __ jmp(&zero_result, Label::kNear);
5669 __ bind(&heap_number);
5671 // Surprisingly, all of the hand-crafted bit-manipulations below are much
5672 // faster than the x86 FPU built-in instruction, especially since "banker's
5673 // rounding" would be additionally very expensive
5675 // Get exponent word.
5676 __ mov(scratch, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5677 __ mov(scratch3, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5679 // Test for negative values --> clamp to zero
5680 __ test(scratch, scratch);
5681 __ j(negative, &zero_result, Label::kNear);
5683 // Get exponent alone in scratch2.
5684 __ mov(scratch2, scratch);
5685 __ and_(scratch2, HeapNumber::kExponentMask);
5686 __ shr(scratch2, HeapNumber::kExponentShift);
5687 __ j(zero, &zero_result, Label::kNear);
5688 __ sub(scratch2, Immediate(HeapNumber::kExponentBias - 1));
5689 __ j(negative, &zero_result, Label::kNear);
5691 const uint32_t non_int8_exponent = 7;
5692 __ cmp(scratch2, Immediate(non_int8_exponent + 1));
5693 // If the exponent is too big, check for special values.
5694 __ j(greater, &maybe_nan_or_infinity, Label::kNear);
5696 __ bind(&valid_exponent);
5697 // Exponent word in scratch, exponent in scratch2. We know that 0 <= exponent
5698 // < 7. The shift bias is the number of bits to shift the mantissa such that
5699 // with an exponent of 7 such the that top-most one is in bit 30, allowing
5700 // detection the rounding overflow of a 255.5 to 256 (bit 31 goes from 0 to
5702 int shift_bias = (30 - HeapNumber::kExponentShift) - 7 - 1;
5703 __ lea(result_reg, MemOperand(scratch2, shift_bias));
5704 // Here result_reg (ecx) is the shift, scratch is the exponent word. Get the
5705 // top bits of the mantissa.
5706 __ and_(scratch, HeapNumber::kMantissaMask);
5707 // Put back the implicit 1 of the mantissa
5708 __ or_(scratch, 1 << HeapNumber::kExponentShift);
5709 // Shift up to round
5711 // Use "banker's rounding" to spec: If fractional part of number is 0.5, then
5712 // use the bit in the "ones" place and add it to the "halves" place, which has
5713 // the effect of rounding to even.
5714 __ mov(scratch2, scratch);
5715 const uint32_t one_half_bit_shift = 30 - sizeof(uint8_t) * 8;
5716 const uint32_t one_bit_shift = one_half_bit_shift + 1;
5717 __ and_(scratch2, Immediate((1 << one_bit_shift) - 1));
5718 __ cmp(scratch2, Immediate(1 << one_half_bit_shift));
5720 __ j(less, &no_round, Label::kNear);
5722 __ mov(scratch2, Immediate(1 << one_half_bit_shift));
5723 __ j(greater, &round_up, Label::kNear);
5724 __ test(scratch3, scratch3);
5725 __ j(not_zero, &round_up, Label::kNear);
5726 __ mov(scratch2, scratch);
5727 __ and_(scratch2, Immediate(1 << one_bit_shift));
5728 __ shr(scratch2, 1);
5730 __ add(scratch, scratch2);
5731 __ j(overflow, &largest_value, Label::kNear);
5733 __ shr(scratch, 23);
5734 __ mov(result_reg, scratch);
5735 __ jmp(&done, Label::kNear);
5737 __ bind(&maybe_nan_or_infinity);
5738 // Check for NaN/Infinity, all other values map to 255
5739 __ cmp(scratch2, Immediate(HeapNumber::kInfinityOrNanExponent + 1));
5740 __ j(not_equal, &largest_value, Label::kNear);
5742 // Check for NaN, which differs from Infinity in that at least one mantissa
5744 __ and_(scratch, HeapNumber::kMantissaMask);
5745 __ or_(scratch, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5746 __ j(not_zero, &zero_result, Label::kNear); // M!=0 --> NaN
5747 // Infinity -> Fall through to map to 255.
5749 __ bind(&largest_value);
5750 __ mov(result_reg, Immediate(255));
5751 __ jmp(&done, Label::kNear);
5753 __ bind(&zero_result);
5754 __ xor_(result_reg, result_reg);
5755 __ jmp(&done, Label::kNear);
5759 if (!input_reg.is(result_reg)) {
5760 __ mov(result_reg, input_reg);
5762 __ SmiUntag(result_reg);
5763 __ ClampUint8(result_reg);
5768 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5769 X87Register value_reg = ToX87Register(instr->value());
5770 Register result_reg = ToRegister(instr->result());
5772 __ sub(esp, Immediate(kDoubleSize));
5773 __ fst_d(Operand(esp, 0));
5774 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5775 __ mov(result_reg, Operand(esp, kPointerSize));
5777 __ mov(result_reg, Operand(esp, 0));
5779 __ add(esp, Immediate(kDoubleSize));
5783 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5784 Register hi_reg = ToRegister(instr->hi());
5785 Register lo_reg = ToRegister(instr->lo());
5786 X87Register result_reg = ToX87Register(instr->result());
5787 // Follow below pattern to write a x87 fp register.
5788 X87PrepareToWrite(result_reg);
5789 __ sub(esp, Immediate(kDoubleSize));
5790 __ mov(Operand(esp, 0), lo_reg);
5791 __ mov(Operand(esp, kPointerSize), hi_reg);
5792 __ fld_d(Operand(esp, 0));
5793 __ add(esp, Immediate(kDoubleSize));
5794 X87CommitWrite(result_reg);
5798 void LCodeGen::DoAllocate(LAllocate* instr) {
5799 class DeferredAllocate FINAL : public LDeferredCode {
5801 DeferredAllocate(LCodeGen* codegen,
5803 const X87Stack& x87_stack)
5804 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5805 void Generate() OVERRIDE { codegen()->DoDeferredAllocate(instr_); }
5806 LInstruction* instr() OVERRIDE { return instr_; }
5812 DeferredAllocate* deferred =
5813 new(zone()) DeferredAllocate(this, instr, x87_stack_);
5815 Register result = ToRegister(instr->result());
5816 Register temp = ToRegister(instr->temp());
5818 // Allocate memory for the object.
5819 AllocationFlags flags = TAG_OBJECT;
5820 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5821 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5823 if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5824 DCHECK(!instr->hydrogen()->IsOldDataSpaceAllocation());
5825 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5826 flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_POINTER_SPACE);
5827 } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5828 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5829 flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_DATA_SPACE);
5832 if (instr->size()->IsConstantOperand()) {
5833 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5834 if (size <= Page::kMaxRegularHeapObjectSize) {
5835 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5837 __ jmp(deferred->entry());
5840 Register size = ToRegister(instr->size());
5841 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5844 __ bind(deferred->exit());
5846 if (instr->hydrogen()->MustPrefillWithFiller()) {
5847 if (instr->size()->IsConstantOperand()) {
5848 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5849 __ mov(temp, (size / kPointerSize) - 1);
5851 temp = ToRegister(instr->size());
5852 __ shr(temp, kPointerSizeLog2);
5857 __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5858 isolate()->factory()->one_pointer_filler_map());
5860 __ j(not_zero, &loop);
5865 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5866 Register result = ToRegister(instr->result());
5868 // TODO(3095996): Get rid of this. For now, we need to make the
5869 // result register contain a valid pointer because it is already
5870 // contained in the register pointer map.
5871 __ Move(result, Immediate(Smi::FromInt(0)));
5873 PushSafepointRegistersScope scope(this);
5874 if (instr->size()->IsRegister()) {
5875 Register size = ToRegister(instr->size());
5876 DCHECK(!size.is(result));
5877 __ SmiTag(ToRegister(instr->size()));
5880 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5881 if (size >= 0 && size <= Smi::kMaxValue) {
5882 __ push(Immediate(Smi::FromInt(size)));
5884 // We should never get here at runtime => abort
5890 int flags = AllocateDoubleAlignFlag::encode(
5891 instr->hydrogen()->MustAllocateDoubleAligned());
5892 if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5893 DCHECK(!instr->hydrogen()->IsOldDataSpaceAllocation());
5894 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5895 flags = AllocateTargetSpace::update(flags, OLD_POINTER_SPACE);
5896 } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5897 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5898 flags = AllocateTargetSpace::update(flags, OLD_DATA_SPACE);
5900 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5902 __ push(Immediate(Smi::FromInt(flags)));
5904 CallRuntimeFromDeferred(
5905 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5906 __ StoreToSafepointRegisterSlot(result, eax);
5910 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5911 DCHECK(ToRegister(instr->value()).is(eax));
5913 CallRuntime(Runtime::kToFastProperties, 1, instr);
5917 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5918 DCHECK(ToRegister(instr->context()).is(esi));
5920 // Registers will be used as follows:
5921 // ecx = literals array.
5922 // ebx = regexp literal.
5923 // eax = regexp literal clone.
5925 int literal_offset =
5926 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5927 __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5928 __ mov(ebx, FieldOperand(ecx, literal_offset));
5929 __ cmp(ebx, factory()->undefined_value());
5930 __ j(not_equal, &materialized, Label::kNear);
5932 // Create regexp literal using runtime function
5933 // Result will be in eax.
5935 __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5936 __ push(Immediate(instr->hydrogen()->pattern()));
5937 __ push(Immediate(instr->hydrogen()->flags()));
5938 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5941 __ bind(&materialized);
5942 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5943 Label allocated, runtime_allocate;
5944 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5945 __ jmp(&allocated, Label::kNear);
5947 __ bind(&runtime_allocate);
5949 __ push(Immediate(Smi::FromInt(size)));
5950 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5953 __ bind(&allocated);
5954 // Copy the content into the newly allocated memory.
5955 // (Unroll copy loop once for better throughput).
5956 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5957 __ mov(edx, FieldOperand(ebx, i));
5958 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5959 __ mov(FieldOperand(eax, i), edx);
5960 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5962 if ((size % (2 * kPointerSize)) != 0) {
5963 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5964 __ mov(FieldOperand(eax, size - kPointerSize), edx);
5969 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5970 DCHECK(ToRegister(instr->context()).is(esi));
5971 // Use the fast case closure allocation code that allocates in new
5972 // space for nested functions that don't need literals cloning.
5973 bool pretenure = instr->hydrogen()->pretenure();
5974 if (!pretenure && instr->hydrogen()->has_no_literals()) {
5975 FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
5976 instr->hydrogen()->kind());
5977 __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
5978 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5981 __ push(Immediate(instr->hydrogen()->shared_info()));
5982 __ push(Immediate(pretenure ? factory()->true_value()
5983 : factory()->false_value()));
5984 CallRuntime(Runtime::kNewClosure, 3, instr);
5989 void LCodeGen::DoTypeof(LTypeof* instr) {
5990 DCHECK(ToRegister(instr->context()).is(esi));
5991 LOperand* input = instr->value();
5992 EmitPushTaggedOperand(input);
5993 CallRuntime(Runtime::kTypeof, 1, instr);
5997 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5998 Register input = ToRegister(instr->value());
5999 Condition final_branch_condition = EmitTypeofIs(instr, input);
6000 if (final_branch_condition != no_condition) {
6001 EmitBranch(instr, final_branch_condition);
6006 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
6007 Label* true_label = instr->TrueLabel(chunk_);
6008 Label* false_label = instr->FalseLabel(chunk_);
6009 Handle<String> type_name = instr->type_literal();
6010 int left_block = instr->TrueDestination(chunk_);
6011 int right_block = instr->FalseDestination(chunk_);
6012 int next_block = GetNextEmittedBlock();
6014 Label::Distance true_distance = left_block == next_block ? Label::kNear
6016 Label::Distance false_distance = right_block == next_block ? Label::kNear
6018 Condition final_branch_condition = no_condition;
6019 if (String::Equals(type_name, factory()->number_string())) {
6020 __ JumpIfSmi(input, true_label, true_distance);
6021 __ cmp(FieldOperand(input, HeapObject::kMapOffset),
6022 factory()->heap_number_map());
6023 final_branch_condition = equal;
6025 } else if (String::Equals(type_name, factory()->string_string())) {
6026 __ JumpIfSmi(input, false_label, false_distance);
6027 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
6028 __ j(above_equal, false_label, false_distance);
6029 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6030 1 << Map::kIsUndetectable);
6031 final_branch_condition = zero;
6033 } else if (String::Equals(type_name, factory()->symbol_string())) {
6034 __ JumpIfSmi(input, false_label, false_distance);
6035 __ CmpObjectType(input, SYMBOL_TYPE, input);
6036 final_branch_condition = equal;
6038 } else if (String::Equals(type_name, factory()->boolean_string())) {
6039 __ cmp(input, factory()->true_value());
6040 __ j(equal, true_label, true_distance);
6041 __ cmp(input, factory()->false_value());
6042 final_branch_condition = equal;
6044 } else if (String::Equals(type_name, factory()->undefined_string())) {
6045 __ cmp(input, factory()->undefined_value());
6046 __ j(equal, true_label, true_distance);
6047 __ JumpIfSmi(input, false_label, false_distance);
6048 // Check for undetectable objects => true.
6049 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
6050 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6051 1 << Map::kIsUndetectable);
6052 final_branch_condition = not_zero;
6054 } else if (String::Equals(type_name, factory()->function_string())) {
6055 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
6056 __ JumpIfSmi(input, false_label, false_distance);
6057 __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
6058 __ j(equal, true_label, true_distance);
6059 __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
6060 final_branch_condition = equal;
6062 } else if (String::Equals(type_name, factory()->object_string())) {
6063 __ JumpIfSmi(input, false_label, false_distance);
6064 __ cmp(input, factory()->null_value());
6065 __ j(equal, true_label, true_distance);
6066 __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
6067 __ j(below, false_label, false_distance);
6068 __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
6069 __ j(above, false_label, false_distance);
6070 // Check for undetectable objects => false.
6071 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6072 1 << Map::kIsUndetectable);
6073 final_branch_condition = zero;
6076 __ jmp(false_label, false_distance);
6078 return final_branch_condition;
6082 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
6083 Register temp = ToRegister(instr->temp());
6085 EmitIsConstructCall(temp);
6086 EmitBranch(instr, equal);
6090 void LCodeGen::EmitIsConstructCall(Register temp) {
6091 // Get the frame pointer for the calling frame.
6092 __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
6094 // Skip the arguments adaptor frame if it exists.
6095 Label check_frame_marker;
6096 __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
6097 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
6098 __ j(not_equal, &check_frame_marker, Label::kNear);
6099 __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
6101 // Check the marker in the calling frame.
6102 __ bind(&check_frame_marker);
6103 __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
6104 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
6108 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
6109 if (!info()->IsStub()) {
6110 // Ensure that we have enough space after the previous lazy-bailout
6111 // instruction for patching the code here.
6112 int current_pc = masm()->pc_offset();
6113 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
6114 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
6115 __ Nop(padding_size);
6118 last_lazy_deopt_pc_ = masm()->pc_offset();
6122 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
6123 last_lazy_deopt_pc_ = masm()->pc_offset();
6124 DCHECK(instr->HasEnvironment());
6125 LEnvironment* env = instr->environment();
6126 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6127 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6131 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
6132 Deoptimizer::BailoutType type = instr->hydrogen()->type();
6133 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
6134 // needed return address), even though the implementation of LAZY and EAGER is
6135 // now identical. When LAZY is eventually completely folded into EAGER, remove
6136 // the special case below.
6137 if (info()->IsStub() && type == Deoptimizer::EAGER) {
6138 type = Deoptimizer::LAZY;
6140 DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
6144 void LCodeGen::DoDummy(LDummy* instr) {
6145 // Nothing to see here, move on!
6149 void LCodeGen::DoDummyUse(LDummyUse* instr) {
6150 // Nothing to see here, move on!
6154 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
6155 PushSafepointRegistersScope scope(this);
6156 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
6157 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
6158 RecordSafepointWithLazyDeopt(
6159 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
6160 DCHECK(instr->HasEnvironment());
6161 LEnvironment* env = instr->environment();
6162 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6166 void LCodeGen::DoStackCheck(LStackCheck* instr) {
6167 class DeferredStackCheck FINAL : public LDeferredCode {
6169 DeferredStackCheck(LCodeGen* codegen,
6171 const X87Stack& x87_stack)
6172 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
6173 void Generate() OVERRIDE { codegen()->DoDeferredStackCheck(instr_); }
6174 LInstruction* instr() OVERRIDE { return instr_; }
6177 LStackCheck* instr_;
6180 DCHECK(instr->HasEnvironment());
6181 LEnvironment* env = instr->environment();
6182 // There is no LLazyBailout instruction for stack-checks. We have to
6183 // prepare for lazy deoptimization explicitly here.
6184 if (instr->hydrogen()->is_function_entry()) {
6185 // Perform stack overflow check.
6187 ExternalReference stack_limit =
6188 ExternalReference::address_of_stack_limit(isolate());
6189 __ cmp(esp, Operand::StaticVariable(stack_limit));
6190 __ j(above_equal, &done, Label::kNear);
6192 DCHECK(instr->context()->IsRegister());
6193 DCHECK(ToRegister(instr->context()).is(esi));
6194 CallCode(isolate()->builtins()->StackCheck(),
6195 RelocInfo::CODE_TARGET,
6199 DCHECK(instr->hydrogen()->is_backwards_branch());
6200 // Perform stack overflow check if this goto needs it before jumping.
6201 DeferredStackCheck* deferred_stack_check =
6202 new(zone()) DeferredStackCheck(this, instr, x87_stack_);
6203 ExternalReference stack_limit =
6204 ExternalReference::address_of_stack_limit(isolate());
6205 __ cmp(esp, Operand::StaticVariable(stack_limit));
6206 __ j(below, deferred_stack_check->entry());
6207 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
6208 __ bind(instr->done_label());
6209 deferred_stack_check->SetExit(instr->done_label());
6210 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6211 // Don't record a deoptimization index for the safepoint here.
6212 // This will be done explicitly when emitting call and the safepoint in
6213 // the deferred code.
6218 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
6219 // This is a pseudo-instruction that ensures that the environment here is
6220 // properly registered for deoptimization and records the assembler's PC
6222 LEnvironment* environment = instr->environment();
6224 // If the environment were already registered, we would have no way of
6225 // backpatching it with the spill slot operands.
6226 DCHECK(!environment->HasBeenRegistered());
6227 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
6229 GenerateOsrPrologue();
6233 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
6234 DCHECK(ToRegister(instr->context()).is(esi));
6235 __ cmp(eax, isolate()->factory()->undefined_value());
6236 DeoptimizeIf(equal, instr, Deoptimizer::kUndefined);
6238 __ cmp(eax, isolate()->factory()->null_value());
6239 DeoptimizeIf(equal, instr, Deoptimizer::kNull);
6241 __ test(eax, Immediate(kSmiTagMask));
6242 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
6244 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
6245 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
6246 DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
6248 Label use_cache, call_runtime;
6249 __ CheckEnumCache(&call_runtime);
6251 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
6252 __ jmp(&use_cache, Label::kNear);
6254 // Get the set of properties to enumerate.
6255 __ bind(&call_runtime);
6257 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
6259 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
6260 isolate()->factory()->meta_map());
6261 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
6262 __ bind(&use_cache);
6266 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
6267 Register map = ToRegister(instr->map());
6268 Register result = ToRegister(instr->result());
6269 Label load_cache, done;
6270 __ EnumLength(result, map);
6271 __ cmp(result, Immediate(Smi::FromInt(0)));
6272 __ j(not_equal, &load_cache, Label::kNear);
6273 __ mov(result, isolate()->factory()->empty_fixed_array());
6274 __ jmp(&done, Label::kNear);
6276 __ bind(&load_cache);
6277 __ LoadInstanceDescriptors(map, result);
6279 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
6281 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
6283 __ test(result, result);
6284 DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
6288 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
6289 Register object = ToRegister(instr->value());
6290 __ cmp(ToRegister(instr->map()),
6291 FieldOperand(object, HeapObject::kMapOffset));
6292 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
6296 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
6299 PushSafepointRegistersScope scope(this);
6303 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
6304 RecordSafepointWithRegisters(
6305 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
6306 __ StoreToSafepointRegisterSlot(object, eax);
6310 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
6311 class DeferredLoadMutableDouble FINAL : public LDeferredCode {
6313 DeferredLoadMutableDouble(LCodeGen* codegen,
6314 LLoadFieldByIndex* instr,
6317 const X87Stack& x87_stack)
6318 : LDeferredCode(codegen, x87_stack),
6323 void Generate() OVERRIDE {
6324 codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
6326 LInstruction* instr() OVERRIDE { return instr_; }
6329 LLoadFieldByIndex* instr_;
6334 Register object = ToRegister(instr->object());
6335 Register index = ToRegister(instr->index());
6337 DeferredLoadMutableDouble* deferred;
6338 deferred = new(zone()) DeferredLoadMutableDouble(
6339 this, instr, object, index, x87_stack_);
6341 Label out_of_object, done;
6342 __ test(index, Immediate(Smi::FromInt(1)));
6343 __ j(not_zero, deferred->entry());
6347 __ cmp(index, Immediate(0));
6348 __ j(less, &out_of_object, Label::kNear);
6349 __ mov(object, FieldOperand(object,
6351 times_half_pointer_size,
6352 JSObject::kHeaderSize));
6353 __ jmp(&done, Label::kNear);
6355 __ bind(&out_of_object);
6356 __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
6358 // Index is now equal to out of object property index plus 1.
6359 __ mov(object, FieldOperand(object,
6361 times_half_pointer_size,
6362 FixedArray::kHeaderSize - kPointerSize));
6363 __ bind(deferred->exit());
6368 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
6369 Register context = ToRegister(instr->context());
6370 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
6374 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
6375 Handle<ScopeInfo> scope_info = instr->scope_info();
6376 __ Push(scope_info);
6377 __ push(ToRegister(instr->function()));
6378 CallRuntime(Runtime::kPushBlockContext, 2, instr);
6379 RecordSafepoint(Safepoint::kNoLazyDeopt);
6385 } } // namespace v8::internal
6387 #endif // V8_TARGET_ARCH_X87