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 (is_sloppy(info()->language_mode()) && info()->MayUseThis() &&
114 !info()->is_native() && info()->scope()->has_this_declaration()) {
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 DCHECK(!info()->scope()->is_script_scope());
228 if (heap_slots <= FastNewContextStub::kMaximumSlots) {
229 FastNewContextStub stub(isolate(), heap_slots);
231 // Result of FastNewContextStub is always in new space.
232 need_write_barrier = false;
235 __ CallRuntime(Runtime::kNewFunctionContext, 1);
237 RecordSafepoint(Safepoint::kNoLazyDeopt);
238 // Context is returned in eax. It replaces the context passed to us.
239 // It's saved in the stack and kept live in esi.
241 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
243 // Copy parameters into context if necessary.
244 int num_parameters = scope()->num_parameters();
245 int first_parameter = scope()->has_this_declaration() ? -1 : 0;
246 for (int i = first_parameter; i < num_parameters; i++) {
247 Variable* var = (i == -1) ? scope()->receiver() : scope()->parameter(i);
248 if (var->IsContextSlot()) {
249 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
250 (num_parameters - 1 - i) * kPointerSize;
251 // Load parameter from stack.
252 __ mov(eax, Operand(ebp, parameter_offset));
253 // Store it in the context.
254 int context_offset = Context::SlotOffset(var->index());
255 __ mov(Operand(esi, context_offset), eax);
256 // Update the write barrier. This clobbers eax and ebx.
257 if (need_write_barrier) {
258 __ RecordWriteContextSlot(esi, context_offset, eax, ebx,
260 } else if (FLAG_debug_code) {
262 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
263 __ Abort(kExpectedNewSpaceObject);
268 Comment(";;; End allocate local context");
271 // Initailize FPU state.
274 if (FLAG_trace && info()->IsOptimizing()) {
275 // We have not executed any compiled code yet, so esi still holds the
277 __ CallRuntime(Runtime::kTraceEnter, 0);
279 return !is_aborted();
283 void LCodeGen::GenerateOsrPrologue() {
284 // Generate the OSR entry prologue at the first unknown OSR value, or if there
285 // are none, at the OSR entrypoint instruction.
286 if (osr_pc_offset_ >= 0) return;
288 osr_pc_offset_ = masm()->pc_offset();
290 // Move state of dynamic frame alignment into edx.
291 __ Move(edx, Immediate(kNoAlignmentPadding));
293 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
294 Label do_not_pad, align_loop;
295 // Align ebp + 4 to a multiple of 2 * kPointerSize.
296 __ test(ebp, Immediate(kPointerSize));
297 __ j(zero, &do_not_pad, Label::kNear);
298 __ push(Immediate(0));
300 __ mov(edx, Immediate(kAlignmentPaddingPushed));
302 // Move all parts of the frame over one word. The frame consists of:
303 // unoptimized frame slots, alignment state, context, frame pointer, return
304 // address, receiver, and the arguments.
305 __ mov(ecx, Immediate(scope()->num_parameters() +
306 5 + graph()->osr()->UnoptimizedFrameSlots()));
308 __ bind(&align_loop);
309 __ mov(eax, Operand(ebx, 1 * kPointerSize));
310 __ mov(Operand(ebx, 0), eax);
311 __ add(Operand(ebx), Immediate(kPointerSize));
313 __ j(not_zero, &align_loop, Label::kNear);
314 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
315 __ sub(Operand(ebp), Immediate(kPointerSize));
316 __ bind(&do_not_pad);
319 // Save the first local, which is overwritten by the alignment state.
320 Operand alignment_loc = MemOperand(ebp, -3 * kPointerSize);
321 __ push(alignment_loc);
323 // Set the dynamic frame alignment state.
324 __ mov(alignment_loc, edx);
326 // Adjust the frame size, subsuming the unoptimized frame into the
328 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
330 __ sub(esp, Immediate((slots - 1) * kPointerSize));
332 // Initailize FPU state.
337 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
338 if (instr->IsCall()) {
339 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
341 if (!instr->IsLazyBailout() && !instr->IsGap()) {
342 safepoints_.BumpLastLazySafepointIndex();
344 FlushX87StackIfNecessary(instr);
348 void LCodeGen::GenerateBodyInstructionPost(LInstruction* instr) {
349 // When return from function call, FPU should be initialized again.
350 if (instr->IsCall() && instr->ClobbersDoubleRegisters(isolate())) {
351 bool double_result = instr->HasDoubleRegisterResult();
353 __ lea(esp, Operand(esp, -kDoubleSize));
354 __ fstp_d(Operand(esp, 0));
358 __ fld_d(Operand(esp, 0));
359 __ lea(esp, Operand(esp, kDoubleSize));
362 if (instr->IsGoto()) {
363 x87_stack_.LeavingBlock(current_block_, LGoto::cast(instr), this);
364 } else if (FLAG_debug_code && FLAG_enable_slow_asserts &&
365 !instr->IsGap() && !instr->IsReturn()) {
366 if (instr->ClobbersDoubleRegisters(isolate())) {
367 if (instr->HasDoubleRegisterResult()) {
368 DCHECK_EQ(1, x87_stack_.depth());
370 DCHECK_EQ(0, x87_stack_.depth());
373 __ VerifyX87StackDepth(x87_stack_.depth());
378 bool LCodeGen::GenerateJumpTable() {
379 if (!jump_table_.length()) return !is_aborted();
382 Comment(";;; -------------------- Jump table --------------------");
384 for (int i = 0; i < jump_table_.length(); i++) {
385 Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
386 __ bind(&table_entry->label);
387 Address entry = table_entry->address;
388 DeoptComment(table_entry->deopt_info);
389 if (table_entry->needs_frame) {
390 DCHECK(!info()->saves_caller_doubles());
391 __ push(Immediate(ExternalReference::ForDeoptEntry(entry)));
392 __ call(&needs_frame);
394 __ call(entry, RelocInfo::RUNTIME_ENTRY);
396 info()->LogDeoptCallPosition(masm()->pc_offset(),
397 table_entry->deopt_info.inlining_id);
399 if (needs_frame.is_linked()) {
400 __ bind(&needs_frame);
404 3: return address <-- esp
409 __ sub(esp, Immediate(kPointerSize)); // Reserve space for stub marker.
410 __ push(MemOperand(esp, kPointerSize)); // Copy return address.
411 __ push(MemOperand(esp, 3 * kPointerSize)); // Copy entry address.
418 0: entry address <-- esp
420 __ mov(MemOperand(esp, 4 * kPointerSize), ebp); // Save ebp.
423 __ mov(ebp, MemOperand(ebp, StandardFrameConstants::kContextOffset));
424 __ mov(MemOperand(esp, 3 * kPointerSize), ebp);
425 // Fill ebp with the right stack frame address.
426 __ lea(ebp, MemOperand(esp, 4 * kPointerSize));
428 // This variant of deopt can only be used with stubs. Since we don't
429 // have a function pointer to install in the stack frame that we're
430 // building, install a special marker there instead.
431 DCHECK(info()->IsStub());
432 __ mov(MemOperand(esp, 2 * kPointerSize),
433 Immediate(Smi::FromInt(StackFrame::STUB)));
440 0: entry address <-- esp
442 __ ret(0); // Call the continuation without clobbering registers.
444 return !is_aborted();
448 bool LCodeGen::GenerateDeferredCode() {
449 DCHECK(is_generating());
450 if (deferred_.length() > 0) {
451 for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
452 LDeferredCode* code = deferred_[i];
453 X87Stack copy(code->x87_stack());
457 instructions_->at(code->instruction_index())->hydrogen_value();
458 RecordAndWritePosition(
459 chunk()->graph()->SourcePositionToScriptPosition(value->position()));
461 Comment(";;; <@%d,#%d> "
462 "-------------------- Deferred %s --------------------",
463 code->instruction_index(),
464 code->instr()->hydrogen_value()->id(),
465 code->instr()->Mnemonic());
466 __ bind(code->entry());
467 if (NeedsDeferredFrame()) {
468 Comment(";;; Build frame");
469 DCHECK(!frame_is_built_);
470 DCHECK(info()->IsStub());
471 frame_is_built_ = true;
472 // Build the frame in such a way that esi isn't trashed.
473 __ push(ebp); // Caller's frame pointer.
474 __ push(Operand(ebp, StandardFrameConstants::kContextOffset));
475 __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
476 __ lea(ebp, Operand(esp, 2 * kPointerSize));
477 Comment(";;; Deferred code");
480 if (NeedsDeferredFrame()) {
481 __ bind(code->done());
482 Comment(";;; Destroy frame");
483 DCHECK(frame_is_built_);
484 frame_is_built_ = false;
488 __ jmp(code->exit());
492 // Deferred code is the last part of the instruction sequence. Mark
493 // the generated code as done unless we bailed out.
494 if (!is_aborted()) status_ = DONE;
495 return !is_aborted();
499 bool LCodeGen::GenerateSafepointTable() {
501 if (!info()->IsStub()) {
502 // For lazy deoptimization we need space to patch a call after every call.
503 // Ensure there is always space for such patching, even if the code ends
505 int target_offset = masm()->pc_offset() + Deoptimizer::patch_size();
506 while (masm()->pc_offset() < target_offset) {
510 safepoints_.Emit(masm(), GetStackSlotCount());
511 return !is_aborted();
515 Register LCodeGen::ToRegister(int index) const {
516 return Register::FromAllocationIndex(index);
520 X87Register LCodeGen::ToX87Register(int index) const {
521 return X87Register::FromAllocationIndex(index);
525 void LCodeGen::X87LoadForUsage(X87Register reg) {
526 DCHECK(x87_stack_.Contains(reg));
527 x87_stack_.Fxch(reg);
532 void LCodeGen::X87LoadForUsage(X87Register reg1, X87Register reg2) {
533 DCHECK(x87_stack_.Contains(reg1));
534 DCHECK(x87_stack_.Contains(reg2));
535 if (reg1.is(reg2) && x87_stack_.depth() == 1) {
536 __ fld(x87_stack_.st(reg1));
537 x87_stack_.push(reg1);
541 x87_stack_.Fxch(reg1, 1);
542 x87_stack_.Fxch(reg2);
549 int LCodeGen::X87Stack::GetLayout() {
550 int layout = stack_depth_;
551 for (int i = 0; i < stack_depth_; i++) {
552 layout |= (stack_[stack_depth_ - 1 - i].code() << ((i + 1) * 3));
559 void LCodeGen::X87Stack::Fxch(X87Register reg, int other_slot) {
561 DCHECK(Contains(reg) && stack_depth_ > other_slot);
562 int i = ArrayIndex(reg);
564 if (st != other_slot) {
565 int other_i = st2idx(other_slot);
566 X87Register other = stack_[other_i];
567 stack_[other_i] = reg;
571 } else if (other_slot == 0) {
582 int LCodeGen::X87Stack::st2idx(int pos) {
583 return stack_depth_ - pos - 1;
587 int LCodeGen::X87Stack::ArrayIndex(X87Register reg) {
588 for (int i = 0; i < stack_depth_; i++) {
589 if (stack_[i].is(reg)) return i;
596 bool LCodeGen::X87Stack::Contains(X87Register reg) {
597 for (int i = 0; i < stack_depth_; i++) {
598 if (stack_[i].is(reg)) return true;
604 void LCodeGen::X87Stack::Free(X87Register reg) {
606 DCHECK(Contains(reg));
607 int i = ArrayIndex(reg);
610 // keep track of how fstp(i) changes the order of elements
611 int tos_i = st2idx(0);
612 stack_[i] = stack_[tos_i];
619 void LCodeGen::X87Mov(X87Register dst, Operand src, X87OperandType opts) {
620 if (x87_stack_.Contains(dst)) {
621 x87_stack_.Fxch(dst);
624 x87_stack_.push(dst);
630 void LCodeGen::X87Mov(X87Register dst, X87Register src, X87OperandType opts) {
631 if (x87_stack_.Contains(dst)) {
632 x87_stack_.Fxch(dst);
635 // Push ST(i) onto the FPU register stack
636 __ fld(x87_stack_.st(src));
637 x87_stack_.push(dst);
639 // Push ST(i) onto the FPU register stack
640 __ fld(x87_stack_.st(src));
641 x87_stack_.push(dst);
646 void LCodeGen::X87Fld(Operand src, X87OperandType opts) {
647 DCHECK(!src.is_reg_only());
649 case kX87DoubleOperand:
652 case kX87FloatOperand:
664 void LCodeGen::X87Mov(Operand dst, X87Register src, X87OperandType opts) {
665 DCHECK(!dst.is_reg_only());
666 x87_stack_.Fxch(src);
668 case kX87DoubleOperand:
671 case kX87FloatOperand:
683 void LCodeGen::X87Stack::PrepareToWrite(X87Register reg) {
688 // Mark this register as the next register to write to
689 stack_[stack_depth_] = reg;
693 void LCodeGen::X87Stack::CommitWrite(X87Register reg) {
695 // Assert the reg is prepared to write, but not on the virtual stack yet
696 DCHECK(!Contains(reg) && stack_[stack_depth_].is(reg) &&
697 stack_depth_ < X87Register::kMaxNumAllocatableRegisters);
702 void LCodeGen::X87PrepareBinaryOp(
703 X87Register left, X87Register right, X87Register result) {
704 // You need to use DefineSameAsFirst for x87 instructions
705 DCHECK(result.is(left));
706 x87_stack_.Fxch(right, 1);
707 x87_stack_.Fxch(left);
711 void LCodeGen::X87Stack::FlushIfNecessary(LInstruction* instr, LCodeGen* cgen) {
712 if (stack_depth_ > 0 && instr->ClobbersDoubleRegisters(isolate())) {
713 bool double_inputs = instr->HasDoubleRegisterInput();
715 // Flush stack from tos down, since FreeX87() will mess with tos
716 for (int i = stack_depth_-1; i >= 0; i--) {
717 X87Register reg = stack_[i];
718 // Skip registers which contain the inputs for the next instruction
719 // when flushing the stack
720 if (double_inputs && instr->IsDoubleInput(reg, cgen)) {
724 if (i < stack_depth_-1) i++;
727 if (instr->IsReturn()) {
728 while (stack_depth_ > 0) {
732 if (FLAG_debug_code && FLAG_enable_slow_asserts) __ VerifyX87StackDepth(0);
737 void LCodeGen::X87Stack::LeavingBlock(int current_block_id, LGoto* goto_instr,
739 // For going to a joined block, an explicit LClobberDoubles is inserted before
740 // LGoto. Because all used x87 registers are spilled to stack slots. The
741 // ResolvePhis phase of register allocator could guarantee the two input's x87
742 // stacks have the same layout. So don't check stack_depth_ <= 1 here.
743 int goto_block_id = goto_instr->block_id();
744 if (current_block_id + 1 != goto_block_id) {
745 // If we have a value on the x87 stack on leaving a block, it must be a
746 // phi input. If the next block we compile is not the join block, we have
747 // to discard the stack state.
748 // Before discarding the stack state, we need to save it if the "goto block"
749 // has unreachable last predecessor when FLAG_unreachable_code_elimination.
750 if (FLAG_unreachable_code_elimination) {
751 int length = goto_instr->block()->predecessors()->length();
752 bool has_unreachable_last_predecessor = false;
753 for (int i = 0; i < length; i++) {
754 HBasicBlock* block = goto_instr->block()->predecessors()->at(i);
755 if (block->IsUnreachable() &&
756 (block->block_id() + 1) == goto_block_id) {
757 has_unreachable_last_predecessor = true;
760 if (has_unreachable_last_predecessor) {
761 if (cgen->x87_stack_map_.find(goto_block_id) ==
762 cgen->x87_stack_map_.end()) {
763 X87Stack* stack = new (cgen->zone()) X87Stack(*this);
764 cgen->x87_stack_map_.insert(std::make_pair(goto_block_id, stack));
769 // Discard the stack state.
775 void LCodeGen::EmitFlushX87ForDeopt() {
776 // The deoptimizer does not support X87 Registers. But as long as we
777 // deopt from a stub its not a problem, since we will re-materialize the
778 // original stub inputs, which can't be double registers.
779 // DCHECK(info()->IsStub());
780 if (FLAG_debug_code && FLAG_enable_slow_asserts) {
782 __ VerifyX87StackDepth(x87_stack_.depth());
786 // Flush X87 stack in the deoptimizer entry.
790 Register LCodeGen::ToRegister(LOperand* op) const {
791 DCHECK(op->IsRegister());
792 return ToRegister(op->index());
796 X87Register LCodeGen::ToX87Register(LOperand* op) const {
797 DCHECK(op->IsDoubleRegister());
798 return ToX87Register(op->index());
802 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
803 return ToRepresentation(op, Representation::Integer32());
807 int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
808 const Representation& r) const {
809 HConstant* constant = chunk_->LookupConstant(op);
810 if (r.IsExternal()) {
811 return reinterpret_cast<int32_t>(
812 constant->ExternalReferenceValue().address());
814 int32_t value = constant->Integer32Value();
815 if (r.IsInteger32()) return value;
816 DCHECK(r.IsSmiOrTagged());
817 return reinterpret_cast<int32_t>(Smi::FromInt(value));
821 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
822 HConstant* constant = chunk_->LookupConstant(op);
823 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
824 return constant->handle(isolate());
828 double LCodeGen::ToDouble(LConstantOperand* op) const {
829 HConstant* constant = chunk_->LookupConstant(op);
830 DCHECK(constant->HasDoubleValue());
831 return constant->DoubleValue();
835 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
836 HConstant* constant = chunk_->LookupConstant(op);
837 DCHECK(constant->HasExternalReferenceValue());
838 return constant->ExternalReferenceValue();
842 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
843 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
847 bool LCodeGen::IsSmi(LConstantOperand* op) const {
848 return chunk_->LookupLiteralRepresentation(op).IsSmi();
852 static int ArgumentsOffsetWithoutFrame(int index) {
854 return -(index + 1) * kPointerSize + kPCOnStackSize;
858 Operand LCodeGen::ToOperand(LOperand* op) const {
859 if (op->IsRegister()) return Operand(ToRegister(op));
860 DCHECK(!op->IsDoubleRegister());
861 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
862 if (NeedsEagerFrame()) {
863 return Operand(ebp, StackSlotOffset(op->index()));
865 // Retrieve parameter without eager stack-frame relative to the
867 return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
872 Operand LCodeGen::HighOperand(LOperand* op) {
873 DCHECK(op->IsDoubleStackSlot());
874 if (NeedsEagerFrame()) {
875 return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
877 // Retrieve parameter without eager stack-frame relative to the
880 esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
885 void LCodeGen::WriteTranslation(LEnvironment* environment,
886 Translation* translation) {
887 if (environment == NULL) return;
889 // The translation includes one command per value in the environment.
890 int translation_size = environment->translation_size();
892 WriteTranslation(environment->outer(), translation);
893 WriteTranslationFrame(environment, translation);
895 int object_index = 0;
896 int dematerialized_index = 0;
897 for (int i = 0; i < translation_size; ++i) {
898 LOperand* value = environment->values()->at(i);
899 AddToTranslation(environment,
902 environment->HasTaggedValueAt(i),
903 environment->HasUint32ValueAt(i),
905 &dematerialized_index);
910 void LCodeGen::AddToTranslation(LEnvironment* environment,
911 Translation* translation,
915 int* object_index_pointer,
916 int* dematerialized_index_pointer) {
917 if (op == LEnvironment::materialization_marker()) {
918 int object_index = (*object_index_pointer)++;
919 if (environment->ObjectIsDuplicateAt(object_index)) {
920 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
921 translation->DuplicateObject(dupe_of);
924 int object_length = environment->ObjectLengthAt(object_index);
925 if (environment->ObjectIsArgumentsAt(object_index)) {
926 translation->BeginArgumentsObject(object_length);
928 translation->BeginCapturedObject(object_length);
930 int dematerialized_index = *dematerialized_index_pointer;
931 int env_offset = environment->translation_size() + dematerialized_index;
932 *dematerialized_index_pointer += object_length;
933 for (int i = 0; i < object_length; ++i) {
934 LOperand* value = environment->values()->at(env_offset + i);
935 AddToTranslation(environment,
938 environment->HasTaggedValueAt(env_offset + i),
939 environment->HasUint32ValueAt(env_offset + i),
940 object_index_pointer,
941 dematerialized_index_pointer);
946 if (op->IsStackSlot()) {
948 translation->StoreStackSlot(op->index());
949 } else if (is_uint32) {
950 translation->StoreUint32StackSlot(op->index());
952 translation->StoreInt32StackSlot(op->index());
954 } else if (op->IsDoubleStackSlot()) {
955 translation->StoreDoubleStackSlot(op->index());
956 } else if (op->IsRegister()) {
957 Register reg = ToRegister(op);
959 translation->StoreRegister(reg);
960 } else if (is_uint32) {
961 translation->StoreUint32Register(reg);
963 translation->StoreInt32Register(reg);
965 } else if (op->IsDoubleRegister()) {
966 X87Register reg = ToX87Register(op);
967 translation->StoreDoubleRegister(reg);
968 } else if (op->IsConstantOperand()) {
969 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
970 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
971 translation->StoreLiteral(src_index);
978 void LCodeGen::CallCodeGeneric(Handle<Code> code,
979 RelocInfo::Mode mode,
981 SafepointMode safepoint_mode) {
982 DCHECK(instr != NULL);
984 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
986 // Signal that we don't inline smi code before these stubs in the
987 // optimizing code generator.
988 if (code->kind() == Code::BINARY_OP_IC ||
989 code->kind() == Code::COMPARE_IC) {
995 void LCodeGen::CallCode(Handle<Code> code,
996 RelocInfo::Mode mode,
997 LInstruction* instr) {
998 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
1002 void LCodeGen::CallRuntime(const Runtime::Function* fun, int argc,
1003 LInstruction* instr, SaveFPRegsMode save_doubles) {
1004 DCHECK(instr != NULL);
1005 DCHECK(instr->HasPointerMap());
1007 __ CallRuntime(fun, argc, save_doubles);
1009 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
1011 DCHECK(info()->is_calling());
1015 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
1016 if (context->IsRegister()) {
1017 if (!ToRegister(context).is(esi)) {
1018 __ mov(esi, ToRegister(context));
1020 } else if (context->IsStackSlot()) {
1021 __ mov(esi, ToOperand(context));
1022 } else if (context->IsConstantOperand()) {
1023 HConstant* constant =
1024 chunk_->LookupConstant(LConstantOperand::cast(context));
1025 __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
1031 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
1033 LInstruction* instr,
1034 LOperand* context) {
1035 LoadContextFromDeferred(context);
1037 __ CallRuntimeSaveDoubles(id);
1038 RecordSafepointWithRegisters(
1039 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
1041 DCHECK(info()->is_calling());
1045 void LCodeGen::RegisterEnvironmentForDeoptimization(
1046 LEnvironment* environment, Safepoint::DeoptMode mode) {
1047 environment->set_has_been_used();
1048 if (!environment->HasBeenRegistered()) {
1049 // Physical stack frame layout:
1050 // -x ............. -4 0 ..................................... y
1051 // [incoming arguments] [spill slots] [pushed outgoing arguments]
1053 // Layout of the environment:
1054 // 0 ..................................................... size-1
1055 // [parameters] [locals] [expression stack including arguments]
1057 // Layout of the translation:
1058 // 0 ........................................................ size - 1 + 4
1059 // [expression stack including arguments] [locals] [4 words] [parameters]
1060 // |>------------ translation_size ------------<|
1062 int frame_count = 0;
1063 int jsframe_count = 0;
1064 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
1066 if (e->frame_type() == JS_FUNCTION) {
1070 Translation translation(&translations_, frame_count, jsframe_count, zone());
1071 WriteTranslation(environment, &translation);
1072 int deoptimization_index = deoptimizations_.length();
1073 int pc_offset = masm()->pc_offset();
1074 environment->Register(deoptimization_index,
1075 translation.index(),
1076 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
1077 deoptimizations_.Add(environment, zone());
1082 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1083 Deoptimizer::DeoptReason deopt_reason,
1084 Deoptimizer::BailoutType bailout_type) {
1085 LEnvironment* environment = instr->environment();
1086 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
1087 DCHECK(environment->HasBeenRegistered());
1088 int id = environment->deoptimization_index();
1089 DCHECK(info()->IsOptimizing() || info()->IsStub());
1091 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
1092 if (entry == NULL) {
1093 Abort(kBailoutWasNotPrepared);
1097 if (DeoptEveryNTimes()) {
1098 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
1102 __ mov(eax, Operand::StaticVariable(count));
1103 __ sub(eax, Immediate(1));
1104 __ j(not_zero, &no_deopt, Label::kNear);
1105 if (FLAG_trap_on_deopt) __ int3();
1106 __ mov(eax, Immediate(FLAG_deopt_every_n_times));
1107 __ mov(Operand::StaticVariable(count), eax);
1110 DCHECK(frame_is_built_);
1111 // Put the x87 stack layout in TOS.
1112 if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1113 __ push(Immediate(x87_stack_.GetLayout()));
1114 __ fild_s(MemOperand(esp, 0));
1115 // Don't touch eflags.
1116 __ lea(esp, Operand(esp, kPointerSize));
1117 __ call(entry, RelocInfo::RUNTIME_ENTRY);
1119 __ mov(Operand::StaticVariable(count), eax);
1124 // Put the x87 stack layout in TOS, so that we can save x87 fp registers in
1125 // the correct location.
1128 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1129 if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1131 int x87_stack_layout = x87_stack_.GetLayout();
1132 __ push(Immediate(x87_stack_layout));
1133 __ fild_s(MemOperand(esp, 0));
1134 // Don't touch eflags.
1135 __ lea(esp, Operand(esp, kPointerSize));
1139 if (info()->ShouldTrapOnDeopt()) {
1141 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1146 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
1148 DCHECK(info()->IsStub() || frame_is_built_);
1149 if (cc == no_condition && frame_is_built_) {
1150 DeoptComment(deopt_info);
1151 __ call(entry, RelocInfo::RUNTIME_ENTRY);
1152 info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
1154 Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
1156 // We often have several deopts to the same entry, reuse the last
1157 // jump entry if this is the case.
1158 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
1159 jump_table_.is_empty() ||
1160 !table_entry.IsEquivalentTo(jump_table_.last())) {
1161 jump_table_.Add(table_entry, zone());
1163 if (cc == no_condition) {
1164 __ jmp(&jump_table_.last().label);
1166 __ j(cc, &jump_table_.last().label);
1172 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1173 Deoptimizer::DeoptReason deopt_reason) {
1174 Deoptimizer::BailoutType bailout_type = info()->IsStub()
1176 : Deoptimizer::EAGER;
1177 DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
1181 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
1182 int length = deoptimizations_.length();
1183 if (length == 0) return;
1184 Handle<DeoptimizationInputData> data =
1185 DeoptimizationInputData::New(isolate(), length, TENURED);
1187 Handle<ByteArray> translations =
1188 translations_.CreateByteArray(isolate()->factory());
1189 data->SetTranslationByteArray(*translations);
1190 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
1191 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
1192 if (info_->IsOptimizing()) {
1193 // Reference to shared function info does not change between phases.
1194 AllowDeferredHandleDereference allow_handle_dereference;
1195 data->SetSharedFunctionInfo(*info_->shared_info());
1197 data->SetSharedFunctionInfo(Smi::FromInt(0));
1199 data->SetWeakCellCache(Smi::FromInt(0));
1201 Handle<FixedArray> literals =
1202 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
1203 { AllowDeferredHandleDereference copy_handles;
1204 for (int i = 0; i < deoptimization_literals_.length(); i++) {
1205 literals->set(i, *deoptimization_literals_[i]);
1207 data->SetLiteralArray(*literals);
1210 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
1211 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
1213 // Populate the deoptimization entries.
1214 for (int i = 0; i < length; i++) {
1215 LEnvironment* env = deoptimizations_[i];
1216 data->SetAstId(i, env->ast_id());
1217 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
1218 data->SetArgumentsStackHeight(i,
1219 Smi::FromInt(env->arguments_stack_height()));
1220 data->SetPc(i, Smi::FromInt(env->pc_offset()));
1222 code->set_deoptimization_data(*data);
1226 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
1227 DCHECK_EQ(0, deoptimization_literals_.length());
1228 for (auto function : chunk()->inlined_functions()) {
1229 DefineDeoptimizationLiteral(function);
1231 inlined_function_count_ = deoptimization_literals_.length();
1235 void LCodeGen::RecordSafepointWithLazyDeopt(
1236 LInstruction* instr, SafepointMode safepoint_mode) {
1237 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
1238 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
1240 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
1241 RecordSafepointWithRegisters(
1242 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
1247 void LCodeGen::RecordSafepoint(
1248 LPointerMap* pointers,
1249 Safepoint::Kind kind,
1251 Safepoint::DeoptMode deopt_mode) {
1252 DCHECK(kind == expected_safepoint_kind_);
1253 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
1254 Safepoint safepoint =
1255 safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
1256 for (int i = 0; i < operands->length(); i++) {
1257 LOperand* pointer = operands->at(i);
1258 if (pointer->IsStackSlot()) {
1259 safepoint.DefinePointerSlot(pointer->index(), zone());
1260 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
1261 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
1267 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
1268 Safepoint::DeoptMode mode) {
1269 RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
1273 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
1274 LPointerMap empty_pointers(zone());
1275 RecordSafepoint(&empty_pointers, mode);
1279 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
1281 Safepoint::DeoptMode mode) {
1282 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1286 void LCodeGen::RecordAndWritePosition(int position) {
1287 if (position == RelocInfo::kNoPosition) return;
1288 masm()->positions_recorder()->RecordPosition(position);
1289 masm()->positions_recorder()->WriteRecordedPositions();
1293 static const char* LabelType(LLabel* label) {
1294 if (label->is_loop_header()) return " (loop header)";
1295 if (label->is_osr_entry()) return " (OSR entry)";
1300 void LCodeGen::DoLabel(LLabel* label) {
1301 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1302 current_instruction_,
1303 label->hydrogen_value()->id(),
1306 __ bind(label->label());
1307 current_block_ = label->block_id();
1308 if (label->block()->predecessors()->length() > 1) {
1309 // A join block's x87 stack is that of its last visited predecessor.
1310 // If the last visited predecessor block is unreachable, the stack state
1311 // will be wrong. In such case, use the x87 stack of reachable predecessor.
1312 X87StackMap::const_iterator it = x87_stack_map_.find(current_block_);
1313 // Restore x87 stack.
1314 if (it != x87_stack_map_.end()) {
1315 x87_stack_ = *(it->second);
1322 void LCodeGen::DoParallelMove(LParallelMove* move) {
1323 resolver_.Resolve(move);
1327 void LCodeGen::DoGap(LGap* gap) {
1328 for (int i = LGap::FIRST_INNER_POSITION;
1329 i <= LGap::LAST_INNER_POSITION;
1331 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1332 LParallelMove* move = gap->GetParallelMove(inner_pos);
1333 if (move != NULL) DoParallelMove(move);
1338 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1343 void LCodeGen::DoParameter(LParameter* instr) {
1348 void LCodeGen::DoCallStub(LCallStub* instr) {
1349 DCHECK(ToRegister(instr->context()).is(esi));
1350 DCHECK(ToRegister(instr->result()).is(eax));
1351 switch (instr->hydrogen()->major_key()) {
1352 case CodeStub::RegExpExec: {
1353 RegExpExecStub stub(isolate());
1354 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1357 case CodeStub::SubString: {
1358 SubStringStub stub(isolate());
1359 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1362 case CodeStub::StringCompare: {
1363 StringCompareStub stub(isolate());
1364 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1373 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1374 GenerateOsrPrologue();
1378 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1379 Register dividend = ToRegister(instr->dividend());
1380 int32_t divisor = instr->divisor();
1381 DCHECK(dividend.is(ToRegister(instr->result())));
1383 // Theoretically, a variation of the branch-free code for integer division by
1384 // a power of 2 (calculating the remainder via an additional multiplication
1385 // (which gets simplified to an 'and') and subtraction) should be faster, and
1386 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1387 // indicate that positive dividends are heavily favored, so the branching
1388 // version performs better.
1389 HMod* hmod = instr->hydrogen();
1390 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1391 Label dividend_is_not_negative, done;
1392 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1393 __ test(dividend, dividend);
1394 __ j(not_sign, ÷nd_is_not_negative, Label::kNear);
1395 // Note that this is correct even for kMinInt operands.
1397 __ and_(dividend, mask);
1399 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1400 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1402 __ jmp(&done, Label::kNear);
1405 __ bind(÷nd_is_not_negative);
1406 __ and_(dividend, mask);
1411 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1412 Register dividend = ToRegister(instr->dividend());
1413 int32_t divisor = instr->divisor();
1414 DCHECK(ToRegister(instr->result()).is(eax));
1417 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1421 __ TruncatingDiv(dividend, Abs(divisor));
1422 __ imul(edx, edx, Abs(divisor));
1423 __ mov(eax, dividend);
1426 // Check for negative zero.
1427 HMod* hmod = instr->hydrogen();
1428 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1429 Label remainder_not_zero;
1430 __ j(not_zero, &remainder_not_zero, Label::kNear);
1431 __ cmp(dividend, Immediate(0));
1432 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1433 __ bind(&remainder_not_zero);
1438 void LCodeGen::DoModI(LModI* instr) {
1439 HMod* hmod = instr->hydrogen();
1441 Register left_reg = ToRegister(instr->left());
1442 DCHECK(left_reg.is(eax));
1443 Register right_reg = ToRegister(instr->right());
1444 DCHECK(!right_reg.is(eax));
1445 DCHECK(!right_reg.is(edx));
1446 Register result_reg = ToRegister(instr->result());
1447 DCHECK(result_reg.is(edx));
1450 // Check for x % 0, idiv would signal a divide error. We have to
1451 // deopt in this case because we can't return a NaN.
1452 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1453 __ test(right_reg, Operand(right_reg));
1454 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1457 // Check for kMinInt % -1, idiv would signal a divide error. We
1458 // have to deopt if we care about -0, because we can't return that.
1459 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1460 Label no_overflow_possible;
1461 __ cmp(left_reg, kMinInt);
1462 __ j(not_equal, &no_overflow_possible, Label::kNear);
1463 __ cmp(right_reg, -1);
1464 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1465 DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1467 __ j(not_equal, &no_overflow_possible, Label::kNear);
1468 __ Move(result_reg, Immediate(0));
1469 __ jmp(&done, Label::kNear);
1471 __ bind(&no_overflow_possible);
1474 // Sign extend dividend in eax into edx:eax.
1477 // If we care about -0, test if the dividend is <0 and the result is 0.
1478 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1479 Label positive_left;
1480 __ test(left_reg, Operand(left_reg));
1481 __ j(not_sign, &positive_left, Label::kNear);
1483 __ test(result_reg, Operand(result_reg));
1484 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1485 __ jmp(&done, Label::kNear);
1486 __ bind(&positive_left);
1493 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1494 Register dividend = ToRegister(instr->dividend());
1495 int32_t divisor = instr->divisor();
1496 Register result = ToRegister(instr->result());
1497 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1498 DCHECK(!result.is(dividend));
1500 // Check for (0 / -x) that will produce negative zero.
1501 HDiv* hdiv = instr->hydrogen();
1502 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1503 __ test(dividend, dividend);
1504 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1506 // Check for (kMinInt / -1).
1507 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1508 __ cmp(dividend, kMinInt);
1509 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1511 // Deoptimize if remainder will not be 0.
1512 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1513 divisor != 1 && divisor != -1) {
1514 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1515 __ test(dividend, Immediate(mask));
1516 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1518 __ Move(result, dividend);
1519 int32_t shift = WhichPowerOf2Abs(divisor);
1521 // The arithmetic shift is always OK, the 'if' is an optimization only.
1522 if (shift > 1) __ sar(result, 31);
1523 __ shr(result, 32 - shift);
1524 __ add(result, dividend);
1525 __ sar(result, shift);
1527 if (divisor < 0) __ neg(result);
1531 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1532 Register dividend = ToRegister(instr->dividend());
1533 int32_t divisor = instr->divisor();
1534 DCHECK(ToRegister(instr->result()).is(edx));
1537 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1541 // Check for (0 / -x) that will produce negative zero.
1542 HDiv* hdiv = instr->hydrogen();
1543 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1544 __ test(dividend, dividend);
1545 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1548 __ TruncatingDiv(dividend, Abs(divisor));
1549 if (divisor < 0) __ neg(edx);
1551 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1553 __ imul(eax, eax, divisor);
1554 __ sub(eax, dividend);
1555 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1560 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1561 void LCodeGen::DoDivI(LDivI* instr) {
1562 HBinaryOperation* hdiv = instr->hydrogen();
1563 Register dividend = ToRegister(instr->dividend());
1564 Register divisor = ToRegister(instr->divisor());
1565 Register remainder = ToRegister(instr->temp());
1566 DCHECK(dividend.is(eax));
1567 DCHECK(remainder.is(edx));
1568 DCHECK(ToRegister(instr->result()).is(eax));
1569 DCHECK(!divisor.is(eax));
1570 DCHECK(!divisor.is(edx));
1573 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1574 __ test(divisor, divisor);
1575 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1578 // Check for (0 / -x) that will produce negative zero.
1579 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1580 Label dividend_not_zero;
1581 __ test(dividend, dividend);
1582 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1583 __ test(divisor, divisor);
1584 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1585 __ bind(÷nd_not_zero);
1588 // Check for (kMinInt / -1).
1589 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1590 Label dividend_not_min_int;
1591 __ cmp(dividend, kMinInt);
1592 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1593 __ cmp(divisor, -1);
1594 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1595 __ bind(÷nd_not_min_int);
1598 // Sign extend to edx (= remainder).
1602 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1603 // Deoptimize if remainder is not 0.
1604 __ test(remainder, remainder);
1605 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1610 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1611 Register dividend = ToRegister(instr->dividend());
1612 int32_t divisor = instr->divisor();
1613 DCHECK(dividend.is(ToRegister(instr->result())));
1615 // If the divisor is positive, things are easy: There can be no deopts and we
1616 // can simply do an arithmetic right shift.
1617 if (divisor == 1) return;
1618 int32_t shift = WhichPowerOf2Abs(divisor);
1620 __ sar(dividend, shift);
1624 // If the divisor is negative, we have to negate and handle edge cases.
1626 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1627 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1630 // Dividing by -1 is basically negation, unless we overflow.
1631 if (divisor == -1) {
1632 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1633 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1638 // If the negation could not overflow, simply shifting is OK.
1639 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1640 __ sar(dividend, shift);
1644 Label not_kmin_int, done;
1645 __ j(no_overflow, ¬_kmin_int, Label::kNear);
1646 __ mov(dividend, Immediate(kMinInt / divisor));
1647 __ jmp(&done, Label::kNear);
1648 __ bind(¬_kmin_int);
1649 __ sar(dividend, shift);
1654 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1655 Register dividend = ToRegister(instr->dividend());
1656 int32_t divisor = instr->divisor();
1657 DCHECK(ToRegister(instr->result()).is(edx));
1660 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1664 // Check for (0 / -x) that will produce negative zero.
1665 HMathFloorOfDiv* hdiv = instr->hydrogen();
1666 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1667 __ test(dividend, dividend);
1668 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1671 // Easy case: We need no dynamic check for the dividend and the flooring
1672 // division is the same as the truncating division.
1673 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1674 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1675 __ TruncatingDiv(dividend, Abs(divisor));
1676 if (divisor < 0) __ neg(edx);
1680 // In the general case we may need to adjust before and after the truncating
1681 // division to get a flooring division.
1682 Register temp = ToRegister(instr->temp3());
1683 DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1684 Label needs_adjustment, done;
1685 __ cmp(dividend, Immediate(0));
1686 __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1687 __ TruncatingDiv(dividend, Abs(divisor));
1688 if (divisor < 0) __ neg(edx);
1689 __ jmp(&done, Label::kNear);
1690 __ bind(&needs_adjustment);
1691 __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1692 __ TruncatingDiv(temp, Abs(divisor));
1693 if (divisor < 0) __ neg(edx);
1699 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1700 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1701 HBinaryOperation* hdiv = instr->hydrogen();
1702 Register dividend = ToRegister(instr->dividend());
1703 Register divisor = ToRegister(instr->divisor());
1704 Register remainder = ToRegister(instr->temp());
1705 Register result = ToRegister(instr->result());
1706 DCHECK(dividend.is(eax));
1707 DCHECK(remainder.is(edx));
1708 DCHECK(result.is(eax));
1709 DCHECK(!divisor.is(eax));
1710 DCHECK(!divisor.is(edx));
1713 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1714 __ test(divisor, divisor);
1715 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1718 // Check for (0 / -x) that will produce negative zero.
1719 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1720 Label dividend_not_zero;
1721 __ test(dividend, dividend);
1722 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1723 __ test(divisor, divisor);
1724 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1725 __ bind(÷nd_not_zero);
1728 // Check for (kMinInt / -1).
1729 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1730 Label dividend_not_min_int;
1731 __ cmp(dividend, kMinInt);
1732 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1733 __ cmp(divisor, -1);
1734 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1735 __ bind(÷nd_not_min_int);
1738 // Sign extend to edx (= remainder).
1743 __ test(remainder, remainder);
1744 __ j(zero, &done, Label::kNear);
1745 __ xor_(remainder, divisor);
1746 __ sar(remainder, 31);
1747 __ add(result, remainder);
1752 void LCodeGen::DoMulI(LMulI* instr) {
1753 Register left = ToRegister(instr->left());
1754 LOperand* right = instr->right();
1756 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1757 __ mov(ToRegister(instr->temp()), left);
1760 if (right->IsConstantOperand()) {
1761 // Try strength reductions on the multiplication.
1762 // All replacement instructions are at most as long as the imul
1763 // and have better latency.
1764 int constant = ToInteger32(LConstantOperand::cast(right));
1765 if (constant == -1) {
1767 } else if (constant == 0) {
1768 __ xor_(left, Operand(left));
1769 } else if (constant == 2) {
1770 __ add(left, Operand(left));
1771 } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1772 // If we know that the multiplication can't overflow, it's safe to
1773 // use instructions that don't set the overflow flag for the
1780 __ lea(left, Operand(left, left, times_2, 0));
1786 __ lea(left, Operand(left, left, times_4, 0));
1792 __ lea(left, Operand(left, left, times_8, 0));
1798 __ imul(left, left, constant);
1802 __ imul(left, left, constant);
1805 if (instr->hydrogen()->representation().IsSmi()) {
1808 __ imul(left, ToOperand(right));
1811 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1812 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1815 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1816 // Bail out if the result is supposed to be negative zero.
1818 __ test(left, Operand(left));
1819 __ j(not_zero, &done);
1820 if (right->IsConstantOperand()) {
1821 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1822 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1823 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1824 __ cmp(ToRegister(instr->temp()), Immediate(0));
1825 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1828 // Test the non-zero operand for negative sign.
1829 __ or_(ToRegister(instr->temp()), ToOperand(right));
1830 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1837 void LCodeGen::DoBitI(LBitI* instr) {
1838 LOperand* left = instr->left();
1839 LOperand* right = instr->right();
1840 DCHECK(left->Equals(instr->result()));
1841 DCHECK(left->IsRegister());
1843 if (right->IsConstantOperand()) {
1844 int32_t right_operand =
1845 ToRepresentation(LConstantOperand::cast(right),
1846 instr->hydrogen()->representation());
1847 switch (instr->op()) {
1848 case Token::BIT_AND:
1849 __ and_(ToRegister(left), right_operand);
1852 __ or_(ToRegister(left), right_operand);
1854 case Token::BIT_XOR:
1855 if (right_operand == int32_t(~0)) {
1856 __ not_(ToRegister(left));
1858 __ xor_(ToRegister(left), right_operand);
1866 switch (instr->op()) {
1867 case Token::BIT_AND:
1868 __ and_(ToRegister(left), ToOperand(right));
1871 __ or_(ToRegister(left), ToOperand(right));
1873 case Token::BIT_XOR:
1874 __ xor_(ToRegister(left), ToOperand(right));
1884 void LCodeGen::DoShiftI(LShiftI* instr) {
1885 LOperand* left = instr->left();
1886 LOperand* right = instr->right();
1887 DCHECK(left->Equals(instr->result()));
1888 DCHECK(left->IsRegister());
1889 if (right->IsRegister()) {
1890 DCHECK(ToRegister(right).is(ecx));
1892 switch (instr->op()) {
1894 __ ror_cl(ToRegister(left));
1897 __ sar_cl(ToRegister(left));
1900 __ shr_cl(ToRegister(left));
1901 if (instr->can_deopt()) {
1902 __ test(ToRegister(left), ToRegister(left));
1903 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1907 __ shl_cl(ToRegister(left));
1914 int value = ToInteger32(LConstantOperand::cast(right));
1915 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1916 switch (instr->op()) {
1918 if (shift_count == 0 && instr->can_deopt()) {
1919 __ test(ToRegister(left), ToRegister(left));
1920 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1922 __ ror(ToRegister(left), shift_count);
1926 if (shift_count != 0) {
1927 __ sar(ToRegister(left), shift_count);
1931 if (shift_count != 0) {
1932 __ shr(ToRegister(left), shift_count);
1933 } else if (instr->can_deopt()) {
1934 __ test(ToRegister(left), ToRegister(left));
1935 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1939 if (shift_count != 0) {
1940 if (instr->hydrogen_value()->representation().IsSmi() &&
1941 instr->can_deopt()) {
1942 if (shift_count != 1) {
1943 __ shl(ToRegister(left), shift_count - 1);
1945 __ SmiTag(ToRegister(left));
1946 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1948 __ shl(ToRegister(left), shift_count);
1960 void LCodeGen::DoSubI(LSubI* instr) {
1961 LOperand* left = instr->left();
1962 LOperand* right = instr->right();
1963 DCHECK(left->Equals(instr->result()));
1965 if (right->IsConstantOperand()) {
1966 __ sub(ToOperand(left),
1967 ToImmediate(right, instr->hydrogen()->representation()));
1969 __ sub(ToRegister(left), ToOperand(right));
1971 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1972 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1977 void LCodeGen::DoConstantI(LConstantI* instr) {
1978 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1982 void LCodeGen::DoConstantS(LConstantS* instr) {
1983 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1987 void LCodeGen::DoConstantD(LConstantD* instr) {
1988 uint64_t const bits = instr->bits();
1989 uint32_t const lower = static_cast<uint32_t>(bits);
1990 uint32_t const upper = static_cast<uint32_t>(bits >> 32);
1991 DCHECK(instr->result()->IsDoubleRegister());
1993 __ push(Immediate(upper));
1994 __ push(Immediate(lower));
1995 X87Register reg = ToX87Register(instr->result());
1996 X87Mov(reg, Operand(esp, 0));
1997 __ add(Operand(esp), Immediate(kDoubleSize));
2001 void LCodeGen::DoConstantE(LConstantE* instr) {
2002 __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
2006 void LCodeGen::DoConstantT(LConstantT* instr) {
2007 Register reg = ToRegister(instr->result());
2008 Handle<Object> object = instr->value(isolate());
2009 AllowDeferredHandleDereference smi_check;
2010 __ LoadObject(reg, object);
2014 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
2015 Register result = ToRegister(instr->result());
2016 Register map = ToRegister(instr->value());
2017 __ EnumLength(result, map);
2021 void LCodeGen::DoDateField(LDateField* instr) {
2022 Register object = ToRegister(instr->date());
2023 Register result = ToRegister(instr->result());
2024 Register scratch = ToRegister(instr->temp());
2025 Smi* index = instr->index();
2026 DCHECK(object.is(result));
2027 DCHECK(object.is(eax));
2029 if (index->value() == 0) {
2030 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
2032 Label runtime, done;
2033 if (index->value() < JSDate::kFirstUncachedField) {
2034 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
2035 __ mov(scratch, Operand::StaticVariable(stamp));
2036 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
2037 __ j(not_equal, &runtime, Label::kNear);
2038 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
2039 kPointerSize * index->value()));
2040 __ jmp(&done, Label::kNear);
2043 __ PrepareCallCFunction(2, scratch);
2044 __ mov(Operand(esp, 0), object);
2045 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
2046 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
2052 Operand LCodeGen::BuildSeqStringOperand(Register string,
2054 String::Encoding encoding) {
2055 if (index->IsConstantOperand()) {
2056 int offset = ToRepresentation(LConstantOperand::cast(index),
2057 Representation::Integer32());
2058 if (encoding == String::TWO_BYTE_ENCODING) {
2059 offset *= kUC16Size;
2061 STATIC_ASSERT(kCharSize == 1);
2062 return FieldOperand(string, SeqString::kHeaderSize + offset);
2064 return FieldOperand(
2065 string, ToRegister(index),
2066 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
2067 SeqString::kHeaderSize);
2071 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
2072 String::Encoding encoding = instr->hydrogen()->encoding();
2073 Register result = ToRegister(instr->result());
2074 Register string = ToRegister(instr->string());
2076 if (FLAG_debug_code) {
2078 __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
2079 __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
2081 __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
2082 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2083 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2084 __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
2085 ? one_byte_seq_type : two_byte_seq_type));
2086 __ Check(equal, kUnexpectedStringType);
2090 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2091 if (encoding == String::ONE_BYTE_ENCODING) {
2092 __ movzx_b(result, operand);
2094 __ movzx_w(result, operand);
2099 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
2100 String::Encoding encoding = instr->hydrogen()->encoding();
2101 Register string = ToRegister(instr->string());
2103 if (FLAG_debug_code) {
2104 Register value = ToRegister(instr->value());
2105 Register index = ToRegister(instr->index());
2106 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2107 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2109 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
2110 ? one_byte_seq_type : two_byte_seq_type;
2111 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
2114 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2115 if (instr->value()->IsConstantOperand()) {
2116 int value = ToRepresentation(LConstantOperand::cast(instr->value()),
2117 Representation::Integer32());
2118 DCHECK_LE(0, value);
2119 if (encoding == String::ONE_BYTE_ENCODING) {
2120 DCHECK_LE(value, String::kMaxOneByteCharCode);
2121 __ mov_b(operand, static_cast<int8_t>(value));
2123 DCHECK_LE(value, String::kMaxUtf16CodeUnit);
2124 __ mov_w(operand, static_cast<int16_t>(value));
2127 Register value = ToRegister(instr->value());
2128 if (encoding == String::ONE_BYTE_ENCODING) {
2129 __ mov_b(operand, value);
2131 __ mov_w(operand, value);
2137 void LCodeGen::DoAddI(LAddI* instr) {
2138 LOperand* left = instr->left();
2139 LOperand* right = instr->right();
2141 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
2142 if (right->IsConstantOperand()) {
2143 int32_t offset = ToRepresentation(LConstantOperand::cast(right),
2144 instr->hydrogen()->representation());
2145 __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
2147 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
2148 __ lea(ToRegister(instr->result()), address);
2151 if (right->IsConstantOperand()) {
2152 __ add(ToOperand(left),
2153 ToImmediate(right, instr->hydrogen()->representation()));
2155 __ add(ToRegister(left), ToOperand(right));
2157 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
2158 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
2164 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
2165 LOperand* left = instr->left();
2166 LOperand* right = instr->right();
2167 DCHECK(left->Equals(instr->result()));
2168 HMathMinMax::Operation operation = instr->hydrogen()->operation();
2169 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
2171 Condition condition = (operation == HMathMinMax::kMathMin)
2174 if (right->IsConstantOperand()) {
2175 Operand left_op = ToOperand(left);
2176 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
2177 instr->hydrogen()->representation());
2178 __ cmp(left_op, immediate);
2179 __ j(condition, &return_left, Label::kNear);
2180 __ mov(left_op, immediate);
2182 Register left_reg = ToRegister(left);
2183 Operand right_op = ToOperand(right);
2184 __ cmp(left_reg, right_op);
2185 __ j(condition, &return_left, Label::kNear);
2186 __ mov(left_reg, right_op);
2188 __ bind(&return_left);
2190 DCHECK(instr->hydrogen()->representation().IsDouble());
2191 Label check_nan_left, check_zero, return_left, return_right;
2192 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
2193 X87Register left_reg = ToX87Register(left);
2194 X87Register right_reg = ToX87Register(right);
2196 X87PrepareBinaryOp(left_reg, right_reg, ToX87Register(instr->result()));
2200 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
2201 __ j(equal, &check_zero, Label::kNear); // left == right.
2202 __ j(condition, &return_left, Label::kNear);
2203 __ jmp(&return_right, Label::kNear);
2205 __ bind(&check_zero);
2209 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
2210 // At this point, both left and right are either 0 or -0.
2211 if (operation == HMathMinMax::kMathMin) {
2212 // Push st0 and st1 to stack, then pop them to temp registers and OR them,
2214 Register scratch_reg = ToRegister(instr->temp());
2217 __ sub(esp, Immediate(2 * kPointerSize));
2218 __ fstp_s(MemOperand(esp, 0));
2219 __ fstp_s(MemOperand(esp, kPointerSize));
2220 __ pop(scratch_reg);
2221 __ xor_(MemOperand(esp, 0), scratch_reg);
2222 X87Mov(left_reg, MemOperand(esp, 0), kX87FloatOperand);
2223 __ pop(scratch_reg); // restore esp
2225 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
2229 __ jmp(&return_left, Label::kNear);
2231 __ bind(&check_nan_left);
2234 __ FCmp(); // NaN check.
2235 __ j(parity_even, &return_left, Label::kNear); // left == NaN.
2237 __ bind(&return_right);
2239 X87Mov(left_reg, right_reg);
2241 __ bind(&return_left);
2246 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
2247 X87Register left = ToX87Register(instr->left());
2248 X87Register right = ToX87Register(instr->right());
2249 X87Register result = ToX87Register(instr->result());
2250 if (instr->op() != Token::MOD) {
2251 X87PrepareBinaryOp(left, right, result);
2253 // Set the precision control to double-precision.
2254 __ X87SetFPUCW(0x027F);
2255 switch (instr->op()) {
2269 // Pass two doubles as arguments on the stack.
2270 __ PrepareCallCFunction(4, eax);
2271 X87Mov(Operand(esp, 1 * kDoubleSize), right);
2272 X87Mov(Operand(esp, 0), left);
2274 DCHECK(left.is(result));
2275 X87PrepareToWrite(result);
2277 ExternalReference::mod_two_doubles_operation(isolate()),
2280 // Return value is in st(0) on ia32.
2281 X87CommitWrite(result);
2289 // Restore the default value of control word.
2290 __ X87SetFPUCW(0x037F);
2294 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2295 DCHECK(ToRegister(instr->context()).is(esi));
2296 DCHECK(ToRegister(instr->left()).is(edx));
2297 DCHECK(ToRegister(instr->right()).is(eax));
2298 DCHECK(ToRegister(instr->result()).is(eax));
2301 CodeFactory::BinaryOpIC(isolate(), instr->op(), instr->strength()).code();
2302 CallCode(code, RelocInfo::CODE_TARGET, instr);
2306 template<class InstrType>
2307 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2308 int left_block = instr->TrueDestination(chunk_);
2309 int right_block = instr->FalseDestination(chunk_);
2311 int next_block = GetNextEmittedBlock();
2313 if (right_block == left_block || cc == no_condition) {
2314 EmitGoto(left_block);
2315 } else if (left_block == next_block) {
2316 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2317 } else if (right_block == next_block) {
2318 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2320 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2321 __ jmp(chunk_->GetAssemblyLabel(right_block));
2326 template<class InstrType>
2327 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2328 int false_block = instr->FalseDestination(chunk_);
2329 if (cc == no_condition) {
2330 __ jmp(chunk_->GetAssemblyLabel(false_block));
2332 __ j(cc, chunk_->GetAssemblyLabel(false_block));
2337 void LCodeGen::DoBranch(LBranch* instr) {
2338 Representation r = instr->hydrogen()->value()->representation();
2339 if (r.IsSmiOrInteger32()) {
2340 Register reg = ToRegister(instr->value());
2341 __ test(reg, Operand(reg));
2342 EmitBranch(instr, not_zero);
2343 } else if (r.IsDouble()) {
2344 X87Register reg = ToX87Register(instr->value());
2345 X87LoadForUsage(reg);
2348 EmitBranch(instr, not_zero);
2350 DCHECK(r.IsTagged());
2351 Register reg = ToRegister(instr->value());
2352 HType type = instr->hydrogen()->value()->type();
2353 if (type.IsBoolean()) {
2354 DCHECK(!info()->IsStub());
2355 __ cmp(reg, factory()->true_value());
2356 EmitBranch(instr, equal);
2357 } else if (type.IsSmi()) {
2358 DCHECK(!info()->IsStub());
2359 __ test(reg, Operand(reg));
2360 EmitBranch(instr, not_equal);
2361 } else if (type.IsJSArray()) {
2362 DCHECK(!info()->IsStub());
2363 EmitBranch(instr, no_condition);
2364 } else if (type.IsHeapNumber()) {
2366 } else if (type.IsString()) {
2367 DCHECK(!info()->IsStub());
2368 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2369 EmitBranch(instr, not_equal);
2371 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2372 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2374 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2375 // undefined -> false.
2376 __ cmp(reg, factory()->undefined_value());
2377 __ j(equal, instr->FalseLabel(chunk_));
2379 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2381 __ cmp(reg, factory()->true_value());
2382 __ j(equal, instr->TrueLabel(chunk_));
2384 __ cmp(reg, factory()->false_value());
2385 __ j(equal, instr->FalseLabel(chunk_));
2387 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2389 __ cmp(reg, factory()->null_value());
2390 __ j(equal, instr->FalseLabel(chunk_));
2393 if (expected.Contains(ToBooleanStub::SMI)) {
2394 // Smis: 0 -> false, all other -> true.
2395 __ test(reg, Operand(reg));
2396 __ j(equal, instr->FalseLabel(chunk_));
2397 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2398 } else if (expected.NeedsMap()) {
2399 // If we need a map later and have a Smi -> deopt.
2400 __ test(reg, Immediate(kSmiTagMask));
2401 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2404 Register map = no_reg; // Keep the compiler happy.
2405 if (expected.NeedsMap()) {
2406 map = ToRegister(instr->temp());
2407 DCHECK(!map.is(reg));
2408 __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2410 if (expected.CanBeUndetectable()) {
2411 // Undetectable -> false.
2412 __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2413 1 << Map::kIsUndetectable);
2414 __ j(not_zero, instr->FalseLabel(chunk_));
2418 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2419 // spec object -> true.
2420 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2421 __ j(above_equal, instr->TrueLabel(chunk_));
2424 if (expected.Contains(ToBooleanStub::STRING)) {
2425 // String value -> false iff empty.
2427 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2428 __ j(above_equal, ¬_string, Label::kNear);
2429 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2430 __ j(not_zero, instr->TrueLabel(chunk_));
2431 __ jmp(instr->FalseLabel(chunk_));
2432 __ bind(¬_string);
2435 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2436 // Symbol value -> true.
2437 __ CmpInstanceType(map, SYMBOL_TYPE);
2438 __ j(equal, instr->TrueLabel(chunk_));
2441 if (expected.Contains(ToBooleanStub::SIMD_VALUE)) {
2442 // SIMD value -> true.
2443 __ CmpInstanceType(map, FLOAT32X4_TYPE);
2444 __ j(equal, instr->TrueLabel(chunk_));
2447 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2448 // heap number -> false iff +0, -0, or NaN.
2449 Label not_heap_number;
2450 __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2451 factory()->heap_number_map());
2452 __ j(not_equal, ¬_heap_number, Label::kNear);
2454 __ fld_d(FieldOperand(reg, HeapNumber::kValueOffset));
2456 __ j(zero, instr->FalseLabel(chunk_));
2457 __ jmp(instr->TrueLabel(chunk_));
2458 __ bind(¬_heap_number);
2461 if (!expected.IsGeneric()) {
2462 // We've seen something for the first time -> deopt.
2463 // This can only happen if we are not generic already.
2464 DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2471 void LCodeGen::EmitGoto(int block) {
2472 if (!IsNextEmittedBlock(block)) {
2473 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2478 void LCodeGen::DoClobberDoubles(LClobberDoubles* instr) {
2482 void LCodeGen::DoGoto(LGoto* instr) {
2483 EmitGoto(instr->block_id());
2487 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2488 Condition cond = no_condition;
2491 case Token::EQ_STRICT:
2495 case Token::NE_STRICT:
2499 cond = is_unsigned ? below : less;
2502 cond = is_unsigned ? above : greater;
2505 cond = is_unsigned ? below_equal : less_equal;
2508 cond = is_unsigned ? above_equal : greater_equal;
2511 case Token::INSTANCEOF:
2519 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2520 LOperand* left = instr->left();
2521 LOperand* right = instr->right();
2523 instr->is_double() ||
2524 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2525 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2526 Condition cc = TokenToCondition(instr->op(), is_unsigned);
2528 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2529 // We can statically evaluate the comparison.
2530 double left_val = ToDouble(LConstantOperand::cast(left));
2531 double right_val = ToDouble(LConstantOperand::cast(right));
2532 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2533 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2534 EmitGoto(next_block);
2536 if (instr->is_double()) {
2537 X87LoadForUsage(ToX87Register(right), ToX87Register(left));
2539 // Don't base result on EFLAGS when a NaN is involved. Instead
2540 // jump to the false block.
2541 __ j(parity_even, instr->FalseLabel(chunk_));
2543 if (right->IsConstantOperand()) {
2544 __ cmp(ToOperand(left),
2545 ToImmediate(right, instr->hydrogen()->representation()));
2546 } else if (left->IsConstantOperand()) {
2547 __ cmp(ToOperand(right),
2548 ToImmediate(left, instr->hydrogen()->representation()));
2549 // We commuted the operands, so commute the condition.
2550 cc = CommuteCondition(cc);
2552 __ cmp(ToRegister(left), ToOperand(right));
2555 EmitBranch(instr, cc);
2560 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2561 Register left = ToRegister(instr->left());
2563 if (instr->right()->IsConstantOperand()) {
2564 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2565 __ CmpObject(left, right);
2567 Operand right = ToOperand(instr->right());
2568 __ cmp(left, right);
2570 EmitBranch(instr, equal);
2574 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2575 if (instr->hydrogen()->representation().IsTagged()) {
2576 Register input_reg = ToRegister(instr->object());
2577 __ cmp(input_reg, factory()->the_hole_value());
2578 EmitBranch(instr, equal);
2582 // Put the value to the top of stack
2583 X87Register src = ToX87Register(instr->object());
2584 X87LoadForUsage(src);
2589 __ j(parity_even, &ok, Label::kNear);
2591 EmitFalseBranch(instr, no_condition);
2595 __ sub(esp, Immediate(kDoubleSize));
2596 __ fstp_d(MemOperand(esp, 0));
2598 __ add(esp, Immediate(kDoubleSize));
2599 int offset = sizeof(kHoleNanUpper32);
2600 // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
2601 // so we check the upper with 0xffffffff for hole as a temporary fix.
2602 __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
2603 EmitBranch(instr, equal);
2607 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2608 Representation rep = instr->hydrogen()->value()->representation();
2609 DCHECK(!rep.IsInteger32());
2611 if (rep.IsDouble()) {
2612 X87Register input = ToX87Register(instr->value());
2613 X87LoadForUsage(input);
2615 EmitBranch(instr, equal);
2617 Register value = ToRegister(instr->value());
2618 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2619 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2620 __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2622 EmitFalseBranch(instr, no_overflow);
2623 __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2624 Immediate(0x00000000));
2625 EmitBranch(instr, equal);
2630 Condition LCodeGen::EmitIsObject(Register input,
2632 Label* is_not_object,
2634 __ JumpIfSmi(input, is_not_object);
2636 __ cmp(input, isolate()->factory()->null_value());
2637 __ j(equal, is_object);
2639 __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
2640 // Undetectable objects behave like undefined.
2641 __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
2642 1 << Map::kIsUndetectable);
2643 __ j(not_zero, is_not_object);
2645 __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
2646 __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2647 __ j(below, is_not_object);
2648 __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2653 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2654 Register reg = ToRegister(instr->value());
2655 Register temp = ToRegister(instr->temp());
2657 Condition true_cond = EmitIsObject(
2658 reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2660 EmitBranch(instr, true_cond);
2664 Condition LCodeGen::EmitIsString(Register input,
2666 Label* is_not_string,
2667 SmiCheck check_needed = INLINE_SMI_CHECK) {
2668 if (check_needed == INLINE_SMI_CHECK) {
2669 __ JumpIfSmi(input, is_not_string);
2672 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2678 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2679 Register reg = ToRegister(instr->value());
2680 Register temp = ToRegister(instr->temp());
2682 SmiCheck check_needed =
2683 instr->hydrogen()->value()->type().IsHeapObject()
2684 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2686 Condition true_cond = EmitIsString(
2687 reg, temp, instr->FalseLabel(chunk_), check_needed);
2689 EmitBranch(instr, true_cond);
2693 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2694 Operand input = ToOperand(instr->value());
2696 __ test(input, Immediate(kSmiTagMask));
2697 EmitBranch(instr, zero);
2701 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2702 Register input = ToRegister(instr->value());
2703 Register temp = ToRegister(instr->temp());
2705 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2706 STATIC_ASSERT(kSmiTag == 0);
2707 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2709 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2710 __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2711 1 << Map::kIsUndetectable);
2712 EmitBranch(instr, not_zero);
2716 static Condition ComputeCompareCondition(Token::Value op) {
2718 case Token::EQ_STRICT:
2728 return greater_equal;
2731 return no_condition;
2736 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2737 Token::Value op = instr->op();
2740 CodeFactory::CompareIC(isolate(), op, Strength::WEAK).code();
2741 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2743 Condition condition = ComputeCompareCondition(op);
2744 __ test(eax, Operand(eax));
2746 EmitBranch(instr, condition);
2750 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2751 InstanceType from = instr->from();
2752 InstanceType to = instr->to();
2753 if (from == FIRST_TYPE) return to;
2754 DCHECK(from == to || to == LAST_TYPE);
2759 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2760 InstanceType from = instr->from();
2761 InstanceType to = instr->to();
2762 if (from == to) return equal;
2763 if (to == LAST_TYPE) return above_equal;
2764 if (from == FIRST_TYPE) return below_equal;
2770 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2771 Register input = ToRegister(instr->value());
2772 Register temp = ToRegister(instr->temp());
2774 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2775 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2778 __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2779 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2783 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2784 Register input = ToRegister(instr->value());
2785 Register result = ToRegister(instr->result());
2787 __ AssertString(input);
2789 __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2790 __ IndexFromHash(result, result);
2794 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2795 LHasCachedArrayIndexAndBranch* instr) {
2796 Register input = ToRegister(instr->value());
2798 __ test(FieldOperand(input, String::kHashFieldOffset),
2799 Immediate(String::kContainsCachedArrayIndexMask));
2800 EmitBranch(instr, equal);
2804 // Branches to a label or falls through with the answer in the z flag. Trashes
2805 // the temp registers, but not the input.
2806 void LCodeGen::EmitClassOfTest(Label* is_true,
2808 Handle<String>class_name,
2812 DCHECK(!input.is(temp));
2813 DCHECK(!input.is(temp2));
2814 DCHECK(!temp.is(temp2));
2815 __ JumpIfSmi(input, is_false);
2817 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2818 // Assuming the following assertions, we can use the same compares to test
2819 // for both being a function type and being in the object type range.
2820 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2821 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2822 FIRST_SPEC_OBJECT_TYPE + 1);
2823 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2824 LAST_SPEC_OBJECT_TYPE - 1);
2825 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2826 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2827 __ j(below, is_false);
2828 __ j(equal, is_true);
2829 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2830 __ j(equal, is_true);
2832 // Faster code path to avoid two compares: subtract lower bound from the
2833 // actual type and do a signed compare with the width of the type range.
2834 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2835 __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2836 __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2837 __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2838 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2839 __ j(above, is_false);
2842 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2843 // Check if the constructor in the map is a function.
2844 __ GetMapConstructor(temp, temp, temp2);
2845 // Objects with a non-function constructor have class 'Object'.
2846 __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2847 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2848 __ j(not_equal, is_true);
2850 __ j(not_equal, is_false);
2853 // temp now contains the constructor function. Grab the
2854 // instance class name from there.
2855 __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2856 __ mov(temp, FieldOperand(temp,
2857 SharedFunctionInfo::kInstanceClassNameOffset));
2858 // The class name we are testing against is internalized since it's a literal.
2859 // The name in the constructor is internalized because of the way the context
2860 // is booted. This routine isn't expected to work for random API-created
2861 // classes and it doesn't have to because you can't access it with natives
2862 // syntax. Since both sides are internalized it is sufficient to use an
2863 // identity comparison.
2864 __ cmp(temp, class_name);
2865 // End with the answer in the z flag.
2869 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2870 Register input = ToRegister(instr->value());
2871 Register temp = ToRegister(instr->temp());
2872 Register temp2 = ToRegister(instr->temp2());
2874 Handle<String> class_name = instr->hydrogen()->class_name();
2876 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2877 class_name, input, temp, temp2);
2879 EmitBranch(instr, equal);
2883 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2884 Register reg = ToRegister(instr->value());
2885 __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2886 EmitBranch(instr, equal);
2890 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2891 // Object and function are in fixed registers defined by the stub.
2892 DCHECK(ToRegister(instr->context()).is(esi));
2893 InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2894 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2896 Label true_value, done;
2897 __ test(eax, Operand(eax));
2898 __ j(zero, &true_value, Label::kNear);
2899 __ mov(ToRegister(instr->result()), factory()->false_value());
2900 __ jmp(&done, Label::kNear);
2901 __ bind(&true_value);
2902 __ mov(ToRegister(instr->result()), factory()->true_value());
2907 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2908 class DeferredInstanceOfKnownGlobal final : public LDeferredCode {
2910 DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2911 LInstanceOfKnownGlobal* instr,
2912 const X87Stack& x87_stack)
2913 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
2914 void Generate() override {
2915 codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2917 LInstruction* instr() override { return instr_; }
2918 Label* map_check() { return &map_check_; }
2920 LInstanceOfKnownGlobal* instr_;
2924 DeferredInstanceOfKnownGlobal* deferred;
2925 deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr, x87_stack_);
2927 Label done, false_result;
2928 Register object = ToRegister(instr->value());
2929 Register temp = ToRegister(instr->temp());
2931 // A Smi is not an instance of anything.
2932 __ JumpIfSmi(object, &false_result, Label::kNear);
2934 // This is the inlined call site instanceof cache. The two occurences of the
2935 // hole value will be patched to the last map/result pair generated by the
2938 Register map = ToRegister(instr->temp());
2939 __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2940 __ bind(deferred->map_check()); // Label for calculating code patching.
2941 Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2942 __ cmp(map, Operand::ForCell(cache_cell)); // Patched to cached map.
2943 __ j(not_equal, &cache_miss, Label::kNear);
2944 __ mov(eax, factory()->the_hole_value()); // Patched to either true or false.
2945 __ jmp(&done, Label::kNear);
2947 // The inlined call site cache did not match. Check for null and string
2948 // before calling the deferred code.
2949 __ bind(&cache_miss);
2950 // Null is not an instance of anything.
2951 __ cmp(object, factory()->null_value());
2952 __ j(equal, &false_result, Label::kNear);
2954 // String values are not instances of anything.
2955 Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2956 __ j(is_string, &false_result, Label::kNear);
2958 // Go to the deferred code.
2959 __ jmp(deferred->entry());
2961 __ bind(&false_result);
2962 __ mov(ToRegister(instr->result()), factory()->false_value());
2964 // Here result has either true or false. Deferred code also produces true or
2966 __ bind(deferred->exit());
2971 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
2973 PushSafepointRegistersScope scope(this);
2975 InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
2976 flags = static_cast<InstanceofStub::Flags>(
2977 flags | InstanceofStub::kArgsInRegisters);
2978 flags = static_cast<InstanceofStub::Flags>(
2979 flags | InstanceofStub::kCallSiteInlineCheck);
2980 flags = static_cast<InstanceofStub::Flags>(
2981 flags | InstanceofStub::kReturnTrueFalseObject);
2982 InstanceofStub stub(isolate(), flags);
2984 // Get the temp register reserved by the instruction. This needs to be a
2985 // register which is pushed last by PushSafepointRegisters as top of the
2986 // stack is used to pass the offset to the location of the map check to
2988 Register temp = ToRegister(instr->temp());
2989 DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
2990 __ LoadHeapObject(InstanceofStub::right(), instr->function());
2991 static const int kAdditionalDelta = 13;
2992 int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
2993 __ mov(temp, Immediate(delta));
2994 __ StoreToSafepointRegisterSlot(temp, temp);
2995 CallCodeGeneric(stub.GetCode(),
2996 RelocInfo::CODE_TARGET,
2998 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
2999 // Get the deoptimization index of the LLazyBailout-environment that
3000 // corresponds to this instruction.
3001 LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
3002 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
3004 // Put the result value into the eax slot and restore all registers.
3005 __ StoreToSafepointRegisterSlot(eax, eax);
3009 void LCodeGen::DoCmpT(LCmpT* instr) {
3010 Token::Value op = instr->op();
3013 CodeFactory::CompareIC(isolate(), op, instr->strength()).code();
3014 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3016 Condition condition = ComputeCompareCondition(op);
3017 Label true_value, done;
3018 __ test(eax, Operand(eax));
3019 __ j(condition, &true_value, Label::kNear);
3020 __ mov(ToRegister(instr->result()), factory()->false_value());
3021 __ jmp(&done, Label::kNear);
3022 __ bind(&true_value);
3023 __ mov(ToRegister(instr->result()), factory()->true_value());
3028 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
3029 int extra_value_count = dynamic_frame_alignment ? 2 : 1;
3031 if (instr->has_constant_parameter_count()) {
3032 int parameter_count = ToInteger32(instr->constant_parameter_count());
3033 if (dynamic_frame_alignment && FLAG_debug_code) {
3035 (parameter_count + extra_value_count) * kPointerSize),
3036 Immediate(kAlignmentZapValue));
3037 __ Assert(equal, kExpectedAlignmentMarker);
3039 __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
3041 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
3042 Register reg = ToRegister(instr->parameter_count());
3043 // The argument count parameter is a smi
3045 Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
3046 if (dynamic_frame_alignment && FLAG_debug_code) {
3047 DCHECK(extra_value_count == 2);
3048 __ cmp(Operand(esp, reg, times_pointer_size,
3049 extra_value_count * kPointerSize),
3050 Immediate(kAlignmentZapValue));
3051 __ Assert(equal, kExpectedAlignmentMarker);
3054 // emit code to restore stack based on instr->parameter_count()
3055 __ pop(return_addr_reg); // save return address
3056 if (dynamic_frame_alignment) {
3057 __ inc(reg); // 1 more for alignment
3059 __ shl(reg, kPointerSizeLog2);
3061 __ jmp(return_addr_reg);
3066 void LCodeGen::DoReturn(LReturn* instr) {
3067 if (FLAG_trace && info()->IsOptimizing()) {
3068 // Preserve the return value on the stack and rely on the runtime call
3069 // to return the value in the same register. We're leaving the code
3070 // managed by the register allocator and tearing down the frame, it's
3071 // safe to write to the context register.
3073 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3074 __ CallRuntime(Runtime::kTraceExit, 1);
3076 if (dynamic_frame_alignment_) {
3077 // Fetch the state of the dynamic frame alignment.
3078 __ mov(edx, Operand(ebp,
3079 JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
3081 int no_frame_start = -1;
3082 if (NeedsEagerFrame()) {
3085 no_frame_start = masm_->pc_offset();
3087 if (dynamic_frame_alignment_) {
3089 __ cmp(edx, Immediate(kNoAlignmentPadding));
3090 __ j(equal, &no_padding, Label::kNear);
3092 EmitReturn(instr, true);
3093 __ bind(&no_padding);
3096 EmitReturn(instr, false);
3097 if (no_frame_start != -1) {
3098 info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
3104 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
3105 Register vector_register = ToRegister(instr->temp_vector());
3106 Register slot_register = LoadWithVectorDescriptor::SlotRegister();
3107 DCHECK(vector_register.is(LoadWithVectorDescriptor::VectorRegister()));
3108 DCHECK(slot_register.is(eax));
3110 AllowDeferredHandleDereference vector_structure_check;
3111 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3112 __ mov(vector_register, vector);
3113 // No need to allocate this register.
3114 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
3115 int index = vector->GetIndex(slot);
3116 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3121 void LCodeGen::EmitVectorStoreICRegisters(T* instr) {
3122 Register vector_register = ToRegister(instr->temp_vector());
3123 Register slot_register = ToRegister(instr->temp_slot());
3125 AllowDeferredHandleDereference vector_structure_check;
3126 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3127 __ mov(vector_register, vector);
3128 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
3129 int index = vector->GetIndex(slot);
3130 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3134 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
3135 DCHECK(ToRegister(instr->context()).is(esi));
3136 DCHECK(ToRegister(instr->global_object())
3137 .is(LoadDescriptor::ReceiverRegister()));
3138 DCHECK(ToRegister(instr->result()).is(eax));
3140 __ mov(LoadDescriptor::NameRegister(), instr->name());
3141 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
3143 CodeFactory::LoadICInOptimizedCode(isolate(), instr->typeof_mode(),
3144 SLOPPY, PREMONOMORPHIC).code();
3145 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3149 void LCodeGen::DoLoadGlobalViaContext(LLoadGlobalViaContext* instr) {
3150 DCHECK(ToRegister(instr->context()).is(esi));
3151 DCHECK(ToRegister(instr->result()).is(eax));
3153 int const slot = instr->slot_index();
3154 int const depth = instr->depth();
3155 if (depth <= LoadGlobalViaContextStub::kMaximumDepth) {
3156 __ mov(LoadGlobalViaContextDescriptor::SlotRegister(), Immediate(slot));
3158 CodeFactory::LoadGlobalViaContext(isolate(), depth).code();
3159 CallCode(stub, RelocInfo::CODE_TARGET, instr);
3161 __ Push(Smi::FromInt(slot));
3162 __ CallRuntime(Runtime::kLoadGlobalViaContext, 1);
3167 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
3168 Register context = ToRegister(instr->context());
3169 Register result = ToRegister(instr->result());
3170 __ mov(result, ContextOperand(context, instr->slot_index()));
3172 if (instr->hydrogen()->RequiresHoleCheck()) {
3173 __ cmp(result, factory()->the_hole_value());
3174 if (instr->hydrogen()->DeoptimizesOnHole()) {
3175 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3178 __ j(not_equal, &is_not_hole, Label::kNear);
3179 __ mov(result, factory()->undefined_value());
3180 __ bind(&is_not_hole);
3186 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
3187 Register context = ToRegister(instr->context());
3188 Register value = ToRegister(instr->value());
3190 Label skip_assignment;
3192 Operand target = ContextOperand(context, instr->slot_index());
3193 if (instr->hydrogen()->RequiresHoleCheck()) {
3194 __ cmp(target, factory()->the_hole_value());
3195 if (instr->hydrogen()->DeoptimizesOnHole()) {
3196 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3198 __ j(not_equal, &skip_assignment, Label::kNear);
3202 __ mov(target, value);
3203 if (instr->hydrogen()->NeedsWriteBarrier()) {
3204 SmiCheck check_needed =
3205 instr->hydrogen()->value()->type().IsHeapObject()
3206 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
3207 Register temp = ToRegister(instr->temp());
3208 int offset = Context::SlotOffset(instr->slot_index());
3209 __ RecordWriteContextSlot(context, offset, value, temp, kSaveFPRegs,
3210 EMIT_REMEMBERED_SET, check_needed);
3213 __ bind(&skip_assignment);
3217 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
3218 HObjectAccess access = instr->hydrogen()->access();
3219 int offset = access.offset();
3221 if (access.IsExternalMemory()) {
3222 Register result = ToRegister(instr->result());
3223 MemOperand operand = instr->object()->IsConstantOperand()
3224 ? MemOperand::StaticVariable(ToExternalReference(
3225 LConstantOperand::cast(instr->object())))
3226 : MemOperand(ToRegister(instr->object()), offset);
3227 __ Load(result, operand, access.representation());
3231 Register object = ToRegister(instr->object());
3232 if (instr->hydrogen()->representation().IsDouble()) {
3233 X87Mov(ToX87Register(instr->result()), FieldOperand(object, offset));
3237 Register result = ToRegister(instr->result());
3238 if (!access.IsInobject()) {
3239 __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
3242 __ Load(result, FieldOperand(object, offset), access.representation());
3246 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
3247 DCHECK(!operand->IsDoubleRegister());
3248 if (operand->IsConstantOperand()) {
3249 Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
3250 AllowDeferredHandleDereference smi_check;
3251 if (object->IsSmi()) {
3252 __ Push(Handle<Smi>::cast(object));
3254 __ PushHeapObject(Handle<HeapObject>::cast(object));
3256 } else if (operand->IsRegister()) {
3257 __ push(ToRegister(operand));
3259 __ push(ToOperand(operand));
3264 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3265 DCHECK(ToRegister(instr->context()).is(esi));
3266 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3267 DCHECK(ToRegister(instr->result()).is(eax));
3269 __ mov(LoadDescriptor::NameRegister(), instr->name());
3270 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3272 CodeFactory::LoadICInOptimizedCode(
3273 isolate(), NOT_INSIDE_TYPEOF, instr->hydrogen()->language_mode(),
3274 instr->hydrogen()->initialization_state()).code();
3275 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3279 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3280 Register function = ToRegister(instr->function());
3281 Register temp = ToRegister(instr->temp());
3282 Register result = ToRegister(instr->result());
3284 // Get the prototype or initial map from the function.
3286 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
3288 // Check that the function has a prototype or an initial map.
3289 __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3290 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3292 // If the function does not have an initial map, we're done.
3294 __ CmpObjectType(result, MAP_TYPE, temp);
3295 __ j(not_equal, &done, Label::kNear);
3297 // Get the prototype from the initial map.
3298 __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3305 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3306 Register result = ToRegister(instr->result());
3307 __ LoadRoot(result, instr->index());
3311 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3312 Register arguments = ToRegister(instr->arguments());
3313 Register result = ToRegister(instr->result());
3314 if (instr->length()->IsConstantOperand() &&
3315 instr->index()->IsConstantOperand()) {
3316 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3317 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3318 int index = (const_length - const_index) + 1;
3319 __ mov(result, Operand(arguments, index * kPointerSize));
3321 Register length = ToRegister(instr->length());
3322 Operand index = ToOperand(instr->index());
3323 // There are two words between the frame pointer and the last argument.
3324 // Subtracting from length accounts for one of them add one more.
3325 __ sub(length, index);
3326 __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3331 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3332 ElementsKind elements_kind = instr->elements_kind();
3333 LOperand* key = instr->key();
3334 if (!key->IsConstantOperand() &&
3335 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3337 __ SmiUntag(ToRegister(key));
3339 Operand operand(BuildFastArrayOperand(
3342 instr->hydrogen()->key()->representation(),
3344 instr->base_offset()));
3345 if (elements_kind == FLOAT32_ELEMENTS) {
3346 X87Mov(ToX87Register(instr->result()), operand, kX87FloatOperand);
3347 } else if (elements_kind == FLOAT64_ELEMENTS) {
3348 X87Mov(ToX87Register(instr->result()), operand);
3350 Register result(ToRegister(instr->result()));
3351 switch (elements_kind) {
3353 __ movsx_b(result, operand);
3355 case UINT8_ELEMENTS:
3356 case UINT8_CLAMPED_ELEMENTS:
3357 __ movzx_b(result, operand);
3359 case INT16_ELEMENTS:
3360 __ movsx_w(result, operand);
3362 case UINT16_ELEMENTS:
3363 __ movzx_w(result, operand);
3365 case INT32_ELEMENTS:
3366 __ mov(result, operand);
3368 case UINT32_ELEMENTS:
3369 __ mov(result, operand);
3370 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3371 __ test(result, Operand(result));
3372 DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3375 case FLOAT32_ELEMENTS:
3376 case FLOAT64_ELEMENTS:
3377 case FAST_SMI_ELEMENTS:
3379 case FAST_DOUBLE_ELEMENTS:
3380 case FAST_HOLEY_SMI_ELEMENTS:
3381 case FAST_HOLEY_ELEMENTS:
3382 case FAST_HOLEY_DOUBLE_ELEMENTS:
3383 case DICTIONARY_ELEMENTS:
3384 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
3385 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
3393 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3394 if (instr->hydrogen()->RequiresHoleCheck()) {
3395 Operand hole_check_operand = BuildFastArrayOperand(
3396 instr->elements(), instr->key(),
3397 instr->hydrogen()->key()->representation(),
3398 FAST_DOUBLE_ELEMENTS,
3399 instr->base_offset() + sizeof(kHoleNanLower32));
3400 __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3401 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3404 Operand double_load_operand = BuildFastArrayOperand(
3407 instr->hydrogen()->key()->representation(),
3408 FAST_DOUBLE_ELEMENTS,
3409 instr->base_offset());
3410 X87Mov(ToX87Register(instr->result()), double_load_operand);
3414 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3415 Register result = ToRegister(instr->result());
3419 BuildFastArrayOperand(instr->elements(), instr->key(),
3420 instr->hydrogen()->key()->representation(),
3421 FAST_ELEMENTS, instr->base_offset()));
3423 // Check for the hole value.
3424 if (instr->hydrogen()->RequiresHoleCheck()) {
3425 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3426 __ test(result, Immediate(kSmiTagMask));
3427 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3429 __ cmp(result, factory()->the_hole_value());
3430 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3432 } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3433 DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3435 __ cmp(result, factory()->the_hole_value());
3436 __ j(not_equal, &done);
3437 if (info()->IsStub()) {
3438 // A stub can safely convert the hole to undefined only if the array
3439 // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3440 // it needs to bail out.
3441 __ mov(result, isolate()->factory()->array_protector());
3442 __ cmp(FieldOperand(result, PropertyCell::kValueOffset),
3443 Immediate(Smi::FromInt(Isolate::kArrayProtectorValid)));
3444 DeoptimizeIf(not_equal, instr, Deoptimizer::kHole);
3446 __ mov(result, isolate()->factory()->undefined_value());
3452 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3453 if (instr->is_fixed_typed_array()) {
3454 DoLoadKeyedExternalArray(instr);
3455 } else if (instr->hydrogen()->representation().IsDouble()) {
3456 DoLoadKeyedFixedDoubleArray(instr);
3458 DoLoadKeyedFixedArray(instr);
3463 Operand LCodeGen::BuildFastArrayOperand(
3464 LOperand* elements_pointer,
3466 Representation key_representation,
3467 ElementsKind elements_kind,
3468 uint32_t base_offset) {
3469 Register elements_pointer_reg = ToRegister(elements_pointer);
3470 int element_shift_size = ElementsKindToShiftSize(elements_kind);
3471 int shift_size = element_shift_size;
3472 if (key->IsConstantOperand()) {
3473 int constant_value = ToInteger32(LConstantOperand::cast(key));
3474 if (constant_value & 0xF0000000) {
3475 Abort(kArrayIndexConstantValueTooBig);
3477 return Operand(elements_pointer_reg,
3478 ((constant_value) << shift_size)
3481 // Take the tag bit into account while computing the shift size.
3482 if (key_representation.IsSmi() && (shift_size >= 1)) {
3483 shift_size -= kSmiTagSize;
3485 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3486 return Operand(elements_pointer_reg,
3494 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3495 DCHECK(ToRegister(instr->context()).is(esi));
3496 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3497 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3499 if (instr->hydrogen()->HasVectorAndSlot()) {
3500 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3503 Handle<Code> ic = CodeFactory::KeyedLoadICInOptimizedCode(
3504 isolate(), instr->hydrogen()->language_mode(),
3505 instr->hydrogen()->initialization_state()).code();
3506 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3510 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3511 Register result = ToRegister(instr->result());
3513 if (instr->hydrogen()->from_inlined()) {
3514 __ lea(result, Operand(esp, -2 * kPointerSize));
3516 // Check for arguments adapter frame.
3517 Label done, adapted;
3518 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3519 __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3520 __ cmp(Operand(result),
3521 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3522 __ j(equal, &adapted, Label::kNear);
3524 // No arguments adaptor frame.
3525 __ mov(result, Operand(ebp));
3526 __ jmp(&done, Label::kNear);
3528 // Arguments adaptor frame present.
3530 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3532 // Result is the frame pointer for the frame if not adapted and for the real
3533 // frame below the adaptor frame if adapted.
3539 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3540 Operand elem = ToOperand(instr->elements());
3541 Register result = ToRegister(instr->result());
3545 // If no arguments adaptor frame the number of arguments is fixed.
3547 __ mov(result, Immediate(scope()->num_parameters()));
3548 __ j(equal, &done, Label::kNear);
3550 // Arguments adaptor frame present. Get argument length from there.
3551 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3552 __ mov(result, Operand(result,
3553 ArgumentsAdaptorFrameConstants::kLengthOffset));
3554 __ SmiUntag(result);
3556 // Argument length is in result register.
3561 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3562 Register receiver = ToRegister(instr->receiver());
3563 Register function = ToRegister(instr->function());
3565 // If the receiver is null or undefined, we have to pass the global
3566 // object as a receiver to normal functions. Values have to be
3567 // passed unchanged to builtins and strict-mode functions.
3568 Label receiver_ok, global_object;
3569 Register scratch = ToRegister(instr->temp());
3571 if (!instr->hydrogen()->known_function()) {
3572 // Do not transform the receiver to object for strict mode
3575 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3576 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3577 1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3578 __ j(not_equal, &receiver_ok);
3580 // Do not transform the receiver to object for builtins.
3581 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3582 1 << SharedFunctionInfo::kNativeBitWithinByte);
3583 __ j(not_equal, &receiver_ok);
3586 // Normal function. Replace undefined or null with global receiver.
3587 __ cmp(receiver, factory()->null_value());
3588 __ j(equal, &global_object);
3589 __ cmp(receiver, factory()->undefined_value());
3590 __ j(equal, &global_object);
3592 // The receiver should be a JS object.
3593 __ test(receiver, Immediate(kSmiTagMask));
3594 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3595 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3596 DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3598 __ jmp(&receiver_ok, Label::kNear);
3599 __ bind(&global_object);
3600 __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3601 const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3602 __ mov(receiver, Operand(receiver, global_offset));
3603 const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3604 __ mov(receiver, FieldOperand(receiver, proxy_offset));
3605 __ bind(&receiver_ok);
3609 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3610 Register receiver = ToRegister(instr->receiver());
3611 Register function = ToRegister(instr->function());
3612 Register length = ToRegister(instr->length());
3613 Register elements = ToRegister(instr->elements());
3614 DCHECK(receiver.is(eax)); // Used for parameter count.
3615 DCHECK(function.is(edi)); // Required by InvokeFunction.
3616 DCHECK(ToRegister(instr->result()).is(eax));
3618 // Copy the arguments to this function possibly from the
3619 // adaptor frame below it.
3620 const uint32_t kArgumentsLimit = 1 * KB;
3621 __ cmp(length, kArgumentsLimit);
3622 DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3625 __ mov(receiver, length);
3627 // Loop through the arguments pushing them onto the execution
3630 // length is a small non-negative integer, due to the test above.
3631 __ test(length, Operand(length));
3632 __ j(zero, &invoke, Label::kNear);
3634 __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3636 __ j(not_zero, &loop);
3638 // Invoke the function.
3640 DCHECK(instr->HasPointerMap());
3641 LPointerMap* pointers = instr->pointer_map();
3642 SafepointGenerator safepoint_generator(
3643 this, pointers, Safepoint::kLazyDeopt);
3644 ParameterCount actual(eax);
3645 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3649 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3654 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3655 LOperand* argument = instr->value();
3656 EmitPushTaggedOperand(argument);
3660 void LCodeGen::DoDrop(LDrop* instr) {
3661 __ Drop(instr->count());
3665 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3666 Register result = ToRegister(instr->result());
3667 __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3671 void LCodeGen::DoContext(LContext* instr) {
3672 Register result = ToRegister(instr->result());
3673 if (info()->IsOptimizing()) {
3674 __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3676 // If there is no frame, the context must be in esi.
3677 DCHECK(result.is(esi));
3682 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3683 DCHECK(ToRegister(instr->context()).is(esi));
3684 __ push(esi); // The context is the first argument.
3685 __ push(Immediate(instr->hydrogen()->pairs()));
3686 __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3687 CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3691 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3692 int formal_parameter_count, int arity,
3693 LInstruction* instr) {
3694 bool dont_adapt_arguments =
3695 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3696 bool can_invoke_directly =
3697 dont_adapt_arguments || formal_parameter_count == arity;
3699 Register function_reg = edi;
3701 if (can_invoke_directly) {
3703 __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3705 // Set eax to arguments count if adaption is not needed. Assumes that eax
3706 // is available to write to at this point.
3707 if (dont_adapt_arguments) {
3711 // Invoke function directly.
3712 if (function.is_identical_to(info()->closure())) {
3715 __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3717 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3719 // We need to adapt arguments.
3720 LPointerMap* pointers = instr->pointer_map();
3721 SafepointGenerator generator(
3722 this, pointers, Safepoint::kLazyDeopt);
3723 ParameterCount count(arity);
3724 ParameterCount expected(formal_parameter_count);
3725 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3730 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3731 DCHECK(ToRegister(instr->result()).is(eax));
3733 if (instr->hydrogen()->IsTailCall()) {
3734 if (NeedsEagerFrame()) __ leave();
3736 if (instr->target()->IsConstantOperand()) {
3737 LConstantOperand* target = LConstantOperand::cast(instr->target());
3738 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3739 __ jmp(code, RelocInfo::CODE_TARGET);
3741 DCHECK(instr->target()->IsRegister());
3742 Register target = ToRegister(instr->target());
3743 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3747 LPointerMap* pointers = instr->pointer_map();
3748 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3750 if (instr->target()->IsConstantOperand()) {
3751 LConstantOperand* target = LConstantOperand::cast(instr->target());
3752 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3753 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3754 __ call(code, RelocInfo::CODE_TARGET);
3756 DCHECK(instr->target()->IsRegister());
3757 Register target = ToRegister(instr->target());
3758 generator.BeforeCall(__ CallSize(Operand(target)));
3759 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3762 generator.AfterCall();
3767 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3768 DCHECK(ToRegister(instr->function()).is(edi));
3769 DCHECK(ToRegister(instr->result()).is(eax));
3771 if (instr->hydrogen()->pass_argument_count()) {
3772 __ mov(eax, instr->arity());
3776 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3778 bool is_self_call = false;
3779 if (instr->hydrogen()->function()->IsConstant()) {
3780 HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3781 Handle<JSFunction> jsfun =
3782 Handle<JSFunction>::cast(fun_const->handle(isolate()));
3783 is_self_call = jsfun.is_identical_to(info()->closure());
3789 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3792 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3796 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3797 Register input_reg = ToRegister(instr->value());
3798 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3799 factory()->heap_number_map());
3800 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3802 Label slow, allocated, done;
3803 Register tmp = input_reg.is(eax) ? ecx : eax;
3804 Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3806 // Preserve the value of all registers.
3807 PushSafepointRegistersScope scope(this);
3809 __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3810 // Check the sign of the argument. If the argument is positive, just
3811 // return it. We do not need to patch the stack since |input| and
3812 // |result| are the same register and |input| will be restored
3813 // unchanged by popping safepoint registers.
3814 __ test(tmp, Immediate(HeapNumber::kSignMask));
3815 __ j(zero, &done, Label::kNear);
3817 __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3818 __ jmp(&allocated, Label::kNear);
3820 // Slow case: Call the runtime system to do the number allocation.
3822 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3823 instr, instr->context());
3824 // Set the pointer to the new heap number in tmp.
3825 if (!tmp.is(eax)) __ mov(tmp, eax);
3826 // Restore input_reg after call to runtime.
3827 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3829 __ bind(&allocated);
3830 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3831 __ and_(tmp2, ~HeapNumber::kSignMask);
3832 __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3833 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3834 __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3835 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3841 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3842 Register input_reg = ToRegister(instr->value());
3843 __ test(input_reg, Operand(input_reg));
3845 __ j(not_sign, &is_positive, Label::kNear);
3846 __ neg(input_reg); // Sets flags.
3847 DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3848 __ bind(&is_positive);
3852 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3853 // Class for deferred case.
3854 class DeferredMathAbsTaggedHeapNumber final : public LDeferredCode {
3856 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3858 const X87Stack& x87_stack)
3859 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
3860 void Generate() override {
3861 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3863 LInstruction* instr() override { return instr_; }
3869 DCHECK(instr->value()->Equals(instr->result()));
3870 Representation r = instr->hydrogen()->value()->representation();
3873 X87Register value = ToX87Register(instr->value());
3876 } else if (r.IsSmiOrInteger32()) {
3877 EmitIntegerMathAbs(instr);
3878 } else { // Tagged case.
3879 DeferredMathAbsTaggedHeapNumber* deferred =
3880 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr, x87_stack_);
3881 Register input_reg = ToRegister(instr->value());
3883 __ JumpIfNotSmi(input_reg, deferred->entry());
3884 EmitIntegerMathAbs(instr);
3885 __ bind(deferred->exit());
3890 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3891 Register output_reg = ToRegister(instr->result());
3892 X87Register input_reg = ToX87Register(instr->value());
3895 Label not_minus_zero, done;
3896 // Deoptimize on unordered.
3900 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3901 __ j(below, ¬_minus_zero, Label::kNear);
3903 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3904 // Check for negative zero.
3905 __ j(not_equal, ¬_minus_zero, Label::kNear);
3909 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3910 __ Move(output_reg, Immediate(0));
3911 __ jmp(&done, Label::kFar);
3915 // rc=01B, round down.
3916 __ bind(¬_minus_zero);
3918 __ X87SetRC(0x0400);
3919 __ sub(esp, Immediate(kPointerSize));
3920 __ fist_s(Operand(esp, 0));
3923 DeoptimizeIf(equal, instr, Deoptimizer::kOverflow);
3925 __ X87SetRC(0x0000);
3930 void LCodeGen::DoMathRound(LMathRound* instr) {
3931 X87Register input_reg = ToX87Register(instr->value());
3932 Register result = ToRegister(instr->result());
3934 Label below_one_half, below_minus_one_half, done;
3936 ExternalReference one_half = ExternalReference::address_of_one_half();
3937 ExternalReference minus_one_half =
3938 ExternalReference::address_of_minus_one_half();
3940 __ fld_d(Operand::StaticVariable(one_half));
3943 __ j(carry, &below_one_half);
3945 // Use rounds towards zero, since 0.5 <= x, we use floor(0.5 + x)
3947 __ fadd_d(Operand::StaticVariable(one_half));
3948 // rc=11B, round toward zero.
3949 __ X87SetRC(0x0c00);
3950 __ sub(esp, Immediate(kPointerSize));
3951 // Clear exception bits.
3953 __ fistp_s(MemOperand(esp, 0));
3957 DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
3959 // Restore round mode.
3960 __ X87SetRC(0x0000);
3963 __ bind(&below_one_half);
3964 __ fld_d(Operand::StaticVariable(minus_one_half));
3967 __ j(carry, &below_minus_one_half);
3968 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3969 // we can ignore the difference between a result of -0 and +0.
3970 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3971 // If the sign is positive, we return +0.
3974 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3976 __ Move(result, Immediate(0));
3979 __ bind(&below_minus_one_half);
3981 __ fadd_d(Operand::StaticVariable(one_half));
3982 // rc=01B, round down.
3983 __ X87SetRC(0x0400);
3984 __ sub(esp, Immediate(kPointerSize));
3985 // Clear exception bits.
3987 __ fistp_s(MemOperand(esp, 0));
3991 DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
3993 // Restore round mode.
3994 __ X87SetRC(0x0000);
4000 void LCodeGen::DoMathFround(LMathFround* instr) {
4001 X87Register input_reg = ToX87Register(instr->value());
4003 __ sub(esp, Immediate(kPointerSize));
4004 __ fstp_s(MemOperand(esp, 0));
4005 X87Fld(MemOperand(esp, 0), kX87FloatOperand);
4006 __ add(esp, Immediate(kPointerSize));
4010 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
4011 X87Register input = ToX87Register(instr->value());
4012 X87Register result_reg = ToX87Register(instr->result());
4013 Register temp_result = ToRegister(instr->temp1());
4014 Register temp = ToRegister(instr->temp2());
4015 Label slow, done, smi, finish;
4016 DCHECK(result_reg.is(input));
4018 // Store input into Heap number and call runtime function kMathExpRT.
4019 if (FLAG_inline_new) {
4020 __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4021 __ jmp(&done, Label::kNear);
4024 // Slow case: Call the runtime system to do the number allocation.
4027 // TODO(3095996): Put a valid pointer value in the stack slot where the
4028 // result register is stored, as this register is in the pointer map, but
4029 // contains an integer value.
4030 __ Move(temp_result, Immediate(0));
4032 // Preserve the value of all registers.
4033 PushSafepointRegistersScope scope(this);
4035 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4036 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4037 RecordSafepointWithRegisters(
4038 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4039 __ StoreToSafepointRegisterSlot(temp_result, eax);
4042 X87LoadForUsage(input);
4043 __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4046 // Preserve the value of all registers.
4047 PushSafepointRegistersScope scope(this);
4049 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4050 __ push(temp_result);
4051 __ CallRuntimeSaveDoubles(Runtime::kMathSqrt);
4052 RecordSafepointWithRegisters(instr->pointer_map(), 1,
4053 Safepoint::kNoLazyDeopt);
4054 __ StoreToSafepointRegisterSlot(temp_result, eax);
4056 X87PrepareToWrite(result_reg);
4057 // return value of MathExpRT is Smi or Heap Number.
4058 __ JumpIfSmi(temp_result, &smi);
4059 // Heap number(double)
4060 __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4064 __ SmiUntag(temp_result);
4065 __ push(temp_result);
4066 __ fild_s(MemOperand(esp, 0));
4067 __ pop(temp_result);
4069 X87CommitWrite(result_reg);
4073 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
4074 X87Register input_reg = ToX87Register(instr->value());
4075 DCHECK(ToX87Register(instr->result()).is(input_reg));
4077 // Note that according to ECMA-262 15.8.2.13:
4078 // Math.pow(-Infinity, 0.5) == Infinity
4079 // Math.sqrt(-Infinity) == NaN
4081 // Check base for -Infinity. C3 == 0, C2 == 1, C1 == 1 and C0 == 1
4085 __ and_(eax, Immediate(0x4700));
4086 __ cmp(eax, Immediate(0x0700));
4087 __ j(not_equal, &sqrt, Label::kNear);
4088 // If input is -Infinity, return Infinity.
4090 __ jmp(&done, Label::kNear);
4095 __ faddp(); // Convert -0 to +0.
4102 void LCodeGen::DoPower(LPower* instr) {
4103 Representation exponent_type = instr->hydrogen()->right()->representation();
4104 X87Register result = ToX87Register(instr->result());
4105 // Having marked this as a call, we can use any registers.
4106 X87Register base = ToX87Register(instr->left());
4107 ExternalReference one_half = ExternalReference::address_of_one_half();
4109 if (exponent_type.IsSmi()) {
4110 Register exponent = ToRegister(instr->right());
4111 X87LoadForUsage(base);
4112 __ SmiUntag(exponent);
4114 __ fild_s(MemOperand(esp, 0));
4116 } else if (exponent_type.IsTagged()) {
4117 Register exponent = ToRegister(instr->right());
4118 Register temp = exponent.is(ecx) ? eax : ecx;
4119 Label no_deopt, done;
4120 X87LoadForUsage(base);
4121 __ JumpIfSmi(exponent, &no_deopt);
4122 __ CmpObjectType(exponent, HEAP_NUMBER_TYPE, temp);
4123 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4124 // Heap number(double)
4125 __ fld_d(FieldOperand(exponent, HeapNumber::kValueOffset));
4129 __ SmiUntag(exponent);
4131 __ fild_s(MemOperand(esp, 0));
4134 } else if (exponent_type.IsInteger32()) {
4135 Register exponent = ToRegister(instr->right());
4136 X87LoadForUsage(base);
4138 __ fild_s(MemOperand(esp, 0));
4141 DCHECK(exponent_type.IsDouble());
4142 X87Register exponent_double = ToX87Register(instr->right());
4143 X87LoadForUsage(base, exponent_double);
4146 // FP data stack {base, exponent(TOS)}.
4147 // Handle (exponent==+-0.5 && base == -0).
4151 X87Fld(Operand::StaticVariable(one_half), kX87DoubleOperand);
4153 __ j(parity_even, ¬_plus_0, Label::kNear); // NaN.
4154 __ j(not_equal, ¬_plus_0, Label::kNear);
4156 // FP data stack {base, exponent(TOS), zero}.
4158 __ bind(¬_plus_0);
4161 __ PrepareCallCFunction(4, eax);
4162 __ fstp_d(MemOperand(esp, kDoubleSize)); // Exponent value.
4163 __ fstp_d(MemOperand(esp, 0)); // Base value.
4164 X87PrepareToWrite(result);
4165 __ CallCFunction(ExternalReference::power_double_double_function(isolate()),
4167 // Return value is in st(0) on ia32.
4168 X87CommitWrite(result);
4173 void LCodeGen::DoMathLog(LMathLog* instr) {
4174 DCHECK(instr->value()->Equals(instr->result()));
4175 X87Register input_reg = ToX87Register(instr->value());
4178 Label positive, done, zero, nan_result;
4182 __ j(below, &nan_result, Label::kNear);
4183 __ j(equal, &zero, Label::kNear);
4191 __ jmp(&done, Label::kNear);
4193 __ bind(&nan_result);
4194 X87PrepareToWrite(input_reg);
4195 __ push(Immediate(0xffffffff));
4196 __ push(Immediate(0x7fffffff));
4197 __ fld_d(MemOperand(esp, 0));
4198 __ lea(esp, Operand(esp, kDoubleSize));
4199 X87CommitWrite(input_reg);
4200 __ jmp(&done, Label::kNear);
4203 ExternalReference ninf = ExternalReference::address_of_negative_infinity();
4204 X87PrepareToWrite(input_reg);
4205 __ fld_d(Operand::StaticVariable(ninf));
4206 X87CommitWrite(input_reg);
4212 void LCodeGen::DoMathClz32(LMathClz32* instr) {
4213 Register input = ToRegister(instr->value());
4214 Register result = ToRegister(instr->result());
4216 __ Lzcnt(result, input);
4220 void LCodeGen::DoMathExp(LMathExp* instr) {
4221 X87Register input = ToX87Register(instr->value());
4222 X87Register result_reg = ToX87Register(instr->result());
4223 Register temp_result = ToRegister(instr->temp1());
4224 Register temp = ToRegister(instr->temp2());
4225 Label slow, done, smi, finish;
4226 DCHECK(result_reg.is(input));
4228 // Store input into Heap number and call runtime function kMathExpRT.
4229 if (FLAG_inline_new) {
4230 __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4231 __ jmp(&done, Label::kNear);
4234 // Slow case: Call the runtime system to do the number allocation.
4237 // TODO(3095996): Put a valid pointer value in the stack slot where the
4238 // result register is stored, as this register is in the pointer map, but
4239 // contains an integer value.
4240 __ Move(temp_result, Immediate(0));
4242 // Preserve the value of all registers.
4243 PushSafepointRegistersScope scope(this);
4245 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4246 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4247 RecordSafepointWithRegisters(instr->pointer_map(), 0,
4248 Safepoint::kNoLazyDeopt);
4249 __ StoreToSafepointRegisterSlot(temp_result, eax);
4252 X87LoadForUsage(input);
4253 __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4256 // Preserve the value of all registers.
4257 PushSafepointRegistersScope scope(this);
4259 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4260 __ push(temp_result);
4261 __ CallRuntimeSaveDoubles(Runtime::kMathExpRT);
4262 RecordSafepointWithRegisters(instr->pointer_map(), 1,
4263 Safepoint::kNoLazyDeopt);
4264 __ StoreToSafepointRegisterSlot(temp_result, eax);
4266 X87PrepareToWrite(result_reg);
4267 // return value of MathExpRT is Smi or Heap Number.
4268 __ JumpIfSmi(temp_result, &smi);
4269 // Heap number(double)
4270 __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4274 __ SmiUntag(temp_result);
4275 __ push(temp_result);
4276 __ fild_s(MemOperand(esp, 0));
4277 __ pop(temp_result);
4279 X87CommitWrite(result_reg);
4283 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
4284 DCHECK(ToRegister(instr->context()).is(esi));
4285 DCHECK(ToRegister(instr->function()).is(edi));
4286 DCHECK(instr->HasPointerMap());
4288 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
4289 if (known_function.is_null()) {
4290 LPointerMap* pointers = instr->pointer_map();
4291 SafepointGenerator generator(
4292 this, pointers, Safepoint::kLazyDeopt);
4293 ParameterCount count(instr->arity());
4294 __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
4296 CallKnownFunction(known_function,
4297 instr->hydrogen()->formal_parameter_count(),
4298 instr->arity(), instr);
4303 void LCodeGen::DoCallFunction(LCallFunction* instr) {
4304 DCHECK(ToRegister(instr->context()).is(esi));
4305 DCHECK(ToRegister(instr->function()).is(edi));
4306 DCHECK(ToRegister(instr->result()).is(eax));
4308 int arity = instr->arity();
4309 CallFunctionFlags flags = instr->hydrogen()->function_flags();
4310 if (instr->hydrogen()->HasVectorAndSlot()) {
4311 Register slot_register = ToRegister(instr->temp_slot());
4312 Register vector_register = ToRegister(instr->temp_vector());
4313 DCHECK(slot_register.is(edx));
4314 DCHECK(vector_register.is(ebx));
4316 AllowDeferredHandleDereference vector_structure_check;
4317 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
4318 int index = vector->GetIndex(instr->hydrogen()->slot());
4320 __ mov(vector_register, vector);
4321 __ mov(slot_register, Immediate(Smi::FromInt(index)));
4323 CallICState::CallType call_type =
4324 (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
4327 CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
4328 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4330 CallFunctionStub stub(isolate(), arity, flags);
4331 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4336 void LCodeGen::DoCallNew(LCallNew* instr) {
4337 DCHECK(ToRegister(instr->context()).is(esi));
4338 DCHECK(ToRegister(instr->constructor()).is(edi));
4339 DCHECK(ToRegister(instr->result()).is(eax));
4341 // No cell in ebx for construct type feedback in optimized code
4342 __ mov(ebx, isolate()->factory()->undefined_value());
4343 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
4344 __ Move(eax, Immediate(instr->arity()));
4345 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4349 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
4350 DCHECK(ToRegister(instr->context()).is(esi));
4351 DCHECK(ToRegister(instr->constructor()).is(edi));
4352 DCHECK(ToRegister(instr->result()).is(eax));
4354 __ Move(eax, Immediate(instr->arity()));
4355 if (instr->arity() == 1) {
4356 // We only need the allocation site for the case we have a length argument.
4357 // The case may bail out to the runtime, which will determine the correct
4358 // elements kind with the site.
4359 __ mov(ebx, instr->hydrogen()->site());
4361 __ mov(ebx, isolate()->factory()->undefined_value());
4364 ElementsKind kind = instr->hydrogen()->elements_kind();
4365 AllocationSiteOverrideMode override_mode =
4366 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
4367 ? DISABLE_ALLOCATION_SITES
4370 if (instr->arity() == 0) {
4371 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
4372 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4373 } else if (instr->arity() == 1) {
4375 if (IsFastPackedElementsKind(kind)) {
4377 // We might need a change here
4378 // look at the first argument
4379 __ mov(ecx, Operand(esp, 0));
4381 __ j(zero, &packed_case, Label::kNear);
4383 ElementsKind holey_kind = GetHoleyElementsKind(kind);
4384 ArraySingleArgumentConstructorStub stub(isolate(),
4387 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4388 __ jmp(&done, Label::kNear);
4389 __ bind(&packed_case);
4392 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
4393 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4396 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
4397 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4402 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4403 DCHECK(ToRegister(instr->context()).is(esi));
4404 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
4408 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4409 Register function = ToRegister(instr->function());
4410 Register code_object = ToRegister(instr->code_object());
4411 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4412 __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4416 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4417 Register result = ToRegister(instr->result());
4418 Register base = ToRegister(instr->base_object());
4419 if (instr->offset()->IsConstantOperand()) {
4420 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4421 __ lea(result, Operand(base, ToInteger32(offset)));
4423 Register offset = ToRegister(instr->offset());
4424 __ lea(result, Operand(base, offset, times_1, 0));
4429 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4430 Representation representation = instr->hydrogen()->field_representation();
4432 HObjectAccess access = instr->hydrogen()->access();
4433 int offset = access.offset();
4435 if (access.IsExternalMemory()) {
4436 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4437 MemOperand operand = instr->object()->IsConstantOperand()
4438 ? MemOperand::StaticVariable(
4439 ToExternalReference(LConstantOperand::cast(instr->object())))
4440 : MemOperand(ToRegister(instr->object()), offset);
4441 if (instr->value()->IsConstantOperand()) {
4442 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4443 __ mov(operand, Immediate(ToInteger32(operand_value)));
4445 Register value = ToRegister(instr->value());
4446 __ Store(value, operand, representation);
4451 Register object = ToRegister(instr->object());
4452 __ AssertNotSmi(object);
4453 DCHECK(!representation.IsSmi() ||
4454 !instr->value()->IsConstantOperand() ||
4455 IsSmi(LConstantOperand::cast(instr->value())));
4456 if (representation.IsDouble()) {
4457 DCHECK(access.IsInobject());
4458 DCHECK(!instr->hydrogen()->has_transition());
4459 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4460 X87Register value = ToX87Register(instr->value());
4461 X87Mov(FieldOperand(object, offset), value);
4465 if (instr->hydrogen()->has_transition()) {
4466 Handle<Map> transition = instr->hydrogen()->transition_map();
4467 AddDeprecationDependency(transition);
4468 __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4469 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4470 Register temp = ToRegister(instr->temp());
4471 Register temp_map = ToRegister(instr->temp_map());
4472 __ mov(temp_map, transition);
4473 __ mov(FieldOperand(object, HeapObject::kMapOffset), temp_map);
4474 // Update the write barrier for the map field.
4475 __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4480 Register write_register = object;
4481 if (!access.IsInobject()) {
4482 write_register = ToRegister(instr->temp());
4483 __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4486 MemOperand operand = FieldOperand(write_register, offset);
4487 if (instr->value()->IsConstantOperand()) {
4488 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4489 if (operand_value->IsRegister()) {
4490 Register value = ToRegister(operand_value);
4491 __ Store(value, operand, representation);
4492 } else if (representation.IsInteger32() || representation.IsExternal()) {
4493 Immediate immediate = ToImmediate(operand_value, representation);
4494 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4495 __ mov(operand, immediate);
4497 Handle<Object> handle_value = ToHandle(operand_value);
4498 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4499 __ mov(operand, handle_value);
4502 Register value = ToRegister(instr->value());
4503 __ Store(value, operand, representation);
4506 if (instr->hydrogen()->NeedsWriteBarrier()) {
4507 Register value = ToRegister(instr->value());
4508 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4509 // Update the write barrier for the object for in-object properties.
4510 __ RecordWriteField(write_register, offset, value, temp, kSaveFPRegs,
4511 EMIT_REMEMBERED_SET,
4512 instr->hydrogen()->SmiCheckForWriteBarrier(),
4513 instr->hydrogen()->PointersToHereCheckForValue());
4518 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4519 DCHECK(ToRegister(instr->context()).is(esi));
4520 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4521 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4523 if (instr->hydrogen()->HasVectorAndSlot()) {
4524 EmitVectorStoreICRegisters<LStoreNamedGeneric>(instr);
4527 __ mov(StoreDescriptor::NameRegister(), instr->name());
4528 Handle<Code> ic = CodeFactory::StoreICInOptimizedCode(
4529 isolate(), instr->language_mode(),
4530 instr->hydrogen()->initialization_state()).code();
4531 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4535 void LCodeGen::DoStoreGlobalViaContext(LStoreGlobalViaContext* instr) {
4536 DCHECK(ToRegister(instr->context()).is(esi));
4537 DCHECK(ToRegister(instr->value())
4538 .is(StoreGlobalViaContextDescriptor::ValueRegister()));
4540 int const slot = instr->slot_index();
4541 int const depth = instr->depth();
4542 if (depth <= StoreGlobalViaContextStub::kMaximumDepth) {
4543 __ mov(StoreGlobalViaContextDescriptor::SlotRegister(), Immediate(slot));
4544 Handle<Code> stub = CodeFactory::StoreGlobalViaContext(
4545 isolate(), depth, instr->language_mode())
4547 CallCode(stub, RelocInfo::CODE_TARGET, instr);
4549 __ Push(Smi::FromInt(slot));
4550 __ Push(StoreGlobalViaContextDescriptor::ValueRegister());
4551 __ CallRuntime(is_strict(instr->language_mode())
4552 ? Runtime::kStoreGlobalViaContext_Strict
4553 : Runtime::kStoreGlobalViaContext_Sloppy,
4559 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4560 Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4561 if (instr->index()->IsConstantOperand()) {
4562 __ cmp(ToOperand(instr->length()),
4563 ToImmediate(LConstantOperand::cast(instr->index()),
4564 instr->hydrogen()->length()->representation()));
4565 cc = CommuteCondition(cc);
4566 } else if (instr->length()->IsConstantOperand()) {
4567 __ cmp(ToOperand(instr->index()),
4568 ToImmediate(LConstantOperand::cast(instr->length()),
4569 instr->hydrogen()->index()->representation()));
4571 __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4573 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4575 __ j(NegateCondition(cc), &done, Label::kNear);
4579 DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4584 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4585 ElementsKind elements_kind = instr->elements_kind();
4586 LOperand* key = instr->key();
4587 if (!key->IsConstantOperand() &&
4588 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4590 __ SmiUntag(ToRegister(key));
4592 Operand operand(BuildFastArrayOperand(
4595 instr->hydrogen()->key()->representation(),
4597 instr->base_offset()));
4598 if (elements_kind == FLOAT32_ELEMENTS) {
4599 X87Mov(operand, ToX87Register(instr->value()), kX87FloatOperand);
4600 } else if (elements_kind == FLOAT64_ELEMENTS) {
4601 uint64_t int_val = kHoleNanInt64;
4602 int32_t lower = static_cast<int32_t>(int_val);
4603 int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4604 Operand operand2 = BuildFastArrayOperand(
4605 instr->elements(), instr->key(),
4606 instr->hydrogen()->key()->representation(), elements_kind,
4607 instr->base_offset() + kPointerSize);
4609 Label no_special_nan_handling, done;
4610 X87Register value = ToX87Register(instr->value());
4612 __ lea(esp, Operand(esp, -kDoubleSize));
4613 __ fst_d(MemOperand(esp, 0));
4614 __ lea(esp, Operand(esp, kDoubleSize));
4615 int offset = sizeof(kHoleNanUpper32);
4616 // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
4617 // so we check the upper with 0xffffffff for hole as a temporary fix.
4618 __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
4619 __ j(not_equal, &no_special_nan_handling, Label::kNear);
4620 __ mov(operand, Immediate(lower));
4621 __ mov(operand2, Immediate(upper));
4622 __ jmp(&done, Label::kNear);
4624 __ bind(&no_special_nan_handling);
4628 Register value = ToRegister(instr->value());
4629 switch (elements_kind) {
4630 case UINT8_ELEMENTS:
4632 case UINT8_CLAMPED_ELEMENTS:
4633 __ mov_b(operand, value);
4635 case UINT16_ELEMENTS:
4636 case INT16_ELEMENTS:
4637 __ mov_w(operand, value);
4639 case UINT32_ELEMENTS:
4640 case INT32_ELEMENTS:
4641 __ mov(operand, value);
4643 case FLOAT32_ELEMENTS:
4644 case FLOAT64_ELEMENTS:
4645 case FAST_SMI_ELEMENTS:
4647 case FAST_DOUBLE_ELEMENTS:
4648 case FAST_HOLEY_SMI_ELEMENTS:
4649 case FAST_HOLEY_ELEMENTS:
4650 case FAST_HOLEY_DOUBLE_ELEMENTS:
4651 case DICTIONARY_ELEMENTS:
4652 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
4653 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
4661 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4662 Operand double_store_operand = BuildFastArrayOperand(
4665 instr->hydrogen()->key()->representation(),
4666 FAST_DOUBLE_ELEMENTS,
4667 instr->base_offset());
4669 uint64_t int_val = kHoleNanInt64;
4670 int32_t lower = static_cast<int32_t>(int_val);
4671 int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4672 Operand double_store_operand2 = BuildFastArrayOperand(
4673 instr->elements(), instr->key(),
4674 instr->hydrogen()->key()->representation(), FAST_DOUBLE_ELEMENTS,
4675 instr->base_offset() + kPointerSize);
4677 if (instr->hydrogen()->IsConstantHoleStore()) {
4678 // This means we should store the (double) hole. No floating point
4679 // registers required.
4680 __ mov(double_store_operand, Immediate(lower));
4681 __ mov(double_store_operand2, Immediate(upper));
4683 Label no_special_nan_handling, done;
4684 X87Register value = ToX87Register(instr->value());
4687 if (instr->NeedsCanonicalization()) {
4691 __ j(parity_odd, &no_special_nan_handling, Label::kNear);
4692 // All NaNs are Canonicalized to 0x7fffffffffffffff
4693 __ mov(double_store_operand, Immediate(0xffffffff));
4694 __ mov(double_store_operand2, Immediate(0x7fffffff));
4695 __ jmp(&done, Label::kNear);
4697 __ lea(esp, Operand(esp, -kDoubleSize));
4698 __ fst_d(MemOperand(esp, 0));
4699 __ lea(esp, Operand(esp, kDoubleSize));
4700 int offset = sizeof(kHoleNanUpper32);
4701 // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
4702 // so we check the upper with 0xffffffff for hole as a temporary fix.
4703 __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
4704 __ j(not_equal, &no_special_nan_handling, Label::kNear);
4705 __ mov(double_store_operand, Immediate(lower));
4706 __ mov(double_store_operand2, Immediate(upper));
4707 __ jmp(&done, Label::kNear);
4709 __ bind(&no_special_nan_handling);
4710 __ fst_d(double_store_operand);
4716 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4717 Register elements = ToRegister(instr->elements());
4718 Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4720 Operand operand = BuildFastArrayOperand(
4723 instr->hydrogen()->key()->representation(),
4725 instr->base_offset());
4726 if (instr->value()->IsRegister()) {
4727 __ mov(operand, ToRegister(instr->value()));
4729 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4730 if (IsSmi(operand_value)) {
4731 Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4732 __ mov(operand, immediate);
4734 DCHECK(!IsInteger32(operand_value));
4735 Handle<Object> handle_value = ToHandle(operand_value);
4736 __ mov(operand, handle_value);
4740 if (instr->hydrogen()->NeedsWriteBarrier()) {
4741 DCHECK(instr->value()->IsRegister());
4742 Register value = ToRegister(instr->value());
4743 DCHECK(!instr->key()->IsConstantOperand());
4744 SmiCheck check_needed =
4745 instr->hydrogen()->value()->type().IsHeapObject()
4746 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4747 // Compute address of modified element and store it into key register.
4748 __ lea(key, operand);
4749 __ RecordWrite(elements, key, value, kSaveFPRegs, EMIT_REMEMBERED_SET,
4751 instr->hydrogen()->PointersToHereCheckForValue());
4756 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4757 // By cases...external, fast-double, fast
4758 if (instr->is_fixed_typed_array()) {
4759 DoStoreKeyedExternalArray(instr);
4760 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4761 DoStoreKeyedFixedDoubleArray(instr);
4763 DoStoreKeyedFixedArray(instr);
4768 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4769 DCHECK(ToRegister(instr->context()).is(esi));
4770 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4771 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4772 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4774 if (instr->hydrogen()->HasVectorAndSlot()) {
4775 EmitVectorStoreICRegisters<LStoreKeyedGeneric>(instr);
4778 Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4779 isolate(), instr->language_mode(),
4780 instr->hydrogen()->initialization_state()).code();
4781 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4785 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4786 Register object = ToRegister(instr->object());
4787 Register temp = ToRegister(instr->temp());
4788 Label no_memento_found;
4789 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4790 DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4791 __ bind(&no_memento_found);
4795 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
4796 class DeferredMaybeGrowElements final : public LDeferredCode {
4798 DeferredMaybeGrowElements(LCodeGen* codegen,
4799 LMaybeGrowElements* instr,
4800 const X87Stack& x87_stack)
4801 : LDeferredCode(codegen, x87_stack), instr_(instr) {}
4802 void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
4803 LInstruction* instr() override { return instr_; }
4806 LMaybeGrowElements* instr_;
4809 Register result = eax;
4810 DeferredMaybeGrowElements* deferred =
4811 new (zone()) DeferredMaybeGrowElements(this, instr, x87_stack_);
4812 LOperand* key = instr->key();
4813 LOperand* current_capacity = instr->current_capacity();
4815 DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
4816 DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
4817 DCHECK(key->IsConstantOperand() || key->IsRegister());
4818 DCHECK(current_capacity->IsConstantOperand() ||
4819 current_capacity->IsRegister());
4821 if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
4822 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4823 int32_t constant_capacity =
4824 ToInteger32(LConstantOperand::cast(current_capacity));
4825 if (constant_key >= constant_capacity) {
4827 __ jmp(deferred->entry());
4829 } else if (key->IsConstantOperand()) {
4830 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4831 __ cmp(ToOperand(current_capacity), Immediate(constant_key));
4832 __ j(less_equal, deferred->entry());
4833 } else if (current_capacity->IsConstantOperand()) {
4834 int32_t constant_capacity =
4835 ToInteger32(LConstantOperand::cast(current_capacity));
4836 __ cmp(ToRegister(key), Immediate(constant_capacity));
4837 __ j(greater_equal, deferred->entry());
4839 __ cmp(ToRegister(key), ToRegister(current_capacity));
4840 __ j(greater_equal, deferred->entry());
4843 __ mov(result, ToOperand(instr->elements()));
4844 __ bind(deferred->exit());
4848 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
4849 // TODO(3095996): Get rid of this. For now, we need to make the
4850 // result register contain a valid pointer because it is already
4851 // contained in the register pointer map.
4852 Register result = eax;
4853 __ Move(result, Immediate(0));
4855 // We have to call a stub.
4857 PushSafepointRegistersScope scope(this);
4858 if (instr->object()->IsRegister()) {
4859 __ Move(result, ToRegister(instr->object()));
4861 __ mov(result, ToOperand(instr->object()));
4864 LOperand* key = instr->key();
4865 if (key->IsConstantOperand()) {
4866 __ mov(ebx, ToImmediate(key, Representation::Smi()));
4868 __ Move(ebx, ToRegister(key));
4872 GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
4873 instr->hydrogen()->kind());
4875 RecordSafepointWithLazyDeopt(
4876 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4877 __ StoreToSafepointRegisterSlot(result, result);
4880 // Deopt on smi, which means the elements array changed to dictionary mode.
4881 __ test(result, Immediate(kSmiTagMask));
4882 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
4886 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4887 Register object_reg = ToRegister(instr->object());
4889 Handle<Map> from_map = instr->original_map();
4890 Handle<Map> to_map = instr->transitioned_map();
4891 ElementsKind from_kind = instr->from_kind();
4892 ElementsKind to_kind = instr->to_kind();
4894 Label not_applicable;
4895 bool is_simple_map_transition =
4896 IsSimpleMapChangeTransition(from_kind, to_kind);
4897 Label::Distance branch_distance =
4898 is_simple_map_transition ? Label::kNear : Label::kFar;
4899 __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4900 __ j(not_equal, ¬_applicable, branch_distance);
4901 if (is_simple_map_transition) {
4902 Register new_map_reg = ToRegister(instr->new_map_temp());
4903 __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4906 DCHECK_NOT_NULL(instr->temp());
4907 __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4908 ToRegister(instr->temp()), kDontSaveFPRegs);
4910 DCHECK(ToRegister(instr->context()).is(esi));
4911 DCHECK(object_reg.is(eax));
4912 PushSafepointRegistersScope scope(this);
4913 __ mov(ebx, to_map);
4914 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4915 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4917 RecordSafepointWithLazyDeopt(instr,
4918 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4920 __ bind(¬_applicable);
4924 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4925 class DeferredStringCharCodeAt final : public LDeferredCode {
4927 DeferredStringCharCodeAt(LCodeGen* codegen,
4928 LStringCharCodeAt* instr,
4929 const X87Stack& x87_stack)
4930 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4931 void Generate() override { codegen()->DoDeferredStringCharCodeAt(instr_); }
4932 LInstruction* instr() override { return instr_; }
4935 LStringCharCodeAt* instr_;
4938 DeferredStringCharCodeAt* deferred =
4939 new(zone()) DeferredStringCharCodeAt(this, instr, x87_stack_);
4941 StringCharLoadGenerator::Generate(masm(),
4943 ToRegister(instr->string()),
4944 ToRegister(instr->index()),
4945 ToRegister(instr->result()),
4947 __ bind(deferred->exit());
4951 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4952 Register string = ToRegister(instr->string());
4953 Register result = ToRegister(instr->result());
4955 // TODO(3095996): Get rid of this. For now, we need to make the
4956 // result register contain a valid pointer because it is already
4957 // contained in the register pointer map.
4958 __ Move(result, Immediate(0));
4960 PushSafepointRegistersScope scope(this);
4962 // Push the index as a smi. This is safe because of the checks in
4963 // DoStringCharCodeAt above.
4964 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4965 if (instr->index()->IsConstantOperand()) {
4966 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4967 Representation::Smi());
4970 Register index = ToRegister(instr->index());
4974 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4975 instr, instr->context());
4978 __ StoreToSafepointRegisterSlot(result, eax);
4982 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4983 class DeferredStringCharFromCode final : public LDeferredCode {
4985 DeferredStringCharFromCode(LCodeGen* codegen,
4986 LStringCharFromCode* instr,
4987 const X87Stack& x87_stack)
4988 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4989 void Generate() override {
4990 codegen()->DoDeferredStringCharFromCode(instr_);
4992 LInstruction* instr() override { return instr_; }
4995 LStringCharFromCode* instr_;
4998 DeferredStringCharFromCode* deferred =
4999 new(zone()) DeferredStringCharFromCode(this, instr, x87_stack_);
5001 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
5002 Register char_code = ToRegister(instr->char_code());
5003 Register result = ToRegister(instr->result());
5004 DCHECK(!char_code.is(result));
5006 __ cmp(char_code, String::kMaxOneByteCharCode);
5007 __ j(above, deferred->entry());
5008 __ Move(result, Immediate(factory()->single_character_string_cache()));
5009 __ mov(result, FieldOperand(result,
5010 char_code, times_pointer_size,
5011 FixedArray::kHeaderSize));
5012 __ cmp(result, factory()->undefined_value());
5013 __ j(equal, deferred->entry());
5014 __ bind(deferred->exit());
5018 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
5019 Register char_code = ToRegister(instr->char_code());
5020 Register result = ToRegister(instr->result());
5022 // TODO(3095996): Get rid of this. For now, we need to make the
5023 // result register contain a valid pointer because it is already
5024 // contained in the register pointer map.
5025 __ Move(result, Immediate(0));
5027 PushSafepointRegistersScope scope(this);
5028 __ SmiTag(char_code);
5030 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
5031 __ StoreToSafepointRegisterSlot(result, eax);
5035 void LCodeGen::DoStringAdd(LStringAdd* instr) {
5036 DCHECK(ToRegister(instr->context()).is(esi));
5037 DCHECK(ToRegister(instr->left()).is(edx));
5038 DCHECK(ToRegister(instr->right()).is(eax));
5039 StringAddStub stub(isolate(),
5040 instr->hydrogen()->flags(),
5041 instr->hydrogen()->pretenure_flag());
5042 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5046 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
5047 LOperand* input = instr->value();
5048 LOperand* output = instr->result();
5049 DCHECK(input->IsRegister() || input->IsStackSlot());
5050 DCHECK(output->IsDoubleRegister());
5051 if (input->IsRegister()) {
5052 Register input_reg = ToRegister(input);
5054 X87Mov(ToX87Register(output), Operand(esp, 0), kX87IntOperand);
5057 X87Mov(ToX87Register(output), ToOperand(input), kX87IntOperand);
5062 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
5063 LOperand* input = instr->value();
5064 LOperand* output = instr->result();
5065 X87Register res = ToX87Register(output);
5066 X87PrepareToWrite(res);
5067 __ LoadUint32NoSSE2(ToRegister(input));
5068 X87CommitWrite(res);
5072 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
5073 class DeferredNumberTagI final : public LDeferredCode {
5075 DeferredNumberTagI(LCodeGen* codegen,
5077 const X87Stack& x87_stack)
5078 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5079 void Generate() override {
5080 codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
5083 LInstruction* instr() override { return instr_; }
5086 LNumberTagI* instr_;
5089 LOperand* input = instr->value();
5090 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5091 Register reg = ToRegister(input);
5093 DeferredNumberTagI* deferred =
5094 new(zone()) DeferredNumberTagI(this, instr, x87_stack_);
5096 __ j(overflow, deferred->entry());
5097 __ bind(deferred->exit());
5101 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
5102 class DeferredNumberTagU final : public LDeferredCode {
5104 DeferredNumberTagU(LCodeGen* codegen,
5106 const X87Stack& x87_stack)
5107 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5108 void Generate() override {
5109 codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
5112 LInstruction* instr() override { return instr_; }
5115 LNumberTagU* instr_;
5118 LOperand* input = instr->value();
5119 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5120 Register reg = ToRegister(input);
5122 DeferredNumberTagU* deferred =
5123 new(zone()) DeferredNumberTagU(this, instr, x87_stack_);
5124 __ cmp(reg, Immediate(Smi::kMaxValue));
5125 __ j(above, deferred->entry());
5127 __ bind(deferred->exit());
5131 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
5134 IntegerSignedness signedness) {
5136 Register reg = ToRegister(value);
5137 Register tmp = ToRegister(temp);
5139 if (signedness == SIGNED_INT32) {
5140 // There was overflow, so bits 30 and 31 of the original integer
5141 // disagree. Try to allocate a heap number in new space and store
5142 // the value in there. If that fails, call the runtime system.
5144 __ xor_(reg, 0x80000000);
5146 __ fild_s(Operand(esp, 0));
5149 // There's no fild variant for unsigned values, so zero-extend to a 64-bit
5151 __ push(Immediate(0));
5153 __ fild_d(Operand(esp, 0));
5158 if (FLAG_inline_new) {
5159 __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
5160 __ jmp(&done, Label::kNear);
5163 // Slow case: Call the runtime system to do the number allocation.
5166 // TODO(3095996): Put a valid pointer value in the stack slot where the
5167 // result register is stored, as this register is in the pointer map, but
5168 // contains an integer value.
5169 __ Move(reg, Immediate(0));
5171 // Preserve the value of all registers.
5172 PushSafepointRegistersScope scope(this);
5174 // NumberTagI and NumberTagD use the context from the frame, rather than
5175 // the environment's HContext or HInlinedContext value.
5176 // They only call Runtime::kAllocateHeapNumber.
5177 // The corresponding HChange instructions are added in a phase that does
5178 // not have easy access to the local context.
5179 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5180 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5181 RecordSafepointWithRegisters(
5182 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5183 __ StoreToSafepointRegisterSlot(reg, eax);
5187 __ fstp_d(FieldOperand(reg, HeapNumber::kValueOffset));
5191 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
5192 class DeferredNumberTagD final : public LDeferredCode {
5194 DeferredNumberTagD(LCodeGen* codegen,
5196 const X87Stack& x87_stack)
5197 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5198 void Generate() override { codegen()->DoDeferredNumberTagD(instr_); }
5199 LInstruction* instr() override { return instr_; }
5202 LNumberTagD* instr_;
5205 Register reg = ToRegister(instr->result());
5207 // Put the value to the top of stack
5208 X87Register src = ToX87Register(instr->value());
5209 // Don't use X87LoadForUsage here, which is only used by Instruction which
5210 // clobbers fp registers.
5211 x87_stack_.Fxch(src);
5213 DeferredNumberTagD* deferred =
5214 new(zone()) DeferredNumberTagD(this, instr, x87_stack_);
5215 if (FLAG_inline_new) {
5216 Register tmp = ToRegister(instr->temp());
5217 __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
5219 __ jmp(deferred->entry());
5221 __ bind(deferred->exit());
5222 __ fst_d(FieldOperand(reg, HeapNumber::kValueOffset));
5226 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
5227 // TODO(3095996): Get rid of this. For now, we need to make the
5228 // result register contain a valid pointer because it is already
5229 // contained in the register pointer map.
5230 Register reg = ToRegister(instr->result());
5231 __ Move(reg, Immediate(0));
5233 PushSafepointRegistersScope scope(this);
5234 // NumberTagI and NumberTagD use the context from the frame, rather than
5235 // the environment's HContext or HInlinedContext value.
5236 // They only call Runtime::kAllocateHeapNumber.
5237 // The corresponding HChange instructions are added in a phase that does
5238 // not have easy access to the local context.
5239 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5240 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5241 RecordSafepointWithRegisters(
5242 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5243 __ StoreToSafepointRegisterSlot(reg, eax);
5247 void LCodeGen::DoSmiTag(LSmiTag* instr) {
5248 HChange* hchange = instr->hydrogen();
5249 Register input = ToRegister(instr->value());
5250 if (hchange->CheckFlag(HValue::kCanOverflow) &&
5251 hchange->value()->CheckFlag(HValue::kUint32)) {
5252 __ test(input, Immediate(0xc0000000));
5253 DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
5256 if (hchange->CheckFlag(HValue::kCanOverflow) &&
5257 !hchange->value()->CheckFlag(HValue::kUint32)) {
5258 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5263 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
5264 LOperand* input = instr->value();
5265 Register result = ToRegister(input);
5266 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5267 if (instr->needs_check()) {
5268 __ test(result, Immediate(kSmiTagMask));
5269 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5271 __ AssertSmi(result);
5273 __ SmiUntag(result);
5277 void LCodeGen::EmitNumberUntagDNoSSE2(LNumberUntagD* instr, Register input_reg,
5278 Register temp_reg, X87Register res_reg,
5279 NumberUntagDMode mode) {
5280 bool can_convert_undefined_to_nan =
5281 instr->hydrogen()->can_convert_undefined_to_nan();
5282 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
5284 Label load_smi, done;
5286 X87PrepareToWrite(res_reg);
5287 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
5289 __ JumpIfSmi(input_reg, &load_smi);
5291 // Heap number map check.
5292 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5293 factory()->heap_number_map());
5294 if (!can_convert_undefined_to_nan) {
5295 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5297 Label heap_number, convert;
5298 __ j(equal, &heap_number);
5300 // Convert undefined (or hole) to NaN.
5301 __ cmp(input_reg, factory()->undefined_value());
5302 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5305 __ push(Immediate(0xffffffff));
5306 __ push(Immediate(0x7fffffff));
5307 __ fld_d(MemOperand(esp, 0));
5308 __ lea(esp, Operand(esp, kDoubleSize));
5309 __ jmp(&done, Label::kNear);
5311 __ bind(&heap_number);
5313 // Heap number to x87 conversion.
5314 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5315 if (deoptimize_on_minus_zero) {
5318 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5319 __ j(not_zero, &done, Label::kNear);
5321 // Use general purpose registers to check if we have -0.0
5322 __ mov(temp_reg, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5323 __ test(temp_reg, Immediate(HeapNumber::kSignMask));
5324 __ j(zero, &done, Label::kNear);
5326 // Pop FPU stack before deoptimizing.
5328 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5330 __ jmp(&done, Label::kNear);
5332 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
5336 // Clobbering a temp is faster than re-tagging the
5337 // input register since we avoid dependencies.
5338 __ mov(temp_reg, input_reg);
5339 __ SmiUntag(temp_reg); // Untag smi before converting to float.
5341 __ fild_s(Operand(esp, 0));
5342 __ add(esp, Immediate(kPointerSize));
5344 X87CommitWrite(res_reg);
5348 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
5349 Register input_reg = ToRegister(instr->value());
5351 // The input was optimistically untagged; revert it.
5352 STATIC_ASSERT(kSmiTagSize == 1);
5353 __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
5355 if (instr->truncating()) {
5356 Label no_heap_number, check_bools, check_false;
5358 // Heap number map check.
5359 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5360 factory()->heap_number_map());
5361 __ j(not_equal, &no_heap_number, Label::kNear);
5362 __ TruncateHeapNumberToI(input_reg, input_reg);
5365 __ bind(&no_heap_number);
5366 // Check for Oddballs. Undefined/False is converted to zero and True to one
5367 // for truncating conversions.
5368 __ cmp(input_reg, factory()->undefined_value());
5369 __ j(not_equal, &check_bools, Label::kNear);
5370 __ Move(input_reg, Immediate(0));
5373 __ bind(&check_bools);
5374 __ cmp(input_reg, factory()->true_value());
5375 __ j(not_equal, &check_false, Label::kNear);
5376 __ Move(input_reg, Immediate(1));
5379 __ bind(&check_false);
5380 __ cmp(input_reg, factory()->false_value());
5381 DeoptimizeIf(not_equal, instr,
5382 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
5383 __ Move(input_reg, Immediate(0));
5385 // TODO(olivf) Converting a number on the fpu is actually quite slow. We
5386 // should first try a fast conversion and then bailout to this slow case.
5387 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5388 isolate()->factory()->heap_number_map());
5389 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5391 __ sub(esp, Immediate(kPointerSize));
5392 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5394 if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
5395 Label no_precision_lost, not_nan, zero_check;
5398 __ fist_s(MemOperand(esp, 0));
5399 __ fild_s(MemOperand(esp, 0));
5403 __ j(equal, &no_precision_lost, Label::kNear);
5405 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5406 __ bind(&no_precision_lost);
5408 __ j(parity_odd, ¬_nan);
5410 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5413 __ test(input_reg, Operand(input_reg));
5414 __ j(zero, &zero_check, Label::kNear);
5418 __ bind(&zero_check);
5419 // To check for minus zero, we load the value again as float, and check
5420 // if that is still 0.
5421 __ sub(esp, Immediate(kPointerSize));
5422 __ fstp_s(Operand(esp, 0));
5424 __ test(input_reg, Operand(input_reg));
5425 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5427 __ fist_s(MemOperand(esp, 0));
5428 __ fild_s(MemOperand(esp, 0));
5431 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
5432 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
5438 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
5439 class DeferredTaggedToI final : public LDeferredCode {
5441 DeferredTaggedToI(LCodeGen* codegen,
5443 const X87Stack& x87_stack)
5444 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5445 void Generate() override { codegen()->DoDeferredTaggedToI(instr_, done()); }
5446 LInstruction* instr() override { return instr_; }
5452 LOperand* input = instr->value();
5453 DCHECK(input->IsRegister());
5454 Register input_reg = ToRegister(input);
5455 DCHECK(input_reg.is(ToRegister(instr->result())));
5457 if (instr->hydrogen()->value()->representation().IsSmi()) {
5458 __ SmiUntag(input_reg);
5460 DeferredTaggedToI* deferred =
5461 new(zone()) DeferredTaggedToI(this, instr, x87_stack_);
5462 // Optimistically untag the input.
5463 // If the input is a HeapObject, SmiUntag will set the carry flag.
5464 STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
5465 __ SmiUntag(input_reg);
5466 // Branch to deferred code if the input was tagged.
5467 // The deferred code will take care of restoring the tag.
5468 __ j(carry, deferred->entry());
5469 __ bind(deferred->exit());
5474 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
5475 LOperand* input = instr->value();
5476 DCHECK(input->IsRegister());
5477 LOperand* temp = instr->temp();
5478 DCHECK(temp->IsRegister());
5479 LOperand* result = instr->result();
5480 DCHECK(result->IsDoubleRegister());
5482 Register input_reg = ToRegister(input);
5483 Register temp_reg = ToRegister(temp);
5485 HValue* value = instr->hydrogen()->value();
5486 NumberUntagDMode mode = value->representation().IsSmi()
5487 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
5489 EmitNumberUntagDNoSSE2(instr, input_reg, temp_reg, ToX87Register(result),
5494 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
5495 LOperand* input = instr->value();
5496 DCHECK(input->IsDoubleRegister());
5497 LOperand* result = instr->result();
5498 DCHECK(result->IsRegister());
5499 Register result_reg = ToRegister(result);
5501 if (instr->truncating()) {
5502 X87Register input_reg = ToX87Register(input);
5504 __ TruncateX87TOSToI(result_reg);
5506 Label lost_precision, is_nan, minus_zero, done;
5507 X87Register input_reg = ToX87Register(input);
5509 __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5510 &lost_precision, &is_nan, &minus_zero);
5512 __ bind(&lost_precision);
5513 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5515 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5516 __ bind(&minus_zero);
5517 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5523 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
5524 LOperand* input = instr->value();
5525 DCHECK(input->IsDoubleRegister());
5526 LOperand* result = instr->result();
5527 DCHECK(result->IsRegister());
5528 Register result_reg = ToRegister(result);
5530 Label lost_precision, is_nan, minus_zero, done;
5531 X87Register input_reg = ToX87Register(input);
5533 __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5534 &lost_precision, &is_nan, &minus_zero);
5536 __ bind(&lost_precision);
5537 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5539 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5540 __ bind(&minus_zero);
5541 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5543 __ SmiTag(result_reg);
5544 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5548 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
5549 LOperand* input = instr->value();
5550 __ test(ToOperand(input), Immediate(kSmiTagMask));
5551 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5555 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5556 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
5557 LOperand* input = instr->value();
5558 __ test(ToOperand(input), Immediate(kSmiTagMask));
5559 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5564 void LCodeGen::DoCheckArrayBufferNotNeutered(
5565 LCheckArrayBufferNotNeutered* instr) {
5566 Register view = ToRegister(instr->view());
5567 Register scratch = ToRegister(instr->scratch());
5569 __ mov(scratch, FieldOperand(view, JSArrayBufferView::kBufferOffset));
5570 __ test_b(FieldOperand(scratch, JSArrayBuffer::kBitFieldOffset),
5571 1 << JSArrayBuffer::WasNeutered::kShift);
5572 DeoptimizeIf(not_zero, instr, Deoptimizer::kOutOfBounds);
5576 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
5577 Register input = ToRegister(instr->value());
5578 Register temp = ToRegister(instr->temp());
5580 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
5582 if (instr->hydrogen()->is_interval_check()) {
5585 instr->hydrogen()->GetCheckInterval(&first, &last);
5587 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5588 static_cast<int8_t>(first));
5590 // If there is only one type in the interval check for equality.
5591 if (first == last) {
5592 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5594 DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
5595 // Omit check for the last type.
5596 if (last != LAST_TYPE) {
5597 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5598 static_cast<int8_t>(last));
5599 DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5605 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5607 if (base::bits::IsPowerOfTwo32(mask)) {
5608 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5609 __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5610 DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5611 Deoptimizer::kWrongInstanceType);
5613 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5614 __ and_(temp, mask);
5616 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5622 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5623 Handle<HeapObject> object = instr->hydrogen()->object().handle();
5624 if (instr->hydrogen()->object_in_new_space()) {
5625 Register reg = ToRegister(instr->value());
5626 Handle<Cell> cell = isolate()->factory()->NewCell(object);
5627 __ cmp(reg, Operand::ForCell(cell));
5629 Operand operand = ToOperand(instr->value());
5630 __ cmp(operand, object);
5632 DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5636 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5638 PushSafepointRegistersScope scope(this);
5641 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5642 RecordSafepointWithRegisters(
5643 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5645 __ test(eax, Immediate(kSmiTagMask));
5647 DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5651 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5652 class DeferredCheckMaps final : public LDeferredCode {
5654 DeferredCheckMaps(LCodeGen* codegen,
5657 const X87Stack& x87_stack)
5658 : LDeferredCode(codegen, x87_stack), instr_(instr), object_(object) {
5659 SetExit(check_maps());
5661 void Generate() override {
5662 codegen()->DoDeferredInstanceMigration(instr_, object_);
5664 Label* check_maps() { return &check_maps_; }
5665 LInstruction* instr() override { return instr_; }
5673 if (instr->hydrogen()->IsStabilityCheck()) {
5674 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5675 for (int i = 0; i < maps->size(); ++i) {
5676 AddStabilityDependency(maps->at(i).handle());
5681 LOperand* input = instr->value();
5682 DCHECK(input->IsRegister());
5683 Register reg = ToRegister(input);
5685 DeferredCheckMaps* deferred = NULL;
5686 if (instr->hydrogen()->HasMigrationTarget()) {
5687 deferred = new(zone()) DeferredCheckMaps(this, instr, reg, x87_stack_);
5688 __ bind(deferred->check_maps());
5691 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5693 for (int i = 0; i < maps->size() - 1; i++) {
5694 Handle<Map> map = maps->at(i).handle();
5695 __ CompareMap(reg, map);
5696 __ j(equal, &success, Label::kNear);
5699 Handle<Map> map = maps->at(maps->size() - 1).handle();
5700 __ CompareMap(reg, map);
5701 if (instr->hydrogen()->HasMigrationTarget()) {
5702 __ j(not_equal, deferred->entry());
5704 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5711 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5712 X87Register value_reg = ToX87Register(instr->unclamped());
5713 Register result_reg = ToRegister(instr->result());
5715 __ ClampTOSToUint8(result_reg);
5719 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5720 DCHECK(instr->unclamped()->Equals(instr->result()));
5721 Register value_reg = ToRegister(instr->result());
5722 __ ClampUint8(value_reg);
5726 void LCodeGen::DoClampTToUint8NoSSE2(LClampTToUint8NoSSE2* instr) {
5727 Register input_reg = ToRegister(instr->unclamped());
5728 Register result_reg = ToRegister(instr->result());
5729 Register scratch = ToRegister(instr->scratch());
5730 Register scratch2 = ToRegister(instr->scratch2());
5731 Register scratch3 = ToRegister(instr->scratch3());
5732 Label is_smi, done, heap_number, valid_exponent,
5733 largest_value, zero_result, maybe_nan_or_infinity;
5735 __ JumpIfSmi(input_reg, &is_smi);
5737 // Check for heap number
5738 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5739 factory()->heap_number_map());
5740 __ j(equal, &heap_number, Label::kNear);
5742 // Check for undefined. Undefined is converted to zero for clamping
5744 __ cmp(input_reg, factory()->undefined_value());
5745 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5746 __ jmp(&zero_result, Label::kNear);
5749 __ bind(&heap_number);
5751 // Surprisingly, all of the hand-crafted bit-manipulations below are much
5752 // faster than the x86 FPU built-in instruction, especially since "banker's
5753 // rounding" would be additionally very expensive
5755 // Get exponent word.
5756 __ mov(scratch, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5757 __ mov(scratch3, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5759 // Test for negative values --> clamp to zero
5760 __ test(scratch, scratch);
5761 __ j(negative, &zero_result, Label::kNear);
5763 // Get exponent alone in scratch2.
5764 __ mov(scratch2, scratch);
5765 __ and_(scratch2, HeapNumber::kExponentMask);
5766 __ shr(scratch2, HeapNumber::kExponentShift);
5767 __ j(zero, &zero_result, Label::kNear);
5768 __ sub(scratch2, Immediate(HeapNumber::kExponentBias - 1));
5769 __ j(negative, &zero_result, Label::kNear);
5771 const uint32_t non_int8_exponent = 7;
5772 __ cmp(scratch2, Immediate(non_int8_exponent + 1));
5773 // If the exponent is too big, check for special values.
5774 __ j(greater, &maybe_nan_or_infinity, Label::kNear);
5776 __ bind(&valid_exponent);
5777 // Exponent word in scratch, exponent in scratch2. We know that 0 <= exponent
5778 // < 7. The shift bias is the number of bits to shift the mantissa such that
5779 // with an exponent of 7 such the that top-most one is in bit 30, allowing
5780 // detection the rounding overflow of a 255.5 to 256 (bit 31 goes from 0 to
5782 int shift_bias = (30 - HeapNumber::kExponentShift) - 7 - 1;
5783 __ lea(result_reg, MemOperand(scratch2, shift_bias));
5784 // Here result_reg (ecx) is the shift, scratch is the exponent word. Get the
5785 // top bits of the mantissa.
5786 __ and_(scratch, HeapNumber::kMantissaMask);
5787 // Put back the implicit 1 of the mantissa
5788 __ or_(scratch, 1 << HeapNumber::kExponentShift);
5789 // Shift up to round
5791 // Use "banker's rounding" to spec: If fractional part of number is 0.5, then
5792 // use the bit in the "ones" place and add it to the "halves" place, which has
5793 // the effect of rounding to even.
5794 __ mov(scratch2, scratch);
5795 const uint32_t one_half_bit_shift = 30 - sizeof(uint8_t) * 8;
5796 const uint32_t one_bit_shift = one_half_bit_shift + 1;
5797 __ and_(scratch2, Immediate((1 << one_bit_shift) - 1));
5798 __ cmp(scratch2, Immediate(1 << one_half_bit_shift));
5800 __ j(less, &no_round, Label::kNear);
5802 __ mov(scratch2, Immediate(1 << one_half_bit_shift));
5803 __ j(greater, &round_up, Label::kNear);
5804 __ test(scratch3, scratch3);
5805 __ j(not_zero, &round_up, Label::kNear);
5806 __ mov(scratch2, scratch);
5807 __ and_(scratch2, Immediate(1 << one_bit_shift));
5808 __ shr(scratch2, 1);
5810 __ add(scratch, scratch2);
5811 __ j(overflow, &largest_value, Label::kNear);
5813 __ shr(scratch, 23);
5814 __ mov(result_reg, scratch);
5815 __ jmp(&done, Label::kNear);
5817 __ bind(&maybe_nan_or_infinity);
5818 // Check for NaN/Infinity, all other values map to 255
5819 __ cmp(scratch2, Immediate(HeapNumber::kInfinityOrNanExponent + 1));
5820 __ j(not_equal, &largest_value, Label::kNear);
5822 // Check for NaN, which differs from Infinity in that at least one mantissa
5824 __ and_(scratch, HeapNumber::kMantissaMask);
5825 __ or_(scratch, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5826 __ j(not_zero, &zero_result, Label::kNear); // M!=0 --> NaN
5827 // Infinity -> Fall through to map to 255.
5829 __ bind(&largest_value);
5830 __ mov(result_reg, Immediate(255));
5831 __ jmp(&done, Label::kNear);
5833 __ bind(&zero_result);
5834 __ xor_(result_reg, result_reg);
5835 __ jmp(&done, Label::kNear);
5839 if (!input_reg.is(result_reg)) {
5840 __ mov(result_reg, input_reg);
5842 __ SmiUntag(result_reg);
5843 __ ClampUint8(result_reg);
5848 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5849 X87Register value_reg = ToX87Register(instr->value());
5850 Register result_reg = ToRegister(instr->result());
5852 __ sub(esp, Immediate(kDoubleSize));
5853 __ fst_d(Operand(esp, 0));
5854 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5855 __ mov(result_reg, Operand(esp, kPointerSize));
5857 __ mov(result_reg, Operand(esp, 0));
5859 __ add(esp, Immediate(kDoubleSize));
5863 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5864 Register hi_reg = ToRegister(instr->hi());
5865 Register lo_reg = ToRegister(instr->lo());
5866 X87Register result_reg = ToX87Register(instr->result());
5867 // Follow below pattern to write a x87 fp register.
5868 X87PrepareToWrite(result_reg);
5869 __ sub(esp, Immediate(kDoubleSize));
5870 __ mov(Operand(esp, 0), lo_reg);
5871 __ mov(Operand(esp, kPointerSize), hi_reg);
5872 __ fld_d(Operand(esp, 0));
5873 __ add(esp, Immediate(kDoubleSize));
5874 X87CommitWrite(result_reg);
5878 void LCodeGen::DoAllocate(LAllocate* instr) {
5879 class DeferredAllocate final : public LDeferredCode {
5881 DeferredAllocate(LCodeGen* codegen,
5883 const X87Stack& x87_stack)
5884 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5885 void Generate() override { codegen()->DoDeferredAllocate(instr_); }
5886 LInstruction* instr() override { return instr_; }
5892 DeferredAllocate* deferred =
5893 new(zone()) DeferredAllocate(this, instr, x87_stack_);
5895 Register result = ToRegister(instr->result());
5896 Register temp = ToRegister(instr->temp());
5898 // Allocate memory for the object.
5899 AllocationFlags flags = TAG_OBJECT;
5900 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5901 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5903 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5904 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5905 flags = static_cast<AllocationFlags>(flags | PRETENURE);
5908 if (instr->size()->IsConstantOperand()) {
5909 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5910 if (size <= Page::kMaxRegularHeapObjectSize) {
5911 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5913 __ jmp(deferred->entry());
5916 Register size = ToRegister(instr->size());
5917 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5920 __ bind(deferred->exit());
5922 if (instr->hydrogen()->MustPrefillWithFiller()) {
5923 if (instr->size()->IsConstantOperand()) {
5924 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5925 __ mov(temp, (size / kPointerSize) - 1);
5927 temp = ToRegister(instr->size());
5928 __ shr(temp, kPointerSizeLog2);
5933 __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5934 isolate()->factory()->one_pointer_filler_map());
5936 __ j(not_zero, &loop);
5941 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5942 Register result = ToRegister(instr->result());
5944 // TODO(3095996): Get rid of this. For now, we need to make the
5945 // result register contain a valid pointer because it is already
5946 // contained in the register pointer map.
5947 __ Move(result, Immediate(Smi::FromInt(0)));
5949 PushSafepointRegistersScope scope(this);
5950 if (instr->size()->IsRegister()) {
5951 Register size = ToRegister(instr->size());
5952 DCHECK(!size.is(result));
5953 __ SmiTag(ToRegister(instr->size()));
5956 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5957 if (size >= 0 && size <= Smi::kMaxValue) {
5958 __ push(Immediate(Smi::FromInt(size)));
5960 // We should never get here at runtime => abort
5966 int flags = AllocateDoubleAlignFlag::encode(
5967 instr->hydrogen()->MustAllocateDoubleAligned());
5968 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5969 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5970 flags = AllocateTargetSpace::update(flags, OLD_SPACE);
5972 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5974 __ push(Immediate(Smi::FromInt(flags)));
5976 CallRuntimeFromDeferred(
5977 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5978 __ StoreToSafepointRegisterSlot(result, eax);
5982 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5983 DCHECK(ToRegister(instr->value()).is(eax));
5985 CallRuntime(Runtime::kToFastProperties, 1, instr);
5989 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5990 DCHECK(ToRegister(instr->context()).is(esi));
5992 // Registers will be used as follows:
5993 // ecx = literals array.
5994 // ebx = regexp literal.
5995 // eax = regexp literal clone.
5997 int literal_offset =
5998 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5999 __ LoadHeapObject(ecx, instr->hydrogen()->literals());
6000 __ mov(ebx, FieldOperand(ecx, literal_offset));
6001 __ cmp(ebx, factory()->undefined_value());
6002 __ j(not_equal, &materialized, Label::kNear);
6004 // Create regexp literal using runtime function
6005 // Result will be in eax.
6007 __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
6008 __ push(Immediate(instr->hydrogen()->pattern()));
6009 __ push(Immediate(instr->hydrogen()->flags()));
6010 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
6013 __ bind(&materialized);
6014 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
6015 Label allocated, runtime_allocate;
6016 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
6017 __ jmp(&allocated, Label::kNear);
6019 __ bind(&runtime_allocate);
6021 __ push(Immediate(Smi::FromInt(size)));
6022 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
6025 __ bind(&allocated);
6026 // Copy the content into the newly allocated memory.
6027 // (Unroll copy loop once for better throughput).
6028 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
6029 __ mov(edx, FieldOperand(ebx, i));
6030 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
6031 __ mov(FieldOperand(eax, i), edx);
6032 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
6034 if ((size % (2 * kPointerSize)) != 0) {
6035 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
6036 __ mov(FieldOperand(eax, size - kPointerSize), edx);
6041 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
6042 DCHECK(ToRegister(instr->context()).is(esi));
6043 // Use the fast case closure allocation code that allocates in new
6044 // space for nested functions that don't need literals cloning.
6045 bool pretenure = instr->hydrogen()->pretenure();
6046 if (!pretenure && instr->hydrogen()->has_no_literals()) {
6047 FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
6048 instr->hydrogen()->kind());
6049 __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
6050 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
6053 __ push(Immediate(instr->hydrogen()->shared_info()));
6054 __ push(Immediate(pretenure ? factory()->true_value()
6055 : factory()->false_value()));
6056 CallRuntime(Runtime::kNewClosure, 3, instr);
6061 void LCodeGen::DoTypeof(LTypeof* instr) {
6062 DCHECK(ToRegister(instr->context()).is(esi));
6063 DCHECK(ToRegister(instr->value()).is(ebx));
6065 Register value_register = ToRegister(instr->value());
6066 __ JumpIfNotSmi(value_register, &do_call);
6067 __ mov(eax, Immediate(isolate()->factory()->number_string()));
6070 TypeofStub stub(isolate());
6071 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
6076 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
6077 Register input = ToRegister(instr->value());
6078 Condition final_branch_condition = EmitTypeofIs(instr, input);
6079 if (final_branch_condition != no_condition) {
6080 EmitBranch(instr, final_branch_condition);
6085 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
6086 Label* true_label = instr->TrueLabel(chunk_);
6087 Label* false_label = instr->FalseLabel(chunk_);
6088 Handle<String> type_name = instr->type_literal();
6089 int left_block = instr->TrueDestination(chunk_);
6090 int right_block = instr->FalseDestination(chunk_);
6091 int next_block = GetNextEmittedBlock();
6093 Label::Distance true_distance = left_block == next_block ? Label::kNear
6095 Label::Distance false_distance = right_block == next_block ? Label::kNear
6097 Condition final_branch_condition = no_condition;
6098 if (String::Equals(type_name, factory()->number_string())) {
6099 __ JumpIfSmi(input, true_label, true_distance);
6100 __ cmp(FieldOperand(input, HeapObject::kMapOffset),
6101 factory()->heap_number_map());
6102 final_branch_condition = equal;
6104 } else if (String::Equals(type_name, factory()->string_string())) {
6105 __ JumpIfSmi(input, false_label, false_distance);
6106 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
6107 __ j(above_equal, false_label, false_distance);
6108 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6109 1 << Map::kIsUndetectable);
6110 final_branch_condition = zero;
6112 } else if (String::Equals(type_name, factory()->symbol_string())) {
6113 __ JumpIfSmi(input, false_label, false_distance);
6114 __ CmpObjectType(input, SYMBOL_TYPE, input);
6115 final_branch_condition = equal;
6117 } else if (String::Equals(type_name, factory()->boolean_string())) {
6118 __ cmp(input, factory()->true_value());
6119 __ j(equal, true_label, true_distance);
6120 __ cmp(input, factory()->false_value());
6121 final_branch_condition = equal;
6123 } else if (String::Equals(type_name, factory()->undefined_string())) {
6124 __ cmp(input, factory()->undefined_value());
6125 __ j(equal, true_label, true_distance);
6126 __ JumpIfSmi(input, false_label, false_distance);
6127 // Check for undetectable objects => true.
6128 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
6129 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6130 1 << Map::kIsUndetectable);
6131 final_branch_condition = not_zero;
6133 } else if (String::Equals(type_name, factory()->function_string())) {
6134 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
6135 __ JumpIfSmi(input, false_label, false_distance);
6136 __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
6137 __ j(equal, true_label, true_distance);
6138 __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
6139 final_branch_condition = equal;
6141 } else if (String::Equals(type_name, factory()->object_string())) {
6142 __ JumpIfSmi(input, false_label, false_distance);
6143 __ cmp(input, factory()->null_value());
6144 __ j(equal, true_label, true_distance);
6145 __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
6146 __ j(below, false_label, false_distance);
6147 __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
6148 __ j(above, false_label, false_distance);
6149 // Check for undetectable objects => false.
6150 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6151 1 << Map::kIsUndetectable);
6152 final_branch_condition = zero;
6154 } else if (String::Equals(type_name, factory()->float32x4_string())) {
6155 __ JumpIfSmi(input, false_label, false_distance);
6156 __ CmpObjectType(input, FLOAT32X4_TYPE, input);
6157 final_branch_condition = equal;
6160 __ jmp(false_label, false_distance);
6162 return final_branch_condition;
6166 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
6167 Register temp = ToRegister(instr->temp());
6169 EmitIsConstructCall(temp);
6170 EmitBranch(instr, equal);
6174 void LCodeGen::EmitIsConstructCall(Register temp) {
6175 // Get the frame pointer for the calling frame.
6176 __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
6178 // Skip the arguments adaptor frame if it exists.
6179 Label check_frame_marker;
6180 __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
6181 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
6182 __ j(not_equal, &check_frame_marker, Label::kNear);
6183 __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
6185 // Check the marker in the calling frame.
6186 __ bind(&check_frame_marker);
6187 __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
6188 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
6192 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
6193 if (!info()->IsStub()) {
6194 // Ensure that we have enough space after the previous lazy-bailout
6195 // instruction for patching the code here.
6196 int current_pc = masm()->pc_offset();
6197 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
6198 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
6199 __ Nop(padding_size);
6202 last_lazy_deopt_pc_ = masm()->pc_offset();
6206 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
6207 last_lazy_deopt_pc_ = masm()->pc_offset();
6208 DCHECK(instr->HasEnvironment());
6209 LEnvironment* env = instr->environment();
6210 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6211 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6215 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
6216 Deoptimizer::BailoutType type = instr->hydrogen()->type();
6217 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
6218 // needed return address), even though the implementation of LAZY and EAGER is
6219 // now identical. When LAZY is eventually completely folded into EAGER, remove
6220 // the special case below.
6221 if (info()->IsStub() && type == Deoptimizer::EAGER) {
6222 type = Deoptimizer::LAZY;
6224 DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
6228 void LCodeGen::DoDummy(LDummy* instr) {
6229 // Nothing to see here, move on!
6233 void LCodeGen::DoDummyUse(LDummyUse* instr) {
6234 // Nothing to see here, move on!
6238 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
6239 PushSafepointRegistersScope scope(this);
6240 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
6241 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
6242 RecordSafepointWithLazyDeopt(
6243 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
6244 DCHECK(instr->HasEnvironment());
6245 LEnvironment* env = instr->environment();
6246 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6250 void LCodeGen::DoStackCheck(LStackCheck* instr) {
6251 class DeferredStackCheck final : public LDeferredCode {
6253 DeferredStackCheck(LCodeGen* codegen,
6255 const X87Stack& x87_stack)
6256 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
6257 void Generate() override { codegen()->DoDeferredStackCheck(instr_); }
6258 LInstruction* instr() override { return instr_; }
6261 LStackCheck* instr_;
6264 DCHECK(instr->HasEnvironment());
6265 LEnvironment* env = instr->environment();
6266 // There is no LLazyBailout instruction for stack-checks. We have to
6267 // prepare for lazy deoptimization explicitly here.
6268 if (instr->hydrogen()->is_function_entry()) {
6269 // Perform stack overflow check.
6271 ExternalReference stack_limit =
6272 ExternalReference::address_of_stack_limit(isolate());
6273 __ cmp(esp, Operand::StaticVariable(stack_limit));
6274 __ j(above_equal, &done, Label::kNear);
6276 DCHECK(instr->context()->IsRegister());
6277 DCHECK(ToRegister(instr->context()).is(esi));
6278 CallCode(isolate()->builtins()->StackCheck(),
6279 RelocInfo::CODE_TARGET,
6283 DCHECK(instr->hydrogen()->is_backwards_branch());
6284 // Perform stack overflow check if this goto needs it before jumping.
6285 DeferredStackCheck* deferred_stack_check =
6286 new(zone()) DeferredStackCheck(this, instr, x87_stack_);
6287 ExternalReference stack_limit =
6288 ExternalReference::address_of_stack_limit(isolate());
6289 __ cmp(esp, Operand::StaticVariable(stack_limit));
6290 __ j(below, deferred_stack_check->entry());
6291 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
6292 __ bind(instr->done_label());
6293 deferred_stack_check->SetExit(instr->done_label());
6294 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6295 // Don't record a deoptimization index for the safepoint here.
6296 // This will be done explicitly when emitting call and the safepoint in
6297 // the deferred code.
6302 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
6303 // This is a pseudo-instruction that ensures that the environment here is
6304 // properly registered for deoptimization and records the assembler's PC
6306 LEnvironment* environment = instr->environment();
6308 // If the environment were already registered, we would have no way of
6309 // backpatching it with the spill slot operands.
6310 DCHECK(!environment->HasBeenRegistered());
6311 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
6313 GenerateOsrPrologue();
6317 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
6318 DCHECK(ToRegister(instr->context()).is(esi));
6319 __ test(eax, Immediate(kSmiTagMask));
6320 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
6322 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
6323 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
6324 DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
6326 Label use_cache, call_runtime;
6327 __ CheckEnumCache(&call_runtime);
6329 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
6330 __ jmp(&use_cache, Label::kNear);
6332 // Get the set of properties to enumerate.
6333 __ bind(&call_runtime);
6335 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
6337 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
6338 isolate()->factory()->meta_map());
6339 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
6340 __ bind(&use_cache);
6344 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
6345 Register map = ToRegister(instr->map());
6346 Register result = ToRegister(instr->result());
6347 Label load_cache, done;
6348 __ EnumLength(result, map);
6349 __ cmp(result, Immediate(Smi::FromInt(0)));
6350 __ j(not_equal, &load_cache, Label::kNear);
6351 __ mov(result, isolate()->factory()->empty_fixed_array());
6352 __ jmp(&done, Label::kNear);
6354 __ bind(&load_cache);
6355 __ LoadInstanceDescriptors(map, result);
6357 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
6359 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
6361 __ test(result, result);
6362 DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
6366 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
6367 Register object = ToRegister(instr->value());
6368 __ cmp(ToRegister(instr->map()),
6369 FieldOperand(object, HeapObject::kMapOffset));
6370 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
6374 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
6377 PushSafepointRegistersScope scope(this);
6381 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
6382 RecordSafepointWithRegisters(
6383 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
6384 __ StoreToSafepointRegisterSlot(object, eax);
6388 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
6389 class DeferredLoadMutableDouble final : public LDeferredCode {
6391 DeferredLoadMutableDouble(LCodeGen* codegen,
6392 LLoadFieldByIndex* instr,
6395 const X87Stack& x87_stack)
6396 : LDeferredCode(codegen, x87_stack),
6401 void Generate() override {
6402 codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
6404 LInstruction* instr() override { return instr_; }
6407 LLoadFieldByIndex* instr_;
6412 Register object = ToRegister(instr->object());
6413 Register index = ToRegister(instr->index());
6415 DeferredLoadMutableDouble* deferred;
6416 deferred = new(zone()) DeferredLoadMutableDouble(
6417 this, instr, object, index, x87_stack_);
6419 Label out_of_object, done;
6420 __ test(index, Immediate(Smi::FromInt(1)));
6421 __ j(not_zero, deferred->entry());
6425 __ cmp(index, Immediate(0));
6426 __ j(less, &out_of_object, Label::kNear);
6427 __ mov(object, FieldOperand(object,
6429 times_half_pointer_size,
6430 JSObject::kHeaderSize));
6431 __ jmp(&done, Label::kNear);
6433 __ bind(&out_of_object);
6434 __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
6436 // Index is now equal to out of object property index plus 1.
6437 __ mov(object, FieldOperand(object,
6439 times_half_pointer_size,
6440 FixedArray::kHeaderSize - kPointerSize));
6441 __ bind(deferred->exit());
6446 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
6447 Register context = ToRegister(instr->context());
6448 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
6452 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
6453 Handle<ScopeInfo> scope_info = instr->scope_info();
6454 __ Push(scope_info);
6455 __ push(ToRegister(instr->function()));
6456 CallRuntime(Runtime::kPushBlockContext, 2, instr);
6457 RecordSafepoint(Safepoint::kNoLazyDeopt);
6463 } // namespace internal
6466 #endif // V8_TARGET_ARCH_X87