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 int32_t value = constant->Integer32Value();
811 if (r.IsInteger32()) return value;
812 DCHECK(r.IsSmiOrTagged());
813 return reinterpret_cast<int32_t>(Smi::FromInt(value));
817 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
818 HConstant* constant = chunk_->LookupConstant(op);
819 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
820 return constant->handle(isolate());
824 double LCodeGen::ToDouble(LConstantOperand* op) const {
825 HConstant* constant = chunk_->LookupConstant(op);
826 DCHECK(constant->HasDoubleValue());
827 return constant->DoubleValue();
831 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
832 HConstant* constant = chunk_->LookupConstant(op);
833 DCHECK(constant->HasExternalReferenceValue());
834 return constant->ExternalReferenceValue();
838 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
839 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
843 bool LCodeGen::IsSmi(LConstantOperand* op) const {
844 return chunk_->LookupLiteralRepresentation(op).IsSmi();
848 static int ArgumentsOffsetWithoutFrame(int index) {
850 return -(index + 1) * kPointerSize + kPCOnStackSize;
854 Operand LCodeGen::ToOperand(LOperand* op) const {
855 if (op->IsRegister()) return Operand(ToRegister(op));
856 DCHECK(!op->IsDoubleRegister());
857 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
858 if (NeedsEagerFrame()) {
859 return Operand(ebp, StackSlotOffset(op->index()));
861 // Retrieve parameter without eager stack-frame relative to the
863 return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
868 Operand LCodeGen::HighOperand(LOperand* op) {
869 DCHECK(op->IsDoubleStackSlot());
870 if (NeedsEagerFrame()) {
871 return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
873 // Retrieve parameter without eager stack-frame relative to the
876 esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
881 void LCodeGen::WriteTranslation(LEnvironment* environment,
882 Translation* translation) {
883 if (environment == NULL) return;
885 // The translation includes one command per value in the environment.
886 int translation_size = environment->translation_size();
887 // The output frame height does not include the parameters.
888 int height = translation_size - environment->parameter_count();
890 WriteTranslation(environment->outer(), translation);
891 bool has_closure_id = !info()->closure().is_null() &&
892 !info()->closure().is_identical_to(environment->closure());
893 int closure_id = has_closure_id
894 ? DefineDeoptimizationLiteral(environment->closure())
895 : Translation::kSelfLiteralId;
896 switch (environment->frame_type()) {
898 translation->BeginJSFrame(environment->ast_id(), closure_id, height);
901 translation->BeginConstructStubFrame(closure_id, translation_size);
904 DCHECK(translation_size == 1);
906 translation->BeginGetterStubFrame(closure_id);
909 DCHECK(translation_size == 2);
911 translation->BeginSetterStubFrame(closure_id);
913 case ARGUMENTS_ADAPTOR:
914 translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
917 translation->BeginCompiledStubFrame(translation_size);
923 int object_index = 0;
924 int dematerialized_index = 0;
925 for (int i = 0; i < translation_size; ++i) {
926 LOperand* value = environment->values()->at(i);
927 AddToTranslation(environment,
930 environment->HasTaggedValueAt(i),
931 environment->HasUint32ValueAt(i),
933 &dematerialized_index);
938 void LCodeGen::AddToTranslation(LEnvironment* environment,
939 Translation* translation,
943 int* object_index_pointer,
944 int* dematerialized_index_pointer) {
945 if (op == LEnvironment::materialization_marker()) {
946 int object_index = (*object_index_pointer)++;
947 if (environment->ObjectIsDuplicateAt(object_index)) {
948 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
949 translation->DuplicateObject(dupe_of);
952 int object_length = environment->ObjectLengthAt(object_index);
953 if (environment->ObjectIsArgumentsAt(object_index)) {
954 translation->BeginArgumentsObject(object_length);
956 translation->BeginCapturedObject(object_length);
958 int dematerialized_index = *dematerialized_index_pointer;
959 int env_offset = environment->translation_size() + dematerialized_index;
960 *dematerialized_index_pointer += object_length;
961 for (int i = 0; i < object_length; ++i) {
962 LOperand* value = environment->values()->at(env_offset + i);
963 AddToTranslation(environment,
966 environment->HasTaggedValueAt(env_offset + i),
967 environment->HasUint32ValueAt(env_offset + i),
968 object_index_pointer,
969 dematerialized_index_pointer);
974 if (op->IsStackSlot()) {
976 translation->StoreStackSlot(op->index());
977 } else if (is_uint32) {
978 translation->StoreUint32StackSlot(op->index());
980 translation->StoreInt32StackSlot(op->index());
982 } else if (op->IsDoubleStackSlot()) {
983 translation->StoreDoubleStackSlot(op->index());
984 } else if (op->IsRegister()) {
985 Register reg = ToRegister(op);
987 translation->StoreRegister(reg);
988 } else if (is_uint32) {
989 translation->StoreUint32Register(reg);
991 translation->StoreInt32Register(reg);
993 } else if (op->IsDoubleRegister()) {
994 X87Register reg = ToX87Register(op);
995 translation->StoreDoubleRegister(reg);
996 } else if (op->IsConstantOperand()) {
997 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
998 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
999 translation->StoreLiteral(src_index);
1006 void LCodeGen::CallCodeGeneric(Handle<Code> code,
1007 RelocInfo::Mode mode,
1008 LInstruction* instr,
1009 SafepointMode safepoint_mode) {
1010 DCHECK(instr != NULL);
1011 __ call(code, mode);
1012 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
1014 // Signal that we don't inline smi code before these stubs in the
1015 // optimizing code generator.
1016 if (code->kind() == Code::BINARY_OP_IC ||
1017 code->kind() == Code::COMPARE_IC) {
1023 void LCodeGen::CallCode(Handle<Code> code,
1024 RelocInfo::Mode mode,
1025 LInstruction* instr) {
1026 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
1030 void LCodeGen::CallRuntime(const Runtime::Function* fun, int argc,
1031 LInstruction* instr, SaveFPRegsMode save_doubles) {
1032 DCHECK(instr != NULL);
1033 DCHECK(instr->HasPointerMap());
1035 __ CallRuntime(fun, argc, save_doubles);
1037 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
1039 DCHECK(info()->is_calling());
1043 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
1044 if (context->IsRegister()) {
1045 if (!ToRegister(context).is(esi)) {
1046 __ mov(esi, ToRegister(context));
1048 } else if (context->IsStackSlot()) {
1049 __ mov(esi, ToOperand(context));
1050 } else if (context->IsConstantOperand()) {
1051 HConstant* constant =
1052 chunk_->LookupConstant(LConstantOperand::cast(context));
1053 __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
1059 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
1061 LInstruction* instr,
1062 LOperand* context) {
1063 LoadContextFromDeferred(context);
1065 __ CallRuntimeSaveDoubles(id);
1066 RecordSafepointWithRegisters(
1067 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
1069 DCHECK(info()->is_calling());
1073 void LCodeGen::RegisterEnvironmentForDeoptimization(
1074 LEnvironment* environment, Safepoint::DeoptMode mode) {
1075 environment->set_has_been_used();
1076 if (!environment->HasBeenRegistered()) {
1077 // Physical stack frame layout:
1078 // -x ............. -4 0 ..................................... y
1079 // [incoming arguments] [spill slots] [pushed outgoing arguments]
1081 // Layout of the environment:
1082 // 0 ..................................................... size-1
1083 // [parameters] [locals] [expression stack including arguments]
1085 // Layout of the translation:
1086 // 0 ........................................................ size - 1 + 4
1087 // [expression stack including arguments] [locals] [4 words] [parameters]
1088 // |>------------ translation_size ------------<|
1090 int frame_count = 0;
1091 int jsframe_count = 0;
1092 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
1094 if (e->frame_type() == JS_FUNCTION) {
1098 Translation translation(&translations_, frame_count, jsframe_count, zone());
1099 WriteTranslation(environment, &translation);
1100 int deoptimization_index = deoptimizations_.length();
1101 int pc_offset = masm()->pc_offset();
1102 environment->Register(deoptimization_index,
1103 translation.index(),
1104 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
1105 deoptimizations_.Add(environment, zone());
1110 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1111 Deoptimizer::DeoptReason deopt_reason,
1112 Deoptimizer::BailoutType bailout_type) {
1113 LEnvironment* environment = instr->environment();
1114 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
1115 DCHECK(environment->HasBeenRegistered());
1116 int id = environment->deoptimization_index();
1117 DCHECK(info()->IsOptimizing() || info()->IsStub());
1119 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
1120 if (entry == NULL) {
1121 Abort(kBailoutWasNotPrepared);
1125 if (DeoptEveryNTimes()) {
1126 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
1130 __ mov(eax, Operand::StaticVariable(count));
1131 __ sub(eax, Immediate(1));
1132 __ j(not_zero, &no_deopt, Label::kNear);
1133 if (FLAG_trap_on_deopt) __ int3();
1134 __ mov(eax, Immediate(FLAG_deopt_every_n_times));
1135 __ mov(Operand::StaticVariable(count), eax);
1138 DCHECK(frame_is_built_);
1139 // Put the x87 stack layout in TOS.
1140 if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1141 __ push(Immediate(x87_stack_.GetLayout()));
1142 __ fild_s(MemOperand(esp, 0));
1143 // Don't touch eflags.
1144 __ lea(esp, Operand(esp, kPointerSize));
1145 __ call(entry, RelocInfo::RUNTIME_ENTRY);
1147 __ mov(Operand::StaticVariable(count), eax);
1152 // Put the x87 stack layout in TOS, so that we can save x87 fp registers in
1153 // the correct location.
1156 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1157 if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1159 int x87_stack_layout = x87_stack_.GetLayout();
1160 __ push(Immediate(x87_stack_layout));
1161 __ fild_s(MemOperand(esp, 0));
1162 // Don't touch eflags.
1163 __ lea(esp, Operand(esp, kPointerSize));
1167 if (info()->ShouldTrapOnDeopt()) {
1169 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1174 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
1176 DCHECK(info()->IsStub() || frame_is_built_);
1177 if (cc == no_condition && frame_is_built_) {
1178 DeoptComment(deopt_info);
1179 __ call(entry, RelocInfo::RUNTIME_ENTRY);
1180 info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
1182 Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
1184 // We often have several deopts to the same entry, reuse the last
1185 // jump entry if this is the case.
1186 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
1187 jump_table_.is_empty() ||
1188 !table_entry.IsEquivalentTo(jump_table_.last())) {
1189 jump_table_.Add(table_entry, zone());
1191 if (cc == no_condition) {
1192 __ jmp(&jump_table_.last().label);
1194 __ j(cc, &jump_table_.last().label);
1200 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1201 Deoptimizer::DeoptReason deopt_reason) {
1202 Deoptimizer::BailoutType bailout_type = info()->IsStub()
1204 : Deoptimizer::EAGER;
1205 DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
1209 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
1210 int length = deoptimizations_.length();
1211 if (length == 0) return;
1212 Handle<DeoptimizationInputData> data =
1213 DeoptimizationInputData::New(isolate(), length, TENURED);
1215 Handle<ByteArray> translations =
1216 translations_.CreateByteArray(isolate()->factory());
1217 data->SetTranslationByteArray(*translations);
1218 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
1219 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
1220 if (info_->IsOptimizing()) {
1221 // Reference to shared function info does not change between phases.
1222 AllowDeferredHandleDereference allow_handle_dereference;
1223 data->SetSharedFunctionInfo(*info_->shared_info());
1225 data->SetSharedFunctionInfo(Smi::FromInt(0));
1227 data->SetWeakCellCache(Smi::FromInt(0));
1229 Handle<FixedArray> literals =
1230 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
1231 { AllowDeferredHandleDereference copy_handles;
1232 for (int i = 0; i < deoptimization_literals_.length(); i++) {
1233 literals->set(i, *deoptimization_literals_[i]);
1235 data->SetLiteralArray(*literals);
1238 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
1239 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
1241 // Populate the deoptimization entries.
1242 for (int i = 0; i < length; i++) {
1243 LEnvironment* env = deoptimizations_[i];
1244 data->SetAstId(i, env->ast_id());
1245 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
1246 data->SetArgumentsStackHeight(i,
1247 Smi::FromInt(env->arguments_stack_height()));
1248 data->SetPc(i, Smi::FromInt(env->pc_offset()));
1250 code->set_deoptimization_data(*data);
1254 int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
1255 int result = deoptimization_literals_.length();
1256 for (int i = 0; i < deoptimization_literals_.length(); ++i) {
1257 if (deoptimization_literals_[i].is_identical_to(literal)) return i;
1259 deoptimization_literals_.Add(literal, zone());
1264 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
1265 DCHECK_EQ(0, deoptimization_literals_.length());
1266 for (auto function : chunk()->inlined_functions()) {
1267 DefineDeoptimizationLiteral(function);
1269 inlined_function_count_ = deoptimization_literals_.length();
1273 void LCodeGen::RecordSafepointWithLazyDeopt(
1274 LInstruction* instr, SafepointMode safepoint_mode) {
1275 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
1276 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
1278 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
1279 RecordSafepointWithRegisters(
1280 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
1285 void LCodeGen::RecordSafepoint(
1286 LPointerMap* pointers,
1287 Safepoint::Kind kind,
1289 Safepoint::DeoptMode deopt_mode) {
1290 DCHECK(kind == expected_safepoint_kind_);
1291 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
1292 Safepoint safepoint =
1293 safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
1294 for (int i = 0; i < operands->length(); i++) {
1295 LOperand* pointer = operands->at(i);
1296 if (pointer->IsStackSlot()) {
1297 safepoint.DefinePointerSlot(pointer->index(), zone());
1298 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
1299 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
1305 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
1306 Safepoint::DeoptMode mode) {
1307 RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
1311 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
1312 LPointerMap empty_pointers(zone());
1313 RecordSafepoint(&empty_pointers, mode);
1317 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
1319 Safepoint::DeoptMode mode) {
1320 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1324 void LCodeGen::RecordAndWritePosition(int position) {
1325 if (position == RelocInfo::kNoPosition) return;
1326 masm()->positions_recorder()->RecordPosition(position);
1327 masm()->positions_recorder()->WriteRecordedPositions();
1331 static const char* LabelType(LLabel* label) {
1332 if (label->is_loop_header()) return " (loop header)";
1333 if (label->is_osr_entry()) return " (OSR entry)";
1338 void LCodeGen::DoLabel(LLabel* label) {
1339 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1340 current_instruction_,
1341 label->hydrogen_value()->id(),
1344 __ bind(label->label());
1345 current_block_ = label->block_id();
1346 if (label->block()->predecessors()->length() > 1) {
1347 // A join block's x87 stack is that of its last visited predecessor.
1348 // If the last visited predecessor block is unreachable, the stack state
1349 // will be wrong. In such case, use the x87 stack of reachable predecessor.
1350 X87StackMap::const_iterator it = x87_stack_map_.find(current_block_);
1351 // Restore x87 stack.
1352 if (it != x87_stack_map_.end()) {
1353 x87_stack_ = *(it->second);
1360 void LCodeGen::DoParallelMove(LParallelMove* move) {
1361 resolver_.Resolve(move);
1365 void LCodeGen::DoGap(LGap* gap) {
1366 for (int i = LGap::FIRST_INNER_POSITION;
1367 i <= LGap::LAST_INNER_POSITION;
1369 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1370 LParallelMove* move = gap->GetParallelMove(inner_pos);
1371 if (move != NULL) DoParallelMove(move);
1376 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1381 void LCodeGen::DoParameter(LParameter* instr) {
1386 void LCodeGen::DoCallStub(LCallStub* instr) {
1387 DCHECK(ToRegister(instr->context()).is(esi));
1388 DCHECK(ToRegister(instr->result()).is(eax));
1389 switch (instr->hydrogen()->major_key()) {
1390 case CodeStub::RegExpExec: {
1391 RegExpExecStub stub(isolate());
1392 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1395 case CodeStub::SubString: {
1396 SubStringStub stub(isolate());
1397 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1400 case CodeStub::StringCompare: {
1401 StringCompareStub stub(isolate());
1402 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1411 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1412 GenerateOsrPrologue();
1416 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1417 Register dividend = ToRegister(instr->dividend());
1418 int32_t divisor = instr->divisor();
1419 DCHECK(dividend.is(ToRegister(instr->result())));
1421 // Theoretically, a variation of the branch-free code for integer division by
1422 // a power of 2 (calculating the remainder via an additional multiplication
1423 // (which gets simplified to an 'and') and subtraction) should be faster, and
1424 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1425 // indicate that positive dividends are heavily favored, so the branching
1426 // version performs better.
1427 HMod* hmod = instr->hydrogen();
1428 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1429 Label dividend_is_not_negative, done;
1430 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1431 __ test(dividend, dividend);
1432 __ j(not_sign, ÷nd_is_not_negative, Label::kNear);
1433 // Note that this is correct even for kMinInt operands.
1435 __ and_(dividend, mask);
1437 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1438 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1440 __ jmp(&done, Label::kNear);
1443 __ bind(÷nd_is_not_negative);
1444 __ and_(dividend, mask);
1449 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1450 Register dividend = ToRegister(instr->dividend());
1451 int32_t divisor = instr->divisor();
1452 DCHECK(ToRegister(instr->result()).is(eax));
1455 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1459 __ TruncatingDiv(dividend, Abs(divisor));
1460 __ imul(edx, edx, Abs(divisor));
1461 __ mov(eax, dividend);
1464 // Check for negative zero.
1465 HMod* hmod = instr->hydrogen();
1466 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1467 Label remainder_not_zero;
1468 __ j(not_zero, &remainder_not_zero, Label::kNear);
1469 __ cmp(dividend, Immediate(0));
1470 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1471 __ bind(&remainder_not_zero);
1476 void LCodeGen::DoModI(LModI* instr) {
1477 HMod* hmod = instr->hydrogen();
1479 Register left_reg = ToRegister(instr->left());
1480 DCHECK(left_reg.is(eax));
1481 Register right_reg = ToRegister(instr->right());
1482 DCHECK(!right_reg.is(eax));
1483 DCHECK(!right_reg.is(edx));
1484 Register result_reg = ToRegister(instr->result());
1485 DCHECK(result_reg.is(edx));
1488 // Check for x % 0, idiv would signal a divide error. We have to
1489 // deopt in this case because we can't return a NaN.
1490 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1491 __ test(right_reg, Operand(right_reg));
1492 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1495 // Check for kMinInt % -1, idiv would signal a divide error. We
1496 // have to deopt if we care about -0, because we can't return that.
1497 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1498 Label no_overflow_possible;
1499 __ cmp(left_reg, kMinInt);
1500 __ j(not_equal, &no_overflow_possible, Label::kNear);
1501 __ cmp(right_reg, -1);
1502 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1503 DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1505 __ j(not_equal, &no_overflow_possible, Label::kNear);
1506 __ Move(result_reg, Immediate(0));
1507 __ jmp(&done, Label::kNear);
1509 __ bind(&no_overflow_possible);
1512 // Sign extend dividend in eax into edx:eax.
1515 // If we care about -0, test if the dividend is <0 and the result is 0.
1516 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1517 Label positive_left;
1518 __ test(left_reg, Operand(left_reg));
1519 __ j(not_sign, &positive_left, Label::kNear);
1521 __ test(result_reg, Operand(result_reg));
1522 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1523 __ jmp(&done, Label::kNear);
1524 __ bind(&positive_left);
1531 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1532 Register dividend = ToRegister(instr->dividend());
1533 int32_t divisor = instr->divisor();
1534 Register result = ToRegister(instr->result());
1535 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1536 DCHECK(!result.is(dividend));
1538 // Check for (0 / -x) that will produce negative zero.
1539 HDiv* hdiv = instr->hydrogen();
1540 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1541 __ test(dividend, dividend);
1542 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1544 // Check for (kMinInt / -1).
1545 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1546 __ cmp(dividend, kMinInt);
1547 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1549 // Deoptimize if remainder will not be 0.
1550 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1551 divisor != 1 && divisor != -1) {
1552 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1553 __ test(dividend, Immediate(mask));
1554 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1556 __ Move(result, dividend);
1557 int32_t shift = WhichPowerOf2Abs(divisor);
1559 // The arithmetic shift is always OK, the 'if' is an optimization only.
1560 if (shift > 1) __ sar(result, 31);
1561 __ shr(result, 32 - shift);
1562 __ add(result, dividend);
1563 __ sar(result, shift);
1565 if (divisor < 0) __ neg(result);
1569 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1570 Register dividend = ToRegister(instr->dividend());
1571 int32_t divisor = instr->divisor();
1572 DCHECK(ToRegister(instr->result()).is(edx));
1575 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1579 // Check for (0 / -x) that will produce negative zero.
1580 HDiv* hdiv = instr->hydrogen();
1581 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1582 __ test(dividend, dividend);
1583 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1586 __ TruncatingDiv(dividend, Abs(divisor));
1587 if (divisor < 0) __ neg(edx);
1589 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1591 __ imul(eax, eax, divisor);
1592 __ sub(eax, dividend);
1593 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1598 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1599 void LCodeGen::DoDivI(LDivI* instr) {
1600 HBinaryOperation* hdiv = instr->hydrogen();
1601 Register dividend = ToRegister(instr->dividend());
1602 Register divisor = ToRegister(instr->divisor());
1603 Register remainder = ToRegister(instr->temp());
1604 DCHECK(dividend.is(eax));
1605 DCHECK(remainder.is(edx));
1606 DCHECK(ToRegister(instr->result()).is(eax));
1607 DCHECK(!divisor.is(eax));
1608 DCHECK(!divisor.is(edx));
1611 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1612 __ test(divisor, divisor);
1613 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1616 // Check for (0 / -x) that will produce negative zero.
1617 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1618 Label dividend_not_zero;
1619 __ test(dividend, dividend);
1620 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1621 __ test(divisor, divisor);
1622 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1623 __ bind(÷nd_not_zero);
1626 // Check for (kMinInt / -1).
1627 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1628 Label dividend_not_min_int;
1629 __ cmp(dividend, kMinInt);
1630 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1631 __ cmp(divisor, -1);
1632 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1633 __ bind(÷nd_not_min_int);
1636 // Sign extend to edx (= remainder).
1640 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1641 // Deoptimize if remainder is not 0.
1642 __ test(remainder, remainder);
1643 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1648 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1649 Register dividend = ToRegister(instr->dividend());
1650 int32_t divisor = instr->divisor();
1651 DCHECK(dividend.is(ToRegister(instr->result())));
1653 // If the divisor is positive, things are easy: There can be no deopts and we
1654 // can simply do an arithmetic right shift.
1655 if (divisor == 1) return;
1656 int32_t shift = WhichPowerOf2Abs(divisor);
1658 __ sar(dividend, shift);
1662 // If the divisor is negative, we have to negate and handle edge cases.
1664 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1665 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1668 // Dividing by -1 is basically negation, unless we overflow.
1669 if (divisor == -1) {
1670 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1671 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1676 // If the negation could not overflow, simply shifting is OK.
1677 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1678 __ sar(dividend, shift);
1682 Label not_kmin_int, done;
1683 __ j(no_overflow, ¬_kmin_int, Label::kNear);
1684 __ mov(dividend, Immediate(kMinInt / divisor));
1685 __ jmp(&done, Label::kNear);
1686 __ bind(¬_kmin_int);
1687 __ sar(dividend, shift);
1692 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1693 Register dividend = ToRegister(instr->dividend());
1694 int32_t divisor = instr->divisor();
1695 DCHECK(ToRegister(instr->result()).is(edx));
1698 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1702 // Check for (0 / -x) that will produce negative zero.
1703 HMathFloorOfDiv* hdiv = instr->hydrogen();
1704 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1705 __ test(dividend, dividend);
1706 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1709 // Easy case: We need no dynamic check for the dividend and the flooring
1710 // division is the same as the truncating division.
1711 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1712 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1713 __ TruncatingDiv(dividend, Abs(divisor));
1714 if (divisor < 0) __ neg(edx);
1718 // In the general case we may need to adjust before and after the truncating
1719 // division to get a flooring division.
1720 Register temp = ToRegister(instr->temp3());
1721 DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1722 Label needs_adjustment, done;
1723 __ cmp(dividend, Immediate(0));
1724 __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1725 __ TruncatingDiv(dividend, Abs(divisor));
1726 if (divisor < 0) __ neg(edx);
1727 __ jmp(&done, Label::kNear);
1728 __ bind(&needs_adjustment);
1729 __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1730 __ TruncatingDiv(temp, Abs(divisor));
1731 if (divisor < 0) __ neg(edx);
1737 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1738 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1739 HBinaryOperation* hdiv = instr->hydrogen();
1740 Register dividend = ToRegister(instr->dividend());
1741 Register divisor = ToRegister(instr->divisor());
1742 Register remainder = ToRegister(instr->temp());
1743 Register result = ToRegister(instr->result());
1744 DCHECK(dividend.is(eax));
1745 DCHECK(remainder.is(edx));
1746 DCHECK(result.is(eax));
1747 DCHECK(!divisor.is(eax));
1748 DCHECK(!divisor.is(edx));
1751 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1752 __ test(divisor, divisor);
1753 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1756 // Check for (0 / -x) that will produce negative zero.
1757 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1758 Label dividend_not_zero;
1759 __ test(dividend, dividend);
1760 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1761 __ test(divisor, divisor);
1762 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1763 __ bind(÷nd_not_zero);
1766 // Check for (kMinInt / -1).
1767 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1768 Label dividend_not_min_int;
1769 __ cmp(dividend, kMinInt);
1770 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1771 __ cmp(divisor, -1);
1772 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1773 __ bind(÷nd_not_min_int);
1776 // Sign extend to edx (= remainder).
1781 __ test(remainder, remainder);
1782 __ j(zero, &done, Label::kNear);
1783 __ xor_(remainder, divisor);
1784 __ sar(remainder, 31);
1785 __ add(result, remainder);
1790 void LCodeGen::DoMulI(LMulI* instr) {
1791 Register left = ToRegister(instr->left());
1792 LOperand* right = instr->right();
1794 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1795 __ mov(ToRegister(instr->temp()), left);
1798 if (right->IsConstantOperand()) {
1799 // Try strength reductions on the multiplication.
1800 // All replacement instructions are at most as long as the imul
1801 // and have better latency.
1802 int constant = ToInteger32(LConstantOperand::cast(right));
1803 if (constant == -1) {
1805 } else if (constant == 0) {
1806 __ xor_(left, Operand(left));
1807 } else if (constant == 2) {
1808 __ add(left, Operand(left));
1809 } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1810 // If we know that the multiplication can't overflow, it's safe to
1811 // use instructions that don't set the overflow flag for the
1818 __ lea(left, Operand(left, left, times_2, 0));
1824 __ lea(left, Operand(left, left, times_4, 0));
1830 __ lea(left, Operand(left, left, times_8, 0));
1836 __ imul(left, left, constant);
1840 __ imul(left, left, constant);
1843 if (instr->hydrogen()->representation().IsSmi()) {
1846 __ imul(left, ToOperand(right));
1849 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1850 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1853 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1854 // Bail out if the result is supposed to be negative zero.
1856 __ test(left, Operand(left));
1857 __ j(not_zero, &done);
1858 if (right->IsConstantOperand()) {
1859 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1860 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1861 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1862 __ cmp(ToRegister(instr->temp()), Immediate(0));
1863 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1866 // Test the non-zero operand for negative sign.
1867 __ or_(ToRegister(instr->temp()), ToOperand(right));
1868 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1875 void LCodeGen::DoBitI(LBitI* instr) {
1876 LOperand* left = instr->left();
1877 LOperand* right = instr->right();
1878 DCHECK(left->Equals(instr->result()));
1879 DCHECK(left->IsRegister());
1881 if (right->IsConstantOperand()) {
1882 int32_t right_operand =
1883 ToRepresentation(LConstantOperand::cast(right),
1884 instr->hydrogen()->representation());
1885 switch (instr->op()) {
1886 case Token::BIT_AND:
1887 __ and_(ToRegister(left), right_operand);
1890 __ or_(ToRegister(left), right_operand);
1892 case Token::BIT_XOR:
1893 if (right_operand == int32_t(~0)) {
1894 __ not_(ToRegister(left));
1896 __ xor_(ToRegister(left), right_operand);
1904 switch (instr->op()) {
1905 case Token::BIT_AND:
1906 __ and_(ToRegister(left), ToOperand(right));
1909 __ or_(ToRegister(left), ToOperand(right));
1911 case Token::BIT_XOR:
1912 __ xor_(ToRegister(left), ToOperand(right));
1922 void LCodeGen::DoShiftI(LShiftI* instr) {
1923 LOperand* left = instr->left();
1924 LOperand* right = instr->right();
1925 DCHECK(left->Equals(instr->result()));
1926 DCHECK(left->IsRegister());
1927 if (right->IsRegister()) {
1928 DCHECK(ToRegister(right).is(ecx));
1930 switch (instr->op()) {
1932 __ ror_cl(ToRegister(left));
1935 __ sar_cl(ToRegister(left));
1938 __ shr_cl(ToRegister(left));
1939 if (instr->can_deopt()) {
1940 __ test(ToRegister(left), ToRegister(left));
1941 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1945 __ shl_cl(ToRegister(left));
1952 int value = ToInteger32(LConstantOperand::cast(right));
1953 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1954 switch (instr->op()) {
1956 if (shift_count == 0 && instr->can_deopt()) {
1957 __ test(ToRegister(left), ToRegister(left));
1958 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1960 __ ror(ToRegister(left), shift_count);
1964 if (shift_count != 0) {
1965 __ sar(ToRegister(left), shift_count);
1969 if (shift_count != 0) {
1970 __ shr(ToRegister(left), shift_count);
1971 } else if (instr->can_deopt()) {
1972 __ test(ToRegister(left), ToRegister(left));
1973 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1977 if (shift_count != 0) {
1978 if (instr->hydrogen_value()->representation().IsSmi() &&
1979 instr->can_deopt()) {
1980 if (shift_count != 1) {
1981 __ shl(ToRegister(left), shift_count - 1);
1983 __ SmiTag(ToRegister(left));
1984 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1986 __ shl(ToRegister(left), shift_count);
1998 void LCodeGen::DoSubI(LSubI* instr) {
1999 LOperand* left = instr->left();
2000 LOperand* right = instr->right();
2001 DCHECK(left->Equals(instr->result()));
2003 if (right->IsConstantOperand()) {
2004 __ sub(ToOperand(left),
2005 ToImmediate(right, instr->hydrogen()->representation()));
2007 __ sub(ToRegister(left), ToOperand(right));
2009 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
2010 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
2015 void LCodeGen::DoConstantI(LConstantI* instr) {
2016 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
2020 void LCodeGen::DoConstantS(LConstantS* instr) {
2021 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
2025 void LCodeGen::DoConstantD(LConstantD* instr) {
2026 uint64_t const bits = instr->bits();
2027 uint32_t const lower = static_cast<uint32_t>(bits);
2028 uint32_t const upper = static_cast<uint32_t>(bits >> 32);
2029 DCHECK(instr->result()->IsDoubleRegister());
2031 __ push(Immediate(upper));
2032 __ push(Immediate(lower));
2033 X87Register reg = ToX87Register(instr->result());
2034 X87Mov(reg, Operand(esp, 0));
2035 __ add(Operand(esp), Immediate(kDoubleSize));
2039 void LCodeGen::DoConstantE(LConstantE* instr) {
2040 __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
2044 void LCodeGen::DoConstantT(LConstantT* instr) {
2045 Register reg = ToRegister(instr->result());
2046 Handle<Object> object = instr->value(isolate());
2047 AllowDeferredHandleDereference smi_check;
2048 __ LoadObject(reg, object);
2052 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
2053 Register result = ToRegister(instr->result());
2054 Register map = ToRegister(instr->value());
2055 __ EnumLength(result, map);
2059 void LCodeGen::DoDateField(LDateField* instr) {
2060 Register object = ToRegister(instr->date());
2061 Register result = ToRegister(instr->result());
2062 Register scratch = ToRegister(instr->temp());
2063 Smi* index = instr->index();
2064 Label runtime, done;
2065 DCHECK(object.is(result));
2066 DCHECK(object.is(eax));
2068 __ test(object, Immediate(kSmiTagMask));
2069 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2070 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
2071 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotADateObject);
2073 if (index->value() == 0) {
2074 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
2076 if (index->value() < JSDate::kFirstUncachedField) {
2077 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
2078 __ mov(scratch, Operand::StaticVariable(stamp));
2079 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
2080 __ j(not_equal, &runtime, Label::kNear);
2081 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
2082 kPointerSize * index->value()));
2083 __ jmp(&done, Label::kNear);
2086 __ PrepareCallCFunction(2, scratch);
2087 __ mov(Operand(esp, 0), object);
2088 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
2089 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
2095 Operand LCodeGen::BuildSeqStringOperand(Register string,
2097 String::Encoding encoding) {
2098 if (index->IsConstantOperand()) {
2099 int offset = ToRepresentation(LConstantOperand::cast(index),
2100 Representation::Integer32());
2101 if (encoding == String::TWO_BYTE_ENCODING) {
2102 offset *= kUC16Size;
2104 STATIC_ASSERT(kCharSize == 1);
2105 return FieldOperand(string, SeqString::kHeaderSize + offset);
2107 return FieldOperand(
2108 string, ToRegister(index),
2109 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
2110 SeqString::kHeaderSize);
2114 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
2115 String::Encoding encoding = instr->hydrogen()->encoding();
2116 Register result = ToRegister(instr->result());
2117 Register string = ToRegister(instr->string());
2119 if (FLAG_debug_code) {
2121 __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
2122 __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
2124 __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
2125 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2126 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2127 __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
2128 ? one_byte_seq_type : two_byte_seq_type));
2129 __ Check(equal, kUnexpectedStringType);
2133 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2134 if (encoding == String::ONE_BYTE_ENCODING) {
2135 __ movzx_b(result, operand);
2137 __ movzx_w(result, operand);
2142 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
2143 String::Encoding encoding = instr->hydrogen()->encoding();
2144 Register string = ToRegister(instr->string());
2146 if (FLAG_debug_code) {
2147 Register value = ToRegister(instr->value());
2148 Register index = ToRegister(instr->index());
2149 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2150 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2152 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
2153 ? one_byte_seq_type : two_byte_seq_type;
2154 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
2157 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2158 if (instr->value()->IsConstantOperand()) {
2159 int value = ToRepresentation(LConstantOperand::cast(instr->value()),
2160 Representation::Integer32());
2161 DCHECK_LE(0, value);
2162 if (encoding == String::ONE_BYTE_ENCODING) {
2163 DCHECK_LE(value, String::kMaxOneByteCharCode);
2164 __ mov_b(operand, static_cast<int8_t>(value));
2166 DCHECK_LE(value, String::kMaxUtf16CodeUnit);
2167 __ mov_w(operand, static_cast<int16_t>(value));
2170 Register value = ToRegister(instr->value());
2171 if (encoding == String::ONE_BYTE_ENCODING) {
2172 __ mov_b(operand, value);
2174 __ mov_w(operand, value);
2180 void LCodeGen::DoAddI(LAddI* instr) {
2181 LOperand* left = instr->left();
2182 LOperand* right = instr->right();
2184 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
2185 if (right->IsConstantOperand()) {
2186 int32_t offset = ToRepresentation(LConstantOperand::cast(right),
2187 instr->hydrogen()->representation());
2188 __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
2190 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
2191 __ lea(ToRegister(instr->result()), address);
2194 if (right->IsConstantOperand()) {
2195 __ add(ToOperand(left),
2196 ToImmediate(right, instr->hydrogen()->representation()));
2198 __ add(ToRegister(left), ToOperand(right));
2200 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
2201 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
2207 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
2208 LOperand* left = instr->left();
2209 LOperand* right = instr->right();
2210 DCHECK(left->Equals(instr->result()));
2211 HMathMinMax::Operation operation = instr->hydrogen()->operation();
2212 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
2214 Condition condition = (operation == HMathMinMax::kMathMin)
2217 if (right->IsConstantOperand()) {
2218 Operand left_op = ToOperand(left);
2219 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
2220 instr->hydrogen()->representation());
2221 __ cmp(left_op, immediate);
2222 __ j(condition, &return_left, Label::kNear);
2223 __ mov(left_op, immediate);
2225 Register left_reg = ToRegister(left);
2226 Operand right_op = ToOperand(right);
2227 __ cmp(left_reg, right_op);
2228 __ j(condition, &return_left, Label::kNear);
2229 __ mov(left_reg, right_op);
2231 __ bind(&return_left);
2233 DCHECK(instr->hydrogen()->representation().IsDouble());
2234 Label check_nan_left, check_zero, return_left, return_right;
2235 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
2236 X87Register left_reg = ToX87Register(left);
2237 X87Register right_reg = ToX87Register(right);
2239 X87PrepareBinaryOp(left_reg, right_reg, ToX87Register(instr->result()));
2243 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
2244 __ j(equal, &check_zero, Label::kNear); // left == right.
2245 __ j(condition, &return_left, Label::kNear);
2246 __ jmp(&return_right, Label::kNear);
2248 __ bind(&check_zero);
2252 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
2253 // At this point, both left and right are either 0 or -0.
2254 if (operation == HMathMinMax::kMathMin) {
2255 // Push st0 and st1 to stack, then pop them to temp registers and OR them,
2257 Register scratch_reg = ToRegister(instr->temp());
2260 __ sub(esp, Immediate(2 * kPointerSize));
2261 __ fstp_s(MemOperand(esp, 0));
2262 __ fstp_s(MemOperand(esp, kPointerSize));
2263 __ pop(scratch_reg);
2264 __ xor_(MemOperand(esp, 0), scratch_reg);
2265 X87Mov(left_reg, MemOperand(esp, 0), kX87FloatOperand);
2266 __ pop(scratch_reg); // restore esp
2268 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
2272 __ jmp(&return_left, Label::kNear);
2274 __ bind(&check_nan_left);
2277 __ FCmp(); // NaN check.
2278 __ j(parity_even, &return_left, Label::kNear); // left == NaN.
2280 __ bind(&return_right);
2282 X87Mov(left_reg, right_reg);
2284 __ bind(&return_left);
2289 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
2290 X87Register left = ToX87Register(instr->left());
2291 X87Register right = ToX87Register(instr->right());
2292 X87Register result = ToX87Register(instr->result());
2293 if (instr->op() != Token::MOD) {
2294 X87PrepareBinaryOp(left, right, result);
2296 // Set the precision control to double-precision.
2297 __ X87SetFPUCW(0x027F);
2298 switch (instr->op()) {
2312 // Pass two doubles as arguments on the stack.
2313 __ PrepareCallCFunction(4, eax);
2314 X87Mov(Operand(esp, 1 * kDoubleSize), right);
2315 X87Mov(Operand(esp, 0), left);
2317 DCHECK(left.is(result));
2318 X87PrepareToWrite(result);
2320 ExternalReference::mod_two_doubles_operation(isolate()),
2323 // Return value is in st(0) on ia32.
2324 X87CommitWrite(result);
2332 // Restore the default value of control word.
2333 __ X87SetFPUCW(0x037F);
2337 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2338 DCHECK(ToRegister(instr->context()).is(esi));
2339 DCHECK(ToRegister(instr->left()).is(edx));
2340 DCHECK(ToRegister(instr->right()).is(eax));
2341 DCHECK(ToRegister(instr->result()).is(eax));
2343 Handle<Code> code = CodeFactory::BinaryOpIC(
2344 isolate(), instr->op(), instr->language_mode()).code();
2345 CallCode(code, RelocInfo::CODE_TARGET, instr);
2349 template<class InstrType>
2350 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2351 int left_block = instr->TrueDestination(chunk_);
2352 int right_block = instr->FalseDestination(chunk_);
2354 int next_block = GetNextEmittedBlock();
2356 if (right_block == left_block || cc == no_condition) {
2357 EmitGoto(left_block);
2358 } else if (left_block == next_block) {
2359 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2360 } else if (right_block == next_block) {
2361 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2363 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2364 __ jmp(chunk_->GetAssemblyLabel(right_block));
2369 template<class InstrType>
2370 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2371 int false_block = instr->FalseDestination(chunk_);
2372 if (cc == no_condition) {
2373 __ jmp(chunk_->GetAssemblyLabel(false_block));
2375 __ j(cc, chunk_->GetAssemblyLabel(false_block));
2380 void LCodeGen::DoBranch(LBranch* instr) {
2381 Representation r = instr->hydrogen()->value()->representation();
2382 if (r.IsSmiOrInteger32()) {
2383 Register reg = ToRegister(instr->value());
2384 __ test(reg, Operand(reg));
2385 EmitBranch(instr, not_zero);
2386 } else if (r.IsDouble()) {
2387 X87Register reg = ToX87Register(instr->value());
2388 X87LoadForUsage(reg);
2391 EmitBranch(instr, not_zero);
2393 DCHECK(r.IsTagged());
2394 Register reg = ToRegister(instr->value());
2395 HType type = instr->hydrogen()->value()->type();
2396 if (type.IsBoolean()) {
2397 DCHECK(!info()->IsStub());
2398 __ cmp(reg, factory()->true_value());
2399 EmitBranch(instr, equal);
2400 } else if (type.IsSmi()) {
2401 DCHECK(!info()->IsStub());
2402 __ test(reg, Operand(reg));
2403 EmitBranch(instr, not_equal);
2404 } else if (type.IsJSArray()) {
2405 DCHECK(!info()->IsStub());
2406 EmitBranch(instr, no_condition);
2407 } else if (type.IsHeapNumber()) {
2409 } else if (type.IsString()) {
2410 DCHECK(!info()->IsStub());
2411 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2412 EmitBranch(instr, not_equal);
2414 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2415 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2417 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2418 // undefined -> false.
2419 __ cmp(reg, factory()->undefined_value());
2420 __ j(equal, instr->FalseLabel(chunk_));
2422 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2424 __ cmp(reg, factory()->true_value());
2425 __ j(equal, instr->TrueLabel(chunk_));
2427 __ cmp(reg, factory()->false_value());
2428 __ j(equal, instr->FalseLabel(chunk_));
2430 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2432 __ cmp(reg, factory()->null_value());
2433 __ j(equal, instr->FalseLabel(chunk_));
2436 if (expected.Contains(ToBooleanStub::SMI)) {
2437 // Smis: 0 -> false, all other -> true.
2438 __ test(reg, Operand(reg));
2439 __ j(equal, instr->FalseLabel(chunk_));
2440 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2441 } else if (expected.NeedsMap()) {
2442 // If we need a map later and have a Smi -> deopt.
2443 __ test(reg, Immediate(kSmiTagMask));
2444 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2447 Register map = no_reg; // Keep the compiler happy.
2448 if (expected.NeedsMap()) {
2449 map = ToRegister(instr->temp());
2450 DCHECK(!map.is(reg));
2451 __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2453 if (expected.CanBeUndetectable()) {
2454 // Undetectable -> false.
2455 __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2456 1 << Map::kIsUndetectable);
2457 __ j(not_zero, instr->FalseLabel(chunk_));
2461 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2462 // spec object -> true.
2463 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2464 __ j(above_equal, instr->TrueLabel(chunk_));
2467 if (expected.Contains(ToBooleanStub::STRING)) {
2468 // String value -> false iff empty.
2470 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2471 __ j(above_equal, ¬_string, Label::kNear);
2472 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2473 __ j(not_zero, instr->TrueLabel(chunk_));
2474 __ jmp(instr->FalseLabel(chunk_));
2475 __ bind(¬_string);
2478 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2479 // Symbol value -> true.
2480 __ CmpInstanceType(map, SYMBOL_TYPE);
2481 __ j(equal, instr->TrueLabel(chunk_));
2484 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2485 // heap number -> false iff +0, -0, or NaN.
2486 Label not_heap_number;
2487 __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2488 factory()->heap_number_map());
2489 __ j(not_equal, ¬_heap_number, Label::kNear);
2491 __ fld_d(FieldOperand(reg, HeapNumber::kValueOffset));
2493 __ j(zero, instr->FalseLabel(chunk_));
2494 __ jmp(instr->TrueLabel(chunk_));
2495 __ bind(¬_heap_number);
2498 if (!expected.IsGeneric()) {
2499 // We've seen something for the first time -> deopt.
2500 // This can only happen if we are not generic already.
2501 DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2508 void LCodeGen::EmitGoto(int block) {
2509 if (!IsNextEmittedBlock(block)) {
2510 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2515 void LCodeGen::DoClobberDoubles(LClobberDoubles* instr) {
2519 void LCodeGen::DoGoto(LGoto* instr) {
2520 EmitGoto(instr->block_id());
2524 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2525 Condition cond = no_condition;
2528 case Token::EQ_STRICT:
2532 case Token::NE_STRICT:
2536 cond = is_unsigned ? below : less;
2539 cond = is_unsigned ? above : greater;
2542 cond = is_unsigned ? below_equal : less_equal;
2545 cond = is_unsigned ? above_equal : greater_equal;
2548 case Token::INSTANCEOF:
2556 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2557 LOperand* left = instr->left();
2558 LOperand* right = instr->right();
2560 instr->is_double() ||
2561 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2562 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2563 Condition cc = TokenToCondition(instr->op(), is_unsigned);
2565 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2566 // We can statically evaluate the comparison.
2567 double left_val = ToDouble(LConstantOperand::cast(left));
2568 double right_val = ToDouble(LConstantOperand::cast(right));
2569 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2570 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2571 EmitGoto(next_block);
2573 if (instr->is_double()) {
2574 X87LoadForUsage(ToX87Register(right), ToX87Register(left));
2576 // Don't base result on EFLAGS when a NaN is involved. Instead
2577 // jump to the false block.
2578 __ j(parity_even, instr->FalseLabel(chunk_));
2580 if (right->IsConstantOperand()) {
2581 __ cmp(ToOperand(left),
2582 ToImmediate(right, instr->hydrogen()->representation()));
2583 } else if (left->IsConstantOperand()) {
2584 __ cmp(ToOperand(right),
2585 ToImmediate(left, instr->hydrogen()->representation()));
2586 // We commuted the operands, so commute the condition.
2587 cc = CommuteCondition(cc);
2589 __ cmp(ToRegister(left), ToOperand(right));
2592 EmitBranch(instr, cc);
2597 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2598 Register left = ToRegister(instr->left());
2600 if (instr->right()->IsConstantOperand()) {
2601 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2602 __ CmpObject(left, right);
2604 Operand right = ToOperand(instr->right());
2605 __ cmp(left, right);
2607 EmitBranch(instr, equal);
2611 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2612 if (instr->hydrogen()->representation().IsTagged()) {
2613 Register input_reg = ToRegister(instr->object());
2614 __ cmp(input_reg, factory()->the_hole_value());
2615 EmitBranch(instr, equal);
2619 // Put the value to the top of stack
2620 X87Register src = ToX87Register(instr->object());
2621 X87LoadForUsage(src);
2626 __ j(parity_even, &ok, Label::kNear);
2628 EmitFalseBranch(instr, no_condition);
2632 __ sub(esp, Immediate(kDoubleSize));
2633 __ fstp_d(MemOperand(esp, 0));
2635 __ add(esp, Immediate(kDoubleSize));
2636 int offset = sizeof(kHoleNanUpper32);
2637 // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
2638 // so we check the upper with 0xffffffff for hole as a temporary fix.
2639 __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
2640 EmitBranch(instr, equal);
2644 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2645 Representation rep = instr->hydrogen()->value()->representation();
2646 DCHECK(!rep.IsInteger32());
2648 if (rep.IsDouble()) {
2649 X87Register input = ToX87Register(instr->value());
2650 X87LoadForUsage(input);
2652 EmitBranch(instr, equal);
2654 Register value = ToRegister(instr->value());
2655 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2656 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2657 __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2659 EmitFalseBranch(instr, no_overflow);
2660 __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2661 Immediate(0x00000000));
2662 EmitBranch(instr, equal);
2667 Condition LCodeGen::EmitIsObject(Register input,
2669 Label* is_not_object,
2671 __ JumpIfSmi(input, is_not_object);
2673 __ cmp(input, isolate()->factory()->null_value());
2674 __ j(equal, is_object);
2676 __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
2677 // Undetectable objects behave like undefined.
2678 __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
2679 1 << Map::kIsUndetectable);
2680 __ j(not_zero, is_not_object);
2682 __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
2683 __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2684 __ j(below, is_not_object);
2685 __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2690 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2691 Register reg = ToRegister(instr->value());
2692 Register temp = ToRegister(instr->temp());
2694 Condition true_cond = EmitIsObject(
2695 reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2697 EmitBranch(instr, true_cond);
2701 Condition LCodeGen::EmitIsString(Register input,
2703 Label* is_not_string,
2704 SmiCheck check_needed = INLINE_SMI_CHECK) {
2705 if (check_needed == INLINE_SMI_CHECK) {
2706 __ JumpIfSmi(input, is_not_string);
2709 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2715 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2716 Register reg = ToRegister(instr->value());
2717 Register temp = ToRegister(instr->temp());
2719 SmiCheck check_needed =
2720 instr->hydrogen()->value()->type().IsHeapObject()
2721 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2723 Condition true_cond = EmitIsString(
2724 reg, temp, instr->FalseLabel(chunk_), check_needed);
2726 EmitBranch(instr, true_cond);
2730 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2731 Operand input = ToOperand(instr->value());
2733 __ test(input, Immediate(kSmiTagMask));
2734 EmitBranch(instr, zero);
2738 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2739 Register input = ToRegister(instr->value());
2740 Register temp = ToRegister(instr->temp());
2742 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2743 STATIC_ASSERT(kSmiTag == 0);
2744 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2746 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2747 __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2748 1 << Map::kIsUndetectable);
2749 EmitBranch(instr, not_zero);
2753 static Condition ComputeCompareCondition(Token::Value op) {
2755 case Token::EQ_STRICT:
2765 return greater_equal;
2768 return no_condition;
2773 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2774 Token::Value op = instr->op();
2776 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op, SLOPPY).code();
2777 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2779 Condition condition = ComputeCompareCondition(op);
2780 __ test(eax, Operand(eax));
2782 EmitBranch(instr, condition);
2786 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2787 InstanceType from = instr->from();
2788 InstanceType to = instr->to();
2789 if (from == FIRST_TYPE) return to;
2790 DCHECK(from == to || to == LAST_TYPE);
2795 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2796 InstanceType from = instr->from();
2797 InstanceType to = instr->to();
2798 if (from == to) return equal;
2799 if (to == LAST_TYPE) return above_equal;
2800 if (from == FIRST_TYPE) return below_equal;
2806 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2807 Register input = ToRegister(instr->value());
2808 Register temp = ToRegister(instr->temp());
2810 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2811 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2814 __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2815 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2819 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2820 Register input = ToRegister(instr->value());
2821 Register result = ToRegister(instr->result());
2823 __ AssertString(input);
2825 __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2826 __ IndexFromHash(result, result);
2830 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2831 LHasCachedArrayIndexAndBranch* instr) {
2832 Register input = ToRegister(instr->value());
2834 __ test(FieldOperand(input, String::kHashFieldOffset),
2835 Immediate(String::kContainsCachedArrayIndexMask));
2836 EmitBranch(instr, equal);
2840 // Branches to a label or falls through with the answer in the z flag. Trashes
2841 // the temp registers, but not the input.
2842 void LCodeGen::EmitClassOfTest(Label* is_true,
2844 Handle<String>class_name,
2848 DCHECK(!input.is(temp));
2849 DCHECK(!input.is(temp2));
2850 DCHECK(!temp.is(temp2));
2851 __ JumpIfSmi(input, is_false);
2853 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2854 // Assuming the following assertions, we can use the same compares to test
2855 // for both being a function type and being in the object type range.
2856 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2857 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2858 FIRST_SPEC_OBJECT_TYPE + 1);
2859 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2860 LAST_SPEC_OBJECT_TYPE - 1);
2861 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2862 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2863 __ j(below, is_false);
2864 __ j(equal, is_true);
2865 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2866 __ j(equal, is_true);
2868 // Faster code path to avoid two compares: subtract lower bound from the
2869 // actual type and do a signed compare with the width of the type range.
2870 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2871 __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2872 __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2873 __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2874 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2875 __ j(above, is_false);
2878 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2879 // Check if the constructor in the map is a function.
2880 __ GetMapConstructor(temp, temp, temp2);
2881 // Objects with a non-function constructor have class 'Object'.
2882 __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2883 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2884 __ j(not_equal, is_true);
2886 __ j(not_equal, is_false);
2889 // temp now contains the constructor function. Grab the
2890 // instance class name from there.
2891 __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2892 __ mov(temp, FieldOperand(temp,
2893 SharedFunctionInfo::kInstanceClassNameOffset));
2894 // The class name we are testing against is internalized since it's a literal.
2895 // The name in the constructor is internalized because of the way the context
2896 // is booted. This routine isn't expected to work for random API-created
2897 // classes and it doesn't have to because you can't access it with natives
2898 // syntax. Since both sides are internalized it is sufficient to use an
2899 // identity comparison.
2900 __ cmp(temp, class_name);
2901 // End with the answer in the z flag.
2905 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2906 Register input = ToRegister(instr->value());
2907 Register temp = ToRegister(instr->temp());
2908 Register temp2 = ToRegister(instr->temp2());
2910 Handle<String> class_name = instr->hydrogen()->class_name();
2912 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2913 class_name, input, temp, temp2);
2915 EmitBranch(instr, equal);
2919 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2920 Register reg = ToRegister(instr->value());
2921 __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2922 EmitBranch(instr, equal);
2926 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2927 // Object and function are in fixed registers defined by the stub.
2928 DCHECK(ToRegister(instr->context()).is(esi));
2929 InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2930 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2932 Label true_value, done;
2933 __ test(eax, Operand(eax));
2934 __ j(zero, &true_value, Label::kNear);
2935 __ mov(ToRegister(instr->result()), factory()->false_value());
2936 __ jmp(&done, Label::kNear);
2937 __ bind(&true_value);
2938 __ mov(ToRegister(instr->result()), factory()->true_value());
2943 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2944 class DeferredInstanceOfKnownGlobal final : public LDeferredCode {
2946 DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2947 LInstanceOfKnownGlobal* instr,
2948 const X87Stack& x87_stack)
2949 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
2950 void Generate() override {
2951 codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2953 LInstruction* instr() override { return instr_; }
2954 Label* map_check() { return &map_check_; }
2956 LInstanceOfKnownGlobal* instr_;
2960 DeferredInstanceOfKnownGlobal* deferred;
2961 deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr, x87_stack_);
2963 Label done, false_result;
2964 Register object = ToRegister(instr->value());
2965 Register temp = ToRegister(instr->temp());
2967 // A Smi is not an instance of anything.
2968 __ JumpIfSmi(object, &false_result, Label::kNear);
2970 // This is the inlined call site instanceof cache. The two occurences of the
2971 // hole value will be patched to the last map/result pair generated by the
2974 Register map = ToRegister(instr->temp());
2975 __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2976 __ bind(deferred->map_check()); // Label for calculating code patching.
2977 Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2978 __ cmp(map, Operand::ForCell(cache_cell)); // Patched to cached map.
2979 __ j(not_equal, &cache_miss, Label::kNear);
2980 __ mov(eax, factory()->the_hole_value()); // Patched to either true or false.
2981 __ jmp(&done, Label::kNear);
2983 // The inlined call site cache did not match. Check for null and string
2984 // before calling the deferred code.
2985 __ bind(&cache_miss);
2986 // Null is not an instance of anything.
2987 __ cmp(object, factory()->null_value());
2988 __ j(equal, &false_result, Label::kNear);
2990 // String values are not instances of anything.
2991 Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2992 __ j(is_string, &false_result, Label::kNear);
2994 // Go to the deferred code.
2995 __ jmp(deferred->entry());
2997 __ bind(&false_result);
2998 __ mov(ToRegister(instr->result()), factory()->false_value());
3000 // Here result has either true or false. Deferred code also produces true or
3002 __ bind(deferred->exit());
3007 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
3009 PushSafepointRegistersScope scope(this);
3011 InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
3012 flags = static_cast<InstanceofStub::Flags>(
3013 flags | InstanceofStub::kArgsInRegisters);
3014 flags = static_cast<InstanceofStub::Flags>(
3015 flags | InstanceofStub::kCallSiteInlineCheck);
3016 flags = static_cast<InstanceofStub::Flags>(
3017 flags | InstanceofStub::kReturnTrueFalseObject);
3018 InstanceofStub stub(isolate(), flags);
3020 // Get the temp register reserved by the instruction. This needs to be a
3021 // register which is pushed last by PushSafepointRegisters as top of the
3022 // stack is used to pass the offset to the location of the map check to
3024 Register temp = ToRegister(instr->temp());
3025 DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
3026 __ LoadHeapObject(InstanceofStub::right(), instr->function());
3027 static const int kAdditionalDelta = 13;
3028 int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
3029 __ mov(temp, Immediate(delta));
3030 __ StoreToSafepointRegisterSlot(temp, temp);
3031 CallCodeGeneric(stub.GetCode(),
3032 RelocInfo::CODE_TARGET,
3034 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
3035 // Get the deoptimization index of the LLazyBailout-environment that
3036 // corresponds to this instruction.
3037 LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
3038 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
3040 // Put the result value into the eax slot and restore all registers.
3041 __ StoreToSafepointRegisterSlot(eax, eax);
3045 void LCodeGen::DoCmpT(LCmpT* instr) {
3046 Token::Value op = instr->op();
3049 CodeFactory::CompareIC(isolate(), op, instr->language_mode()).code();
3050 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3052 Condition condition = ComputeCompareCondition(op);
3053 Label true_value, done;
3054 __ test(eax, Operand(eax));
3055 __ j(condition, &true_value, Label::kNear);
3056 __ mov(ToRegister(instr->result()), factory()->false_value());
3057 __ jmp(&done, Label::kNear);
3058 __ bind(&true_value);
3059 __ mov(ToRegister(instr->result()), factory()->true_value());
3064 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
3065 int extra_value_count = dynamic_frame_alignment ? 2 : 1;
3067 if (instr->has_constant_parameter_count()) {
3068 int parameter_count = ToInteger32(instr->constant_parameter_count());
3069 if (dynamic_frame_alignment && FLAG_debug_code) {
3071 (parameter_count + extra_value_count) * kPointerSize),
3072 Immediate(kAlignmentZapValue));
3073 __ Assert(equal, kExpectedAlignmentMarker);
3075 __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
3077 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
3078 Register reg = ToRegister(instr->parameter_count());
3079 // The argument count parameter is a smi
3081 Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
3082 if (dynamic_frame_alignment && FLAG_debug_code) {
3083 DCHECK(extra_value_count == 2);
3084 __ cmp(Operand(esp, reg, times_pointer_size,
3085 extra_value_count * kPointerSize),
3086 Immediate(kAlignmentZapValue));
3087 __ Assert(equal, kExpectedAlignmentMarker);
3090 // emit code to restore stack based on instr->parameter_count()
3091 __ pop(return_addr_reg); // save return address
3092 if (dynamic_frame_alignment) {
3093 __ inc(reg); // 1 more for alignment
3095 __ shl(reg, kPointerSizeLog2);
3097 __ jmp(return_addr_reg);
3102 void LCodeGen::DoReturn(LReturn* instr) {
3103 if (FLAG_trace && info()->IsOptimizing()) {
3104 // Preserve the return value on the stack and rely on the runtime call
3105 // to return the value in the same register. We're leaving the code
3106 // managed by the register allocator and tearing down the frame, it's
3107 // safe to write to the context register.
3109 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3110 __ CallRuntime(Runtime::kTraceExit, 1);
3112 if (dynamic_frame_alignment_) {
3113 // Fetch the state of the dynamic frame alignment.
3114 __ mov(edx, Operand(ebp,
3115 JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
3117 int no_frame_start = -1;
3118 if (NeedsEagerFrame()) {
3121 no_frame_start = masm_->pc_offset();
3123 if (dynamic_frame_alignment_) {
3125 __ cmp(edx, Immediate(kNoAlignmentPadding));
3126 __ j(equal, &no_padding, Label::kNear);
3128 EmitReturn(instr, true);
3129 __ bind(&no_padding);
3132 EmitReturn(instr, false);
3133 if (no_frame_start != -1) {
3134 info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
3140 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
3141 Register vector_register = ToRegister(instr->temp_vector());
3142 Register slot_register = LoadWithVectorDescriptor::SlotRegister();
3143 DCHECK(vector_register.is(LoadWithVectorDescriptor::VectorRegister()));
3144 DCHECK(slot_register.is(eax));
3146 AllowDeferredHandleDereference vector_structure_check;
3147 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3148 __ mov(vector_register, vector);
3149 // No need to allocate this register.
3150 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
3151 int index = vector->GetIndex(slot);
3152 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3156 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
3157 DCHECK(ToRegister(instr->context()).is(esi));
3158 DCHECK(ToRegister(instr->global_object())
3159 .is(LoadDescriptor::ReceiverRegister()));
3160 DCHECK(ToRegister(instr->result()).is(eax));
3162 __ mov(LoadDescriptor::NameRegister(), instr->name());
3163 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
3164 ContextualMode mode = instr->for_typeof() ? NOT_CONTEXTUAL : CONTEXTUAL;
3165 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(isolate(), mode,
3166 PREMONOMORPHIC).code();
3167 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3171 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
3172 Register context = ToRegister(instr->context());
3173 Register result = ToRegister(instr->result());
3174 __ mov(result, ContextOperand(context, instr->slot_index()));
3176 if (instr->hydrogen()->RequiresHoleCheck()) {
3177 __ cmp(result, factory()->the_hole_value());
3178 if (instr->hydrogen()->DeoptimizesOnHole()) {
3179 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3182 __ j(not_equal, &is_not_hole, Label::kNear);
3183 __ mov(result, factory()->undefined_value());
3184 __ bind(&is_not_hole);
3190 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
3191 Register context = ToRegister(instr->context());
3192 Register value = ToRegister(instr->value());
3194 Label skip_assignment;
3196 Operand target = ContextOperand(context, instr->slot_index());
3197 if (instr->hydrogen()->RequiresHoleCheck()) {
3198 __ cmp(target, factory()->the_hole_value());
3199 if (instr->hydrogen()->DeoptimizesOnHole()) {
3200 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3202 __ j(not_equal, &skip_assignment, Label::kNear);
3206 __ mov(target, value);
3207 if (instr->hydrogen()->NeedsWriteBarrier()) {
3208 SmiCheck check_needed =
3209 instr->hydrogen()->value()->type().IsHeapObject()
3210 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
3211 Register temp = ToRegister(instr->temp());
3212 int offset = Context::SlotOffset(instr->slot_index());
3213 __ RecordWriteContextSlot(context, offset, value, temp, kSaveFPRegs,
3214 EMIT_REMEMBERED_SET, check_needed);
3217 __ bind(&skip_assignment);
3221 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
3222 HObjectAccess access = instr->hydrogen()->access();
3223 int offset = access.offset();
3225 if (access.IsExternalMemory()) {
3226 Register result = ToRegister(instr->result());
3227 MemOperand operand = instr->object()->IsConstantOperand()
3228 ? MemOperand::StaticVariable(ToExternalReference(
3229 LConstantOperand::cast(instr->object())))
3230 : MemOperand(ToRegister(instr->object()), offset);
3231 __ Load(result, operand, access.representation());
3235 Register object = ToRegister(instr->object());
3236 if (instr->hydrogen()->representation().IsDouble()) {
3237 X87Mov(ToX87Register(instr->result()), FieldOperand(object, offset));
3241 Register result = ToRegister(instr->result());
3242 if (!access.IsInobject()) {
3243 __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
3246 __ Load(result, FieldOperand(object, offset), access.representation());
3250 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
3251 DCHECK(!operand->IsDoubleRegister());
3252 if (operand->IsConstantOperand()) {
3253 Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
3254 AllowDeferredHandleDereference smi_check;
3255 if (object->IsSmi()) {
3256 __ Push(Handle<Smi>::cast(object));
3258 __ PushHeapObject(Handle<HeapObject>::cast(object));
3260 } else if (operand->IsRegister()) {
3261 __ push(ToRegister(operand));
3263 __ push(ToOperand(operand));
3268 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3269 DCHECK(ToRegister(instr->context()).is(esi));
3270 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3271 DCHECK(ToRegister(instr->result()).is(eax));
3273 __ mov(LoadDescriptor::NameRegister(), instr->name());
3274 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3275 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(
3276 isolate(), NOT_CONTEXTUAL,
3277 instr->hydrogen()->initialization_state()).code();
3278 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3282 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3283 Register function = ToRegister(instr->function());
3284 Register temp = ToRegister(instr->temp());
3285 Register result = ToRegister(instr->result());
3287 // Get the prototype or initial map from the function.
3289 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
3291 // Check that the function has a prototype or an initial map.
3292 __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3293 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3295 // If the function does not have an initial map, we're done.
3297 __ CmpObjectType(result, MAP_TYPE, temp);
3298 __ j(not_equal, &done, Label::kNear);
3300 // Get the prototype from the initial map.
3301 __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3308 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3309 Register result = ToRegister(instr->result());
3310 __ LoadRoot(result, instr->index());
3314 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3315 Register arguments = ToRegister(instr->arguments());
3316 Register result = ToRegister(instr->result());
3317 if (instr->length()->IsConstantOperand() &&
3318 instr->index()->IsConstantOperand()) {
3319 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3320 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3321 int index = (const_length - const_index) + 1;
3322 __ mov(result, Operand(arguments, index * kPointerSize));
3324 Register length = ToRegister(instr->length());
3325 Operand index = ToOperand(instr->index());
3326 // There are two words between the frame pointer and the last argument.
3327 // Subtracting from length accounts for one of them add one more.
3328 __ sub(length, index);
3329 __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3334 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3335 ElementsKind elements_kind = instr->elements_kind();
3336 LOperand* key = instr->key();
3337 if (!key->IsConstantOperand() &&
3338 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3340 __ SmiUntag(ToRegister(key));
3342 Operand operand(BuildFastArrayOperand(
3345 instr->hydrogen()->key()->representation(),
3347 instr->base_offset()));
3348 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
3349 elements_kind == FLOAT32_ELEMENTS) {
3350 X87Mov(ToX87Register(instr->result()), operand, kX87FloatOperand);
3351 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
3352 elements_kind == FLOAT64_ELEMENTS) {
3353 X87Mov(ToX87Register(instr->result()), operand);
3355 Register result(ToRegister(instr->result()));
3356 switch (elements_kind) {
3357 case EXTERNAL_INT8_ELEMENTS:
3359 __ movsx_b(result, operand);
3361 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3362 case EXTERNAL_UINT8_ELEMENTS:
3363 case UINT8_ELEMENTS:
3364 case UINT8_CLAMPED_ELEMENTS:
3365 __ movzx_b(result, operand);
3367 case EXTERNAL_INT16_ELEMENTS:
3368 case INT16_ELEMENTS:
3369 __ movsx_w(result, operand);
3371 case EXTERNAL_UINT16_ELEMENTS:
3372 case UINT16_ELEMENTS:
3373 __ movzx_w(result, operand);
3375 case EXTERNAL_INT32_ELEMENTS:
3376 case INT32_ELEMENTS:
3377 __ mov(result, operand);
3379 case EXTERNAL_UINT32_ELEMENTS:
3380 case UINT32_ELEMENTS:
3381 __ mov(result, operand);
3382 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3383 __ test(result, Operand(result));
3384 DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3387 case EXTERNAL_FLOAT32_ELEMENTS:
3388 case EXTERNAL_FLOAT64_ELEMENTS:
3389 case FLOAT32_ELEMENTS:
3390 case FLOAT64_ELEMENTS:
3391 case FAST_SMI_ELEMENTS:
3393 case FAST_DOUBLE_ELEMENTS:
3394 case FAST_HOLEY_SMI_ELEMENTS:
3395 case FAST_HOLEY_ELEMENTS:
3396 case FAST_HOLEY_DOUBLE_ELEMENTS:
3397 case DICTIONARY_ELEMENTS:
3398 case SLOPPY_ARGUMENTS_ELEMENTS:
3406 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3407 if (instr->hydrogen()->RequiresHoleCheck()) {
3408 Operand hole_check_operand = BuildFastArrayOperand(
3409 instr->elements(), instr->key(),
3410 instr->hydrogen()->key()->representation(),
3411 FAST_DOUBLE_ELEMENTS,
3412 instr->base_offset() + sizeof(kHoleNanLower32));
3413 __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3414 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3417 Operand double_load_operand = BuildFastArrayOperand(
3420 instr->hydrogen()->key()->representation(),
3421 FAST_DOUBLE_ELEMENTS,
3422 instr->base_offset());
3423 X87Mov(ToX87Register(instr->result()), double_load_operand);
3427 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3428 Register result = ToRegister(instr->result());
3432 BuildFastArrayOperand(instr->elements(), instr->key(),
3433 instr->hydrogen()->key()->representation(),
3434 FAST_ELEMENTS, instr->base_offset()));
3436 // Check for the hole value.
3437 if (instr->hydrogen()->RequiresHoleCheck()) {
3438 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3439 __ test(result, Immediate(kSmiTagMask));
3440 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3442 __ cmp(result, factory()->the_hole_value());
3443 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3445 } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3446 DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3448 __ cmp(result, factory()->the_hole_value());
3449 __ j(not_equal, &done);
3450 if (info()->IsStub()) {
3451 // A stub can safely convert the hole to undefined only if the array
3452 // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3453 // it needs to bail out.
3454 __ mov(result, isolate()->factory()->array_protector());
3455 __ cmp(FieldOperand(result, PropertyCell::kValueOffset),
3456 Immediate(Smi::FromInt(Isolate::kArrayProtectorValid)));
3457 DeoptimizeIf(not_equal, instr, Deoptimizer::kHole);
3459 __ mov(result, isolate()->factory()->undefined_value());
3465 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3466 if (instr->is_typed_elements()) {
3467 DoLoadKeyedExternalArray(instr);
3468 } else if (instr->hydrogen()->representation().IsDouble()) {
3469 DoLoadKeyedFixedDoubleArray(instr);
3471 DoLoadKeyedFixedArray(instr);
3476 Operand LCodeGen::BuildFastArrayOperand(
3477 LOperand* elements_pointer,
3479 Representation key_representation,
3480 ElementsKind elements_kind,
3481 uint32_t base_offset) {
3482 Register elements_pointer_reg = ToRegister(elements_pointer);
3483 int element_shift_size = ElementsKindToShiftSize(elements_kind);
3484 int shift_size = element_shift_size;
3485 if (key->IsConstantOperand()) {
3486 int constant_value = ToInteger32(LConstantOperand::cast(key));
3487 if (constant_value & 0xF0000000) {
3488 Abort(kArrayIndexConstantValueTooBig);
3490 return Operand(elements_pointer_reg,
3491 ((constant_value) << shift_size)
3494 // Take the tag bit into account while computing the shift size.
3495 if (key_representation.IsSmi() && (shift_size >= 1)) {
3496 shift_size -= kSmiTagSize;
3498 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3499 return Operand(elements_pointer_reg,
3507 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3508 DCHECK(ToRegister(instr->context()).is(esi));
3509 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3510 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3512 if (instr->hydrogen()->HasVectorAndSlot()) {
3513 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3517 CodeFactory::KeyedLoadICInOptimizedCode(
3518 isolate(), instr->hydrogen()->initialization_state()).code();
3519 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3523 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3524 Register result = ToRegister(instr->result());
3526 if (instr->hydrogen()->from_inlined()) {
3527 __ lea(result, Operand(esp, -2 * kPointerSize));
3529 // Check for arguments adapter frame.
3530 Label done, adapted;
3531 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3532 __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3533 __ cmp(Operand(result),
3534 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3535 __ j(equal, &adapted, Label::kNear);
3537 // No arguments adaptor frame.
3538 __ mov(result, Operand(ebp));
3539 __ jmp(&done, Label::kNear);
3541 // Arguments adaptor frame present.
3543 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3545 // Result is the frame pointer for the frame if not adapted and for the real
3546 // frame below the adaptor frame if adapted.
3552 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3553 Operand elem = ToOperand(instr->elements());
3554 Register result = ToRegister(instr->result());
3558 // If no arguments adaptor frame the number of arguments is fixed.
3560 __ mov(result, Immediate(scope()->num_parameters()));
3561 __ j(equal, &done, Label::kNear);
3563 // Arguments adaptor frame present. Get argument length from there.
3564 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3565 __ mov(result, Operand(result,
3566 ArgumentsAdaptorFrameConstants::kLengthOffset));
3567 __ SmiUntag(result);
3569 // Argument length is in result register.
3574 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3575 Register receiver = ToRegister(instr->receiver());
3576 Register function = ToRegister(instr->function());
3578 // If the receiver is null or undefined, we have to pass the global
3579 // object as a receiver to normal functions. Values have to be
3580 // passed unchanged to builtins and strict-mode functions.
3581 Label receiver_ok, global_object;
3582 Register scratch = ToRegister(instr->temp());
3584 if (!instr->hydrogen()->known_function()) {
3585 // Do not transform the receiver to object for strict mode
3588 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3589 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3590 1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3591 __ j(not_equal, &receiver_ok);
3593 // Do not transform the receiver to object for builtins.
3594 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3595 1 << SharedFunctionInfo::kNativeBitWithinByte);
3596 __ j(not_equal, &receiver_ok);
3599 // Normal function. Replace undefined or null with global receiver.
3600 __ cmp(receiver, factory()->null_value());
3601 __ j(equal, &global_object);
3602 __ cmp(receiver, factory()->undefined_value());
3603 __ j(equal, &global_object);
3605 // The receiver should be a JS object.
3606 __ test(receiver, Immediate(kSmiTagMask));
3607 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3608 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3609 DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3611 __ jmp(&receiver_ok, Label::kNear);
3612 __ bind(&global_object);
3613 __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3614 const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3615 __ mov(receiver, Operand(receiver, global_offset));
3616 const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3617 __ mov(receiver, FieldOperand(receiver, proxy_offset));
3618 __ bind(&receiver_ok);
3622 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3623 Register receiver = ToRegister(instr->receiver());
3624 Register function = ToRegister(instr->function());
3625 Register length = ToRegister(instr->length());
3626 Register elements = ToRegister(instr->elements());
3627 DCHECK(receiver.is(eax)); // Used for parameter count.
3628 DCHECK(function.is(edi)); // Required by InvokeFunction.
3629 DCHECK(ToRegister(instr->result()).is(eax));
3631 // Copy the arguments to this function possibly from the
3632 // adaptor frame below it.
3633 const uint32_t kArgumentsLimit = 1 * KB;
3634 __ cmp(length, kArgumentsLimit);
3635 DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3638 __ mov(receiver, length);
3640 // Loop through the arguments pushing them onto the execution
3643 // length is a small non-negative integer, due to the test above.
3644 __ test(length, Operand(length));
3645 __ j(zero, &invoke, Label::kNear);
3647 __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3649 __ j(not_zero, &loop);
3651 // Invoke the function.
3653 DCHECK(instr->HasPointerMap());
3654 LPointerMap* pointers = instr->pointer_map();
3655 SafepointGenerator safepoint_generator(
3656 this, pointers, Safepoint::kLazyDeopt);
3657 ParameterCount actual(eax);
3658 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3662 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3667 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3668 LOperand* argument = instr->value();
3669 EmitPushTaggedOperand(argument);
3673 void LCodeGen::DoDrop(LDrop* instr) {
3674 __ Drop(instr->count());
3678 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3679 Register result = ToRegister(instr->result());
3680 __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3684 void LCodeGen::DoContext(LContext* instr) {
3685 Register result = ToRegister(instr->result());
3686 if (info()->IsOptimizing()) {
3687 __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3689 // If there is no frame, the context must be in esi.
3690 DCHECK(result.is(esi));
3695 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3696 DCHECK(ToRegister(instr->context()).is(esi));
3697 __ push(esi); // The context is the first argument.
3698 __ push(Immediate(instr->hydrogen()->pairs()));
3699 __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3700 CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3704 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3705 int formal_parameter_count, int arity,
3706 LInstruction* instr) {
3707 bool dont_adapt_arguments =
3708 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3709 bool can_invoke_directly =
3710 dont_adapt_arguments || formal_parameter_count == arity;
3712 Register function_reg = edi;
3714 if (can_invoke_directly) {
3716 __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3718 // Set eax to arguments count if adaption is not needed. Assumes that eax
3719 // is available to write to at this point.
3720 if (dont_adapt_arguments) {
3724 // Invoke function directly.
3725 if (function.is_identical_to(info()->closure())) {
3728 __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3730 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3732 // We need to adapt arguments.
3733 LPointerMap* pointers = instr->pointer_map();
3734 SafepointGenerator generator(
3735 this, pointers, Safepoint::kLazyDeopt);
3736 ParameterCount count(arity);
3737 ParameterCount expected(formal_parameter_count);
3738 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3743 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3744 DCHECK(ToRegister(instr->result()).is(eax));
3746 if (instr->hydrogen()->IsTailCall()) {
3747 if (NeedsEagerFrame()) __ leave();
3749 if (instr->target()->IsConstantOperand()) {
3750 LConstantOperand* target = LConstantOperand::cast(instr->target());
3751 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3752 __ jmp(code, RelocInfo::CODE_TARGET);
3754 DCHECK(instr->target()->IsRegister());
3755 Register target = ToRegister(instr->target());
3756 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3760 LPointerMap* pointers = instr->pointer_map();
3761 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3763 if (instr->target()->IsConstantOperand()) {
3764 LConstantOperand* target = LConstantOperand::cast(instr->target());
3765 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3766 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3767 __ call(code, RelocInfo::CODE_TARGET);
3769 DCHECK(instr->target()->IsRegister());
3770 Register target = ToRegister(instr->target());
3771 generator.BeforeCall(__ CallSize(Operand(target)));
3772 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3775 generator.AfterCall();
3780 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3781 DCHECK(ToRegister(instr->function()).is(edi));
3782 DCHECK(ToRegister(instr->result()).is(eax));
3784 if (instr->hydrogen()->pass_argument_count()) {
3785 __ mov(eax, instr->arity());
3789 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3791 bool is_self_call = false;
3792 if (instr->hydrogen()->function()->IsConstant()) {
3793 HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3794 Handle<JSFunction> jsfun =
3795 Handle<JSFunction>::cast(fun_const->handle(isolate()));
3796 is_self_call = jsfun.is_identical_to(info()->closure());
3802 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3805 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3809 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3810 Register input_reg = ToRegister(instr->value());
3811 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3812 factory()->heap_number_map());
3813 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3815 Label slow, allocated, done;
3816 Register tmp = input_reg.is(eax) ? ecx : eax;
3817 Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3819 // Preserve the value of all registers.
3820 PushSafepointRegistersScope scope(this);
3822 __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3823 // Check the sign of the argument. If the argument is positive, just
3824 // return it. We do not need to patch the stack since |input| and
3825 // |result| are the same register and |input| will be restored
3826 // unchanged by popping safepoint registers.
3827 __ test(tmp, Immediate(HeapNumber::kSignMask));
3828 __ j(zero, &done, Label::kNear);
3830 __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3831 __ jmp(&allocated, Label::kNear);
3833 // Slow case: Call the runtime system to do the number allocation.
3835 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3836 instr, instr->context());
3837 // Set the pointer to the new heap number in tmp.
3838 if (!tmp.is(eax)) __ mov(tmp, eax);
3839 // Restore input_reg after call to runtime.
3840 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3842 __ bind(&allocated);
3843 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3844 __ and_(tmp2, ~HeapNumber::kSignMask);
3845 __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3846 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3847 __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3848 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3854 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3855 Register input_reg = ToRegister(instr->value());
3856 __ test(input_reg, Operand(input_reg));
3858 __ j(not_sign, &is_positive, Label::kNear);
3859 __ neg(input_reg); // Sets flags.
3860 DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3861 __ bind(&is_positive);
3865 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3866 // Class for deferred case.
3867 class DeferredMathAbsTaggedHeapNumber final : public LDeferredCode {
3869 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3871 const X87Stack& x87_stack)
3872 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
3873 void Generate() override {
3874 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3876 LInstruction* instr() override { return instr_; }
3882 DCHECK(instr->value()->Equals(instr->result()));
3883 Representation r = instr->hydrogen()->value()->representation();
3886 X87Register value = ToX87Register(instr->value());
3889 } else if (r.IsSmiOrInteger32()) {
3890 EmitIntegerMathAbs(instr);
3891 } else { // Tagged case.
3892 DeferredMathAbsTaggedHeapNumber* deferred =
3893 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr, x87_stack_);
3894 Register input_reg = ToRegister(instr->value());
3896 __ JumpIfNotSmi(input_reg, deferred->entry());
3897 EmitIntegerMathAbs(instr);
3898 __ bind(deferred->exit());
3903 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3904 Register output_reg = ToRegister(instr->result());
3905 X87Register input_reg = ToX87Register(instr->value());
3908 Label not_minus_zero, done;
3909 // Deoptimize on unordered.
3913 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3914 __ j(below, ¬_minus_zero, Label::kNear);
3916 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3917 // Check for negative zero.
3918 __ j(not_equal, ¬_minus_zero, Label::kNear);
3922 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3923 __ Move(output_reg, Immediate(0));
3924 __ jmp(&done, Label::kFar);
3928 // rc=01B, round down.
3929 __ bind(¬_minus_zero);
3931 __ X87SetRC(0x0400);
3932 __ sub(esp, Immediate(kPointerSize));
3933 __ fist_s(Operand(esp, 0));
3936 DeoptimizeIf(equal, instr, Deoptimizer::kOverflow);
3938 __ X87SetRC(0x0000);
3943 void LCodeGen::DoMathRound(LMathRound* instr) {
3944 X87Register input_reg = ToX87Register(instr->value());
3945 Register result = ToRegister(instr->result());
3947 Label below_one_half, below_minus_one_half, done;
3949 ExternalReference one_half = ExternalReference::address_of_one_half();
3950 ExternalReference minus_one_half =
3951 ExternalReference::address_of_minus_one_half();
3953 __ fld_d(Operand::StaticVariable(one_half));
3956 __ j(carry, &below_one_half);
3958 // Use rounds towards zero, since 0.5 <= x, we use floor(0.5 + x)
3960 __ fadd_d(Operand::StaticVariable(one_half));
3961 // rc=11B, round toward zero.
3962 __ X87SetRC(0x0c00);
3963 __ sub(esp, Immediate(kPointerSize));
3964 // Clear exception bits.
3966 __ fistp_s(MemOperand(esp, 0));
3970 DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
3972 // Restore round mode.
3973 __ X87SetRC(0x0000);
3976 __ bind(&below_one_half);
3977 __ fld_d(Operand::StaticVariable(minus_one_half));
3980 __ j(carry, &below_minus_one_half);
3981 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3982 // we can ignore the difference between a result of -0 and +0.
3983 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3984 // If the sign is positive, we return +0.
3987 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3989 __ Move(result, Immediate(0));
3992 __ bind(&below_minus_one_half);
3994 __ fadd_d(Operand::StaticVariable(one_half));
3995 // rc=01B, round down.
3996 __ X87SetRC(0x0400);
3997 __ sub(esp, Immediate(kPointerSize));
3998 // Clear exception bits.
4000 __ fistp_s(MemOperand(esp, 0));
4004 DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
4006 // Restore round mode.
4007 __ X87SetRC(0x0000);
4013 void LCodeGen::DoMathFround(LMathFround* instr) {
4014 X87Register input_reg = ToX87Register(instr->value());
4016 __ sub(esp, Immediate(kPointerSize));
4017 __ fstp_s(MemOperand(esp, 0));
4018 X87Fld(MemOperand(esp, 0), kX87FloatOperand);
4019 __ add(esp, Immediate(kPointerSize));
4023 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
4024 X87Register input = ToX87Register(instr->value());
4025 X87Register result_reg = ToX87Register(instr->result());
4026 Register temp_result = ToRegister(instr->temp1());
4027 Register temp = ToRegister(instr->temp2());
4028 Label slow, done, smi, finish;
4029 DCHECK(result_reg.is(input));
4031 // Store input into Heap number and call runtime function kMathExpRT.
4032 if (FLAG_inline_new) {
4033 __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4034 __ jmp(&done, Label::kNear);
4037 // Slow case: Call the runtime system to do the number allocation.
4040 // TODO(3095996): Put a valid pointer value in the stack slot where the
4041 // result register is stored, as this register is in the pointer map, but
4042 // contains an integer value.
4043 __ Move(temp_result, Immediate(0));
4045 // Preserve the value of all registers.
4046 PushSafepointRegistersScope scope(this);
4048 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4049 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4050 RecordSafepointWithRegisters(
4051 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4052 __ StoreToSafepointRegisterSlot(temp_result, eax);
4055 X87LoadForUsage(input);
4056 __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4059 // Preserve the value of all registers.
4060 PushSafepointRegistersScope scope(this);
4062 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4063 __ push(temp_result);
4064 __ CallRuntimeSaveDoubles(Runtime::kMathSqrt);
4065 RecordSafepointWithRegisters(instr->pointer_map(), 1,
4066 Safepoint::kNoLazyDeopt);
4067 __ StoreToSafepointRegisterSlot(temp_result, eax);
4069 X87PrepareToWrite(result_reg);
4070 // return value of MathExpRT is Smi or Heap Number.
4071 __ JumpIfSmi(temp_result, &smi);
4072 // Heap number(double)
4073 __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4077 __ SmiUntag(temp_result);
4078 __ push(temp_result);
4079 __ fild_s(MemOperand(esp, 0));
4080 __ pop(temp_result);
4082 X87CommitWrite(result_reg);
4086 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
4087 X87Register input_reg = ToX87Register(instr->value());
4088 DCHECK(ToX87Register(instr->result()).is(input_reg));
4090 // Note that according to ECMA-262 15.8.2.13:
4091 // Math.pow(-Infinity, 0.5) == Infinity
4092 // Math.sqrt(-Infinity) == NaN
4094 // Check base for -Infinity. C3 == 0, C2 == 1, C1 == 1 and C0 == 1
4098 __ and_(eax, Immediate(0x4700));
4099 __ cmp(eax, Immediate(0x0700));
4100 __ j(not_equal, &sqrt, Label::kNear);
4101 // If input is -Infinity, return Infinity.
4103 __ jmp(&done, Label::kNear);
4108 __ faddp(); // Convert -0 to +0.
4115 void LCodeGen::DoPower(LPower* instr) {
4116 Representation exponent_type = instr->hydrogen()->right()->representation();
4117 X87Register result = ToX87Register(instr->result());
4118 // Having marked this as a call, we can use any registers.
4119 X87Register base = ToX87Register(instr->left());
4120 ExternalReference one_half = ExternalReference::address_of_one_half();
4122 if (exponent_type.IsSmi()) {
4123 Register exponent = ToRegister(instr->right());
4124 X87LoadForUsage(base);
4125 __ SmiUntag(exponent);
4127 __ fild_s(MemOperand(esp, 0));
4129 } else if (exponent_type.IsTagged()) {
4130 Register exponent = ToRegister(instr->right());
4131 Register temp = exponent.is(ecx) ? eax : ecx;
4132 Label no_deopt, done;
4133 X87LoadForUsage(base);
4134 __ JumpIfSmi(exponent, &no_deopt);
4135 __ CmpObjectType(exponent, HEAP_NUMBER_TYPE, temp);
4136 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4137 // Heap number(double)
4138 __ fld_d(FieldOperand(exponent, HeapNumber::kValueOffset));
4142 __ SmiUntag(exponent);
4144 __ fild_s(MemOperand(esp, 0));
4147 } else if (exponent_type.IsInteger32()) {
4148 Register exponent = ToRegister(instr->right());
4149 X87LoadForUsage(base);
4151 __ fild_s(MemOperand(esp, 0));
4154 DCHECK(exponent_type.IsDouble());
4155 X87Register exponent_double = ToX87Register(instr->right());
4156 X87LoadForUsage(base, exponent_double);
4159 // FP data stack {base, exponent(TOS)}.
4160 // Handle (exponent==+-0.5 && base == -0).
4164 X87Fld(Operand::StaticVariable(one_half), kX87DoubleOperand);
4166 __ j(parity_even, ¬_plus_0, Label::kNear); // NaN.
4167 __ j(not_equal, ¬_plus_0, Label::kNear);
4169 // FP data stack {base, exponent(TOS), zero}.
4171 __ bind(¬_plus_0);
4174 __ PrepareCallCFunction(4, eax);
4175 __ fstp_d(MemOperand(esp, kDoubleSize)); // Exponent value.
4176 __ fstp_d(MemOperand(esp, 0)); // Base value.
4177 X87PrepareToWrite(result);
4178 __ CallCFunction(ExternalReference::power_double_double_function(isolate()),
4180 // Return value is in st(0) on ia32.
4181 X87CommitWrite(result);
4186 void LCodeGen::DoMathLog(LMathLog* instr) {
4187 DCHECK(instr->value()->Equals(instr->result()));
4188 X87Register input_reg = ToX87Register(instr->value());
4191 Label positive, done, zero, nan_result;
4195 __ j(below, &nan_result, Label::kNear);
4196 __ j(equal, &zero, Label::kNear);
4204 __ jmp(&done, Label::kNear);
4206 __ bind(&nan_result);
4207 X87PrepareToWrite(input_reg);
4208 __ push(Immediate(0xffffffff));
4209 __ push(Immediate(0x7fffffff));
4210 __ fld_d(MemOperand(esp, 0));
4211 __ lea(esp, Operand(esp, kDoubleSize));
4212 X87CommitWrite(input_reg);
4213 __ jmp(&done, Label::kNear);
4216 ExternalReference ninf = ExternalReference::address_of_negative_infinity();
4217 X87PrepareToWrite(input_reg);
4218 __ fld_d(Operand::StaticVariable(ninf));
4219 X87CommitWrite(input_reg);
4225 void LCodeGen::DoMathClz32(LMathClz32* instr) {
4226 Register input = ToRegister(instr->value());
4227 Register result = ToRegister(instr->result());
4229 __ Lzcnt(result, input);
4233 void LCodeGen::DoMathExp(LMathExp* instr) {
4234 X87Register input = ToX87Register(instr->value());
4235 X87Register result_reg = ToX87Register(instr->result());
4236 Register temp_result = ToRegister(instr->temp1());
4237 Register temp = ToRegister(instr->temp2());
4238 Label slow, done, smi, finish;
4239 DCHECK(result_reg.is(input));
4241 // Store input into Heap number and call runtime function kMathExpRT.
4242 if (FLAG_inline_new) {
4243 __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4244 __ jmp(&done, Label::kNear);
4247 // Slow case: Call the runtime system to do the number allocation.
4250 // TODO(3095996): Put a valid pointer value in the stack slot where the
4251 // result register is stored, as this register is in the pointer map, but
4252 // contains an integer value.
4253 __ Move(temp_result, Immediate(0));
4255 // Preserve the value of all registers.
4256 PushSafepointRegistersScope scope(this);
4258 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4259 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4260 RecordSafepointWithRegisters(instr->pointer_map(), 0,
4261 Safepoint::kNoLazyDeopt);
4262 __ StoreToSafepointRegisterSlot(temp_result, eax);
4265 X87LoadForUsage(input);
4266 __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4269 // Preserve the value of all registers.
4270 PushSafepointRegistersScope scope(this);
4272 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4273 __ push(temp_result);
4274 __ CallRuntimeSaveDoubles(Runtime::kMathExpRT);
4275 RecordSafepointWithRegisters(instr->pointer_map(), 1,
4276 Safepoint::kNoLazyDeopt);
4277 __ StoreToSafepointRegisterSlot(temp_result, eax);
4279 X87PrepareToWrite(result_reg);
4280 // return value of MathExpRT is Smi or Heap Number.
4281 __ JumpIfSmi(temp_result, &smi);
4282 // Heap number(double)
4283 __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4287 __ SmiUntag(temp_result);
4288 __ push(temp_result);
4289 __ fild_s(MemOperand(esp, 0));
4290 __ pop(temp_result);
4292 X87CommitWrite(result_reg);
4296 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
4297 DCHECK(ToRegister(instr->context()).is(esi));
4298 DCHECK(ToRegister(instr->function()).is(edi));
4299 DCHECK(instr->HasPointerMap());
4301 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
4302 if (known_function.is_null()) {
4303 LPointerMap* pointers = instr->pointer_map();
4304 SafepointGenerator generator(
4305 this, pointers, Safepoint::kLazyDeopt);
4306 ParameterCount count(instr->arity());
4307 __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
4309 CallKnownFunction(known_function,
4310 instr->hydrogen()->formal_parameter_count(),
4311 instr->arity(), instr);
4316 void LCodeGen::DoCallFunction(LCallFunction* instr) {
4317 DCHECK(ToRegister(instr->context()).is(esi));
4318 DCHECK(ToRegister(instr->function()).is(edi));
4319 DCHECK(ToRegister(instr->result()).is(eax));
4321 int arity = instr->arity();
4322 CallFunctionFlags flags = instr->hydrogen()->function_flags();
4323 if (instr->hydrogen()->HasVectorAndSlot()) {
4324 Register slot_register = ToRegister(instr->temp_slot());
4325 Register vector_register = ToRegister(instr->temp_vector());
4326 DCHECK(slot_register.is(edx));
4327 DCHECK(vector_register.is(ebx));
4329 AllowDeferredHandleDereference vector_structure_check;
4330 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
4331 int index = vector->GetIndex(instr->hydrogen()->slot());
4333 __ mov(vector_register, vector);
4334 __ mov(slot_register, Immediate(Smi::FromInt(index)));
4336 CallICState::CallType call_type =
4337 (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
4340 CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
4341 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4343 CallFunctionStub stub(isolate(), arity, flags);
4344 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4349 void LCodeGen::DoCallNew(LCallNew* instr) {
4350 DCHECK(ToRegister(instr->context()).is(esi));
4351 DCHECK(ToRegister(instr->constructor()).is(edi));
4352 DCHECK(ToRegister(instr->result()).is(eax));
4354 // No cell in ebx for construct type feedback in optimized code
4355 __ mov(ebx, isolate()->factory()->undefined_value());
4356 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
4357 __ Move(eax, Immediate(instr->arity()));
4358 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4362 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
4363 DCHECK(ToRegister(instr->context()).is(esi));
4364 DCHECK(ToRegister(instr->constructor()).is(edi));
4365 DCHECK(ToRegister(instr->result()).is(eax));
4367 __ Move(eax, Immediate(instr->arity()));
4368 if (instr->arity() == 1) {
4369 // We only need the allocation site for the case we have a length argument.
4370 // The case may bail out to the runtime, which will determine the correct
4371 // elements kind with the site.
4372 __ mov(ebx, instr->hydrogen()->site());
4374 __ mov(ebx, isolate()->factory()->undefined_value());
4377 ElementsKind kind = instr->hydrogen()->elements_kind();
4378 AllocationSiteOverrideMode override_mode =
4379 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
4380 ? DISABLE_ALLOCATION_SITES
4383 if (instr->arity() == 0) {
4384 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
4385 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4386 } else if (instr->arity() == 1) {
4388 if (IsFastPackedElementsKind(kind)) {
4390 // We might need a change here
4391 // look at the first argument
4392 __ mov(ecx, Operand(esp, 0));
4394 __ j(zero, &packed_case, Label::kNear);
4396 ElementsKind holey_kind = GetHoleyElementsKind(kind);
4397 ArraySingleArgumentConstructorStub stub(isolate(),
4400 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4401 __ jmp(&done, Label::kNear);
4402 __ bind(&packed_case);
4405 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
4406 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4409 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
4410 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4415 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4416 DCHECK(ToRegister(instr->context()).is(esi));
4417 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
4421 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4422 Register function = ToRegister(instr->function());
4423 Register code_object = ToRegister(instr->code_object());
4424 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4425 __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4429 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4430 Register result = ToRegister(instr->result());
4431 Register base = ToRegister(instr->base_object());
4432 if (instr->offset()->IsConstantOperand()) {
4433 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4434 __ lea(result, Operand(base, ToInteger32(offset)));
4436 Register offset = ToRegister(instr->offset());
4437 __ lea(result, Operand(base, offset, times_1, 0));
4442 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4443 Representation representation = instr->hydrogen()->field_representation();
4445 HObjectAccess access = instr->hydrogen()->access();
4446 int offset = access.offset();
4448 if (access.IsExternalMemory()) {
4449 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4450 MemOperand operand = instr->object()->IsConstantOperand()
4451 ? MemOperand::StaticVariable(
4452 ToExternalReference(LConstantOperand::cast(instr->object())))
4453 : MemOperand(ToRegister(instr->object()), offset);
4454 if (instr->value()->IsConstantOperand()) {
4455 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4456 __ mov(operand, Immediate(ToInteger32(operand_value)));
4458 Register value = ToRegister(instr->value());
4459 __ Store(value, operand, representation);
4464 Register object = ToRegister(instr->object());
4465 __ AssertNotSmi(object);
4466 DCHECK(!representation.IsSmi() ||
4467 !instr->value()->IsConstantOperand() ||
4468 IsSmi(LConstantOperand::cast(instr->value())));
4469 if (representation.IsDouble()) {
4470 DCHECK(access.IsInobject());
4471 DCHECK(!instr->hydrogen()->has_transition());
4472 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4473 X87Register value = ToX87Register(instr->value());
4474 X87Mov(FieldOperand(object, offset), value);
4478 if (instr->hydrogen()->has_transition()) {
4479 Handle<Map> transition = instr->hydrogen()->transition_map();
4480 AddDeprecationDependency(transition);
4481 __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4482 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4483 Register temp = ToRegister(instr->temp());
4484 Register temp_map = ToRegister(instr->temp_map());
4485 __ mov(temp_map, transition);
4486 __ mov(FieldOperand(object, HeapObject::kMapOffset), temp_map);
4487 // Update the write barrier for the map field.
4488 __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4493 Register write_register = object;
4494 if (!access.IsInobject()) {
4495 write_register = ToRegister(instr->temp());
4496 __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4499 MemOperand operand = FieldOperand(write_register, offset);
4500 if (instr->value()->IsConstantOperand()) {
4501 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4502 if (operand_value->IsRegister()) {
4503 Register value = ToRegister(operand_value);
4504 __ Store(value, operand, representation);
4505 } else if (representation.IsInteger32()) {
4506 Immediate immediate = ToImmediate(operand_value, representation);
4507 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4508 __ mov(operand, immediate);
4510 Handle<Object> handle_value = ToHandle(operand_value);
4511 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4512 __ mov(operand, handle_value);
4515 Register value = ToRegister(instr->value());
4516 __ Store(value, operand, representation);
4519 if (instr->hydrogen()->NeedsWriteBarrier()) {
4520 Register value = ToRegister(instr->value());
4521 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4522 // Update the write barrier for the object for in-object properties.
4523 __ RecordWriteField(write_register, offset, value, temp, kSaveFPRegs,
4524 EMIT_REMEMBERED_SET,
4525 instr->hydrogen()->SmiCheckForWriteBarrier(),
4526 instr->hydrogen()->PointersToHereCheckForValue());
4531 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4532 DCHECK(ToRegister(instr->context()).is(esi));
4533 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4534 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4536 __ mov(StoreDescriptor::NameRegister(), instr->name());
4538 StoreIC::initialize_stub(isolate(), instr->language_mode(),
4539 instr->hydrogen()->initialization_state());
4540 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4544 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4545 Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4546 if (instr->index()->IsConstantOperand()) {
4547 __ cmp(ToOperand(instr->length()),
4548 ToImmediate(LConstantOperand::cast(instr->index()),
4549 instr->hydrogen()->length()->representation()));
4550 cc = CommuteCondition(cc);
4551 } else if (instr->length()->IsConstantOperand()) {
4552 __ cmp(ToOperand(instr->index()),
4553 ToImmediate(LConstantOperand::cast(instr->length()),
4554 instr->hydrogen()->index()->representation()));
4556 __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4558 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4560 __ j(NegateCondition(cc), &done, Label::kNear);
4564 DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4569 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4570 ElementsKind elements_kind = instr->elements_kind();
4571 LOperand* key = instr->key();
4572 if (!key->IsConstantOperand() &&
4573 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4575 __ SmiUntag(ToRegister(key));
4577 Operand operand(BuildFastArrayOperand(
4580 instr->hydrogen()->key()->representation(),
4582 instr->base_offset()));
4583 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
4584 elements_kind == FLOAT32_ELEMENTS) {
4585 X87Mov(operand, ToX87Register(instr->value()), kX87FloatOperand);
4586 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
4587 elements_kind == FLOAT64_ELEMENTS) {
4588 uint64_t int_val = kHoleNanInt64;
4589 int32_t lower = static_cast<int32_t>(int_val);
4590 int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4591 Operand operand2 = BuildFastArrayOperand(
4592 instr->elements(), instr->key(),
4593 instr->hydrogen()->key()->representation(), elements_kind,
4594 instr->base_offset() + kPointerSize);
4596 Label no_special_nan_handling, done;
4597 X87Register value = ToX87Register(instr->value());
4599 __ lea(esp, Operand(esp, -kDoubleSize));
4600 __ fst_d(MemOperand(esp, 0));
4601 __ lea(esp, Operand(esp, kDoubleSize));
4602 int offset = sizeof(kHoleNanUpper32);
4603 // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
4604 // so we check the upper with 0xffffffff for hole as a temporary fix.
4605 __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
4606 __ j(not_equal, &no_special_nan_handling, Label::kNear);
4607 __ mov(operand, Immediate(lower));
4608 __ mov(operand2, Immediate(upper));
4609 __ jmp(&done, Label::kNear);
4611 __ bind(&no_special_nan_handling);
4615 Register value = ToRegister(instr->value());
4616 switch (elements_kind) {
4617 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
4618 case EXTERNAL_UINT8_ELEMENTS:
4619 case EXTERNAL_INT8_ELEMENTS:
4620 case UINT8_ELEMENTS:
4622 case UINT8_CLAMPED_ELEMENTS:
4623 __ mov_b(operand, value);
4625 case EXTERNAL_INT16_ELEMENTS:
4626 case EXTERNAL_UINT16_ELEMENTS:
4627 case UINT16_ELEMENTS:
4628 case INT16_ELEMENTS:
4629 __ mov_w(operand, value);
4631 case EXTERNAL_INT32_ELEMENTS:
4632 case EXTERNAL_UINT32_ELEMENTS:
4633 case UINT32_ELEMENTS:
4634 case INT32_ELEMENTS:
4635 __ mov(operand, value);
4637 case EXTERNAL_FLOAT32_ELEMENTS:
4638 case EXTERNAL_FLOAT64_ELEMENTS:
4639 case FLOAT32_ELEMENTS:
4640 case FLOAT64_ELEMENTS:
4641 case FAST_SMI_ELEMENTS:
4643 case FAST_DOUBLE_ELEMENTS:
4644 case FAST_HOLEY_SMI_ELEMENTS:
4645 case FAST_HOLEY_ELEMENTS:
4646 case FAST_HOLEY_DOUBLE_ELEMENTS:
4647 case DICTIONARY_ELEMENTS:
4648 case SLOPPY_ARGUMENTS_ELEMENTS:
4656 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4657 Operand double_store_operand = BuildFastArrayOperand(
4660 instr->hydrogen()->key()->representation(),
4661 FAST_DOUBLE_ELEMENTS,
4662 instr->base_offset());
4664 uint64_t int_val = kHoleNanInt64;
4665 int32_t lower = static_cast<int32_t>(int_val);
4666 int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4667 Operand double_store_operand2 = BuildFastArrayOperand(
4668 instr->elements(), instr->key(),
4669 instr->hydrogen()->key()->representation(), FAST_DOUBLE_ELEMENTS,
4670 instr->base_offset() + kPointerSize);
4672 if (instr->hydrogen()->IsConstantHoleStore()) {
4673 // This means we should store the (double) hole. No floating point
4674 // registers required.
4675 __ mov(double_store_operand, Immediate(lower));
4676 __ mov(double_store_operand2, Immediate(upper));
4678 Label no_special_nan_handling, done;
4679 X87Register value = ToX87Register(instr->value());
4682 if (instr->NeedsCanonicalization()) {
4686 __ j(parity_odd, &no_special_nan_handling, Label::kNear);
4687 // All NaNs are Canonicalized to 0x7fffffffffffffff
4688 __ mov(double_store_operand, Immediate(0xffffffff));
4689 __ mov(double_store_operand2, Immediate(0x7fffffff));
4690 __ jmp(&done, Label::kNear);
4692 __ lea(esp, Operand(esp, -kDoubleSize));
4693 __ fst_d(MemOperand(esp, 0));
4694 __ lea(esp, Operand(esp, kDoubleSize));
4695 int offset = sizeof(kHoleNanUpper32);
4696 // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
4697 // so we check the upper with 0xffffffff for hole as a temporary fix.
4698 __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
4699 __ j(not_equal, &no_special_nan_handling, Label::kNear);
4700 __ mov(double_store_operand, Immediate(lower));
4701 __ mov(double_store_operand2, Immediate(upper));
4702 __ jmp(&done, Label::kNear);
4704 __ bind(&no_special_nan_handling);
4705 __ fst_d(double_store_operand);
4711 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4712 Register elements = ToRegister(instr->elements());
4713 Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4715 Operand operand = BuildFastArrayOperand(
4718 instr->hydrogen()->key()->representation(),
4720 instr->base_offset());
4721 if (instr->value()->IsRegister()) {
4722 __ mov(operand, ToRegister(instr->value()));
4724 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4725 if (IsSmi(operand_value)) {
4726 Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4727 __ mov(operand, immediate);
4729 DCHECK(!IsInteger32(operand_value));
4730 Handle<Object> handle_value = ToHandle(operand_value);
4731 __ mov(operand, handle_value);
4735 if (instr->hydrogen()->NeedsWriteBarrier()) {
4736 DCHECK(instr->value()->IsRegister());
4737 Register value = ToRegister(instr->value());
4738 DCHECK(!instr->key()->IsConstantOperand());
4739 SmiCheck check_needed =
4740 instr->hydrogen()->value()->type().IsHeapObject()
4741 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4742 // Compute address of modified element and store it into key register.
4743 __ lea(key, operand);
4744 __ RecordWrite(elements, key, value, kSaveFPRegs, EMIT_REMEMBERED_SET,
4746 instr->hydrogen()->PointersToHereCheckForValue());
4751 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4752 // By cases...external, fast-double, fast
4753 if (instr->is_typed_elements()) {
4754 DoStoreKeyedExternalArray(instr);
4755 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4756 DoStoreKeyedFixedDoubleArray(instr);
4758 DoStoreKeyedFixedArray(instr);
4763 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4764 DCHECK(ToRegister(instr->context()).is(esi));
4765 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4766 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4767 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4769 Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4770 isolate(), instr->language_mode(),
4771 instr->hydrogen()->initialization_state()).code();
4772 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4776 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4777 Register object = ToRegister(instr->object());
4778 Register temp = ToRegister(instr->temp());
4779 Label no_memento_found;
4780 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4781 DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4782 __ bind(&no_memento_found);
4786 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
4787 class DeferredMaybeGrowElements final : public LDeferredCode {
4789 DeferredMaybeGrowElements(LCodeGen* codegen,
4790 LMaybeGrowElements* instr,
4791 const X87Stack& x87_stack)
4792 : LDeferredCode(codegen, x87_stack), instr_(instr) {}
4793 void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
4794 LInstruction* instr() override { return instr_; }
4797 LMaybeGrowElements* instr_;
4800 Register result = eax;
4801 DeferredMaybeGrowElements* deferred =
4802 new (zone()) DeferredMaybeGrowElements(this, instr, x87_stack_);
4803 LOperand* key = instr->key();
4804 LOperand* current_capacity = instr->current_capacity();
4806 DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
4807 DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
4808 DCHECK(key->IsConstantOperand() || key->IsRegister());
4809 DCHECK(current_capacity->IsConstantOperand() ||
4810 current_capacity->IsRegister());
4812 if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
4813 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4814 int32_t constant_capacity =
4815 ToInteger32(LConstantOperand::cast(current_capacity));
4816 if (constant_key >= constant_capacity) {
4818 __ jmp(deferred->entry());
4820 } else if (key->IsConstantOperand()) {
4821 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4822 __ cmp(ToOperand(current_capacity), Immediate(constant_key));
4823 __ j(less_equal, deferred->entry());
4824 } else if (current_capacity->IsConstantOperand()) {
4825 int32_t constant_capacity =
4826 ToInteger32(LConstantOperand::cast(current_capacity));
4827 __ cmp(ToRegister(key), Immediate(constant_capacity));
4828 __ j(greater_equal, deferred->entry());
4830 __ cmp(ToRegister(key), ToRegister(current_capacity));
4831 __ j(greater_equal, deferred->entry());
4834 __ mov(result, ToOperand(instr->elements()));
4835 __ bind(deferred->exit());
4839 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
4840 // TODO(3095996): Get rid of this. For now, we need to make the
4841 // result register contain a valid pointer because it is already
4842 // contained in the register pointer map.
4843 Register result = eax;
4844 __ Move(result, Immediate(0));
4846 // We have to call a stub.
4848 PushSafepointRegistersScope scope(this);
4849 if (instr->object()->IsRegister()) {
4850 __ Move(result, ToRegister(instr->object()));
4852 __ mov(result, ToOperand(instr->object()));
4855 LOperand* key = instr->key();
4856 if (key->IsConstantOperand()) {
4857 __ mov(ebx, ToImmediate(key, Representation::Smi()));
4859 __ Move(ebx, ToRegister(key));
4863 GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
4864 instr->hydrogen()->kind());
4866 RecordSafepointWithLazyDeopt(
4867 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4868 __ StoreToSafepointRegisterSlot(result, result);
4871 // Deopt on smi, which means the elements array changed to dictionary mode.
4872 __ test(result, Immediate(kSmiTagMask));
4873 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
4877 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4878 Register object_reg = ToRegister(instr->object());
4880 Handle<Map> from_map = instr->original_map();
4881 Handle<Map> to_map = instr->transitioned_map();
4882 ElementsKind from_kind = instr->from_kind();
4883 ElementsKind to_kind = instr->to_kind();
4885 Label not_applicable;
4886 bool is_simple_map_transition =
4887 IsSimpleMapChangeTransition(from_kind, to_kind);
4888 Label::Distance branch_distance =
4889 is_simple_map_transition ? Label::kNear : Label::kFar;
4890 __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4891 __ j(not_equal, ¬_applicable, branch_distance);
4892 if (is_simple_map_transition) {
4893 Register new_map_reg = ToRegister(instr->new_map_temp());
4894 __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4897 DCHECK_NOT_NULL(instr->temp());
4898 __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4899 ToRegister(instr->temp()), kDontSaveFPRegs);
4901 DCHECK(ToRegister(instr->context()).is(esi));
4902 DCHECK(object_reg.is(eax));
4903 PushSafepointRegistersScope scope(this);
4904 __ mov(ebx, to_map);
4905 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4906 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4908 RecordSafepointWithLazyDeopt(instr,
4909 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4911 __ bind(¬_applicable);
4915 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4916 class DeferredStringCharCodeAt final : public LDeferredCode {
4918 DeferredStringCharCodeAt(LCodeGen* codegen,
4919 LStringCharCodeAt* instr,
4920 const X87Stack& x87_stack)
4921 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4922 void Generate() override { codegen()->DoDeferredStringCharCodeAt(instr_); }
4923 LInstruction* instr() override { return instr_; }
4926 LStringCharCodeAt* instr_;
4929 DeferredStringCharCodeAt* deferred =
4930 new(zone()) DeferredStringCharCodeAt(this, instr, x87_stack_);
4932 StringCharLoadGenerator::Generate(masm(),
4934 ToRegister(instr->string()),
4935 ToRegister(instr->index()),
4936 ToRegister(instr->result()),
4938 __ bind(deferred->exit());
4942 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4943 Register string = ToRegister(instr->string());
4944 Register result = ToRegister(instr->result());
4946 // TODO(3095996): Get rid of this. For now, we need to make the
4947 // result register contain a valid pointer because it is already
4948 // contained in the register pointer map.
4949 __ Move(result, Immediate(0));
4951 PushSafepointRegistersScope scope(this);
4953 // Push the index as a smi. This is safe because of the checks in
4954 // DoStringCharCodeAt above.
4955 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4956 if (instr->index()->IsConstantOperand()) {
4957 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4958 Representation::Smi());
4961 Register index = ToRegister(instr->index());
4965 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4966 instr, instr->context());
4969 __ StoreToSafepointRegisterSlot(result, eax);
4973 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4974 class DeferredStringCharFromCode final : public LDeferredCode {
4976 DeferredStringCharFromCode(LCodeGen* codegen,
4977 LStringCharFromCode* instr,
4978 const X87Stack& x87_stack)
4979 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4980 void Generate() override {
4981 codegen()->DoDeferredStringCharFromCode(instr_);
4983 LInstruction* instr() override { return instr_; }
4986 LStringCharFromCode* instr_;
4989 DeferredStringCharFromCode* deferred =
4990 new(zone()) DeferredStringCharFromCode(this, instr, x87_stack_);
4992 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4993 Register char_code = ToRegister(instr->char_code());
4994 Register result = ToRegister(instr->result());
4995 DCHECK(!char_code.is(result));
4997 __ cmp(char_code, String::kMaxOneByteCharCode);
4998 __ j(above, deferred->entry());
4999 __ Move(result, Immediate(factory()->single_character_string_cache()));
5000 __ mov(result, FieldOperand(result,
5001 char_code, times_pointer_size,
5002 FixedArray::kHeaderSize));
5003 __ cmp(result, factory()->undefined_value());
5004 __ j(equal, deferred->entry());
5005 __ bind(deferred->exit());
5009 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
5010 Register char_code = ToRegister(instr->char_code());
5011 Register result = ToRegister(instr->result());
5013 // TODO(3095996): Get rid of this. For now, we need to make the
5014 // result register contain a valid pointer because it is already
5015 // contained in the register pointer map.
5016 __ Move(result, Immediate(0));
5018 PushSafepointRegistersScope scope(this);
5019 __ SmiTag(char_code);
5021 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
5022 __ StoreToSafepointRegisterSlot(result, eax);
5026 void LCodeGen::DoStringAdd(LStringAdd* instr) {
5027 DCHECK(ToRegister(instr->context()).is(esi));
5028 DCHECK(ToRegister(instr->left()).is(edx));
5029 DCHECK(ToRegister(instr->right()).is(eax));
5030 StringAddStub stub(isolate(),
5031 instr->hydrogen()->flags(),
5032 instr->hydrogen()->pretenure_flag());
5033 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5037 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
5038 LOperand* input = instr->value();
5039 LOperand* output = instr->result();
5040 DCHECK(input->IsRegister() || input->IsStackSlot());
5041 DCHECK(output->IsDoubleRegister());
5042 if (input->IsRegister()) {
5043 Register input_reg = ToRegister(input);
5045 X87Mov(ToX87Register(output), Operand(esp, 0), kX87IntOperand);
5048 X87Mov(ToX87Register(output), ToOperand(input), kX87IntOperand);
5053 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
5054 LOperand* input = instr->value();
5055 LOperand* output = instr->result();
5056 X87Register res = ToX87Register(output);
5057 X87PrepareToWrite(res);
5058 __ LoadUint32NoSSE2(ToRegister(input));
5059 X87CommitWrite(res);
5063 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
5064 class DeferredNumberTagI final : public LDeferredCode {
5066 DeferredNumberTagI(LCodeGen* codegen,
5068 const X87Stack& x87_stack)
5069 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5070 void Generate() override {
5071 codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
5074 LInstruction* instr() override { return instr_; }
5077 LNumberTagI* instr_;
5080 LOperand* input = instr->value();
5081 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5082 Register reg = ToRegister(input);
5084 DeferredNumberTagI* deferred =
5085 new(zone()) DeferredNumberTagI(this, instr, x87_stack_);
5087 __ j(overflow, deferred->entry());
5088 __ bind(deferred->exit());
5092 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
5093 class DeferredNumberTagU final : public LDeferredCode {
5095 DeferredNumberTagU(LCodeGen* codegen,
5097 const X87Stack& x87_stack)
5098 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5099 void Generate() override {
5100 codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
5103 LInstruction* instr() override { return instr_; }
5106 LNumberTagU* instr_;
5109 LOperand* input = instr->value();
5110 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5111 Register reg = ToRegister(input);
5113 DeferredNumberTagU* deferred =
5114 new(zone()) DeferredNumberTagU(this, instr, x87_stack_);
5115 __ cmp(reg, Immediate(Smi::kMaxValue));
5116 __ j(above, deferred->entry());
5118 __ bind(deferred->exit());
5122 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
5125 IntegerSignedness signedness) {
5127 Register reg = ToRegister(value);
5128 Register tmp = ToRegister(temp);
5130 if (signedness == SIGNED_INT32) {
5131 // There was overflow, so bits 30 and 31 of the original integer
5132 // disagree. Try to allocate a heap number in new space and store
5133 // the value in there. If that fails, call the runtime system.
5135 __ xor_(reg, 0x80000000);
5137 __ fild_s(Operand(esp, 0));
5140 // There's no fild variant for unsigned values, so zero-extend to a 64-bit
5142 __ push(Immediate(0));
5144 __ fild_d(Operand(esp, 0));
5149 if (FLAG_inline_new) {
5150 __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
5151 __ jmp(&done, Label::kNear);
5154 // Slow case: Call the runtime system to do the number allocation.
5157 // TODO(3095996): Put a valid pointer value in the stack slot where the
5158 // result register is stored, as this register is in the pointer map, but
5159 // contains an integer value.
5160 __ Move(reg, Immediate(0));
5162 // Preserve the value of all registers.
5163 PushSafepointRegistersScope scope(this);
5165 // NumberTagI and NumberTagD use the context from the frame, rather than
5166 // the environment's HContext or HInlinedContext value.
5167 // They only call Runtime::kAllocateHeapNumber.
5168 // The corresponding HChange instructions are added in a phase that does
5169 // not have easy access to the local context.
5170 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5171 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5172 RecordSafepointWithRegisters(
5173 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5174 __ StoreToSafepointRegisterSlot(reg, eax);
5178 __ fstp_d(FieldOperand(reg, HeapNumber::kValueOffset));
5182 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
5183 class DeferredNumberTagD final : public LDeferredCode {
5185 DeferredNumberTagD(LCodeGen* codegen,
5187 const X87Stack& x87_stack)
5188 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5189 void Generate() override { codegen()->DoDeferredNumberTagD(instr_); }
5190 LInstruction* instr() override { return instr_; }
5193 LNumberTagD* instr_;
5196 Register reg = ToRegister(instr->result());
5198 // Put the value to the top of stack
5199 X87Register src = ToX87Register(instr->value());
5200 // Don't use X87LoadForUsage here, which is only used by Instruction which
5201 // clobbers fp registers.
5202 x87_stack_.Fxch(src);
5204 DeferredNumberTagD* deferred =
5205 new(zone()) DeferredNumberTagD(this, instr, x87_stack_);
5206 if (FLAG_inline_new) {
5207 Register tmp = ToRegister(instr->temp());
5208 __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
5210 __ jmp(deferred->entry());
5212 __ bind(deferred->exit());
5213 __ fst_d(FieldOperand(reg, HeapNumber::kValueOffset));
5217 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
5218 // TODO(3095996): Get rid of this. For now, we need to make the
5219 // result register contain a valid pointer because it is already
5220 // contained in the register pointer map.
5221 Register reg = ToRegister(instr->result());
5222 __ Move(reg, Immediate(0));
5224 PushSafepointRegistersScope scope(this);
5225 // NumberTagI and NumberTagD use the context from the frame, rather than
5226 // the environment's HContext or HInlinedContext value.
5227 // They only call Runtime::kAllocateHeapNumber.
5228 // The corresponding HChange instructions are added in a phase that does
5229 // not have easy access to the local context.
5230 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5231 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5232 RecordSafepointWithRegisters(
5233 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5234 __ StoreToSafepointRegisterSlot(reg, eax);
5238 void LCodeGen::DoSmiTag(LSmiTag* instr) {
5239 HChange* hchange = instr->hydrogen();
5240 Register input = ToRegister(instr->value());
5241 if (hchange->CheckFlag(HValue::kCanOverflow) &&
5242 hchange->value()->CheckFlag(HValue::kUint32)) {
5243 __ test(input, Immediate(0xc0000000));
5244 DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
5247 if (hchange->CheckFlag(HValue::kCanOverflow) &&
5248 !hchange->value()->CheckFlag(HValue::kUint32)) {
5249 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5254 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
5255 LOperand* input = instr->value();
5256 Register result = ToRegister(input);
5257 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5258 if (instr->needs_check()) {
5259 __ test(result, Immediate(kSmiTagMask));
5260 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5262 __ AssertSmi(result);
5264 __ SmiUntag(result);
5268 void LCodeGen::EmitNumberUntagDNoSSE2(LNumberUntagD* instr, Register input_reg,
5269 Register temp_reg, X87Register res_reg,
5270 NumberUntagDMode mode) {
5271 bool can_convert_undefined_to_nan =
5272 instr->hydrogen()->can_convert_undefined_to_nan();
5273 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
5275 Label load_smi, done;
5277 X87PrepareToWrite(res_reg);
5278 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
5280 __ JumpIfSmi(input_reg, &load_smi);
5282 // Heap number map check.
5283 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5284 factory()->heap_number_map());
5285 if (!can_convert_undefined_to_nan) {
5286 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5288 Label heap_number, convert;
5289 __ j(equal, &heap_number);
5291 // Convert undefined (or hole) to NaN.
5292 __ cmp(input_reg, factory()->undefined_value());
5293 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5296 __ push(Immediate(0xffffffff));
5297 __ push(Immediate(0x7fffffff));
5298 __ fld_d(MemOperand(esp, 0));
5299 __ lea(esp, Operand(esp, kDoubleSize));
5300 __ jmp(&done, Label::kNear);
5302 __ bind(&heap_number);
5304 // Heap number to x87 conversion.
5305 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5306 if (deoptimize_on_minus_zero) {
5309 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5310 __ j(not_zero, &done, Label::kNear);
5312 // Use general purpose registers to check if we have -0.0
5313 __ mov(temp_reg, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5314 __ test(temp_reg, Immediate(HeapNumber::kSignMask));
5315 __ j(zero, &done, Label::kNear);
5317 // Pop FPU stack before deoptimizing.
5319 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5321 __ jmp(&done, Label::kNear);
5323 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
5327 // Clobbering a temp is faster than re-tagging the
5328 // input register since we avoid dependencies.
5329 __ mov(temp_reg, input_reg);
5330 __ SmiUntag(temp_reg); // Untag smi before converting to float.
5332 __ fild_s(Operand(esp, 0));
5333 __ add(esp, Immediate(kPointerSize));
5335 X87CommitWrite(res_reg);
5339 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
5340 Register input_reg = ToRegister(instr->value());
5342 // The input was optimistically untagged; revert it.
5343 STATIC_ASSERT(kSmiTagSize == 1);
5344 __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
5346 if (instr->truncating()) {
5347 Label no_heap_number, check_bools, check_false;
5349 // Heap number map check.
5350 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5351 factory()->heap_number_map());
5352 __ j(not_equal, &no_heap_number, Label::kNear);
5353 __ TruncateHeapNumberToI(input_reg, input_reg);
5356 __ bind(&no_heap_number);
5357 // Check for Oddballs. Undefined/False is converted to zero and True to one
5358 // for truncating conversions.
5359 __ cmp(input_reg, factory()->undefined_value());
5360 __ j(not_equal, &check_bools, Label::kNear);
5361 __ Move(input_reg, Immediate(0));
5364 __ bind(&check_bools);
5365 __ cmp(input_reg, factory()->true_value());
5366 __ j(not_equal, &check_false, Label::kNear);
5367 __ Move(input_reg, Immediate(1));
5370 __ bind(&check_false);
5371 __ cmp(input_reg, factory()->false_value());
5372 DeoptimizeIf(not_equal, instr,
5373 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
5374 __ Move(input_reg, Immediate(0));
5376 // TODO(olivf) Converting a number on the fpu is actually quite slow. We
5377 // should first try a fast conversion and then bailout to this slow case.
5378 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5379 isolate()->factory()->heap_number_map());
5380 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5382 __ sub(esp, Immediate(kPointerSize));
5383 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5385 if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
5386 Label no_precision_lost, not_nan, zero_check;
5389 __ fist_s(MemOperand(esp, 0));
5390 __ fild_s(MemOperand(esp, 0));
5394 __ j(equal, &no_precision_lost, Label::kNear);
5396 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5397 __ bind(&no_precision_lost);
5399 __ j(parity_odd, ¬_nan);
5401 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5404 __ test(input_reg, Operand(input_reg));
5405 __ j(zero, &zero_check, Label::kNear);
5409 __ bind(&zero_check);
5410 // To check for minus zero, we load the value again as float, and check
5411 // if that is still 0.
5412 __ sub(esp, Immediate(kPointerSize));
5413 __ fstp_s(Operand(esp, 0));
5415 __ test(input_reg, Operand(input_reg));
5416 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5418 __ fist_s(MemOperand(esp, 0));
5419 __ fild_s(MemOperand(esp, 0));
5422 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
5423 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
5429 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
5430 class DeferredTaggedToI final : public LDeferredCode {
5432 DeferredTaggedToI(LCodeGen* codegen,
5434 const X87Stack& x87_stack)
5435 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5436 void Generate() override { codegen()->DoDeferredTaggedToI(instr_, done()); }
5437 LInstruction* instr() override { return instr_; }
5443 LOperand* input = instr->value();
5444 DCHECK(input->IsRegister());
5445 Register input_reg = ToRegister(input);
5446 DCHECK(input_reg.is(ToRegister(instr->result())));
5448 if (instr->hydrogen()->value()->representation().IsSmi()) {
5449 __ SmiUntag(input_reg);
5451 DeferredTaggedToI* deferred =
5452 new(zone()) DeferredTaggedToI(this, instr, x87_stack_);
5453 // Optimistically untag the input.
5454 // If the input is a HeapObject, SmiUntag will set the carry flag.
5455 STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
5456 __ SmiUntag(input_reg);
5457 // Branch to deferred code if the input was tagged.
5458 // The deferred code will take care of restoring the tag.
5459 __ j(carry, deferred->entry());
5460 __ bind(deferred->exit());
5465 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
5466 LOperand* input = instr->value();
5467 DCHECK(input->IsRegister());
5468 LOperand* temp = instr->temp();
5469 DCHECK(temp->IsRegister());
5470 LOperand* result = instr->result();
5471 DCHECK(result->IsDoubleRegister());
5473 Register input_reg = ToRegister(input);
5474 Register temp_reg = ToRegister(temp);
5476 HValue* value = instr->hydrogen()->value();
5477 NumberUntagDMode mode = value->representation().IsSmi()
5478 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
5480 EmitNumberUntagDNoSSE2(instr, input_reg, temp_reg, ToX87Register(result),
5485 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
5486 LOperand* input = instr->value();
5487 DCHECK(input->IsDoubleRegister());
5488 LOperand* result = instr->result();
5489 DCHECK(result->IsRegister());
5490 Register result_reg = ToRegister(result);
5492 if (instr->truncating()) {
5493 X87Register input_reg = ToX87Register(input);
5495 __ TruncateX87TOSToI(result_reg);
5497 Label lost_precision, is_nan, minus_zero, done;
5498 X87Register input_reg = ToX87Register(input);
5500 __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5501 &lost_precision, &is_nan, &minus_zero);
5503 __ bind(&lost_precision);
5504 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5506 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5507 __ bind(&minus_zero);
5508 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5514 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
5515 LOperand* input = instr->value();
5516 DCHECK(input->IsDoubleRegister());
5517 LOperand* result = instr->result();
5518 DCHECK(result->IsRegister());
5519 Register result_reg = ToRegister(result);
5521 Label lost_precision, is_nan, minus_zero, done;
5522 X87Register input_reg = ToX87Register(input);
5524 __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5525 &lost_precision, &is_nan, &minus_zero);
5527 __ bind(&lost_precision);
5528 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5530 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5531 __ bind(&minus_zero);
5532 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5534 __ SmiTag(result_reg);
5535 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5539 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
5540 LOperand* input = instr->value();
5541 __ test(ToOperand(input), Immediate(kSmiTagMask));
5542 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5546 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5547 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
5548 LOperand* input = instr->value();
5549 __ test(ToOperand(input), Immediate(kSmiTagMask));
5550 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5555 void LCodeGen::DoCheckArrayBufferNotNeutered(
5556 LCheckArrayBufferNotNeutered* instr) {
5557 Register view = ToRegister(instr->view());
5558 Register scratch = ToRegister(instr->scratch());
5560 __ mov(scratch, FieldOperand(view, JSArrayBufferView::kBufferOffset));
5561 __ test_b(FieldOperand(scratch, JSArrayBuffer::kBitFieldOffset),
5562 1 << JSArrayBuffer::WasNeutered::kShift);
5563 DeoptimizeIf(not_zero, instr, Deoptimizer::kOutOfBounds);
5567 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
5568 Register input = ToRegister(instr->value());
5569 Register temp = ToRegister(instr->temp());
5571 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
5573 if (instr->hydrogen()->is_interval_check()) {
5576 instr->hydrogen()->GetCheckInterval(&first, &last);
5578 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5579 static_cast<int8_t>(first));
5581 // If there is only one type in the interval check for equality.
5582 if (first == last) {
5583 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5585 DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
5586 // Omit check for the last type.
5587 if (last != LAST_TYPE) {
5588 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5589 static_cast<int8_t>(last));
5590 DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5596 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5598 if (base::bits::IsPowerOfTwo32(mask)) {
5599 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5600 __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5601 DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5602 Deoptimizer::kWrongInstanceType);
5604 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5605 __ and_(temp, mask);
5607 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5613 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5614 Handle<HeapObject> object = instr->hydrogen()->object().handle();
5615 if (instr->hydrogen()->object_in_new_space()) {
5616 Register reg = ToRegister(instr->value());
5617 Handle<Cell> cell = isolate()->factory()->NewCell(object);
5618 __ cmp(reg, Operand::ForCell(cell));
5620 Operand operand = ToOperand(instr->value());
5621 __ cmp(operand, object);
5623 DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5627 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5629 PushSafepointRegistersScope scope(this);
5632 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5633 RecordSafepointWithRegisters(
5634 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5636 __ test(eax, Immediate(kSmiTagMask));
5638 DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5642 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5643 class DeferredCheckMaps final : public LDeferredCode {
5645 DeferredCheckMaps(LCodeGen* codegen,
5648 const X87Stack& x87_stack)
5649 : LDeferredCode(codegen, x87_stack), instr_(instr), object_(object) {
5650 SetExit(check_maps());
5652 void Generate() override {
5653 codegen()->DoDeferredInstanceMigration(instr_, object_);
5655 Label* check_maps() { return &check_maps_; }
5656 LInstruction* instr() override { return instr_; }
5664 if (instr->hydrogen()->IsStabilityCheck()) {
5665 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5666 for (int i = 0; i < maps->size(); ++i) {
5667 AddStabilityDependency(maps->at(i).handle());
5672 LOperand* input = instr->value();
5673 DCHECK(input->IsRegister());
5674 Register reg = ToRegister(input);
5676 DeferredCheckMaps* deferred = NULL;
5677 if (instr->hydrogen()->HasMigrationTarget()) {
5678 deferred = new(zone()) DeferredCheckMaps(this, instr, reg, x87_stack_);
5679 __ bind(deferred->check_maps());
5682 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5684 for (int i = 0; i < maps->size() - 1; i++) {
5685 Handle<Map> map = maps->at(i).handle();
5686 __ CompareMap(reg, map);
5687 __ j(equal, &success, Label::kNear);
5690 Handle<Map> map = maps->at(maps->size() - 1).handle();
5691 __ CompareMap(reg, map);
5692 if (instr->hydrogen()->HasMigrationTarget()) {
5693 __ j(not_equal, deferred->entry());
5695 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5702 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5703 X87Register value_reg = ToX87Register(instr->unclamped());
5704 Register result_reg = ToRegister(instr->result());
5706 __ ClampTOSToUint8(result_reg);
5710 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5711 DCHECK(instr->unclamped()->Equals(instr->result()));
5712 Register value_reg = ToRegister(instr->result());
5713 __ ClampUint8(value_reg);
5717 void LCodeGen::DoClampTToUint8NoSSE2(LClampTToUint8NoSSE2* instr) {
5718 Register input_reg = ToRegister(instr->unclamped());
5719 Register result_reg = ToRegister(instr->result());
5720 Register scratch = ToRegister(instr->scratch());
5721 Register scratch2 = ToRegister(instr->scratch2());
5722 Register scratch3 = ToRegister(instr->scratch3());
5723 Label is_smi, done, heap_number, valid_exponent,
5724 largest_value, zero_result, maybe_nan_or_infinity;
5726 __ JumpIfSmi(input_reg, &is_smi);
5728 // Check for heap number
5729 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5730 factory()->heap_number_map());
5731 __ j(equal, &heap_number, Label::kNear);
5733 // Check for undefined. Undefined is converted to zero for clamping
5735 __ cmp(input_reg, factory()->undefined_value());
5736 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5737 __ jmp(&zero_result, Label::kNear);
5740 __ bind(&heap_number);
5742 // Surprisingly, all of the hand-crafted bit-manipulations below are much
5743 // faster than the x86 FPU built-in instruction, especially since "banker's
5744 // rounding" would be additionally very expensive
5746 // Get exponent word.
5747 __ mov(scratch, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5748 __ mov(scratch3, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5750 // Test for negative values --> clamp to zero
5751 __ test(scratch, scratch);
5752 __ j(negative, &zero_result, Label::kNear);
5754 // Get exponent alone in scratch2.
5755 __ mov(scratch2, scratch);
5756 __ and_(scratch2, HeapNumber::kExponentMask);
5757 __ shr(scratch2, HeapNumber::kExponentShift);
5758 __ j(zero, &zero_result, Label::kNear);
5759 __ sub(scratch2, Immediate(HeapNumber::kExponentBias - 1));
5760 __ j(negative, &zero_result, Label::kNear);
5762 const uint32_t non_int8_exponent = 7;
5763 __ cmp(scratch2, Immediate(non_int8_exponent + 1));
5764 // If the exponent is too big, check for special values.
5765 __ j(greater, &maybe_nan_or_infinity, Label::kNear);
5767 __ bind(&valid_exponent);
5768 // Exponent word in scratch, exponent in scratch2. We know that 0 <= exponent
5769 // < 7. The shift bias is the number of bits to shift the mantissa such that
5770 // with an exponent of 7 such the that top-most one is in bit 30, allowing
5771 // detection the rounding overflow of a 255.5 to 256 (bit 31 goes from 0 to
5773 int shift_bias = (30 - HeapNumber::kExponentShift) - 7 - 1;
5774 __ lea(result_reg, MemOperand(scratch2, shift_bias));
5775 // Here result_reg (ecx) is the shift, scratch is the exponent word. Get the
5776 // top bits of the mantissa.
5777 __ and_(scratch, HeapNumber::kMantissaMask);
5778 // Put back the implicit 1 of the mantissa
5779 __ or_(scratch, 1 << HeapNumber::kExponentShift);
5780 // Shift up to round
5782 // Use "banker's rounding" to spec: If fractional part of number is 0.5, then
5783 // use the bit in the "ones" place and add it to the "halves" place, which has
5784 // the effect of rounding to even.
5785 __ mov(scratch2, scratch);
5786 const uint32_t one_half_bit_shift = 30 - sizeof(uint8_t) * 8;
5787 const uint32_t one_bit_shift = one_half_bit_shift + 1;
5788 __ and_(scratch2, Immediate((1 << one_bit_shift) - 1));
5789 __ cmp(scratch2, Immediate(1 << one_half_bit_shift));
5791 __ j(less, &no_round, Label::kNear);
5793 __ mov(scratch2, Immediate(1 << one_half_bit_shift));
5794 __ j(greater, &round_up, Label::kNear);
5795 __ test(scratch3, scratch3);
5796 __ j(not_zero, &round_up, Label::kNear);
5797 __ mov(scratch2, scratch);
5798 __ and_(scratch2, Immediate(1 << one_bit_shift));
5799 __ shr(scratch2, 1);
5801 __ add(scratch, scratch2);
5802 __ j(overflow, &largest_value, Label::kNear);
5804 __ shr(scratch, 23);
5805 __ mov(result_reg, scratch);
5806 __ jmp(&done, Label::kNear);
5808 __ bind(&maybe_nan_or_infinity);
5809 // Check for NaN/Infinity, all other values map to 255
5810 __ cmp(scratch2, Immediate(HeapNumber::kInfinityOrNanExponent + 1));
5811 __ j(not_equal, &largest_value, Label::kNear);
5813 // Check for NaN, which differs from Infinity in that at least one mantissa
5815 __ and_(scratch, HeapNumber::kMantissaMask);
5816 __ or_(scratch, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5817 __ j(not_zero, &zero_result, Label::kNear); // M!=0 --> NaN
5818 // Infinity -> Fall through to map to 255.
5820 __ bind(&largest_value);
5821 __ mov(result_reg, Immediate(255));
5822 __ jmp(&done, Label::kNear);
5824 __ bind(&zero_result);
5825 __ xor_(result_reg, result_reg);
5826 __ jmp(&done, Label::kNear);
5830 if (!input_reg.is(result_reg)) {
5831 __ mov(result_reg, input_reg);
5833 __ SmiUntag(result_reg);
5834 __ ClampUint8(result_reg);
5839 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5840 X87Register value_reg = ToX87Register(instr->value());
5841 Register result_reg = ToRegister(instr->result());
5843 __ sub(esp, Immediate(kDoubleSize));
5844 __ fst_d(Operand(esp, 0));
5845 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5846 __ mov(result_reg, Operand(esp, kPointerSize));
5848 __ mov(result_reg, Operand(esp, 0));
5850 __ add(esp, Immediate(kDoubleSize));
5854 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5855 Register hi_reg = ToRegister(instr->hi());
5856 Register lo_reg = ToRegister(instr->lo());
5857 X87Register result_reg = ToX87Register(instr->result());
5858 // Follow below pattern to write a x87 fp register.
5859 X87PrepareToWrite(result_reg);
5860 __ sub(esp, Immediate(kDoubleSize));
5861 __ mov(Operand(esp, 0), lo_reg);
5862 __ mov(Operand(esp, kPointerSize), hi_reg);
5863 __ fld_d(Operand(esp, 0));
5864 __ add(esp, Immediate(kDoubleSize));
5865 X87CommitWrite(result_reg);
5869 void LCodeGen::DoAllocate(LAllocate* instr) {
5870 class DeferredAllocate final : public LDeferredCode {
5872 DeferredAllocate(LCodeGen* codegen,
5874 const X87Stack& x87_stack)
5875 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5876 void Generate() override { codegen()->DoDeferredAllocate(instr_); }
5877 LInstruction* instr() override { return instr_; }
5883 DeferredAllocate* deferred =
5884 new(zone()) DeferredAllocate(this, instr, x87_stack_);
5886 Register result = ToRegister(instr->result());
5887 Register temp = ToRegister(instr->temp());
5889 // Allocate memory for the object.
5890 AllocationFlags flags = TAG_OBJECT;
5891 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5892 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5894 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5895 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5896 flags = static_cast<AllocationFlags>(flags | PRETENURE);
5899 if (instr->size()->IsConstantOperand()) {
5900 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5901 if (size <= Page::kMaxRegularHeapObjectSize) {
5902 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5904 __ jmp(deferred->entry());
5907 Register size = ToRegister(instr->size());
5908 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5911 __ bind(deferred->exit());
5913 if (instr->hydrogen()->MustPrefillWithFiller()) {
5914 if (instr->size()->IsConstantOperand()) {
5915 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5916 __ mov(temp, (size / kPointerSize) - 1);
5918 temp = ToRegister(instr->size());
5919 __ shr(temp, kPointerSizeLog2);
5924 __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5925 isolate()->factory()->one_pointer_filler_map());
5927 __ j(not_zero, &loop);
5932 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5933 Register result = ToRegister(instr->result());
5935 // TODO(3095996): Get rid of this. For now, we need to make the
5936 // result register contain a valid pointer because it is already
5937 // contained in the register pointer map.
5938 __ Move(result, Immediate(Smi::FromInt(0)));
5940 PushSafepointRegistersScope scope(this);
5941 if (instr->size()->IsRegister()) {
5942 Register size = ToRegister(instr->size());
5943 DCHECK(!size.is(result));
5944 __ SmiTag(ToRegister(instr->size()));
5947 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5948 if (size >= 0 && size <= Smi::kMaxValue) {
5949 __ push(Immediate(Smi::FromInt(size)));
5951 // We should never get here at runtime => abort
5957 int flags = AllocateDoubleAlignFlag::encode(
5958 instr->hydrogen()->MustAllocateDoubleAligned());
5959 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5960 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5961 flags = AllocateTargetSpace::update(flags, OLD_SPACE);
5963 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5965 __ push(Immediate(Smi::FromInt(flags)));
5967 CallRuntimeFromDeferred(
5968 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5969 __ StoreToSafepointRegisterSlot(result, eax);
5973 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5974 DCHECK(ToRegister(instr->value()).is(eax));
5976 CallRuntime(Runtime::kToFastProperties, 1, instr);
5980 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5981 DCHECK(ToRegister(instr->context()).is(esi));
5983 // Registers will be used as follows:
5984 // ecx = literals array.
5985 // ebx = regexp literal.
5986 // eax = regexp literal clone.
5988 int literal_offset =
5989 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5990 __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5991 __ mov(ebx, FieldOperand(ecx, literal_offset));
5992 __ cmp(ebx, factory()->undefined_value());
5993 __ j(not_equal, &materialized, Label::kNear);
5995 // Create regexp literal using runtime function
5996 // Result will be in eax.
5998 __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5999 __ push(Immediate(instr->hydrogen()->pattern()));
6000 __ push(Immediate(instr->hydrogen()->flags()));
6001 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
6004 __ bind(&materialized);
6005 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
6006 Label allocated, runtime_allocate;
6007 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
6008 __ jmp(&allocated, Label::kNear);
6010 __ bind(&runtime_allocate);
6012 __ push(Immediate(Smi::FromInt(size)));
6013 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
6016 __ bind(&allocated);
6017 // Copy the content into the newly allocated memory.
6018 // (Unroll copy loop once for better throughput).
6019 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
6020 __ mov(edx, FieldOperand(ebx, i));
6021 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
6022 __ mov(FieldOperand(eax, i), edx);
6023 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
6025 if ((size % (2 * kPointerSize)) != 0) {
6026 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
6027 __ mov(FieldOperand(eax, size - kPointerSize), edx);
6032 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
6033 DCHECK(ToRegister(instr->context()).is(esi));
6034 // Use the fast case closure allocation code that allocates in new
6035 // space for nested functions that don't need literals cloning.
6036 bool pretenure = instr->hydrogen()->pretenure();
6037 if (!pretenure && instr->hydrogen()->has_no_literals()) {
6038 FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
6039 instr->hydrogen()->kind());
6040 __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
6041 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
6044 __ push(Immediate(instr->hydrogen()->shared_info()));
6045 __ push(Immediate(pretenure ? factory()->true_value()
6046 : factory()->false_value()));
6047 CallRuntime(Runtime::kNewClosure, 3, instr);
6052 void LCodeGen::DoTypeof(LTypeof* instr) {
6053 DCHECK(ToRegister(instr->context()).is(esi));
6054 DCHECK(ToRegister(instr->value()).is(ebx));
6056 Register value_register = ToRegister(instr->value());
6057 __ JumpIfNotSmi(value_register, &do_call);
6058 __ mov(eax, Immediate(isolate()->factory()->number_string()));
6061 TypeofStub stub(isolate());
6062 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
6067 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
6068 Register input = ToRegister(instr->value());
6069 Condition final_branch_condition = EmitTypeofIs(instr, input);
6070 if (final_branch_condition != no_condition) {
6071 EmitBranch(instr, final_branch_condition);
6076 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
6077 Label* true_label = instr->TrueLabel(chunk_);
6078 Label* false_label = instr->FalseLabel(chunk_);
6079 Handle<String> type_name = instr->type_literal();
6080 int left_block = instr->TrueDestination(chunk_);
6081 int right_block = instr->FalseDestination(chunk_);
6082 int next_block = GetNextEmittedBlock();
6084 Label::Distance true_distance = left_block == next_block ? Label::kNear
6086 Label::Distance false_distance = right_block == next_block ? Label::kNear
6088 Condition final_branch_condition = no_condition;
6089 if (String::Equals(type_name, factory()->number_string())) {
6090 __ JumpIfSmi(input, true_label, true_distance);
6091 __ cmp(FieldOperand(input, HeapObject::kMapOffset),
6092 factory()->heap_number_map());
6093 final_branch_condition = equal;
6095 } else if (String::Equals(type_name, factory()->string_string())) {
6096 __ JumpIfSmi(input, false_label, false_distance);
6097 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
6098 __ j(above_equal, false_label, false_distance);
6099 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6100 1 << Map::kIsUndetectable);
6101 final_branch_condition = zero;
6103 } else if (String::Equals(type_name, factory()->symbol_string())) {
6104 __ JumpIfSmi(input, false_label, false_distance);
6105 __ CmpObjectType(input, SYMBOL_TYPE, input);
6106 final_branch_condition = equal;
6108 } else if (String::Equals(type_name, factory()->boolean_string())) {
6109 __ cmp(input, factory()->true_value());
6110 __ j(equal, true_label, true_distance);
6111 __ cmp(input, factory()->false_value());
6112 final_branch_condition = equal;
6114 } else if (String::Equals(type_name, factory()->undefined_string())) {
6115 __ cmp(input, factory()->undefined_value());
6116 __ j(equal, true_label, true_distance);
6117 __ JumpIfSmi(input, false_label, false_distance);
6118 // Check for undetectable objects => true.
6119 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
6120 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6121 1 << Map::kIsUndetectable);
6122 final_branch_condition = not_zero;
6124 } else if (String::Equals(type_name, factory()->function_string())) {
6125 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
6126 __ JumpIfSmi(input, false_label, false_distance);
6127 __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
6128 __ j(equal, true_label, true_distance);
6129 __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
6130 final_branch_condition = equal;
6132 } else if (String::Equals(type_name, factory()->object_string())) {
6133 __ JumpIfSmi(input, false_label, false_distance);
6134 __ cmp(input, factory()->null_value());
6135 __ j(equal, true_label, true_distance);
6136 __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
6137 __ j(below, false_label, false_distance);
6138 __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
6139 __ j(above, false_label, false_distance);
6140 // Check for undetectable objects => false.
6141 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6142 1 << Map::kIsUndetectable);
6143 final_branch_condition = zero;
6146 __ jmp(false_label, false_distance);
6148 return final_branch_condition;
6152 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
6153 Register temp = ToRegister(instr->temp());
6155 EmitIsConstructCall(temp);
6156 EmitBranch(instr, equal);
6160 void LCodeGen::EmitIsConstructCall(Register temp) {
6161 // Get the frame pointer for the calling frame.
6162 __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
6164 // Skip the arguments adaptor frame if it exists.
6165 Label check_frame_marker;
6166 __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
6167 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
6168 __ j(not_equal, &check_frame_marker, Label::kNear);
6169 __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
6171 // Check the marker in the calling frame.
6172 __ bind(&check_frame_marker);
6173 __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
6174 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
6178 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
6179 if (!info()->IsStub()) {
6180 // Ensure that we have enough space after the previous lazy-bailout
6181 // instruction for patching the code here.
6182 int current_pc = masm()->pc_offset();
6183 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
6184 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
6185 __ Nop(padding_size);
6188 last_lazy_deopt_pc_ = masm()->pc_offset();
6192 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
6193 last_lazy_deopt_pc_ = masm()->pc_offset();
6194 DCHECK(instr->HasEnvironment());
6195 LEnvironment* env = instr->environment();
6196 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6197 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6201 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
6202 Deoptimizer::BailoutType type = instr->hydrogen()->type();
6203 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
6204 // needed return address), even though the implementation of LAZY and EAGER is
6205 // now identical. When LAZY is eventually completely folded into EAGER, remove
6206 // the special case below.
6207 if (info()->IsStub() && type == Deoptimizer::EAGER) {
6208 type = Deoptimizer::LAZY;
6210 DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
6214 void LCodeGen::DoDummy(LDummy* instr) {
6215 // Nothing to see here, move on!
6219 void LCodeGen::DoDummyUse(LDummyUse* instr) {
6220 // Nothing to see here, move on!
6224 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
6225 PushSafepointRegistersScope scope(this);
6226 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
6227 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
6228 RecordSafepointWithLazyDeopt(
6229 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
6230 DCHECK(instr->HasEnvironment());
6231 LEnvironment* env = instr->environment();
6232 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6236 void LCodeGen::DoStackCheck(LStackCheck* instr) {
6237 class DeferredStackCheck final : public LDeferredCode {
6239 DeferredStackCheck(LCodeGen* codegen,
6241 const X87Stack& x87_stack)
6242 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
6243 void Generate() override { codegen()->DoDeferredStackCheck(instr_); }
6244 LInstruction* instr() override { return instr_; }
6247 LStackCheck* instr_;
6250 DCHECK(instr->HasEnvironment());
6251 LEnvironment* env = instr->environment();
6252 // There is no LLazyBailout instruction for stack-checks. We have to
6253 // prepare for lazy deoptimization explicitly here.
6254 if (instr->hydrogen()->is_function_entry()) {
6255 // Perform stack overflow check.
6257 ExternalReference stack_limit =
6258 ExternalReference::address_of_stack_limit(isolate());
6259 __ cmp(esp, Operand::StaticVariable(stack_limit));
6260 __ j(above_equal, &done, Label::kNear);
6262 DCHECK(instr->context()->IsRegister());
6263 DCHECK(ToRegister(instr->context()).is(esi));
6264 CallCode(isolate()->builtins()->StackCheck(),
6265 RelocInfo::CODE_TARGET,
6269 DCHECK(instr->hydrogen()->is_backwards_branch());
6270 // Perform stack overflow check if this goto needs it before jumping.
6271 DeferredStackCheck* deferred_stack_check =
6272 new(zone()) DeferredStackCheck(this, instr, x87_stack_);
6273 ExternalReference stack_limit =
6274 ExternalReference::address_of_stack_limit(isolate());
6275 __ cmp(esp, Operand::StaticVariable(stack_limit));
6276 __ j(below, deferred_stack_check->entry());
6277 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
6278 __ bind(instr->done_label());
6279 deferred_stack_check->SetExit(instr->done_label());
6280 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6281 // Don't record a deoptimization index for the safepoint here.
6282 // This will be done explicitly when emitting call and the safepoint in
6283 // the deferred code.
6288 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
6289 // This is a pseudo-instruction that ensures that the environment here is
6290 // properly registered for deoptimization and records the assembler's PC
6292 LEnvironment* environment = instr->environment();
6294 // If the environment were already registered, we would have no way of
6295 // backpatching it with the spill slot operands.
6296 DCHECK(!environment->HasBeenRegistered());
6297 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
6299 GenerateOsrPrologue();
6303 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
6304 DCHECK(ToRegister(instr->context()).is(esi));
6305 __ test(eax, Immediate(kSmiTagMask));
6306 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
6308 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
6309 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
6310 DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
6312 Label use_cache, call_runtime;
6313 __ CheckEnumCache(&call_runtime);
6315 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
6316 __ jmp(&use_cache, Label::kNear);
6318 // Get the set of properties to enumerate.
6319 __ bind(&call_runtime);
6321 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
6323 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
6324 isolate()->factory()->meta_map());
6325 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
6326 __ bind(&use_cache);
6330 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
6331 Register map = ToRegister(instr->map());
6332 Register result = ToRegister(instr->result());
6333 Label load_cache, done;
6334 __ EnumLength(result, map);
6335 __ cmp(result, Immediate(Smi::FromInt(0)));
6336 __ j(not_equal, &load_cache, Label::kNear);
6337 __ mov(result, isolate()->factory()->empty_fixed_array());
6338 __ jmp(&done, Label::kNear);
6340 __ bind(&load_cache);
6341 __ LoadInstanceDescriptors(map, result);
6343 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
6345 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
6347 __ test(result, result);
6348 DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
6352 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
6353 Register object = ToRegister(instr->value());
6354 __ cmp(ToRegister(instr->map()),
6355 FieldOperand(object, HeapObject::kMapOffset));
6356 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
6360 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
6363 PushSafepointRegistersScope scope(this);
6367 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
6368 RecordSafepointWithRegisters(
6369 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
6370 __ StoreToSafepointRegisterSlot(object, eax);
6374 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
6375 class DeferredLoadMutableDouble final : public LDeferredCode {
6377 DeferredLoadMutableDouble(LCodeGen* codegen,
6378 LLoadFieldByIndex* instr,
6381 const X87Stack& x87_stack)
6382 : LDeferredCode(codegen, x87_stack),
6387 void Generate() override {
6388 codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
6390 LInstruction* instr() override { return instr_; }
6393 LLoadFieldByIndex* instr_;
6398 Register object = ToRegister(instr->object());
6399 Register index = ToRegister(instr->index());
6401 DeferredLoadMutableDouble* deferred;
6402 deferred = new(zone()) DeferredLoadMutableDouble(
6403 this, instr, object, index, x87_stack_);
6405 Label out_of_object, done;
6406 __ test(index, Immediate(Smi::FromInt(1)));
6407 __ j(not_zero, deferred->entry());
6411 __ cmp(index, Immediate(0));
6412 __ j(less, &out_of_object, Label::kNear);
6413 __ mov(object, FieldOperand(object,
6415 times_half_pointer_size,
6416 JSObject::kHeaderSize));
6417 __ jmp(&done, Label::kNear);
6419 __ bind(&out_of_object);
6420 __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
6422 // Index is now equal to out of object property index plus 1.
6423 __ mov(object, FieldOperand(object,
6425 times_half_pointer_size,
6426 FixedArray::kHeaderSize - kPointerSize));
6427 __ bind(deferred->exit());
6432 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
6433 Register context = ToRegister(instr->context());
6434 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
6438 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
6439 Handle<ScopeInfo> scope_info = instr->scope_info();
6440 __ Push(scope_info);
6441 __ push(ToRegister(instr->function()));
6442 CallRuntime(Runtime::kPushBlockContext, 2, instr);
6443 RecordSafepoint(Safepoint::kNoLazyDeopt);
6449 } // namespace internal
6452 #endif // V8_TARGET_ARCH_X87