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();
888 WriteTranslation(environment->outer(), translation);
889 WriteTranslationFrame(environment, translation);
891 int object_index = 0;
892 int dematerialized_index = 0;
893 for (int i = 0; i < translation_size; ++i) {
894 LOperand* value = environment->values()->at(i);
895 AddToTranslation(environment,
898 environment->HasTaggedValueAt(i),
899 environment->HasUint32ValueAt(i),
901 &dematerialized_index);
906 void LCodeGen::AddToTranslation(LEnvironment* environment,
907 Translation* translation,
911 int* object_index_pointer,
912 int* dematerialized_index_pointer) {
913 if (op == LEnvironment::materialization_marker()) {
914 int object_index = (*object_index_pointer)++;
915 if (environment->ObjectIsDuplicateAt(object_index)) {
916 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
917 translation->DuplicateObject(dupe_of);
920 int object_length = environment->ObjectLengthAt(object_index);
921 if (environment->ObjectIsArgumentsAt(object_index)) {
922 translation->BeginArgumentsObject(object_length);
924 translation->BeginCapturedObject(object_length);
926 int dematerialized_index = *dematerialized_index_pointer;
927 int env_offset = environment->translation_size() + dematerialized_index;
928 *dematerialized_index_pointer += object_length;
929 for (int i = 0; i < object_length; ++i) {
930 LOperand* value = environment->values()->at(env_offset + i);
931 AddToTranslation(environment,
934 environment->HasTaggedValueAt(env_offset + i),
935 environment->HasUint32ValueAt(env_offset + i),
936 object_index_pointer,
937 dematerialized_index_pointer);
942 if (op->IsStackSlot()) {
944 translation->StoreStackSlot(op->index());
945 } else if (is_uint32) {
946 translation->StoreUint32StackSlot(op->index());
948 translation->StoreInt32StackSlot(op->index());
950 } else if (op->IsDoubleStackSlot()) {
951 translation->StoreDoubleStackSlot(op->index());
952 } else if (op->IsRegister()) {
953 Register reg = ToRegister(op);
955 translation->StoreRegister(reg);
956 } else if (is_uint32) {
957 translation->StoreUint32Register(reg);
959 translation->StoreInt32Register(reg);
961 } else if (op->IsDoubleRegister()) {
962 X87Register reg = ToX87Register(op);
963 translation->StoreDoubleRegister(reg);
964 } else if (op->IsConstantOperand()) {
965 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
966 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
967 translation->StoreLiteral(src_index);
974 void LCodeGen::CallCodeGeneric(Handle<Code> code,
975 RelocInfo::Mode mode,
977 SafepointMode safepoint_mode) {
978 DCHECK(instr != NULL);
980 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
982 // Signal that we don't inline smi code before these stubs in the
983 // optimizing code generator.
984 if (code->kind() == Code::BINARY_OP_IC ||
985 code->kind() == Code::COMPARE_IC) {
991 void LCodeGen::CallCode(Handle<Code> code,
992 RelocInfo::Mode mode,
993 LInstruction* instr) {
994 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
998 void LCodeGen::CallRuntime(const Runtime::Function* fun, int argc,
999 LInstruction* instr, SaveFPRegsMode save_doubles) {
1000 DCHECK(instr != NULL);
1001 DCHECK(instr->HasPointerMap());
1003 __ CallRuntime(fun, argc, save_doubles);
1005 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
1007 DCHECK(info()->is_calling());
1011 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
1012 if (context->IsRegister()) {
1013 if (!ToRegister(context).is(esi)) {
1014 __ mov(esi, ToRegister(context));
1016 } else if (context->IsStackSlot()) {
1017 __ mov(esi, ToOperand(context));
1018 } else if (context->IsConstantOperand()) {
1019 HConstant* constant =
1020 chunk_->LookupConstant(LConstantOperand::cast(context));
1021 __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
1027 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
1029 LInstruction* instr,
1030 LOperand* context) {
1031 LoadContextFromDeferred(context);
1033 __ CallRuntimeSaveDoubles(id);
1034 RecordSafepointWithRegisters(
1035 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
1037 DCHECK(info()->is_calling());
1041 void LCodeGen::RegisterEnvironmentForDeoptimization(
1042 LEnvironment* environment, Safepoint::DeoptMode mode) {
1043 environment->set_has_been_used();
1044 if (!environment->HasBeenRegistered()) {
1045 // Physical stack frame layout:
1046 // -x ............. -4 0 ..................................... y
1047 // [incoming arguments] [spill slots] [pushed outgoing arguments]
1049 // Layout of the environment:
1050 // 0 ..................................................... size-1
1051 // [parameters] [locals] [expression stack including arguments]
1053 // Layout of the translation:
1054 // 0 ........................................................ size - 1 + 4
1055 // [expression stack including arguments] [locals] [4 words] [parameters]
1056 // |>------------ translation_size ------------<|
1058 int frame_count = 0;
1059 int jsframe_count = 0;
1060 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
1062 if (e->frame_type() == JS_FUNCTION) {
1066 Translation translation(&translations_, frame_count, jsframe_count, zone());
1067 WriteTranslation(environment, &translation);
1068 int deoptimization_index = deoptimizations_.length();
1069 int pc_offset = masm()->pc_offset();
1070 environment->Register(deoptimization_index,
1071 translation.index(),
1072 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
1073 deoptimizations_.Add(environment, zone());
1078 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1079 Deoptimizer::DeoptReason deopt_reason,
1080 Deoptimizer::BailoutType bailout_type) {
1081 LEnvironment* environment = instr->environment();
1082 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
1083 DCHECK(environment->HasBeenRegistered());
1084 int id = environment->deoptimization_index();
1085 DCHECK(info()->IsOptimizing() || info()->IsStub());
1087 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
1088 if (entry == NULL) {
1089 Abort(kBailoutWasNotPrepared);
1093 if (DeoptEveryNTimes()) {
1094 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
1098 __ mov(eax, Operand::StaticVariable(count));
1099 __ sub(eax, Immediate(1));
1100 __ j(not_zero, &no_deopt, Label::kNear);
1101 if (FLAG_trap_on_deopt) __ int3();
1102 __ mov(eax, Immediate(FLAG_deopt_every_n_times));
1103 __ mov(Operand::StaticVariable(count), eax);
1106 DCHECK(frame_is_built_);
1107 // Put the x87 stack layout in TOS.
1108 if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1109 __ push(Immediate(x87_stack_.GetLayout()));
1110 __ fild_s(MemOperand(esp, 0));
1111 // Don't touch eflags.
1112 __ lea(esp, Operand(esp, kPointerSize));
1113 __ call(entry, RelocInfo::RUNTIME_ENTRY);
1115 __ mov(Operand::StaticVariable(count), eax);
1120 // Put the x87 stack layout in TOS, so that we can save x87 fp registers in
1121 // the correct location.
1124 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1125 if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
1127 int x87_stack_layout = x87_stack_.GetLayout();
1128 __ push(Immediate(x87_stack_layout));
1129 __ fild_s(MemOperand(esp, 0));
1130 // Don't touch eflags.
1131 __ lea(esp, Operand(esp, kPointerSize));
1135 if (info()->ShouldTrapOnDeopt()) {
1137 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1142 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
1144 DCHECK(info()->IsStub() || frame_is_built_);
1145 if (cc == no_condition && frame_is_built_) {
1146 DeoptComment(deopt_info);
1147 __ call(entry, RelocInfo::RUNTIME_ENTRY);
1148 info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
1150 Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
1152 // We often have several deopts to the same entry, reuse the last
1153 // jump entry if this is the case.
1154 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
1155 jump_table_.is_empty() ||
1156 !table_entry.IsEquivalentTo(jump_table_.last())) {
1157 jump_table_.Add(table_entry, zone());
1159 if (cc == no_condition) {
1160 __ jmp(&jump_table_.last().label);
1162 __ j(cc, &jump_table_.last().label);
1168 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1169 Deoptimizer::DeoptReason deopt_reason) {
1170 Deoptimizer::BailoutType bailout_type = info()->IsStub()
1172 : Deoptimizer::EAGER;
1173 DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
1177 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
1178 int length = deoptimizations_.length();
1179 if (length == 0) return;
1180 Handle<DeoptimizationInputData> data =
1181 DeoptimizationInputData::New(isolate(), length, TENURED);
1183 Handle<ByteArray> translations =
1184 translations_.CreateByteArray(isolate()->factory());
1185 data->SetTranslationByteArray(*translations);
1186 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
1187 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
1188 if (info_->IsOptimizing()) {
1189 // Reference to shared function info does not change between phases.
1190 AllowDeferredHandleDereference allow_handle_dereference;
1191 data->SetSharedFunctionInfo(*info_->shared_info());
1193 data->SetSharedFunctionInfo(Smi::FromInt(0));
1195 data->SetWeakCellCache(Smi::FromInt(0));
1197 Handle<FixedArray> literals =
1198 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
1199 { AllowDeferredHandleDereference copy_handles;
1200 for (int i = 0; i < deoptimization_literals_.length(); i++) {
1201 literals->set(i, *deoptimization_literals_[i]);
1203 data->SetLiteralArray(*literals);
1206 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
1207 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
1209 // Populate the deoptimization entries.
1210 for (int i = 0; i < length; i++) {
1211 LEnvironment* env = deoptimizations_[i];
1212 data->SetAstId(i, env->ast_id());
1213 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
1214 data->SetArgumentsStackHeight(i,
1215 Smi::FromInt(env->arguments_stack_height()));
1216 data->SetPc(i, Smi::FromInt(env->pc_offset()));
1218 code->set_deoptimization_data(*data);
1222 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
1223 DCHECK_EQ(0, deoptimization_literals_.length());
1224 for (auto function : chunk()->inlined_functions()) {
1225 DefineDeoptimizationLiteral(function);
1227 inlined_function_count_ = deoptimization_literals_.length();
1231 void LCodeGen::RecordSafepointWithLazyDeopt(
1232 LInstruction* instr, SafepointMode safepoint_mode) {
1233 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
1234 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
1236 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
1237 RecordSafepointWithRegisters(
1238 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
1243 void LCodeGen::RecordSafepoint(
1244 LPointerMap* pointers,
1245 Safepoint::Kind kind,
1247 Safepoint::DeoptMode deopt_mode) {
1248 DCHECK(kind == expected_safepoint_kind_);
1249 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
1250 Safepoint safepoint =
1251 safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
1252 for (int i = 0; i < operands->length(); i++) {
1253 LOperand* pointer = operands->at(i);
1254 if (pointer->IsStackSlot()) {
1255 safepoint.DefinePointerSlot(pointer->index(), zone());
1256 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
1257 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
1263 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
1264 Safepoint::DeoptMode mode) {
1265 RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
1269 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
1270 LPointerMap empty_pointers(zone());
1271 RecordSafepoint(&empty_pointers, mode);
1275 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
1277 Safepoint::DeoptMode mode) {
1278 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1282 void LCodeGen::RecordAndWritePosition(int position) {
1283 if (position == RelocInfo::kNoPosition) return;
1284 masm()->positions_recorder()->RecordPosition(position);
1285 masm()->positions_recorder()->WriteRecordedPositions();
1289 static const char* LabelType(LLabel* label) {
1290 if (label->is_loop_header()) return " (loop header)";
1291 if (label->is_osr_entry()) return " (OSR entry)";
1296 void LCodeGen::DoLabel(LLabel* label) {
1297 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1298 current_instruction_,
1299 label->hydrogen_value()->id(),
1302 __ bind(label->label());
1303 current_block_ = label->block_id();
1304 if (label->block()->predecessors()->length() > 1) {
1305 // A join block's x87 stack is that of its last visited predecessor.
1306 // If the last visited predecessor block is unreachable, the stack state
1307 // will be wrong. In such case, use the x87 stack of reachable predecessor.
1308 X87StackMap::const_iterator it = x87_stack_map_.find(current_block_);
1309 // Restore x87 stack.
1310 if (it != x87_stack_map_.end()) {
1311 x87_stack_ = *(it->second);
1318 void LCodeGen::DoParallelMove(LParallelMove* move) {
1319 resolver_.Resolve(move);
1323 void LCodeGen::DoGap(LGap* gap) {
1324 for (int i = LGap::FIRST_INNER_POSITION;
1325 i <= LGap::LAST_INNER_POSITION;
1327 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1328 LParallelMove* move = gap->GetParallelMove(inner_pos);
1329 if (move != NULL) DoParallelMove(move);
1334 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1339 void LCodeGen::DoParameter(LParameter* instr) {
1344 void LCodeGen::DoCallStub(LCallStub* instr) {
1345 DCHECK(ToRegister(instr->context()).is(esi));
1346 DCHECK(ToRegister(instr->result()).is(eax));
1347 switch (instr->hydrogen()->major_key()) {
1348 case CodeStub::RegExpExec: {
1349 RegExpExecStub stub(isolate());
1350 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1353 case CodeStub::SubString: {
1354 SubStringStub stub(isolate());
1355 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1358 case CodeStub::StringCompare: {
1359 StringCompareStub stub(isolate());
1360 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1369 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1370 GenerateOsrPrologue();
1374 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1375 Register dividend = ToRegister(instr->dividend());
1376 int32_t divisor = instr->divisor();
1377 DCHECK(dividend.is(ToRegister(instr->result())));
1379 // Theoretically, a variation of the branch-free code for integer division by
1380 // a power of 2 (calculating the remainder via an additional multiplication
1381 // (which gets simplified to an 'and') and subtraction) should be faster, and
1382 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1383 // indicate that positive dividends are heavily favored, so the branching
1384 // version performs better.
1385 HMod* hmod = instr->hydrogen();
1386 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1387 Label dividend_is_not_negative, done;
1388 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1389 __ test(dividend, dividend);
1390 __ j(not_sign, ÷nd_is_not_negative, Label::kNear);
1391 // Note that this is correct even for kMinInt operands.
1393 __ and_(dividend, mask);
1395 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1396 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1398 __ jmp(&done, Label::kNear);
1401 __ bind(÷nd_is_not_negative);
1402 __ and_(dividend, mask);
1407 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1408 Register dividend = ToRegister(instr->dividend());
1409 int32_t divisor = instr->divisor();
1410 DCHECK(ToRegister(instr->result()).is(eax));
1413 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1417 __ TruncatingDiv(dividend, Abs(divisor));
1418 __ imul(edx, edx, Abs(divisor));
1419 __ mov(eax, dividend);
1422 // Check for negative zero.
1423 HMod* hmod = instr->hydrogen();
1424 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1425 Label remainder_not_zero;
1426 __ j(not_zero, &remainder_not_zero, Label::kNear);
1427 __ cmp(dividend, Immediate(0));
1428 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1429 __ bind(&remainder_not_zero);
1434 void LCodeGen::DoModI(LModI* instr) {
1435 HMod* hmod = instr->hydrogen();
1437 Register left_reg = ToRegister(instr->left());
1438 DCHECK(left_reg.is(eax));
1439 Register right_reg = ToRegister(instr->right());
1440 DCHECK(!right_reg.is(eax));
1441 DCHECK(!right_reg.is(edx));
1442 Register result_reg = ToRegister(instr->result());
1443 DCHECK(result_reg.is(edx));
1446 // Check for x % 0, idiv would signal a divide error. We have to
1447 // deopt in this case because we can't return a NaN.
1448 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1449 __ test(right_reg, Operand(right_reg));
1450 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1453 // Check for kMinInt % -1, idiv would signal a divide error. We
1454 // have to deopt if we care about -0, because we can't return that.
1455 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1456 Label no_overflow_possible;
1457 __ cmp(left_reg, kMinInt);
1458 __ j(not_equal, &no_overflow_possible, Label::kNear);
1459 __ cmp(right_reg, -1);
1460 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1461 DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1463 __ j(not_equal, &no_overflow_possible, Label::kNear);
1464 __ Move(result_reg, Immediate(0));
1465 __ jmp(&done, Label::kNear);
1467 __ bind(&no_overflow_possible);
1470 // Sign extend dividend in eax into edx:eax.
1473 // If we care about -0, test if the dividend is <0 and the result is 0.
1474 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1475 Label positive_left;
1476 __ test(left_reg, Operand(left_reg));
1477 __ j(not_sign, &positive_left, Label::kNear);
1479 __ test(result_reg, Operand(result_reg));
1480 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1481 __ jmp(&done, Label::kNear);
1482 __ bind(&positive_left);
1489 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1490 Register dividend = ToRegister(instr->dividend());
1491 int32_t divisor = instr->divisor();
1492 Register result = ToRegister(instr->result());
1493 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1494 DCHECK(!result.is(dividend));
1496 // Check for (0 / -x) that will produce negative zero.
1497 HDiv* hdiv = instr->hydrogen();
1498 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1499 __ test(dividend, dividend);
1500 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1502 // Check for (kMinInt / -1).
1503 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1504 __ cmp(dividend, kMinInt);
1505 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1507 // Deoptimize if remainder will not be 0.
1508 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1509 divisor != 1 && divisor != -1) {
1510 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1511 __ test(dividend, Immediate(mask));
1512 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1514 __ Move(result, dividend);
1515 int32_t shift = WhichPowerOf2Abs(divisor);
1517 // The arithmetic shift is always OK, the 'if' is an optimization only.
1518 if (shift > 1) __ sar(result, 31);
1519 __ shr(result, 32 - shift);
1520 __ add(result, dividend);
1521 __ sar(result, shift);
1523 if (divisor < 0) __ neg(result);
1527 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1528 Register dividend = ToRegister(instr->dividend());
1529 int32_t divisor = instr->divisor();
1530 DCHECK(ToRegister(instr->result()).is(edx));
1533 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1537 // Check for (0 / -x) that will produce negative zero.
1538 HDiv* hdiv = instr->hydrogen();
1539 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1540 __ test(dividend, dividend);
1541 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1544 __ TruncatingDiv(dividend, Abs(divisor));
1545 if (divisor < 0) __ neg(edx);
1547 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1549 __ imul(eax, eax, divisor);
1550 __ sub(eax, dividend);
1551 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1556 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1557 void LCodeGen::DoDivI(LDivI* instr) {
1558 HBinaryOperation* hdiv = instr->hydrogen();
1559 Register dividend = ToRegister(instr->dividend());
1560 Register divisor = ToRegister(instr->divisor());
1561 Register remainder = ToRegister(instr->temp());
1562 DCHECK(dividend.is(eax));
1563 DCHECK(remainder.is(edx));
1564 DCHECK(ToRegister(instr->result()).is(eax));
1565 DCHECK(!divisor.is(eax));
1566 DCHECK(!divisor.is(edx));
1569 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1570 __ test(divisor, divisor);
1571 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1574 // Check for (0 / -x) that will produce negative zero.
1575 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1576 Label dividend_not_zero;
1577 __ test(dividend, dividend);
1578 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1579 __ test(divisor, divisor);
1580 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1581 __ bind(÷nd_not_zero);
1584 // Check for (kMinInt / -1).
1585 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1586 Label dividend_not_min_int;
1587 __ cmp(dividend, kMinInt);
1588 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1589 __ cmp(divisor, -1);
1590 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1591 __ bind(÷nd_not_min_int);
1594 // Sign extend to edx (= remainder).
1598 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1599 // Deoptimize if remainder is not 0.
1600 __ test(remainder, remainder);
1601 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1606 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1607 Register dividend = ToRegister(instr->dividend());
1608 int32_t divisor = instr->divisor();
1609 DCHECK(dividend.is(ToRegister(instr->result())));
1611 // If the divisor is positive, things are easy: There can be no deopts and we
1612 // can simply do an arithmetic right shift.
1613 if (divisor == 1) return;
1614 int32_t shift = WhichPowerOf2Abs(divisor);
1616 __ sar(dividend, shift);
1620 // If the divisor is negative, we have to negate and handle edge cases.
1622 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1623 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1626 // Dividing by -1 is basically negation, unless we overflow.
1627 if (divisor == -1) {
1628 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1629 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1634 // If the negation could not overflow, simply shifting is OK.
1635 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1636 __ sar(dividend, shift);
1640 Label not_kmin_int, done;
1641 __ j(no_overflow, ¬_kmin_int, Label::kNear);
1642 __ mov(dividend, Immediate(kMinInt / divisor));
1643 __ jmp(&done, Label::kNear);
1644 __ bind(¬_kmin_int);
1645 __ sar(dividend, shift);
1650 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1651 Register dividend = ToRegister(instr->dividend());
1652 int32_t divisor = instr->divisor();
1653 DCHECK(ToRegister(instr->result()).is(edx));
1656 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1660 // Check for (0 / -x) that will produce negative zero.
1661 HMathFloorOfDiv* hdiv = instr->hydrogen();
1662 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1663 __ test(dividend, dividend);
1664 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1667 // Easy case: We need no dynamic check for the dividend and the flooring
1668 // division is the same as the truncating division.
1669 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1670 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1671 __ TruncatingDiv(dividend, Abs(divisor));
1672 if (divisor < 0) __ neg(edx);
1676 // In the general case we may need to adjust before and after the truncating
1677 // division to get a flooring division.
1678 Register temp = ToRegister(instr->temp3());
1679 DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1680 Label needs_adjustment, done;
1681 __ cmp(dividend, Immediate(0));
1682 __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1683 __ TruncatingDiv(dividend, Abs(divisor));
1684 if (divisor < 0) __ neg(edx);
1685 __ jmp(&done, Label::kNear);
1686 __ bind(&needs_adjustment);
1687 __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1688 __ TruncatingDiv(temp, Abs(divisor));
1689 if (divisor < 0) __ neg(edx);
1695 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1696 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1697 HBinaryOperation* hdiv = instr->hydrogen();
1698 Register dividend = ToRegister(instr->dividend());
1699 Register divisor = ToRegister(instr->divisor());
1700 Register remainder = ToRegister(instr->temp());
1701 Register result = ToRegister(instr->result());
1702 DCHECK(dividend.is(eax));
1703 DCHECK(remainder.is(edx));
1704 DCHECK(result.is(eax));
1705 DCHECK(!divisor.is(eax));
1706 DCHECK(!divisor.is(edx));
1709 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1710 __ test(divisor, divisor);
1711 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1714 // Check for (0 / -x) that will produce negative zero.
1715 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1716 Label dividend_not_zero;
1717 __ test(dividend, dividend);
1718 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1719 __ test(divisor, divisor);
1720 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1721 __ bind(÷nd_not_zero);
1724 // Check for (kMinInt / -1).
1725 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1726 Label dividend_not_min_int;
1727 __ cmp(dividend, kMinInt);
1728 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1729 __ cmp(divisor, -1);
1730 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1731 __ bind(÷nd_not_min_int);
1734 // Sign extend to edx (= remainder).
1739 __ test(remainder, remainder);
1740 __ j(zero, &done, Label::kNear);
1741 __ xor_(remainder, divisor);
1742 __ sar(remainder, 31);
1743 __ add(result, remainder);
1748 void LCodeGen::DoMulI(LMulI* instr) {
1749 Register left = ToRegister(instr->left());
1750 LOperand* right = instr->right();
1752 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1753 __ mov(ToRegister(instr->temp()), left);
1756 if (right->IsConstantOperand()) {
1757 // Try strength reductions on the multiplication.
1758 // All replacement instructions are at most as long as the imul
1759 // and have better latency.
1760 int constant = ToInteger32(LConstantOperand::cast(right));
1761 if (constant == -1) {
1763 } else if (constant == 0) {
1764 __ xor_(left, Operand(left));
1765 } else if (constant == 2) {
1766 __ add(left, Operand(left));
1767 } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1768 // If we know that the multiplication can't overflow, it's safe to
1769 // use instructions that don't set the overflow flag for the
1776 __ lea(left, Operand(left, left, times_2, 0));
1782 __ lea(left, Operand(left, left, times_4, 0));
1788 __ lea(left, Operand(left, left, times_8, 0));
1794 __ imul(left, left, constant);
1798 __ imul(left, left, constant);
1801 if (instr->hydrogen()->representation().IsSmi()) {
1804 __ imul(left, ToOperand(right));
1807 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1808 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1811 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1812 // Bail out if the result is supposed to be negative zero.
1814 __ test(left, Operand(left));
1815 __ j(not_zero, &done);
1816 if (right->IsConstantOperand()) {
1817 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1818 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1819 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1820 __ cmp(ToRegister(instr->temp()), Immediate(0));
1821 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1824 // Test the non-zero operand for negative sign.
1825 __ or_(ToRegister(instr->temp()), ToOperand(right));
1826 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1833 void LCodeGen::DoBitI(LBitI* instr) {
1834 LOperand* left = instr->left();
1835 LOperand* right = instr->right();
1836 DCHECK(left->Equals(instr->result()));
1837 DCHECK(left->IsRegister());
1839 if (right->IsConstantOperand()) {
1840 int32_t right_operand =
1841 ToRepresentation(LConstantOperand::cast(right),
1842 instr->hydrogen()->representation());
1843 switch (instr->op()) {
1844 case Token::BIT_AND:
1845 __ and_(ToRegister(left), right_operand);
1848 __ or_(ToRegister(left), right_operand);
1850 case Token::BIT_XOR:
1851 if (right_operand == int32_t(~0)) {
1852 __ not_(ToRegister(left));
1854 __ xor_(ToRegister(left), right_operand);
1862 switch (instr->op()) {
1863 case Token::BIT_AND:
1864 __ and_(ToRegister(left), ToOperand(right));
1867 __ or_(ToRegister(left), ToOperand(right));
1869 case Token::BIT_XOR:
1870 __ xor_(ToRegister(left), ToOperand(right));
1880 void LCodeGen::DoShiftI(LShiftI* instr) {
1881 LOperand* left = instr->left();
1882 LOperand* right = instr->right();
1883 DCHECK(left->Equals(instr->result()));
1884 DCHECK(left->IsRegister());
1885 if (right->IsRegister()) {
1886 DCHECK(ToRegister(right).is(ecx));
1888 switch (instr->op()) {
1890 __ ror_cl(ToRegister(left));
1893 __ sar_cl(ToRegister(left));
1896 __ shr_cl(ToRegister(left));
1897 if (instr->can_deopt()) {
1898 __ test(ToRegister(left), ToRegister(left));
1899 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1903 __ shl_cl(ToRegister(left));
1910 int value = ToInteger32(LConstantOperand::cast(right));
1911 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1912 switch (instr->op()) {
1914 if (shift_count == 0 && instr->can_deopt()) {
1915 __ test(ToRegister(left), ToRegister(left));
1916 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1918 __ ror(ToRegister(left), shift_count);
1922 if (shift_count != 0) {
1923 __ sar(ToRegister(left), shift_count);
1927 if (shift_count != 0) {
1928 __ shr(ToRegister(left), shift_count);
1929 } else if (instr->can_deopt()) {
1930 __ test(ToRegister(left), ToRegister(left));
1931 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1935 if (shift_count != 0) {
1936 if (instr->hydrogen_value()->representation().IsSmi() &&
1937 instr->can_deopt()) {
1938 if (shift_count != 1) {
1939 __ shl(ToRegister(left), shift_count - 1);
1941 __ SmiTag(ToRegister(left));
1942 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1944 __ shl(ToRegister(left), shift_count);
1956 void LCodeGen::DoSubI(LSubI* instr) {
1957 LOperand* left = instr->left();
1958 LOperand* right = instr->right();
1959 DCHECK(left->Equals(instr->result()));
1961 if (right->IsConstantOperand()) {
1962 __ sub(ToOperand(left),
1963 ToImmediate(right, instr->hydrogen()->representation()));
1965 __ sub(ToRegister(left), ToOperand(right));
1967 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1968 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1973 void LCodeGen::DoConstantI(LConstantI* instr) {
1974 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1978 void LCodeGen::DoConstantS(LConstantS* instr) {
1979 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1983 void LCodeGen::DoConstantD(LConstantD* instr) {
1984 uint64_t const bits = instr->bits();
1985 uint32_t const lower = static_cast<uint32_t>(bits);
1986 uint32_t const upper = static_cast<uint32_t>(bits >> 32);
1987 DCHECK(instr->result()->IsDoubleRegister());
1989 __ push(Immediate(upper));
1990 __ push(Immediate(lower));
1991 X87Register reg = ToX87Register(instr->result());
1992 X87Mov(reg, Operand(esp, 0));
1993 __ add(Operand(esp), Immediate(kDoubleSize));
1997 void LCodeGen::DoConstantE(LConstantE* instr) {
1998 __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
2002 void LCodeGen::DoConstantT(LConstantT* instr) {
2003 Register reg = ToRegister(instr->result());
2004 Handle<Object> object = instr->value(isolate());
2005 AllowDeferredHandleDereference smi_check;
2006 __ LoadObject(reg, object);
2010 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
2011 Register result = ToRegister(instr->result());
2012 Register map = ToRegister(instr->value());
2013 __ EnumLength(result, map);
2017 void LCodeGen::DoDateField(LDateField* instr) {
2018 Register object = ToRegister(instr->date());
2019 Register result = ToRegister(instr->result());
2020 Register scratch = ToRegister(instr->temp());
2021 Smi* index = instr->index();
2022 DCHECK(object.is(result));
2023 DCHECK(object.is(eax));
2025 if (index->value() == 0) {
2026 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
2028 Label runtime, done;
2029 if (index->value() < JSDate::kFirstUncachedField) {
2030 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
2031 __ mov(scratch, Operand::StaticVariable(stamp));
2032 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
2033 __ j(not_equal, &runtime, Label::kNear);
2034 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
2035 kPointerSize * index->value()));
2036 __ jmp(&done, Label::kNear);
2039 __ PrepareCallCFunction(2, scratch);
2040 __ mov(Operand(esp, 0), object);
2041 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
2042 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
2048 Operand LCodeGen::BuildSeqStringOperand(Register string,
2050 String::Encoding encoding) {
2051 if (index->IsConstantOperand()) {
2052 int offset = ToRepresentation(LConstantOperand::cast(index),
2053 Representation::Integer32());
2054 if (encoding == String::TWO_BYTE_ENCODING) {
2055 offset *= kUC16Size;
2057 STATIC_ASSERT(kCharSize == 1);
2058 return FieldOperand(string, SeqString::kHeaderSize + offset);
2060 return FieldOperand(
2061 string, ToRegister(index),
2062 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
2063 SeqString::kHeaderSize);
2067 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
2068 String::Encoding encoding = instr->hydrogen()->encoding();
2069 Register result = ToRegister(instr->result());
2070 Register string = ToRegister(instr->string());
2072 if (FLAG_debug_code) {
2074 __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
2075 __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
2077 __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
2078 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2079 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2080 __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
2081 ? one_byte_seq_type : two_byte_seq_type));
2082 __ Check(equal, kUnexpectedStringType);
2086 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2087 if (encoding == String::ONE_BYTE_ENCODING) {
2088 __ movzx_b(result, operand);
2090 __ movzx_w(result, operand);
2095 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
2096 String::Encoding encoding = instr->hydrogen()->encoding();
2097 Register string = ToRegister(instr->string());
2099 if (FLAG_debug_code) {
2100 Register value = ToRegister(instr->value());
2101 Register index = ToRegister(instr->index());
2102 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
2103 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
2105 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
2106 ? one_byte_seq_type : two_byte_seq_type;
2107 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
2110 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
2111 if (instr->value()->IsConstantOperand()) {
2112 int value = ToRepresentation(LConstantOperand::cast(instr->value()),
2113 Representation::Integer32());
2114 DCHECK_LE(0, value);
2115 if (encoding == String::ONE_BYTE_ENCODING) {
2116 DCHECK_LE(value, String::kMaxOneByteCharCode);
2117 __ mov_b(operand, static_cast<int8_t>(value));
2119 DCHECK_LE(value, String::kMaxUtf16CodeUnit);
2120 __ mov_w(operand, static_cast<int16_t>(value));
2123 Register value = ToRegister(instr->value());
2124 if (encoding == String::ONE_BYTE_ENCODING) {
2125 __ mov_b(operand, value);
2127 __ mov_w(operand, value);
2133 void LCodeGen::DoAddI(LAddI* instr) {
2134 LOperand* left = instr->left();
2135 LOperand* right = instr->right();
2137 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
2138 if (right->IsConstantOperand()) {
2139 int32_t offset = ToRepresentation(LConstantOperand::cast(right),
2140 instr->hydrogen()->representation());
2141 __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
2143 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
2144 __ lea(ToRegister(instr->result()), address);
2147 if (right->IsConstantOperand()) {
2148 __ add(ToOperand(left),
2149 ToImmediate(right, instr->hydrogen()->representation()));
2151 __ add(ToRegister(left), ToOperand(right));
2153 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
2154 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
2160 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
2161 LOperand* left = instr->left();
2162 LOperand* right = instr->right();
2163 DCHECK(left->Equals(instr->result()));
2164 HMathMinMax::Operation operation = instr->hydrogen()->operation();
2165 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
2167 Condition condition = (operation == HMathMinMax::kMathMin)
2170 if (right->IsConstantOperand()) {
2171 Operand left_op = ToOperand(left);
2172 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
2173 instr->hydrogen()->representation());
2174 __ cmp(left_op, immediate);
2175 __ j(condition, &return_left, Label::kNear);
2176 __ mov(left_op, immediate);
2178 Register left_reg = ToRegister(left);
2179 Operand right_op = ToOperand(right);
2180 __ cmp(left_reg, right_op);
2181 __ j(condition, &return_left, Label::kNear);
2182 __ mov(left_reg, right_op);
2184 __ bind(&return_left);
2186 DCHECK(instr->hydrogen()->representation().IsDouble());
2187 Label check_nan_left, check_zero, return_left, return_right;
2188 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
2189 X87Register left_reg = ToX87Register(left);
2190 X87Register right_reg = ToX87Register(right);
2192 X87PrepareBinaryOp(left_reg, right_reg, ToX87Register(instr->result()));
2196 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
2197 __ j(equal, &check_zero, Label::kNear); // left == right.
2198 __ j(condition, &return_left, Label::kNear);
2199 __ jmp(&return_right, Label::kNear);
2201 __ bind(&check_zero);
2205 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
2206 // At this point, both left and right are either 0 or -0.
2207 if (operation == HMathMinMax::kMathMin) {
2208 // Push st0 and st1 to stack, then pop them to temp registers and OR them,
2210 Register scratch_reg = ToRegister(instr->temp());
2213 __ sub(esp, Immediate(2 * kPointerSize));
2214 __ fstp_s(MemOperand(esp, 0));
2215 __ fstp_s(MemOperand(esp, kPointerSize));
2216 __ pop(scratch_reg);
2217 __ xor_(MemOperand(esp, 0), scratch_reg);
2218 X87Mov(left_reg, MemOperand(esp, 0), kX87FloatOperand);
2219 __ pop(scratch_reg); // restore esp
2221 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
2225 __ jmp(&return_left, Label::kNear);
2227 __ bind(&check_nan_left);
2230 __ FCmp(); // NaN check.
2231 __ j(parity_even, &return_left, Label::kNear); // left == NaN.
2233 __ bind(&return_right);
2235 X87Mov(left_reg, right_reg);
2237 __ bind(&return_left);
2242 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
2243 X87Register left = ToX87Register(instr->left());
2244 X87Register right = ToX87Register(instr->right());
2245 X87Register result = ToX87Register(instr->result());
2246 if (instr->op() != Token::MOD) {
2247 X87PrepareBinaryOp(left, right, result);
2249 // Set the precision control to double-precision.
2250 __ X87SetFPUCW(0x027F);
2251 switch (instr->op()) {
2265 // Pass two doubles as arguments on the stack.
2266 __ PrepareCallCFunction(4, eax);
2267 X87Mov(Operand(esp, 1 * kDoubleSize), right);
2268 X87Mov(Operand(esp, 0), left);
2270 DCHECK(left.is(result));
2271 X87PrepareToWrite(result);
2273 ExternalReference::mod_two_doubles_operation(isolate()),
2276 // Return value is in st(0) on ia32.
2277 X87CommitWrite(result);
2285 // Restore the default value of control word.
2286 __ X87SetFPUCW(0x037F);
2290 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2291 DCHECK(ToRegister(instr->context()).is(esi));
2292 DCHECK(ToRegister(instr->left()).is(edx));
2293 DCHECK(ToRegister(instr->right()).is(eax));
2294 DCHECK(ToRegister(instr->result()).is(eax));
2297 CodeFactory::BinaryOpIC(isolate(), instr->op(), instr->strength()).code();
2298 CallCode(code, RelocInfo::CODE_TARGET, instr);
2302 template<class InstrType>
2303 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2304 int left_block = instr->TrueDestination(chunk_);
2305 int right_block = instr->FalseDestination(chunk_);
2307 int next_block = GetNextEmittedBlock();
2309 if (right_block == left_block || cc == no_condition) {
2310 EmitGoto(left_block);
2311 } else if (left_block == next_block) {
2312 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2313 } else if (right_block == next_block) {
2314 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2316 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2317 __ jmp(chunk_->GetAssemblyLabel(right_block));
2322 template<class InstrType>
2323 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2324 int false_block = instr->FalseDestination(chunk_);
2325 if (cc == no_condition) {
2326 __ jmp(chunk_->GetAssemblyLabel(false_block));
2328 __ j(cc, chunk_->GetAssemblyLabel(false_block));
2333 void LCodeGen::DoBranch(LBranch* instr) {
2334 Representation r = instr->hydrogen()->value()->representation();
2335 if (r.IsSmiOrInteger32()) {
2336 Register reg = ToRegister(instr->value());
2337 __ test(reg, Operand(reg));
2338 EmitBranch(instr, not_zero);
2339 } else if (r.IsDouble()) {
2340 X87Register reg = ToX87Register(instr->value());
2341 X87LoadForUsage(reg);
2344 EmitBranch(instr, not_zero);
2346 DCHECK(r.IsTagged());
2347 Register reg = ToRegister(instr->value());
2348 HType type = instr->hydrogen()->value()->type();
2349 if (type.IsBoolean()) {
2350 DCHECK(!info()->IsStub());
2351 __ cmp(reg, factory()->true_value());
2352 EmitBranch(instr, equal);
2353 } else if (type.IsSmi()) {
2354 DCHECK(!info()->IsStub());
2355 __ test(reg, Operand(reg));
2356 EmitBranch(instr, not_equal);
2357 } else if (type.IsJSArray()) {
2358 DCHECK(!info()->IsStub());
2359 EmitBranch(instr, no_condition);
2360 } else if (type.IsHeapNumber()) {
2362 } else if (type.IsString()) {
2363 DCHECK(!info()->IsStub());
2364 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2365 EmitBranch(instr, not_equal);
2367 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2368 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2370 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2371 // undefined -> false.
2372 __ cmp(reg, factory()->undefined_value());
2373 __ j(equal, instr->FalseLabel(chunk_));
2375 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2377 __ cmp(reg, factory()->true_value());
2378 __ j(equal, instr->TrueLabel(chunk_));
2380 __ cmp(reg, factory()->false_value());
2381 __ j(equal, instr->FalseLabel(chunk_));
2383 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2385 __ cmp(reg, factory()->null_value());
2386 __ j(equal, instr->FalseLabel(chunk_));
2389 if (expected.Contains(ToBooleanStub::SMI)) {
2390 // Smis: 0 -> false, all other -> true.
2391 __ test(reg, Operand(reg));
2392 __ j(equal, instr->FalseLabel(chunk_));
2393 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2394 } else if (expected.NeedsMap()) {
2395 // If we need a map later and have a Smi -> deopt.
2396 __ test(reg, Immediate(kSmiTagMask));
2397 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2400 Register map = no_reg; // Keep the compiler happy.
2401 if (expected.NeedsMap()) {
2402 map = ToRegister(instr->temp());
2403 DCHECK(!map.is(reg));
2404 __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2406 if (expected.CanBeUndetectable()) {
2407 // Undetectable -> false.
2408 __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2409 1 << Map::kIsUndetectable);
2410 __ j(not_zero, instr->FalseLabel(chunk_));
2414 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2415 // spec object -> true.
2416 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2417 __ j(above_equal, instr->TrueLabel(chunk_));
2420 if (expected.Contains(ToBooleanStub::STRING)) {
2421 // String value -> false iff empty.
2423 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2424 __ j(above_equal, ¬_string, Label::kNear);
2425 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2426 __ j(not_zero, instr->TrueLabel(chunk_));
2427 __ jmp(instr->FalseLabel(chunk_));
2428 __ bind(¬_string);
2431 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2432 // Symbol value -> true.
2433 __ CmpInstanceType(map, SYMBOL_TYPE);
2434 __ j(equal, instr->TrueLabel(chunk_));
2437 if (expected.Contains(ToBooleanStub::SIMD_VALUE)) {
2438 // SIMD value -> true.
2439 __ CmpInstanceType(map, FLOAT32X4_TYPE);
2440 __ j(equal, instr->TrueLabel(chunk_));
2443 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2444 // heap number -> false iff +0, -0, or NaN.
2445 Label not_heap_number;
2446 __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2447 factory()->heap_number_map());
2448 __ j(not_equal, ¬_heap_number, Label::kNear);
2450 __ fld_d(FieldOperand(reg, HeapNumber::kValueOffset));
2452 __ j(zero, instr->FalseLabel(chunk_));
2453 __ jmp(instr->TrueLabel(chunk_));
2454 __ bind(¬_heap_number);
2457 if (!expected.IsGeneric()) {
2458 // We've seen something for the first time -> deopt.
2459 // This can only happen if we are not generic already.
2460 DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2467 void LCodeGen::EmitGoto(int block) {
2468 if (!IsNextEmittedBlock(block)) {
2469 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2474 void LCodeGen::DoClobberDoubles(LClobberDoubles* instr) {
2478 void LCodeGen::DoGoto(LGoto* instr) {
2479 EmitGoto(instr->block_id());
2483 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2484 Condition cond = no_condition;
2487 case Token::EQ_STRICT:
2491 case Token::NE_STRICT:
2495 cond = is_unsigned ? below : less;
2498 cond = is_unsigned ? above : greater;
2501 cond = is_unsigned ? below_equal : less_equal;
2504 cond = is_unsigned ? above_equal : greater_equal;
2507 case Token::INSTANCEOF:
2515 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2516 LOperand* left = instr->left();
2517 LOperand* right = instr->right();
2519 instr->is_double() ||
2520 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2521 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2522 Condition cc = TokenToCondition(instr->op(), is_unsigned);
2524 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2525 // We can statically evaluate the comparison.
2526 double left_val = ToDouble(LConstantOperand::cast(left));
2527 double right_val = ToDouble(LConstantOperand::cast(right));
2528 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2529 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2530 EmitGoto(next_block);
2532 if (instr->is_double()) {
2533 X87LoadForUsage(ToX87Register(right), ToX87Register(left));
2535 // Don't base result on EFLAGS when a NaN is involved. Instead
2536 // jump to the false block.
2537 __ j(parity_even, instr->FalseLabel(chunk_));
2539 if (right->IsConstantOperand()) {
2540 __ cmp(ToOperand(left),
2541 ToImmediate(right, instr->hydrogen()->representation()));
2542 } else if (left->IsConstantOperand()) {
2543 __ cmp(ToOperand(right),
2544 ToImmediate(left, instr->hydrogen()->representation()));
2545 // We commuted the operands, so commute the condition.
2546 cc = CommuteCondition(cc);
2548 __ cmp(ToRegister(left), ToOperand(right));
2551 EmitBranch(instr, cc);
2556 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2557 Register left = ToRegister(instr->left());
2559 if (instr->right()->IsConstantOperand()) {
2560 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2561 __ CmpObject(left, right);
2563 Operand right = ToOperand(instr->right());
2564 __ cmp(left, right);
2566 EmitBranch(instr, equal);
2570 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2571 if (instr->hydrogen()->representation().IsTagged()) {
2572 Register input_reg = ToRegister(instr->object());
2573 __ cmp(input_reg, factory()->the_hole_value());
2574 EmitBranch(instr, equal);
2578 // Put the value to the top of stack
2579 X87Register src = ToX87Register(instr->object());
2580 X87LoadForUsage(src);
2585 __ j(parity_even, &ok, Label::kNear);
2587 EmitFalseBranch(instr, no_condition);
2591 __ sub(esp, Immediate(kDoubleSize));
2592 __ fstp_d(MemOperand(esp, 0));
2594 __ add(esp, Immediate(kDoubleSize));
2595 int offset = sizeof(kHoleNanUpper32);
2596 // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
2597 // so we check the upper with 0xffffffff for hole as a temporary fix.
2598 __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
2599 EmitBranch(instr, equal);
2603 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2604 Representation rep = instr->hydrogen()->value()->representation();
2605 DCHECK(!rep.IsInteger32());
2607 if (rep.IsDouble()) {
2608 X87Register input = ToX87Register(instr->value());
2609 X87LoadForUsage(input);
2611 EmitBranch(instr, equal);
2613 Register value = ToRegister(instr->value());
2614 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2615 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2616 __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2618 EmitFalseBranch(instr, no_overflow);
2619 __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2620 Immediate(0x00000000));
2621 EmitBranch(instr, equal);
2626 Condition LCodeGen::EmitIsObject(Register input,
2628 Label* is_not_object,
2630 __ JumpIfSmi(input, is_not_object);
2632 __ cmp(input, isolate()->factory()->null_value());
2633 __ j(equal, is_object);
2635 __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
2636 // Undetectable objects behave like undefined.
2637 __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
2638 1 << Map::kIsUndetectable);
2639 __ j(not_zero, is_not_object);
2641 __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
2642 __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2643 __ j(below, is_not_object);
2644 __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2649 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2650 Register reg = ToRegister(instr->value());
2651 Register temp = ToRegister(instr->temp());
2653 Condition true_cond = EmitIsObject(
2654 reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2656 EmitBranch(instr, true_cond);
2660 Condition LCodeGen::EmitIsString(Register input,
2662 Label* is_not_string,
2663 SmiCheck check_needed = INLINE_SMI_CHECK) {
2664 if (check_needed == INLINE_SMI_CHECK) {
2665 __ JumpIfSmi(input, is_not_string);
2668 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2674 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2675 Register reg = ToRegister(instr->value());
2676 Register temp = ToRegister(instr->temp());
2678 SmiCheck check_needed =
2679 instr->hydrogen()->value()->type().IsHeapObject()
2680 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2682 Condition true_cond = EmitIsString(
2683 reg, temp, instr->FalseLabel(chunk_), check_needed);
2685 EmitBranch(instr, true_cond);
2689 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2690 Operand input = ToOperand(instr->value());
2692 __ test(input, Immediate(kSmiTagMask));
2693 EmitBranch(instr, zero);
2697 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2698 Register input = ToRegister(instr->value());
2699 Register temp = ToRegister(instr->temp());
2701 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2702 STATIC_ASSERT(kSmiTag == 0);
2703 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2705 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2706 __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2707 1 << Map::kIsUndetectable);
2708 EmitBranch(instr, not_zero);
2712 static Condition ComputeCompareCondition(Token::Value op) {
2714 case Token::EQ_STRICT:
2724 return greater_equal;
2727 return no_condition;
2732 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2733 Token::Value op = instr->op();
2736 CodeFactory::CompareIC(isolate(), op, Strength::WEAK).code();
2737 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2739 Condition condition = ComputeCompareCondition(op);
2740 __ test(eax, Operand(eax));
2742 EmitBranch(instr, condition);
2746 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2747 InstanceType from = instr->from();
2748 InstanceType to = instr->to();
2749 if (from == FIRST_TYPE) return to;
2750 DCHECK(from == to || to == LAST_TYPE);
2755 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2756 InstanceType from = instr->from();
2757 InstanceType to = instr->to();
2758 if (from == to) return equal;
2759 if (to == LAST_TYPE) return above_equal;
2760 if (from == FIRST_TYPE) return below_equal;
2766 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2767 Register input = ToRegister(instr->value());
2768 Register temp = ToRegister(instr->temp());
2770 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2771 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2774 __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2775 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2779 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2780 Register input = ToRegister(instr->value());
2781 Register result = ToRegister(instr->result());
2783 __ AssertString(input);
2785 __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2786 __ IndexFromHash(result, result);
2790 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2791 LHasCachedArrayIndexAndBranch* instr) {
2792 Register input = ToRegister(instr->value());
2794 __ test(FieldOperand(input, String::kHashFieldOffset),
2795 Immediate(String::kContainsCachedArrayIndexMask));
2796 EmitBranch(instr, equal);
2800 // Branches to a label or falls through with the answer in the z flag. Trashes
2801 // the temp registers, but not the input.
2802 void LCodeGen::EmitClassOfTest(Label* is_true,
2804 Handle<String>class_name,
2808 DCHECK(!input.is(temp));
2809 DCHECK(!input.is(temp2));
2810 DCHECK(!temp.is(temp2));
2811 __ JumpIfSmi(input, is_false);
2813 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2814 // Assuming the following assertions, we can use the same compares to test
2815 // for both being a function type and being in the object type range.
2816 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2817 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2818 FIRST_SPEC_OBJECT_TYPE + 1);
2819 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2820 LAST_SPEC_OBJECT_TYPE - 1);
2821 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2822 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2823 __ j(below, is_false);
2824 __ j(equal, is_true);
2825 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2826 __ j(equal, is_true);
2828 // Faster code path to avoid two compares: subtract lower bound from the
2829 // actual type and do a signed compare with the width of the type range.
2830 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2831 __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2832 __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2833 __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2834 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2835 __ j(above, is_false);
2838 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2839 // Check if the constructor in the map is a function.
2840 __ GetMapConstructor(temp, temp, temp2);
2841 // Objects with a non-function constructor have class 'Object'.
2842 __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2843 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2844 __ j(not_equal, is_true);
2846 __ j(not_equal, is_false);
2849 // temp now contains the constructor function. Grab the
2850 // instance class name from there.
2851 __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2852 __ mov(temp, FieldOperand(temp,
2853 SharedFunctionInfo::kInstanceClassNameOffset));
2854 // The class name we are testing against is internalized since it's a literal.
2855 // The name in the constructor is internalized because of the way the context
2856 // is booted. This routine isn't expected to work for random API-created
2857 // classes and it doesn't have to because you can't access it with natives
2858 // syntax. Since both sides are internalized it is sufficient to use an
2859 // identity comparison.
2860 __ cmp(temp, class_name);
2861 // End with the answer in the z flag.
2865 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2866 Register input = ToRegister(instr->value());
2867 Register temp = ToRegister(instr->temp());
2868 Register temp2 = ToRegister(instr->temp2());
2870 Handle<String> class_name = instr->hydrogen()->class_name();
2872 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2873 class_name, input, temp, temp2);
2875 EmitBranch(instr, equal);
2879 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2880 Register reg = ToRegister(instr->value());
2881 __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2882 EmitBranch(instr, equal);
2886 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2887 // Object and function are in fixed registers defined by the stub.
2888 DCHECK(ToRegister(instr->context()).is(esi));
2889 InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2890 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2892 Label true_value, done;
2893 __ test(eax, Operand(eax));
2894 __ j(zero, &true_value, Label::kNear);
2895 __ mov(ToRegister(instr->result()), factory()->false_value());
2896 __ jmp(&done, Label::kNear);
2897 __ bind(&true_value);
2898 __ mov(ToRegister(instr->result()), factory()->true_value());
2903 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2904 class DeferredInstanceOfKnownGlobal final : public LDeferredCode {
2906 DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2907 LInstanceOfKnownGlobal* instr,
2908 const X87Stack& x87_stack)
2909 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
2910 void Generate() override {
2911 codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2913 LInstruction* instr() override { return instr_; }
2914 Label* map_check() { return &map_check_; }
2916 LInstanceOfKnownGlobal* instr_;
2920 DeferredInstanceOfKnownGlobal* deferred;
2921 deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr, x87_stack_);
2923 Label done, false_result;
2924 Register object = ToRegister(instr->value());
2925 Register temp = ToRegister(instr->temp());
2927 // A Smi is not an instance of anything.
2928 __ JumpIfSmi(object, &false_result, Label::kNear);
2930 // This is the inlined call site instanceof cache. The two occurences of the
2931 // hole value will be patched to the last map/result pair generated by the
2934 Register map = ToRegister(instr->temp());
2935 __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2936 __ bind(deferred->map_check()); // Label for calculating code patching.
2937 Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2938 __ cmp(map, Operand::ForCell(cache_cell)); // Patched to cached map.
2939 __ j(not_equal, &cache_miss, Label::kNear);
2940 __ mov(eax, factory()->the_hole_value()); // Patched to either true or false.
2941 __ jmp(&done, Label::kNear);
2943 // The inlined call site cache did not match. Check for null and string
2944 // before calling the deferred code.
2945 __ bind(&cache_miss);
2946 // Null is not an instance of anything.
2947 __ cmp(object, factory()->null_value());
2948 __ j(equal, &false_result, Label::kNear);
2950 // String values are not instances of anything.
2951 Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2952 __ j(is_string, &false_result, Label::kNear);
2954 // Go to the deferred code.
2955 __ jmp(deferred->entry());
2957 __ bind(&false_result);
2958 __ mov(ToRegister(instr->result()), factory()->false_value());
2960 // Here result has either true or false. Deferred code also produces true or
2962 __ bind(deferred->exit());
2967 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
2969 PushSafepointRegistersScope scope(this);
2971 InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
2972 flags = static_cast<InstanceofStub::Flags>(
2973 flags | InstanceofStub::kArgsInRegisters);
2974 flags = static_cast<InstanceofStub::Flags>(
2975 flags | InstanceofStub::kCallSiteInlineCheck);
2976 flags = static_cast<InstanceofStub::Flags>(
2977 flags | InstanceofStub::kReturnTrueFalseObject);
2978 InstanceofStub stub(isolate(), flags);
2980 // Get the temp register reserved by the instruction. This needs to be a
2981 // register which is pushed last by PushSafepointRegisters as top of the
2982 // stack is used to pass the offset to the location of the map check to
2984 Register temp = ToRegister(instr->temp());
2985 DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
2986 __ LoadHeapObject(InstanceofStub::right(), instr->function());
2987 static const int kAdditionalDelta = 13;
2988 int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
2989 __ mov(temp, Immediate(delta));
2990 __ StoreToSafepointRegisterSlot(temp, temp);
2991 CallCodeGeneric(stub.GetCode(),
2992 RelocInfo::CODE_TARGET,
2994 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
2995 // Get the deoptimization index of the LLazyBailout-environment that
2996 // corresponds to this instruction.
2997 LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
2998 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
3000 // Put the result value into the eax slot and restore all registers.
3001 __ StoreToSafepointRegisterSlot(eax, eax);
3005 void LCodeGen::DoCmpT(LCmpT* instr) {
3006 Token::Value op = instr->op();
3009 CodeFactory::CompareIC(isolate(), op, instr->strength()).code();
3010 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3012 Condition condition = ComputeCompareCondition(op);
3013 Label true_value, done;
3014 __ test(eax, Operand(eax));
3015 __ j(condition, &true_value, Label::kNear);
3016 __ mov(ToRegister(instr->result()), factory()->false_value());
3017 __ jmp(&done, Label::kNear);
3018 __ bind(&true_value);
3019 __ mov(ToRegister(instr->result()), factory()->true_value());
3024 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
3025 int extra_value_count = dynamic_frame_alignment ? 2 : 1;
3027 if (instr->has_constant_parameter_count()) {
3028 int parameter_count = ToInteger32(instr->constant_parameter_count());
3029 if (dynamic_frame_alignment && FLAG_debug_code) {
3031 (parameter_count + extra_value_count) * kPointerSize),
3032 Immediate(kAlignmentZapValue));
3033 __ Assert(equal, kExpectedAlignmentMarker);
3035 __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
3037 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
3038 Register reg = ToRegister(instr->parameter_count());
3039 // The argument count parameter is a smi
3041 Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
3042 if (dynamic_frame_alignment && FLAG_debug_code) {
3043 DCHECK(extra_value_count == 2);
3044 __ cmp(Operand(esp, reg, times_pointer_size,
3045 extra_value_count * kPointerSize),
3046 Immediate(kAlignmentZapValue));
3047 __ Assert(equal, kExpectedAlignmentMarker);
3050 // emit code to restore stack based on instr->parameter_count()
3051 __ pop(return_addr_reg); // save return address
3052 if (dynamic_frame_alignment) {
3053 __ inc(reg); // 1 more for alignment
3055 __ shl(reg, kPointerSizeLog2);
3057 __ jmp(return_addr_reg);
3062 void LCodeGen::DoReturn(LReturn* instr) {
3063 if (FLAG_trace && info()->IsOptimizing()) {
3064 // Preserve the return value on the stack and rely on the runtime call
3065 // to return the value in the same register. We're leaving the code
3066 // managed by the register allocator and tearing down the frame, it's
3067 // safe to write to the context register.
3069 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3070 __ CallRuntime(Runtime::kTraceExit, 1);
3072 if (dynamic_frame_alignment_) {
3073 // Fetch the state of the dynamic frame alignment.
3074 __ mov(edx, Operand(ebp,
3075 JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
3077 int no_frame_start = -1;
3078 if (NeedsEagerFrame()) {
3081 no_frame_start = masm_->pc_offset();
3083 if (dynamic_frame_alignment_) {
3085 __ cmp(edx, Immediate(kNoAlignmentPadding));
3086 __ j(equal, &no_padding, Label::kNear);
3088 EmitReturn(instr, true);
3089 __ bind(&no_padding);
3092 EmitReturn(instr, false);
3093 if (no_frame_start != -1) {
3094 info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
3100 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
3101 Register vector_register = ToRegister(instr->temp_vector());
3102 Register slot_register = LoadWithVectorDescriptor::SlotRegister();
3103 DCHECK(vector_register.is(LoadWithVectorDescriptor::VectorRegister()));
3104 DCHECK(slot_register.is(eax));
3106 AllowDeferredHandleDereference vector_structure_check;
3107 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3108 __ mov(vector_register, vector);
3109 // No need to allocate this register.
3110 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
3111 int index = vector->GetIndex(slot);
3112 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3117 void LCodeGen::EmitVectorStoreICRegisters(T* instr) {
3118 Register vector_register = ToRegister(instr->temp_vector());
3119 Register slot_register = ToRegister(instr->temp_slot());
3121 AllowDeferredHandleDereference vector_structure_check;
3122 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3123 __ mov(vector_register, vector);
3124 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
3125 int index = vector->GetIndex(slot);
3126 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3130 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
3131 DCHECK(ToRegister(instr->context()).is(esi));
3132 DCHECK(ToRegister(instr->global_object())
3133 .is(LoadDescriptor::ReceiverRegister()));
3134 DCHECK(ToRegister(instr->result()).is(eax));
3136 __ mov(LoadDescriptor::NameRegister(), instr->name());
3137 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
3139 CodeFactory::LoadICInOptimizedCode(isolate(), instr->typeof_mode(),
3140 SLOPPY, PREMONOMORPHIC).code();
3141 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3145 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
3146 Register context = ToRegister(instr->context());
3147 Register result = ToRegister(instr->result());
3148 __ mov(result, ContextOperand(context, instr->slot_index()));
3150 if (instr->hydrogen()->RequiresHoleCheck()) {
3151 __ cmp(result, factory()->the_hole_value());
3152 if (instr->hydrogen()->DeoptimizesOnHole()) {
3153 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3156 __ j(not_equal, &is_not_hole, Label::kNear);
3157 __ mov(result, factory()->undefined_value());
3158 __ bind(&is_not_hole);
3164 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
3165 Register context = ToRegister(instr->context());
3166 Register value = ToRegister(instr->value());
3168 Label skip_assignment;
3170 Operand target = ContextOperand(context, instr->slot_index());
3171 if (instr->hydrogen()->RequiresHoleCheck()) {
3172 __ cmp(target, factory()->the_hole_value());
3173 if (instr->hydrogen()->DeoptimizesOnHole()) {
3174 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3176 __ j(not_equal, &skip_assignment, Label::kNear);
3180 __ mov(target, value);
3181 if (instr->hydrogen()->NeedsWriteBarrier()) {
3182 SmiCheck check_needed =
3183 instr->hydrogen()->value()->type().IsHeapObject()
3184 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
3185 Register temp = ToRegister(instr->temp());
3186 int offset = Context::SlotOffset(instr->slot_index());
3187 __ RecordWriteContextSlot(context, offset, value, temp, kSaveFPRegs,
3188 EMIT_REMEMBERED_SET, check_needed);
3191 __ bind(&skip_assignment);
3195 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
3196 HObjectAccess access = instr->hydrogen()->access();
3197 int offset = access.offset();
3199 if (access.IsExternalMemory()) {
3200 Register result = ToRegister(instr->result());
3201 MemOperand operand = instr->object()->IsConstantOperand()
3202 ? MemOperand::StaticVariable(ToExternalReference(
3203 LConstantOperand::cast(instr->object())))
3204 : MemOperand(ToRegister(instr->object()), offset);
3205 __ Load(result, operand, access.representation());
3209 Register object = ToRegister(instr->object());
3210 if (instr->hydrogen()->representation().IsDouble()) {
3211 X87Mov(ToX87Register(instr->result()), FieldOperand(object, offset));
3215 Register result = ToRegister(instr->result());
3216 if (!access.IsInobject()) {
3217 __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
3220 __ Load(result, FieldOperand(object, offset), access.representation());
3224 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
3225 DCHECK(!operand->IsDoubleRegister());
3226 if (operand->IsConstantOperand()) {
3227 Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
3228 AllowDeferredHandleDereference smi_check;
3229 if (object->IsSmi()) {
3230 __ Push(Handle<Smi>::cast(object));
3232 __ PushHeapObject(Handle<HeapObject>::cast(object));
3234 } else if (operand->IsRegister()) {
3235 __ push(ToRegister(operand));
3237 __ push(ToOperand(operand));
3242 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3243 DCHECK(ToRegister(instr->context()).is(esi));
3244 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3245 DCHECK(ToRegister(instr->result()).is(eax));
3247 __ mov(LoadDescriptor::NameRegister(), instr->name());
3248 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3250 CodeFactory::LoadICInOptimizedCode(
3251 isolate(), NOT_INSIDE_TYPEOF, instr->hydrogen()->language_mode(),
3252 instr->hydrogen()->initialization_state()).code();
3253 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3257 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3258 Register function = ToRegister(instr->function());
3259 Register temp = ToRegister(instr->temp());
3260 Register result = ToRegister(instr->result());
3262 // Get the prototype or initial map from the function.
3264 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
3266 // Check that the function has a prototype or an initial map.
3267 __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3268 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3270 // If the function does not have an initial map, we're done.
3272 __ CmpObjectType(result, MAP_TYPE, temp);
3273 __ j(not_equal, &done, Label::kNear);
3275 // Get the prototype from the initial map.
3276 __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3283 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3284 Register result = ToRegister(instr->result());
3285 __ LoadRoot(result, instr->index());
3289 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3290 Register arguments = ToRegister(instr->arguments());
3291 Register result = ToRegister(instr->result());
3292 if (instr->length()->IsConstantOperand() &&
3293 instr->index()->IsConstantOperand()) {
3294 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3295 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3296 int index = (const_length - const_index) + 1;
3297 __ mov(result, Operand(arguments, index * kPointerSize));
3299 Register length = ToRegister(instr->length());
3300 Operand index = ToOperand(instr->index());
3301 // There are two words between the frame pointer and the last argument.
3302 // Subtracting from length accounts for one of them add one more.
3303 __ sub(length, index);
3304 __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3309 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3310 ElementsKind elements_kind = instr->elements_kind();
3311 LOperand* key = instr->key();
3312 if (!key->IsConstantOperand() &&
3313 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3315 __ SmiUntag(ToRegister(key));
3317 Operand operand(BuildFastArrayOperand(
3320 instr->hydrogen()->key()->representation(),
3322 instr->base_offset()));
3323 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
3324 elements_kind == FLOAT32_ELEMENTS) {
3325 X87Mov(ToX87Register(instr->result()), operand, kX87FloatOperand);
3326 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
3327 elements_kind == FLOAT64_ELEMENTS) {
3328 X87Mov(ToX87Register(instr->result()), operand);
3330 Register result(ToRegister(instr->result()));
3331 switch (elements_kind) {
3332 case EXTERNAL_INT8_ELEMENTS:
3334 __ movsx_b(result, operand);
3336 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3337 case EXTERNAL_UINT8_ELEMENTS:
3338 case UINT8_ELEMENTS:
3339 case UINT8_CLAMPED_ELEMENTS:
3340 __ movzx_b(result, operand);
3342 case EXTERNAL_INT16_ELEMENTS:
3343 case INT16_ELEMENTS:
3344 __ movsx_w(result, operand);
3346 case EXTERNAL_UINT16_ELEMENTS:
3347 case UINT16_ELEMENTS:
3348 __ movzx_w(result, operand);
3350 case EXTERNAL_INT32_ELEMENTS:
3351 case INT32_ELEMENTS:
3352 __ mov(result, operand);
3354 case EXTERNAL_UINT32_ELEMENTS:
3355 case UINT32_ELEMENTS:
3356 __ mov(result, operand);
3357 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3358 __ test(result, Operand(result));
3359 DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3362 case EXTERNAL_FLOAT32_ELEMENTS:
3363 case EXTERNAL_FLOAT64_ELEMENTS:
3364 case FLOAT32_ELEMENTS:
3365 case FLOAT64_ELEMENTS:
3366 case FAST_SMI_ELEMENTS:
3368 case FAST_DOUBLE_ELEMENTS:
3369 case FAST_HOLEY_SMI_ELEMENTS:
3370 case FAST_HOLEY_ELEMENTS:
3371 case FAST_HOLEY_DOUBLE_ELEMENTS:
3372 case DICTIONARY_ELEMENTS:
3373 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
3374 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
3382 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3383 if (instr->hydrogen()->RequiresHoleCheck()) {
3384 Operand hole_check_operand = BuildFastArrayOperand(
3385 instr->elements(), instr->key(),
3386 instr->hydrogen()->key()->representation(),
3387 FAST_DOUBLE_ELEMENTS,
3388 instr->base_offset() + sizeof(kHoleNanLower32));
3389 __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3390 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3393 Operand double_load_operand = BuildFastArrayOperand(
3396 instr->hydrogen()->key()->representation(),
3397 FAST_DOUBLE_ELEMENTS,
3398 instr->base_offset());
3399 X87Mov(ToX87Register(instr->result()), double_load_operand);
3403 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3404 Register result = ToRegister(instr->result());
3408 BuildFastArrayOperand(instr->elements(), instr->key(),
3409 instr->hydrogen()->key()->representation(),
3410 FAST_ELEMENTS, instr->base_offset()));
3412 // Check for the hole value.
3413 if (instr->hydrogen()->RequiresHoleCheck()) {
3414 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3415 __ test(result, Immediate(kSmiTagMask));
3416 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3418 __ cmp(result, factory()->the_hole_value());
3419 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3421 } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3422 DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3424 __ cmp(result, factory()->the_hole_value());
3425 __ j(not_equal, &done);
3426 if (info()->IsStub()) {
3427 // A stub can safely convert the hole to undefined only if the array
3428 // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3429 // it needs to bail out.
3430 __ mov(result, isolate()->factory()->array_protector());
3431 __ cmp(FieldOperand(result, PropertyCell::kValueOffset),
3432 Immediate(Smi::FromInt(Isolate::kArrayProtectorValid)));
3433 DeoptimizeIf(not_equal, instr, Deoptimizer::kHole);
3435 __ mov(result, isolate()->factory()->undefined_value());
3441 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3442 if (instr->is_typed_elements()) {
3443 DoLoadKeyedExternalArray(instr);
3444 } else if (instr->hydrogen()->representation().IsDouble()) {
3445 DoLoadKeyedFixedDoubleArray(instr);
3447 DoLoadKeyedFixedArray(instr);
3452 Operand LCodeGen::BuildFastArrayOperand(
3453 LOperand* elements_pointer,
3455 Representation key_representation,
3456 ElementsKind elements_kind,
3457 uint32_t base_offset) {
3458 Register elements_pointer_reg = ToRegister(elements_pointer);
3459 int element_shift_size = ElementsKindToShiftSize(elements_kind);
3460 int shift_size = element_shift_size;
3461 if (key->IsConstantOperand()) {
3462 int constant_value = ToInteger32(LConstantOperand::cast(key));
3463 if (constant_value & 0xF0000000) {
3464 Abort(kArrayIndexConstantValueTooBig);
3466 return Operand(elements_pointer_reg,
3467 ((constant_value) << shift_size)
3470 // Take the tag bit into account while computing the shift size.
3471 if (key_representation.IsSmi() && (shift_size >= 1)) {
3472 shift_size -= kSmiTagSize;
3474 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3475 return Operand(elements_pointer_reg,
3483 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3484 DCHECK(ToRegister(instr->context()).is(esi));
3485 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3486 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3488 if (instr->hydrogen()->HasVectorAndSlot()) {
3489 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3492 Handle<Code> ic = CodeFactory::KeyedLoadICInOptimizedCode(
3493 isolate(), instr->hydrogen()->language_mode(),
3494 instr->hydrogen()->initialization_state()).code();
3495 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3499 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3500 Register result = ToRegister(instr->result());
3502 if (instr->hydrogen()->from_inlined()) {
3503 __ lea(result, Operand(esp, -2 * kPointerSize));
3505 // Check for arguments adapter frame.
3506 Label done, adapted;
3507 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3508 __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3509 __ cmp(Operand(result),
3510 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3511 __ j(equal, &adapted, Label::kNear);
3513 // No arguments adaptor frame.
3514 __ mov(result, Operand(ebp));
3515 __ jmp(&done, Label::kNear);
3517 // Arguments adaptor frame present.
3519 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3521 // Result is the frame pointer for the frame if not adapted and for the real
3522 // frame below the adaptor frame if adapted.
3528 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3529 Operand elem = ToOperand(instr->elements());
3530 Register result = ToRegister(instr->result());
3534 // If no arguments adaptor frame the number of arguments is fixed.
3536 __ mov(result, Immediate(scope()->num_parameters()));
3537 __ j(equal, &done, Label::kNear);
3539 // Arguments adaptor frame present. Get argument length from there.
3540 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3541 __ mov(result, Operand(result,
3542 ArgumentsAdaptorFrameConstants::kLengthOffset));
3543 __ SmiUntag(result);
3545 // Argument length is in result register.
3550 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3551 Register receiver = ToRegister(instr->receiver());
3552 Register function = ToRegister(instr->function());
3554 // If the receiver is null or undefined, we have to pass the global
3555 // object as a receiver to normal functions. Values have to be
3556 // passed unchanged to builtins and strict-mode functions.
3557 Label receiver_ok, global_object;
3558 Register scratch = ToRegister(instr->temp());
3560 if (!instr->hydrogen()->known_function()) {
3561 // Do not transform the receiver to object for strict mode
3564 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3565 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3566 1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3567 __ j(not_equal, &receiver_ok);
3569 // Do not transform the receiver to object for builtins.
3570 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3571 1 << SharedFunctionInfo::kNativeBitWithinByte);
3572 __ j(not_equal, &receiver_ok);
3575 // Normal function. Replace undefined or null with global receiver.
3576 __ cmp(receiver, factory()->null_value());
3577 __ j(equal, &global_object);
3578 __ cmp(receiver, factory()->undefined_value());
3579 __ j(equal, &global_object);
3581 // The receiver should be a JS object.
3582 __ test(receiver, Immediate(kSmiTagMask));
3583 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3584 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3585 DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3587 __ jmp(&receiver_ok, Label::kNear);
3588 __ bind(&global_object);
3589 __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3590 const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3591 __ mov(receiver, Operand(receiver, global_offset));
3592 const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3593 __ mov(receiver, FieldOperand(receiver, proxy_offset));
3594 __ bind(&receiver_ok);
3598 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3599 Register receiver = ToRegister(instr->receiver());
3600 Register function = ToRegister(instr->function());
3601 Register length = ToRegister(instr->length());
3602 Register elements = ToRegister(instr->elements());
3603 DCHECK(receiver.is(eax)); // Used for parameter count.
3604 DCHECK(function.is(edi)); // Required by InvokeFunction.
3605 DCHECK(ToRegister(instr->result()).is(eax));
3607 // Copy the arguments to this function possibly from the
3608 // adaptor frame below it.
3609 const uint32_t kArgumentsLimit = 1 * KB;
3610 __ cmp(length, kArgumentsLimit);
3611 DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3614 __ mov(receiver, length);
3616 // Loop through the arguments pushing them onto the execution
3619 // length is a small non-negative integer, due to the test above.
3620 __ test(length, Operand(length));
3621 __ j(zero, &invoke, Label::kNear);
3623 __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3625 __ j(not_zero, &loop);
3627 // Invoke the function.
3629 DCHECK(instr->HasPointerMap());
3630 LPointerMap* pointers = instr->pointer_map();
3631 SafepointGenerator safepoint_generator(
3632 this, pointers, Safepoint::kLazyDeopt);
3633 ParameterCount actual(eax);
3634 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3638 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3643 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3644 LOperand* argument = instr->value();
3645 EmitPushTaggedOperand(argument);
3649 void LCodeGen::DoDrop(LDrop* instr) {
3650 __ Drop(instr->count());
3654 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3655 Register result = ToRegister(instr->result());
3656 __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3660 void LCodeGen::DoContext(LContext* instr) {
3661 Register result = ToRegister(instr->result());
3662 if (info()->IsOptimizing()) {
3663 __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3665 // If there is no frame, the context must be in esi.
3666 DCHECK(result.is(esi));
3671 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3672 DCHECK(ToRegister(instr->context()).is(esi));
3673 __ push(esi); // The context is the first argument.
3674 __ push(Immediate(instr->hydrogen()->pairs()));
3675 __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3676 CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3680 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3681 int formal_parameter_count, int arity,
3682 LInstruction* instr) {
3683 bool dont_adapt_arguments =
3684 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3685 bool can_invoke_directly =
3686 dont_adapt_arguments || formal_parameter_count == arity;
3688 Register function_reg = edi;
3690 if (can_invoke_directly) {
3692 __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3694 // Set eax to arguments count if adaption is not needed. Assumes that eax
3695 // is available to write to at this point.
3696 if (dont_adapt_arguments) {
3700 // Invoke function directly.
3701 if (function.is_identical_to(info()->closure())) {
3704 __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3706 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3708 // We need to adapt arguments.
3709 LPointerMap* pointers = instr->pointer_map();
3710 SafepointGenerator generator(
3711 this, pointers, Safepoint::kLazyDeopt);
3712 ParameterCount count(arity);
3713 ParameterCount expected(formal_parameter_count);
3714 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3719 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3720 DCHECK(ToRegister(instr->result()).is(eax));
3722 if (instr->hydrogen()->IsTailCall()) {
3723 if (NeedsEagerFrame()) __ leave();
3725 if (instr->target()->IsConstantOperand()) {
3726 LConstantOperand* target = LConstantOperand::cast(instr->target());
3727 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3728 __ jmp(code, RelocInfo::CODE_TARGET);
3730 DCHECK(instr->target()->IsRegister());
3731 Register target = ToRegister(instr->target());
3732 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3736 LPointerMap* pointers = instr->pointer_map();
3737 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3739 if (instr->target()->IsConstantOperand()) {
3740 LConstantOperand* target = LConstantOperand::cast(instr->target());
3741 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3742 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3743 __ call(code, RelocInfo::CODE_TARGET);
3745 DCHECK(instr->target()->IsRegister());
3746 Register target = ToRegister(instr->target());
3747 generator.BeforeCall(__ CallSize(Operand(target)));
3748 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3751 generator.AfterCall();
3756 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3757 DCHECK(ToRegister(instr->function()).is(edi));
3758 DCHECK(ToRegister(instr->result()).is(eax));
3760 if (instr->hydrogen()->pass_argument_count()) {
3761 __ mov(eax, instr->arity());
3765 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3767 bool is_self_call = false;
3768 if (instr->hydrogen()->function()->IsConstant()) {
3769 HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3770 Handle<JSFunction> jsfun =
3771 Handle<JSFunction>::cast(fun_const->handle(isolate()));
3772 is_self_call = jsfun.is_identical_to(info()->closure());
3778 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3781 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3785 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3786 Register input_reg = ToRegister(instr->value());
3787 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3788 factory()->heap_number_map());
3789 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3791 Label slow, allocated, done;
3792 Register tmp = input_reg.is(eax) ? ecx : eax;
3793 Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3795 // Preserve the value of all registers.
3796 PushSafepointRegistersScope scope(this);
3798 __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3799 // Check the sign of the argument. If the argument is positive, just
3800 // return it. We do not need to patch the stack since |input| and
3801 // |result| are the same register and |input| will be restored
3802 // unchanged by popping safepoint registers.
3803 __ test(tmp, Immediate(HeapNumber::kSignMask));
3804 __ j(zero, &done, Label::kNear);
3806 __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3807 __ jmp(&allocated, Label::kNear);
3809 // Slow case: Call the runtime system to do the number allocation.
3811 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3812 instr, instr->context());
3813 // Set the pointer to the new heap number in tmp.
3814 if (!tmp.is(eax)) __ mov(tmp, eax);
3815 // Restore input_reg after call to runtime.
3816 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3818 __ bind(&allocated);
3819 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3820 __ and_(tmp2, ~HeapNumber::kSignMask);
3821 __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3822 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3823 __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3824 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3830 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3831 Register input_reg = ToRegister(instr->value());
3832 __ test(input_reg, Operand(input_reg));
3834 __ j(not_sign, &is_positive, Label::kNear);
3835 __ neg(input_reg); // Sets flags.
3836 DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3837 __ bind(&is_positive);
3841 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3842 // Class for deferred case.
3843 class DeferredMathAbsTaggedHeapNumber final : public LDeferredCode {
3845 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3847 const X87Stack& x87_stack)
3848 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
3849 void Generate() override {
3850 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3852 LInstruction* instr() override { return instr_; }
3858 DCHECK(instr->value()->Equals(instr->result()));
3859 Representation r = instr->hydrogen()->value()->representation();
3862 X87Register value = ToX87Register(instr->value());
3865 } else if (r.IsSmiOrInteger32()) {
3866 EmitIntegerMathAbs(instr);
3867 } else { // Tagged case.
3868 DeferredMathAbsTaggedHeapNumber* deferred =
3869 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr, x87_stack_);
3870 Register input_reg = ToRegister(instr->value());
3872 __ JumpIfNotSmi(input_reg, deferred->entry());
3873 EmitIntegerMathAbs(instr);
3874 __ bind(deferred->exit());
3879 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3880 Register output_reg = ToRegister(instr->result());
3881 X87Register input_reg = ToX87Register(instr->value());
3884 Label not_minus_zero, done;
3885 // Deoptimize on unordered.
3889 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3890 __ j(below, ¬_minus_zero, Label::kNear);
3892 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3893 // Check for negative zero.
3894 __ j(not_equal, ¬_minus_zero, Label::kNear);
3898 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3899 __ Move(output_reg, Immediate(0));
3900 __ jmp(&done, Label::kFar);
3904 // rc=01B, round down.
3905 __ bind(¬_minus_zero);
3907 __ X87SetRC(0x0400);
3908 __ sub(esp, Immediate(kPointerSize));
3909 __ fist_s(Operand(esp, 0));
3912 DeoptimizeIf(equal, instr, Deoptimizer::kOverflow);
3914 __ X87SetRC(0x0000);
3919 void LCodeGen::DoMathRound(LMathRound* instr) {
3920 X87Register input_reg = ToX87Register(instr->value());
3921 Register result = ToRegister(instr->result());
3923 Label below_one_half, below_minus_one_half, done;
3925 ExternalReference one_half = ExternalReference::address_of_one_half();
3926 ExternalReference minus_one_half =
3927 ExternalReference::address_of_minus_one_half();
3929 __ fld_d(Operand::StaticVariable(one_half));
3932 __ j(carry, &below_one_half);
3934 // Use rounds towards zero, since 0.5 <= x, we use floor(0.5 + x)
3936 __ fadd_d(Operand::StaticVariable(one_half));
3937 // rc=11B, round toward zero.
3938 __ X87SetRC(0x0c00);
3939 __ sub(esp, Immediate(kPointerSize));
3940 // Clear exception bits.
3942 __ fistp_s(MemOperand(esp, 0));
3946 DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
3948 // Restore round mode.
3949 __ X87SetRC(0x0000);
3952 __ bind(&below_one_half);
3953 __ fld_d(Operand::StaticVariable(minus_one_half));
3956 __ j(carry, &below_minus_one_half);
3957 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3958 // we can ignore the difference between a result of -0 and +0.
3959 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3960 // If the sign is positive, we return +0.
3963 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3965 __ Move(result, Immediate(0));
3968 __ bind(&below_minus_one_half);
3970 __ fadd_d(Operand::StaticVariable(one_half));
3971 // rc=01B, round down.
3972 __ X87SetRC(0x0400);
3973 __ sub(esp, Immediate(kPointerSize));
3974 // Clear exception bits.
3976 __ fistp_s(MemOperand(esp, 0));
3980 DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
3982 // Restore round mode.
3983 __ X87SetRC(0x0000);
3989 void LCodeGen::DoMathFround(LMathFround* instr) {
3990 X87Register input_reg = ToX87Register(instr->value());
3992 __ sub(esp, Immediate(kPointerSize));
3993 __ fstp_s(MemOperand(esp, 0));
3994 X87Fld(MemOperand(esp, 0), kX87FloatOperand);
3995 __ add(esp, Immediate(kPointerSize));
3999 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
4000 X87Register input = ToX87Register(instr->value());
4001 X87Register result_reg = ToX87Register(instr->result());
4002 Register temp_result = ToRegister(instr->temp1());
4003 Register temp = ToRegister(instr->temp2());
4004 Label slow, done, smi, finish;
4005 DCHECK(result_reg.is(input));
4007 // Store input into Heap number and call runtime function kMathExpRT.
4008 if (FLAG_inline_new) {
4009 __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4010 __ jmp(&done, Label::kNear);
4013 // Slow case: Call the runtime system to do the number allocation.
4016 // TODO(3095996): Put a valid pointer value in the stack slot where the
4017 // result register is stored, as this register is in the pointer map, but
4018 // contains an integer value.
4019 __ Move(temp_result, Immediate(0));
4021 // Preserve the value of all registers.
4022 PushSafepointRegistersScope scope(this);
4024 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4025 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4026 RecordSafepointWithRegisters(
4027 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4028 __ StoreToSafepointRegisterSlot(temp_result, eax);
4031 X87LoadForUsage(input);
4032 __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4035 // Preserve the value of all registers.
4036 PushSafepointRegistersScope scope(this);
4038 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4039 __ push(temp_result);
4040 __ CallRuntimeSaveDoubles(Runtime::kMathSqrt);
4041 RecordSafepointWithRegisters(instr->pointer_map(), 1,
4042 Safepoint::kNoLazyDeopt);
4043 __ StoreToSafepointRegisterSlot(temp_result, eax);
4045 X87PrepareToWrite(result_reg);
4046 // return value of MathExpRT is Smi or Heap Number.
4047 __ JumpIfSmi(temp_result, &smi);
4048 // Heap number(double)
4049 __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4053 __ SmiUntag(temp_result);
4054 __ push(temp_result);
4055 __ fild_s(MemOperand(esp, 0));
4056 __ pop(temp_result);
4058 X87CommitWrite(result_reg);
4062 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
4063 X87Register input_reg = ToX87Register(instr->value());
4064 DCHECK(ToX87Register(instr->result()).is(input_reg));
4066 // Note that according to ECMA-262 15.8.2.13:
4067 // Math.pow(-Infinity, 0.5) == Infinity
4068 // Math.sqrt(-Infinity) == NaN
4070 // Check base for -Infinity. C3 == 0, C2 == 1, C1 == 1 and C0 == 1
4074 __ and_(eax, Immediate(0x4700));
4075 __ cmp(eax, Immediate(0x0700));
4076 __ j(not_equal, &sqrt, Label::kNear);
4077 // If input is -Infinity, return Infinity.
4079 __ jmp(&done, Label::kNear);
4084 __ faddp(); // Convert -0 to +0.
4091 void LCodeGen::DoPower(LPower* instr) {
4092 Representation exponent_type = instr->hydrogen()->right()->representation();
4093 X87Register result = ToX87Register(instr->result());
4094 // Having marked this as a call, we can use any registers.
4095 X87Register base = ToX87Register(instr->left());
4096 ExternalReference one_half = ExternalReference::address_of_one_half();
4098 if (exponent_type.IsSmi()) {
4099 Register exponent = ToRegister(instr->right());
4100 X87LoadForUsage(base);
4101 __ SmiUntag(exponent);
4103 __ fild_s(MemOperand(esp, 0));
4105 } else if (exponent_type.IsTagged()) {
4106 Register exponent = ToRegister(instr->right());
4107 Register temp = exponent.is(ecx) ? eax : ecx;
4108 Label no_deopt, done;
4109 X87LoadForUsage(base);
4110 __ JumpIfSmi(exponent, &no_deopt);
4111 __ CmpObjectType(exponent, HEAP_NUMBER_TYPE, temp);
4112 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4113 // Heap number(double)
4114 __ fld_d(FieldOperand(exponent, HeapNumber::kValueOffset));
4118 __ SmiUntag(exponent);
4120 __ fild_s(MemOperand(esp, 0));
4123 } else if (exponent_type.IsInteger32()) {
4124 Register exponent = ToRegister(instr->right());
4125 X87LoadForUsage(base);
4127 __ fild_s(MemOperand(esp, 0));
4130 DCHECK(exponent_type.IsDouble());
4131 X87Register exponent_double = ToX87Register(instr->right());
4132 X87LoadForUsage(base, exponent_double);
4135 // FP data stack {base, exponent(TOS)}.
4136 // Handle (exponent==+-0.5 && base == -0).
4140 X87Fld(Operand::StaticVariable(one_half), kX87DoubleOperand);
4142 __ j(parity_even, ¬_plus_0, Label::kNear); // NaN.
4143 __ j(not_equal, ¬_plus_0, Label::kNear);
4145 // FP data stack {base, exponent(TOS), zero}.
4147 __ bind(¬_plus_0);
4150 __ PrepareCallCFunction(4, eax);
4151 __ fstp_d(MemOperand(esp, kDoubleSize)); // Exponent value.
4152 __ fstp_d(MemOperand(esp, 0)); // Base value.
4153 X87PrepareToWrite(result);
4154 __ CallCFunction(ExternalReference::power_double_double_function(isolate()),
4156 // Return value is in st(0) on ia32.
4157 X87CommitWrite(result);
4162 void LCodeGen::DoMathLog(LMathLog* instr) {
4163 DCHECK(instr->value()->Equals(instr->result()));
4164 X87Register input_reg = ToX87Register(instr->value());
4167 Label positive, done, zero, nan_result;
4171 __ j(below, &nan_result, Label::kNear);
4172 __ j(equal, &zero, Label::kNear);
4180 __ jmp(&done, Label::kNear);
4182 __ bind(&nan_result);
4183 X87PrepareToWrite(input_reg);
4184 __ push(Immediate(0xffffffff));
4185 __ push(Immediate(0x7fffffff));
4186 __ fld_d(MemOperand(esp, 0));
4187 __ lea(esp, Operand(esp, kDoubleSize));
4188 X87CommitWrite(input_reg);
4189 __ jmp(&done, Label::kNear);
4192 ExternalReference ninf = ExternalReference::address_of_negative_infinity();
4193 X87PrepareToWrite(input_reg);
4194 __ fld_d(Operand::StaticVariable(ninf));
4195 X87CommitWrite(input_reg);
4201 void LCodeGen::DoMathClz32(LMathClz32* instr) {
4202 Register input = ToRegister(instr->value());
4203 Register result = ToRegister(instr->result());
4205 __ Lzcnt(result, input);
4209 void LCodeGen::DoMathExp(LMathExp* instr) {
4210 X87Register input = ToX87Register(instr->value());
4211 X87Register result_reg = ToX87Register(instr->result());
4212 Register temp_result = ToRegister(instr->temp1());
4213 Register temp = ToRegister(instr->temp2());
4214 Label slow, done, smi, finish;
4215 DCHECK(result_reg.is(input));
4217 // Store input into Heap number and call runtime function kMathExpRT.
4218 if (FLAG_inline_new) {
4219 __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
4220 __ jmp(&done, Label::kNear);
4223 // Slow case: Call the runtime system to do the number allocation.
4226 // TODO(3095996): Put a valid pointer value in the stack slot where the
4227 // result register is stored, as this register is in the pointer map, but
4228 // contains an integer value.
4229 __ Move(temp_result, Immediate(0));
4231 // Preserve the value of all registers.
4232 PushSafepointRegistersScope scope(this);
4234 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4235 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4236 RecordSafepointWithRegisters(instr->pointer_map(), 0,
4237 Safepoint::kNoLazyDeopt);
4238 __ StoreToSafepointRegisterSlot(temp_result, eax);
4241 X87LoadForUsage(input);
4242 __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4245 // Preserve the value of all registers.
4246 PushSafepointRegistersScope scope(this);
4248 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4249 __ push(temp_result);
4250 __ CallRuntimeSaveDoubles(Runtime::kMathExpRT);
4251 RecordSafepointWithRegisters(instr->pointer_map(), 1,
4252 Safepoint::kNoLazyDeopt);
4253 __ StoreToSafepointRegisterSlot(temp_result, eax);
4255 X87PrepareToWrite(result_reg);
4256 // return value of MathExpRT is Smi or Heap Number.
4257 __ JumpIfSmi(temp_result, &smi);
4258 // Heap number(double)
4259 __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
4263 __ SmiUntag(temp_result);
4264 __ push(temp_result);
4265 __ fild_s(MemOperand(esp, 0));
4266 __ pop(temp_result);
4268 X87CommitWrite(result_reg);
4272 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
4273 DCHECK(ToRegister(instr->context()).is(esi));
4274 DCHECK(ToRegister(instr->function()).is(edi));
4275 DCHECK(instr->HasPointerMap());
4277 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
4278 if (known_function.is_null()) {
4279 LPointerMap* pointers = instr->pointer_map();
4280 SafepointGenerator generator(
4281 this, pointers, Safepoint::kLazyDeopt);
4282 ParameterCount count(instr->arity());
4283 __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
4285 CallKnownFunction(known_function,
4286 instr->hydrogen()->formal_parameter_count(),
4287 instr->arity(), instr);
4292 void LCodeGen::DoCallFunction(LCallFunction* instr) {
4293 DCHECK(ToRegister(instr->context()).is(esi));
4294 DCHECK(ToRegister(instr->function()).is(edi));
4295 DCHECK(ToRegister(instr->result()).is(eax));
4297 int arity = instr->arity();
4298 CallFunctionFlags flags = instr->hydrogen()->function_flags();
4299 if (instr->hydrogen()->HasVectorAndSlot()) {
4300 Register slot_register = ToRegister(instr->temp_slot());
4301 Register vector_register = ToRegister(instr->temp_vector());
4302 DCHECK(slot_register.is(edx));
4303 DCHECK(vector_register.is(ebx));
4305 AllowDeferredHandleDereference vector_structure_check;
4306 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
4307 int index = vector->GetIndex(instr->hydrogen()->slot());
4309 __ mov(vector_register, vector);
4310 __ mov(slot_register, Immediate(Smi::FromInt(index)));
4312 CallICState::CallType call_type =
4313 (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
4316 CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
4317 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4319 CallFunctionStub stub(isolate(), arity, flags);
4320 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4325 void LCodeGen::DoCallNew(LCallNew* instr) {
4326 DCHECK(ToRegister(instr->context()).is(esi));
4327 DCHECK(ToRegister(instr->constructor()).is(edi));
4328 DCHECK(ToRegister(instr->result()).is(eax));
4330 // No cell in ebx for construct type feedback in optimized code
4331 __ mov(ebx, isolate()->factory()->undefined_value());
4332 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
4333 __ Move(eax, Immediate(instr->arity()));
4334 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4338 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
4339 DCHECK(ToRegister(instr->context()).is(esi));
4340 DCHECK(ToRegister(instr->constructor()).is(edi));
4341 DCHECK(ToRegister(instr->result()).is(eax));
4343 __ Move(eax, Immediate(instr->arity()));
4344 if (instr->arity() == 1) {
4345 // We only need the allocation site for the case we have a length argument.
4346 // The case may bail out to the runtime, which will determine the correct
4347 // elements kind with the site.
4348 __ mov(ebx, instr->hydrogen()->site());
4350 __ mov(ebx, isolate()->factory()->undefined_value());
4353 ElementsKind kind = instr->hydrogen()->elements_kind();
4354 AllocationSiteOverrideMode override_mode =
4355 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
4356 ? DISABLE_ALLOCATION_SITES
4359 if (instr->arity() == 0) {
4360 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
4361 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4362 } else if (instr->arity() == 1) {
4364 if (IsFastPackedElementsKind(kind)) {
4366 // We might need a change here
4367 // look at the first argument
4368 __ mov(ecx, Operand(esp, 0));
4370 __ j(zero, &packed_case, Label::kNear);
4372 ElementsKind holey_kind = GetHoleyElementsKind(kind);
4373 ArraySingleArgumentConstructorStub stub(isolate(),
4376 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4377 __ jmp(&done, Label::kNear);
4378 __ bind(&packed_case);
4381 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
4382 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4385 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
4386 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4391 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4392 DCHECK(ToRegister(instr->context()).is(esi));
4393 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
4397 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4398 Register function = ToRegister(instr->function());
4399 Register code_object = ToRegister(instr->code_object());
4400 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4401 __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4405 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4406 Register result = ToRegister(instr->result());
4407 Register base = ToRegister(instr->base_object());
4408 if (instr->offset()->IsConstantOperand()) {
4409 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4410 __ lea(result, Operand(base, ToInteger32(offset)));
4412 Register offset = ToRegister(instr->offset());
4413 __ lea(result, Operand(base, offset, times_1, 0));
4418 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4419 Representation representation = instr->hydrogen()->field_representation();
4421 HObjectAccess access = instr->hydrogen()->access();
4422 int offset = access.offset();
4424 if (access.IsExternalMemory()) {
4425 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4426 MemOperand operand = instr->object()->IsConstantOperand()
4427 ? MemOperand::StaticVariable(
4428 ToExternalReference(LConstantOperand::cast(instr->object())))
4429 : MemOperand(ToRegister(instr->object()), offset);
4430 if (instr->value()->IsConstantOperand()) {
4431 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4432 __ mov(operand, Immediate(ToInteger32(operand_value)));
4434 Register value = ToRegister(instr->value());
4435 __ Store(value, operand, representation);
4440 Register object = ToRegister(instr->object());
4441 __ AssertNotSmi(object);
4442 DCHECK(!representation.IsSmi() ||
4443 !instr->value()->IsConstantOperand() ||
4444 IsSmi(LConstantOperand::cast(instr->value())));
4445 if (representation.IsDouble()) {
4446 DCHECK(access.IsInobject());
4447 DCHECK(!instr->hydrogen()->has_transition());
4448 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4449 X87Register value = ToX87Register(instr->value());
4450 X87Mov(FieldOperand(object, offset), value);
4454 if (instr->hydrogen()->has_transition()) {
4455 Handle<Map> transition = instr->hydrogen()->transition_map();
4456 AddDeprecationDependency(transition);
4457 __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4458 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4459 Register temp = ToRegister(instr->temp());
4460 Register temp_map = ToRegister(instr->temp_map());
4461 __ mov(temp_map, transition);
4462 __ mov(FieldOperand(object, HeapObject::kMapOffset), temp_map);
4463 // Update the write barrier for the map field.
4464 __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4469 Register write_register = object;
4470 if (!access.IsInobject()) {
4471 write_register = ToRegister(instr->temp());
4472 __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4475 MemOperand operand = FieldOperand(write_register, offset);
4476 if (instr->value()->IsConstantOperand()) {
4477 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4478 if (operand_value->IsRegister()) {
4479 Register value = ToRegister(operand_value);
4480 __ Store(value, operand, representation);
4481 } else if (representation.IsInteger32()) {
4482 Immediate immediate = ToImmediate(operand_value, representation);
4483 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4484 __ mov(operand, immediate);
4486 Handle<Object> handle_value = ToHandle(operand_value);
4487 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4488 __ mov(operand, handle_value);
4491 Register value = ToRegister(instr->value());
4492 __ Store(value, operand, representation);
4495 if (instr->hydrogen()->NeedsWriteBarrier()) {
4496 Register value = ToRegister(instr->value());
4497 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4498 // Update the write barrier for the object for in-object properties.
4499 __ RecordWriteField(write_register, offset, value, temp, kSaveFPRegs,
4500 EMIT_REMEMBERED_SET,
4501 instr->hydrogen()->SmiCheckForWriteBarrier(),
4502 instr->hydrogen()->PointersToHereCheckForValue());
4507 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4508 DCHECK(ToRegister(instr->context()).is(esi));
4509 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4510 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4512 if (instr->hydrogen()->HasVectorAndSlot()) {
4513 EmitVectorStoreICRegisters<LStoreNamedGeneric>(instr);
4516 __ mov(StoreDescriptor::NameRegister(), instr->name());
4517 Handle<Code> ic = CodeFactory::StoreICInOptimizedCode(
4518 isolate(), instr->language_mode(),
4519 instr->hydrogen()->initialization_state()).code();
4520 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4524 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4525 Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4526 if (instr->index()->IsConstantOperand()) {
4527 __ cmp(ToOperand(instr->length()),
4528 ToImmediate(LConstantOperand::cast(instr->index()),
4529 instr->hydrogen()->length()->representation()));
4530 cc = CommuteCondition(cc);
4531 } else if (instr->length()->IsConstantOperand()) {
4532 __ cmp(ToOperand(instr->index()),
4533 ToImmediate(LConstantOperand::cast(instr->length()),
4534 instr->hydrogen()->index()->representation()));
4536 __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4538 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4540 __ j(NegateCondition(cc), &done, Label::kNear);
4544 DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4549 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4550 ElementsKind elements_kind = instr->elements_kind();
4551 LOperand* key = instr->key();
4552 if (!key->IsConstantOperand() &&
4553 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4555 __ SmiUntag(ToRegister(key));
4557 Operand operand(BuildFastArrayOperand(
4560 instr->hydrogen()->key()->representation(),
4562 instr->base_offset()));
4563 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
4564 elements_kind == FLOAT32_ELEMENTS) {
4565 X87Mov(operand, ToX87Register(instr->value()), kX87FloatOperand);
4566 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
4567 elements_kind == FLOAT64_ELEMENTS) {
4568 uint64_t int_val = kHoleNanInt64;
4569 int32_t lower = static_cast<int32_t>(int_val);
4570 int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4571 Operand operand2 = BuildFastArrayOperand(
4572 instr->elements(), instr->key(),
4573 instr->hydrogen()->key()->representation(), elements_kind,
4574 instr->base_offset() + kPointerSize);
4576 Label no_special_nan_handling, done;
4577 X87Register value = ToX87Register(instr->value());
4579 __ lea(esp, Operand(esp, -kDoubleSize));
4580 __ fst_d(MemOperand(esp, 0));
4581 __ lea(esp, Operand(esp, kDoubleSize));
4582 int offset = sizeof(kHoleNanUpper32);
4583 // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
4584 // so we check the upper with 0xffffffff for hole as a temporary fix.
4585 __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
4586 __ j(not_equal, &no_special_nan_handling, Label::kNear);
4587 __ mov(operand, Immediate(lower));
4588 __ mov(operand2, Immediate(upper));
4589 __ jmp(&done, Label::kNear);
4591 __ bind(&no_special_nan_handling);
4595 Register value = ToRegister(instr->value());
4596 switch (elements_kind) {
4597 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
4598 case EXTERNAL_UINT8_ELEMENTS:
4599 case EXTERNAL_INT8_ELEMENTS:
4600 case UINT8_ELEMENTS:
4602 case UINT8_CLAMPED_ELEMENTS:
4603 __ mov_b(operand, value);
4605 case EXTERNAL_INT16_ELEMENTS:
4606 case EXTERNAL_UINT16_ELEMENTS:
4607 case UINT16_ELEMENTS:
4608 case INT16_ELEMENTS:
4609 __ mov_w(operand, value);
4611 case EXTERNAL_INT32_ELEMENTS:
4612 case EXTERNAL_UINT32_ELEMENTS:
4613 case UINT32_ELEMENTS:
4614 case INT32_ELEMENTS:
4615 __ mov(operand, value);
4617 case EXTERNAL_FLOAT32_ELEMENTS:
4618 case EXTERNAL_FLOAT64_ELEMENTS:
4619 case FLOAT32_ELEMENTS:
4620 case FLOAT64_ELEMENTS:
4621 case FAST_SMI_ELEMENTS:
4623 case FAST_DOUBLE_ELEMENTS:
4624 case FAST_HOLEY_SMI_ELEMENTS:
4625 case FAST_HOLEY_ELEMENTS:
4626 case FAST_HOLEY_DOUBLE_ELEMENTS:
4627 case DICTIONARY_ELEMENTS:
4628 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
4629 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
4637 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4638 Operand double_store_operand = BuildFastArrayOperand(
4641 instr->hydrogen()->key()->representation(),
4642 FAST_DOUBLE_ELEMENTS,
4643 instr->base_offset());
4645 uint64_t int_val = kHoleNanInt64;
4646 int32_t lower = static_cast<int32_t>(int_val);
4647 int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
4648 Operand double_store_operand2 = BuildFastArrayOperand(
4649 instr->elements(), instr->key(),
4650 instr->hydrogen()->key()->representation(), FAST_DOUBLE_ELEMENTS,
4651 instr->base_offset() + kPointerSize);
4653 if (instr->hydrogen()->IsConstantHoleStore()) {
4654 // This means we should store the (double) hole. No floating point
4655 // registers required.
4656 __ mov(double_store_operand, Immediate(lower));
4657 __ mov(double_store_operand2, Immediate(upper));
4659 Label no_special_nan_handling, done;
4660 X87Register value = ToX87Register(instr->value());
4663 if (instr->NeedsCanonicalization()) {
4667 __ j(parity_odd, &no_special_nan_handling, Label::kNear);
4668 // All NaNs are Canonicalized to 0x7fffffffffffffff
4669 __ mov(double_store_operand, Immediate(0xffffffff));
4670 __ mov(double_store_operand2, Immediate(0x7fffffff));
4671 __ jmp(&done, Label::kNear);
4673 __ lea(esp, Operand(esp, -kDoubleSize));
4674 __ fst_d(MemOperand(esp, 0));
4675 __ lea(esp, Operand(esp, kDoubleSize));
4676 int offset = sizeof(kHoleNanUpper32);
4677 // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
4678 // so we check the upper with 0xffffffff for hole as a temporary fix.
4679 __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
4680 __ j(not_equal, &no_special_nan_handling, Label::kNear);
4681 __ mov(double_store_operand, Immediate(lower));
4682 __ mov(double_store_operand2, Immediate(upper));
4683 __ jmp(&done, Label::kNear);
4685 __ bind(&no_special_nan_handling);
4686 __ fst_d(double_store_operand);
4692 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4693 Register elements = ToRegister(instr->elements());
4694 Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4696 Operand operand = BuildFastArrayOperand(
4699 instr->hydrogen()->key()->representation(),
4701 instr->base_offset());
4702 if (instr->value()->IsRegister()) {
4703 __ mov(operand, ToRegister(instr->value()));
4705 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4706 if (IsSmi(operand_value)) {
4707 Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4708 __ mov(operand, immediate);
4710 DCHECK(!IsInteger32(operand_value));
4711 Handle<Object> handle_value = ToHandle(operand_value);
4712 __ mov(operand, handle_value);
4716 if (instr->hydrogen()->NeedsWriteBarrier()) {
4717 DCHECK(instr->value()->IsRegister());
4718 Register value = ToRegister(instr->value());
4719 DCHECK(!instr->key()->IsConstantOperand());
4720 SmiCheck check_needed =
4721 instr->hydrogen()->value()->type().IsHeapObject()
4722 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4723 // Compute address of modified element and store it into key register.
4724 __ lea(key, operand);
4725 __ RecordWrite(elements, key, value, kSaveFPRegs, EMIT_REMEMBERED_SET,
4727 instr->hydrogen()->PointersToHereCheckForValue());
4732 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4733 // By cases...external, fast-double, fast
4734 if (instr->is_typed_elements()) {
4735 DoStoreKeyedExternalArray(instr);
4736 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4737 DoStoreKeyedFixedDoubleArray(instr);
4739 DoStoreKeyedFixedArray(instr);
4744 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4745 DCHECK(ToRegister(instr->context()).is(esi));
4746 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4747 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4748 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4750 if (instr->hydrogen()->HasVectorAndSlot()) {
4751 EmitVectorStoreICRegisters<LStoreKeyedGeneric>(instr);
4754 Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4755 isolate(), instr->language_mode(),
4756 instr->hydrogen()->initialization_state()).code();
4757 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4761 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4762 Register object = ToRegister(instr->object());
4763 Register temp = ToRegister(instr->temp());
4764 Label no_memento_found;
4765 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4766 DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4767 __ bind(&no_memento_found);
4771 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
4772 class DeferredMaybeGrowElements final : public LDeferredCode {
4774 DeferredMaybeGrowElements(LCodeGen* codegen,
4775 LMaybeGrowElements* instr,
4776 const X87Stack& x87_stack)
4777 : LDeferredCode(codegen, x87_stack), instr_(instr) {}
4778 void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
4779 LInstruction* instr() override { return instr_; }
4782 LMaybeGrowElements* instr_;
4785 Register result = eax;
4786 DeferredMaybeGrowElements* deferred =
4787 new (zone()) DeferredMaybeGrowElements(this, instr, x87_stack_);
4788 LOperand* key = instr->key();
4789 LOperand* current_capacity = instr->current_capacity();
4791 DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
4792 DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
4793 DCHECK(key->IsConstantOperand() || key->IsRegister());
4794 DCHECK(current_capacity->IsConstantOperand() ||
4795 current_capacity->IsRegister());
4797 if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
4798 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4799 int32_t constant_capacity =
4800 ToInteger32(LConstantOperand::cast(current_capacity));
4801 if (constant_key >= constant_capacity) {
4803 __ jmp(deferred->entry());
4805 } else if (key->IsConstantOperand()) {
4806 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4807 __ cmp(ToOperand(current_capacity), Immediate(constant_key));
4808 __ j(less_equal, deferred->entry());
4809 } else if (current_capacity->IsConstantOperand()) {
4810 int32_t constant_capacity =
4811 ToInteger32(LConstantOperand::cast(current_capacity));
4812 __ cmp(ToRegister(key), Immediate(constant_capacity));
4813 __ j(greater_equal, deferred->entry());
4815 __ cmp(ToRegister(key), ToRegister(current_capacity));
4816 __ j(greater_equal, deferred->entry());
4819 __ mov(result, ToOperand(instr->elements()));
4820 __ bind(deferred->exit());
4824 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
4825 // TODO(3095996): Get rid of this. For now, we need to make the
4826 // result register contain a valid pointer because it is already
4827 // contained in the register pointer map.
4828 Register result = eax;
4829 __ Move(result, Immediate(0));
4831 // We have to call a stub.
4833 PushSafepointRegistersScope scope(this);
4834 if (instr->object()->IsRegister()) {
4835 __ Move(result, ToRegister(instr->object()));
4837 __ mov(result, ToOperand(instr->object()));
4840 LOperand* key = instr->key();
4841 if (key->IsConstantOperand()) {
4842 __ mov(ebx, ToImmediate(key, Representation::Smi()));
4844 __ Move(ebx, ToRegister(key));
4848 GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
4849 instr->hydrogen()->kind());
4851 RecordSafepointWithLazyDeopt(
4852 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4853 __ StoreToSafepointRegisterSlot(result, result);
4856 // Deopt on smi, which means the elements array changed to dictionary mode.
4857 __ test(result, Immediate(kSmiTagMask));
4858 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
4862 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4863 Register object_reg = ToRegister(instr->object());
4865 Handle<Map> from_map = instr->original_map();
4866 Handle<Map> to_map = instr->transitioned_map();
4867 ElementsKind from_kind = instr->from_kind();
4868 ElementsKind to_kind = instr->to_kind();
4870 Label not_applicable;
4871 bool is_simple_map_transition =
4872 IsSimpleMapChangeTransition(from_kind, to_kind);
4873 Label::Distance branch_distance =
4874 is_simple_map_transition ? Label::kNear : Label::kFar;
4875 __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4876 __ j(not_equal, ¬_applicable, branch_distance);
4877 if (is_simple_map_transition) {
4878 Register new_map_reg = ToRegister(instr->new_map_temp());
4879 __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4882 DCHECK_NOT_NULL(instr->temp());
4883 __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4884 ToRegister(instr->temp()), kDontSaveFPRegs);
4886 DCHECK(ToRegister(instr->context()).is(esi));
4887 DCHECK(object_reg.is(eax));
4888 PushSafepointRegistersScope scope(this);
4889 __ mov(ebx, to_map);
4890 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4891 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4893 RecordSafepointWithLazyDeopt(instr,
4894 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4896 __ bind(¬_applicable);
4900 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4901 class DeferredStringCharCodeAt final : public LDeferredCode {
4903 DeferredStringCharCodeAt(LCodeGen* codegen,
4904 LStringCharCodeAt* instr,
4905 const X87Stack& x87_stack)
4906 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4907 void Generate() override { codegen()->DoDeferredStringCharCodeAt(instr_); }
4908 LInstruction* instr() override { return instr_; }
4911 LStringCharCodeAt* instr_;
4914 DeferredStringCharCodeAt* deferred =
4915 new(zone()) DeferredStringCharCodeAt(this, instr, x87_stack_);
4917 StringCharLoadGenerator::Generate(masm(),
4919 ToRegister(instr->string()),
4920 ToRegister(instr->index()),
4921 ToRegister(instr->result()),
4923 __ bind(deferred->exit());
4927 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4928 Register string = ToRegister(instr->string());
4929 Register result = ToRegister(instr->result());
4931 // TODO(3095996): Get rid of this. For now, we need to make the
4932 // result register contain a valid pointer because it is already
4933 // contained in the register pointer map.
4934 __ Move(result, Immediate(0));
4936 PushSafepointRegistersScope scope(this);
4938 // Push the index as a smi. This is safe because of the checks in
4939 // DoStringCharCodeAt above.
4940 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4941 if (instr->index()->IsConstantOperand()) {
4942 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4943 Representation::Smi());
4946 Register index = ToRegister(instr->index());
4950 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4951 instr, instr->context());
4954 __ StoreToSafepointRegisterSlot(result, eax);
4958 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4959 class DeferredStringCharFromCode final : public LDeferredCode {
4961 DeferredStringCharFromCode(LCodeGen* codegen,
4962 LStringCharFromCode* instr,
4963 const X87Stack& x87_stack)
4964 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4965 void Generate() override {
4966 codegen()->DoDeferredStringCharFromCode(instr_);
4968 LInstruction* instr() override { return instr_; }
4971 LStringCharFromCode* instr_;
4974 DeferredStringCharFromCode* deferred =
4975 new(zone()) DeferredStringCharFromCode(this, instr, x87_stack_);
4977 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4978 Register char_code = ToRegister(instr->char_code());
4979 Register result = ToRegister(instr->result());
4980 DCHECK(!char_code.is(result));
4982 __ cmp(char_code, String::kMaxOneByteCharCode);
4983 __ j(above, deferred->entry());
4984 __ Move(result, Immediate(factory()->single_character_string_cache()));
4985 __ mov(result, FieldOperand(result,
4986 char_code, times_pointer_size,
4987 FixedArray::kHeaderSize));
4988 __ cmp(result, factory()->undefined_value());
4989 __ j(equal, deferred->entry());
4990 __ bind(deferred->exit());
4994 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4995 Register char_code = ToRegister(instr->char_code());
4996 Register result = ToRegister(instr->result());
4998 // TODO(3095996): Get rid of this. For now, we need to make the
4999 // result register contain a valid pointer because it is already
5000 // contained in the register pointer map.
5001 __ Move(result, Immediate(0));
5003 PushSafepointRegistersScope scope(this);
5004 __ SmiTag(char_code);
5006 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
5007 __ StoreToSafepointRegisterSlot(result, eax);
5011 void LCodeGen::DoStringAdd(LStringAdd* instr) {
5012 DCHECK(ToRegister(instr->context()).is(esi));
5013 DCHECK(ToRegister(instr->left()).is(edx));
5014 DCHECK(ToRegister(instr->right()).is(eax));
5015 StringAddStub stub(isolate(),
5016 instr->hydrogen()->flags(),
5017 instr->hydrogen()->pretenure_flag());
5018 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5022 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
5023 LOperand* input = instr->value();
5024 LOperand* output = instr->result();
5025 DCHECK(input->IsRegister() || input->IsStackSlot());
5026 DCHECK(output->IsDoubleRegister());
5027 if (input->IsRegister()) {
5028 Register input_reg = ToRegister(input);
5030 X87Mov(ToX87Register(output), Operand(esp, 0), kX87IntOperand);
5033 X87Mov(ToX87Register(output), ToOperand(input), kX87IntOperand);
5038 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
5039 LOperand* input = instr->value();
5040 LOperand* output = instr->result();
5041 X87Register res = ToX87Register(output);
5042 X87PrepareToWrite(res);
5043 __ LoadUint32NoSSE2(ToRegister(input));
5044 X87CommitWrite(res);
5048 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
5049 class DeferredNumberTagI final : public LDeferredCode {
5051 DeferredNumberTagI(LCodeGen* codegen,
5053 const X87Stack& x87_stack)
5054 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5055 void Generate() override {
5056 codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
5059 LInstruction* instr() override { return instr_; }
5062 LNumberTagI* instr_;
5065 LOperand* input = instr->value();
5066 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5067 Register reg = ToRegister(input);
5069 DeferredNumberTagI* deferred =
5070 new(zone()) DeferredNumberTagI(this, instr, x87_stack_);
5072 __ j(overflow, deferred->entry());
5073 __ bind(deferred->exit());
5077 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
5078 class DeferredNumberTagU final : public LDeferredCode {
5080 DeferredNumberTagU(LCodeGen* codegen,
5082 const X87Stack& x87_stack)
5083 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5084 void Generate() override {
5085 codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
5088 LInstruction* instr() override { return instr_; }
5091 LNumberTagU* instr_;
5094 LOperand* input = instr->value();
5095 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5096 Register reg = ToRegister(input);
5098 DeferredNumberTagU* deferred =
5099 new(zone()) DeferredNumberTagU(this, instr, x87_stack_);
5100 __ cmp(reg, Immediate(Smi::kMaxValue));
5101 __ j(above, deferred->entry());
5103 __ bind(deferred->exit());
5107 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
5110 IntegerSignedness signedness) {
5112 Register reg = ToRegister(value);
5113 Register tmp = ToRegister(temp);
5115 if (signedness == SIGNED_INT32) {
5116 // There was overflow, so bits 30 and 31 of the original integer
5117 // disagree. Try to allocate a heap number in new space and store
5118 // the value in there. If that fails, call the runtime system.
5120 __ xor_(reg, 0x80000000);
5122 __ fild_s(Operand(esp, 0));
5125 // There's no fild variant for unsigned values, so zero-extend to a 64-bit
5127 __ push(Immediate(0));
5129 __ fild_d(Operand(esp, 0));
5134 if (FLAG_inline_new) {
5135 __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
5136 __ jmp(&done, Label::kNear);
5139 // Slow case: Call the runtime system to do the number allocation.
5142 // TODO(3095996): Put a valid pointer value in the stack slot where the
5143 // result register is stored, as this register is in the pointer map, but
5144 // contains an integer value.
5145 __ Move(reg, Immediate(0));
5147 // Preserve the value of all registers.
5148 PushSafepointRegistersScope scope(this);
5150 // NumberTagI and NumberTagD use the context from the frame, rather than
5151 // the environment's HContext or HInlinedContext value.
5152 // They only call Runtime::kAllocateHeapNumber.
5153 // The corresponding HChange instructions are added in a phase that does
5154 // not have easy access to the local context.
5155 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5156 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5157 RecordSafepointWithRegisters(
5158 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5159 __ StoreToSafepointRegisterSlot(reg, eax);
5163 __ fstp_d(FieldOperand(reg, HeapNumber::kValueOffset));
5167 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
5168 class DeferredNumberTagD final : public LDeferredCode {
5170 DeferredNumberTagD(LCodeGen* codegen,
5172 const X87Stack& x87_stack)
5173 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5174 void Generate() override { codegen()->DoDeferredNumberTagD(instr_); }
5175 LInstruction* instr() override { return instr_; }
5178 LNumberTagD* instr_;
5181 Register reg = ToRegister(instr->result());
5183 // Put the value to the top of stack
5184 X87Register src = ToX87Register(instr->value());
5185 // Don't use X87LoadForUsage here, which is only used by Instruction which
5186 // clobbers fp registers.
5187 x87_stack_.Fxch(src);
5189 DeferredNumberTagD* deferred =
5190 new(zone()) DeferredNumberTagD(this, instr, x87_stack_);
5191 if (FLAG_inline_new) {
5192 Register tmp = ToRegister(instr->temp());
5193 __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
5195 __ jmp(deferred->entry());
5197 __ bind(deferred->exit());
5198 __ fst_d(FieldOperand(reg, HeapNumber::kValueOffset));
5202 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
5203 // TODO(3095996): Get rid of this. For now, we need to make the
5204 // result register contain a valid pointer because it is already
5205 // contained in the register pointer map.
5206 Register reg = ToRegister(instr->result());
5207 __ Move(reg, Immediate(0));
5209 PushSafepointRegistersScope scope(this);
5210 // NumberTagI and NumberTagD use the context from the frame, rather than
5211 // the environment's HContext or HInlinedContext value.
5212 // They only call Runtime::kAllocateHeapNumber.
5213 // The corresponding HChange instructions are added in a phase that does
5214 // not have easy access to the local context.
5215 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5216 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
5217 RecordSafepointWithRegisters(
5218 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
5219 __ StoreToSafepointRegisterSlot(reg, eax);
5223 void LCodeGen::DoSmiTag(LSmiTag* instr) {
5224 HChange* hchange = instr->hydrogen();
5225 Register input = ToRegister(instr->value());
5226 if (hchange->CheckFlag(HValue::kCanOverflow) &&
5227 hchange->value()->CheckFlag(HValue::kUint32)) {
5228 __ test(input, Immediate(0xc0000000));
5229 DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
5232 if (hchange->CheckFlag(HValue::kCanOverflow) &&
5233 !hchange->value()->CheckFlag(HValue::kUint32)) {
5234 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5239 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
5240 LOperand* input = instr->value();
5241 Register result = ToRegister(input);
5242 DCHECK(input->IsRegister() && input->Equals(instr->result()));
5243 if (instr->needs_check()) {
5244 __ test(result, Immediate(kSmiTagMask));
5245 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5247 __ AssertSmi(result);
5249 __ SmiUntag(result);
5253 void LCodeGen::EmitNumberUntagDNoSSE2(LNumberUntagD* instr, Register input_reg,
5254 Register temp_reg, X87Register res_reg,
5255 NumberUntagDMode mode) {
5256 bool can_convert_undefined_to_nan =
5257 instr->hydrogen()->can_convert_undefined_to_nan();
5258 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
5260 Label load_smi, done;
5262 X87PrepareToWrite(res_reg);
5263 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
5265 __ JumpIfSmi(input_reg, &load_smi);
5267 // Heap number map check.
5268 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5269 factory()->heap_number_map());
5270 if (!can_convert_undefined_to_nan) {
5271 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5273 Label heap_number, convert;
5274 __ j(equal, &heap_number);
5276 // Convert undefined (or hole) to NaN.
5277 __ cmp(input_reg, factory()->undefined_value());
5278 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5281 __ push(Immediate(0xffffffff));
5282 __ push(Immediate(0x7fffffff));
5283 __ fld_d(MemOperand(esp, 0));
5284 __ lea(esp, Operand(esp, kDoubleSize));
5285 __ jmp(&done, Label::kNear);
5287 __ bind(&heap_number);
5289 // Heap number to x87 conversion.
5290 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5291 if (deoptimize_on_minus_zero) {
5294 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5295 __ j(not_zero, &done, Label::kNear);
5297 // Use general purpose registers to check if we have -0.0
5298 __ mov(temp_reg, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5299 __ test(temp_reg, Immediate(HeapNumber::kSignMask));
5300 __ j(zero, &done, Label::kNear);
5302 // Pop FPU stack before deoptimizing.
5304 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5306 __ jmp(&done, Label::kNear);
5308 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
5312 // Clobbering a temp is faster than re-tagging the
5313 // input register since we avoid dependencies.
5314 __ mov(temp_reg, input_reg);
5315 __ SmiUntag(temp_reg); // Untag smi before converting to float.
5317 __ fild_s(Operand(esp, 0));
5318 __ add(esp, Immediate(kPointerSize));
5320 X87CommitWrite(res_reg);
5324 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
5325 Register input_reg = ToRegister(instr->value());
5327 // The input was optimistically untagged; revert it.
5328 STATIC_ASSERT(kSmiTagSize == 1);
5329 __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
5331 if (instr->truncating()) {
5332 Label no_heap_number, check_bools, check_false;
5334 // Heap number map check.
5335 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5336 factory()->heap_number_map());
5337 __ j(not_equal, &no_heap_number, Label::kNear);
5338 __ TruncateHeapNumberToI(input_reg, input_reg);
5341 __ bind(&no_heap_number);
5342 // Check for Oddballs. Undefined/False is converted to zero and True to one
5343 // for truncating conversions.
5344 __ cmp(input_reg, factory()->undefined_value());
5345 __ j(not_equal, &check_bools, Label::kNear);
5346 __ Move(input_reg, Immediate(0));
5349 __ bind(&check_bools);
5350 __ cmp(input_reg, factory()->true_value());
5351 __ j(not_equal, &check_false, Label::kNear);
5352 __ Move(input_reg, Immediate(1));
5355 __ bind(&check_false);
5356 __ cmp(input_reg, factory()->false_value());
5357 DeoptimizeIf(not_equal, instr,
5358 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
5359 __ Move(input_reg, Immediate(0));
5361 // TODO(olivf) Converting a number on the fpu is actually quite slow. We
5362 // should first try a fast conversion and then bailout to this slow case.
5363 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5364 isolate()->factory()->heap_number_map());
5365 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5367 __ sub(esp, Immediate(kPointerSize));
5368 __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
5370 if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
5371 Label no_precision_lost, not_nan, zero_check;
5374 __ fist_s(MemOperand(esp, 0));
5375 __ fild_s(MemOperand(esp, 0));
5379 __ j(equal, &no_precision_lost, Label::kNear);
5381 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5382 __ bind(&no_precision_lost);
5384 __ j(parity_odd, ¬_nan);
5386 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5389 __ test(input_reg, Operand(input_reg));
5390 __ j(zero, &zero_check, Label::kNear);
5394 __ bind(&zero_check);
5395 // To check for minus zero, we load the value again as float, and check
5396 // if that is still 0.
5397 __ sub(esp, Immediate(kPointerSize));
5398 __ fstp_s(Operand(esp, 0));
5400 __ test(input_reg, Operand(input_reg));
5401 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5403 __ fist_s(MemOperand(esp, 0));
5404 __ fild_s(MemOperand(esp, 0));
5407 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
5408 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
5414 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
5415 class DeferredTaggedToI final : public LDeferredCode {
5417 DeferredTaggedToI(LCodeGen* codegen,
5419 const X87Stack& x87_stack)
5420 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5421 void Generate() override { codegen()->DoDeferredTaggedToI(instr_, done()); }
5422 LInstruction* instr() override { return instr_; }
5428 LOperand* input = instr->value();
5429 DCHECK(input->IsRegister());
5430 Register input_reg = ToRegister(input);
5431 DCHECK(input_reg.is(ToRegister(instr->result())));
5433 if (instr->hydrogen()->value()->representation().IsSmi()) {
5434 __ SmiUntag(input_reg);
5436 DeferredTaggedToI* deferred =
5437 new(zone()) DeferredTaggedToI(this, instr, x87_stack_);
5438 // Optimistically untag the input.
5439 // If the input is a HeapObject, SmiUntag will set the carry flag.
5440 STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
5441 __ SmiUntag(input_reg);
5442 // Branch to deferred code if the input was tagged.
5443 // The deferred code will take care of restoring the tag.
5444 __ j(carry, deferred->entry());
5445 __ bind(deferred->exit());
5450 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
5451 LOperand* input = instr->value();
5452 DCHECK(input->IsRegister());
5453 LOperand* temp = instr->temp();
5454 DCHECK(temp->IsRegister());
5455 LOperand* result = instr->result();
5456 DCHECK(result->IsDoubleRegister());
5458 Register input_reg = ToRegister(input);
5459 Register temp_reg = ToRegister(temp);
5461 HValue* value = instr->hydrogen()->value();
5462 NumberUntagDMode mode = value->representation().IsSmi()
5463 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
5465 EmitNumberUntagDNoSSE2(instr, input_reg, temp_reg, ToX87Register(result),
5470 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
5471 LOperand* input = instr->value();
5472 DCHECK(input->IsDoubleRegister());
5473 LOperand* result = instr->result();
5474 DCHECK(result->IsRegister());
5475 Register result_reg = ToRegister(result);
5477 if (instr->truncating()) {
5478 X87Register input_reg = ToX87Register(input);
5480 __ TruncateX87TOSToI(result_reg);
5482 Label lost_precision, is_nan, minus_zero, done;
5483 X87Register input_reg = ToX87Register(input);
5485 __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5486 &lost_precision, &is_nan, &minus_zero);
5488 __ bind(&lost_precision);
5489 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5491 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5492 __ bind(&minus_zero);
5493 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5499 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
5500 LOperand* input = instr->value();
5501 DCHECK(input->IsDoubleRegister());
5502 LOperand* result = instr->result();
5503 DCHECK(result->IsRegister());
5504 Register result_reg = ToRegister(result);
5506 Label lost_precision, is_nan, minus_zero, done;
5507 X87Register input_reg = ToX87Register(input);
5509 __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5510 &lost_precision, &is_nan, &minus_zero);
5512 __ bind(&lost_precision);
5513 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5515 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5516 __ bind(&minus_zero);
5517 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5519 __ SmiTag(result_reg);
5520 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5524 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
5525 LOperand* input = instr->value();
5526 __ test(ToOperand(input), Immediate(kSmiTagMask));
5527 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5531 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5532 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
5533 LOperand* input = instr->value();
5534 __ test(ToOperand(input), Immediate(kSmiTagMask));
5535 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5540 void LCodeGen::DoCheckArrayBufferNotNeutered(
5541 LCheckArrayBufferNotNeutered* instr) {
5542 Register view = ToRegister(instr->view());
5543 Register scratch = ToRegister(instr->scratch());
5545 __ mov(scratch, FieldOperand(view, JSArrayBufferView::kBufferOffset));
5546 __ test_b(FieldOperand(scratch, JSArrayBuffer::kBitFieldOffset),
5547 1 << JSArrayBuffer::WasNeutered::kShift);
5548 DeoptimizeIf(not_zero, instr, Deoptimizer::kOutOfBounds);
5552 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
5553 Register input = ToRegister(instr->value());
5554 Register temp = ToRegister(instr->temp());
5556 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
5558 if (instr->hydrogen()->is_interval_check()) {
5561 instr->hydrogen()->GetCheckInterval(&first, &last);
5563 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5564 static_cast<int8_t>(first));
5566 // If there is only one type in the interval check for equality.
5567 if (first == last) {
5568 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5570 DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
5571 // Omit check for the last type.
5572 if (last != LAST_TYPE) {
5573 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5574 static_cast<int8_t>(last));
5575 DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5581 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5583 if (base::bits::IsPowerOfTwo32(mask)) {
5584 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5585 __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5586 DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5587 Deoptimizer::kWrongInstanceType);
5589 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5590 __ and_(temp, mask);
5592 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5598 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5599 Handle<HeapObject> object = instr->hydrogen()->object().handle();
5600 if (instr->hydrogen()->object_in_new_space()) {
5601 Register reg = ToRegister(instr->value());
5602 Handle<Cell> cell = isolate()->factory()->NewCell(object);
5603 __ cmp(reg, Operand::ForCell(cell));
5605 Operand operand = ToOperand(instr->value());
5606 __ cmp(operand, object);
5608 DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5612 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5614 PushSafepointRegistersScope scope(this);
5617 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5618 RecordSafepointWithRegisters(
5619 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5621 __ test(eax, Immediate(kSmiTagMask));
5623 DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5627 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5628 class DeferredCheckMaps final : public LDeferredCode {
5630 DeferredCheckMaps(LCodeGen* codegen,
5633 const X87Stack& x87_stack)
5634 : LDeferredCode(codegen, x87_stack), instr_(instr), object_(object) {
5635 SetExit(check_maps());
5637 void Generate() override {
5638 codegen()->DoDeferredInstanceMigration(instr_, object_);
5640 Label* check_maps() { return &check_maps_; }
5641 LInstruction* instr() override { return instr_; }
5649 if (instr->hydrogen()->IsStabilityCheck()) {
5650 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5651 for (int i = 0; i < maps->size(); ++i) {
5652 AddStabilityDependency(maps->at(i).handle());
5657 LOperand* input = instr->value();
5658 DCHECK(input->IsRegister());
5659 Register reg = ToRegister(input);
5661 DeferredCheckMaps* deferred = NULL;
5662 if (instr->hydrogen()->HasMigrationTarget()) {
5663 deferred = new(zone()) DeferredCheckMaps(this, instr, reg, x87_stack_);
5664 __ bind(deferred->check_maps());
5667 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5669 for (int i = 0; i < maps->size() - 1; i++) {
5670 Handle<Map> map = maps->at(i).handle();
5671 __ CompareMap(reg, map);
5672 __ j(equal, &success, Label::kNear);
5675 Handle<Map> map = maps->at(maps->size() - 1).handle();
5676 __ CompareMap(reg, map);
5677 if (instr->hydrogen()->HasMigrationTarget()) {
5678 __ j(not_equal, deferred->entry());
5680 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5687 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5688 X87Register value_reg = ToX87Register(instr->unclamped());
5689 Register result_reg = ToRegister(instr->result());
5691 __ ClampTOSToUint8(result_reg);
5695 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5696 DCHECK(instr->unclamped()->Equals(instr->result()));
5697 Register value_reg = ToRegister(instr->result());
5698 __ ClampUint8(value_reg);
5702 void LCodeGen::DoClampTToUint8NoSSE2(LClampTToUint8NoSSE2* instr) {
5703 Register input_reg = ToRegister(instr->unclamped());
5704 Register result_reg = ToRegister(instr->result());
5705 Register scratch = ToRegister(instr->scratch());
5706 Register scratch2 = ToRegister(instr->scratch2());
5707 Register scratch3 = ToRegister(instr->scratch3());
5708 Label is_smi, done, heap_number, valid_exponent,
5709 largest_value, zero_result, maybe_nan_or_infinity;
5711 __ JumpIfSmi(input_reg, &is_smi);
5713 // Check for heap number
5714 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5715 factory()->heap_number_map());
5716 __ j(equal, &heap_number, Label::kNear);
5718 // Check for undefined. Undefined is converted to zero for clamping
5720 __ cmp(input_reg, factory()->undefined_value());
5721 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5722 __ jmp(&zero_result, Label::kNear);
5725 __ bind(&heap_number);
5727 // Surprisingly, all of the hand-crafted bit-manipulations below are much
5728 // faster than the x86 FPU built-in instruction, especially since "banker's
5729 // rounding" would be additionally very expensive
5731 // Get exponent word.
5732 __ mov(scratch, FieldOperand(input_reg, HeapNumber::kExponentOffset));
5733 __ mov(scratch3, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5735 // Test for negative values --> clamp to zero
5736 __ test(scratch, scratch);
5737 __ j(negative, &zero_result, Label::kNear);
5739 // Get exponent alone in scratch2.
5740 __ mov(scratch2, scratch);
5741 __ and_(scratch2, HeapNumber::kExponentMask);
5742 __ shr(scratch2, HeapNumber::kExponentShift);
5743 __ j(zero, &zero_result, Label::kNear);
5744 __ sub(scratch2, Immediate(HeapNumber::kExponentBias - 1));
5745 __ j(negative, &zero_result, Label::kNear);
5747 const uint32_t non_int8_exponent = 7;
5748 __ cmp(scratch2, Immediate(non_int8_exponent + 1));
5749 // If the exponent is too big, check for special values.
5750 __ j(greater, &maybe_nan_or_infinity, Label::kNear);
5752 __ bind(&valid_exponent);
5753 // Exponent word in scratch, exponent in scratch2. We know that 0 <= exponent
5754 // < 7. The shift bias is the number of bits to shift the mantissa such that
5755 // with an exponent of 7 such the that top-most one is in bit 30, allowing
5756 // detection the rounding overflow of a 255.5 to 256 (bit 31 goes from 0 to
5758 int shift_bias = (30 - HeapNumber::kExponentShift) - 7 - 1;
5759 __ lea(result_reg, MemOperand(scratch2, shift_bias));
5760 // Here result_reg (ecx) is the shift, scratch is the exponent word. Get the
5761 // top bits of the mantissa.
5762 __ and_(scratch, HeapNumber::kMantissaMask);
5763 // Put back the implicit 1 of the mantissa
5764 __ or_(scratch, 1 << HeapNumber::kExponentShift);
5765 // Shift up to round
5767 // Use "banker's rounding" to spec: If fractional part of number is 0.5, then
5768 // use the bit in the "ones" place and add it to the "halves" place, which has
5769 // the effect of rounding to even.
5770 __ mov(scratch2, scratch);
5771 const uint32_t one_half_bit_shift = 30 - sizeof(uint8_t) * 8;
5772 const uint32_t one_bit_shift = one_half_bit_shift + 1;
5773 __ and_(scratch2, Immediate((1 << one_bit_shift) - 1));
5774 __ cmp(scratch2, Immediate(1 << one_half_bit_shift));
5776 __ j(less, &no_round, Label::kNear);
5778 __ mov(scratch2, Immediate(1 << one_half_bit_shift));
5779 __ j(greater, &round_up, Label::kNear);
5780 __ test(scratch3, scratch3);
5781 __ j(not_zero, &round_up, Label::kNear);
5782 __ mov(scratch2, scratch);
5783 __ and_(scratch2, Immediate(1 << one_bit_shift));
5784 __ shr(scratch2, 1);
5786 __ add(scratch, scratch2);
5787 __ j(overflow, &largest_value, Label::kNear);
5789 __ shr(scratch, 23);
5790 __ mov(result_reg, scratch);
5791 __ jmp(&done, Label::kNear);
5793 __ bind(&maybe_nan_or_infinity);
5794 // Check for NaN/Infinity, all other values map to 255
5795 __ cmp(scratch2, Immediate(HeapNumber::kInfinityOrNanExponent + 1));
5796 __ j(not_equal, &largest_value, Label::kNear);
5798 // Check for NaN, which differs from Infinity in that at least one mantissa
5800 __ and_(scratch, HeapNumber::kMantissaMask);
5801 __ or_(scratch, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
5802 __ j(not_zero, &zero_result, Label::kNear); // M!=0 --> NaN
5803 // Infinity -> Fall through to map to 255.
5805 __ bind(&largest_value);
5806 __ mov(result_reg, Immediate(255));
5807 __ jmp(&done, Label::kNear);
5809 __ bind(&zero_result);
5810 __ xor_(result_reg, result_reg);
5811 __ jmp(&done, Label::kNear);
5815 if (!input_reg.is(result_reg)) {
5816 __ mov(result_reg, input_reg);
5818 __ SmiUntag(result_reg);
5819 __ ClampUint8(result_reg);
5824 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5825 X87Register value_reg = ToX87Register(instr->value());
5826 Register result_reg = ToRegister(instr->result());
5828 __ sub(esp, Immediate(kDoubleSize));
5829 __ fst_d(Operand(esp, 0));
5830 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5831 __ mov(result_reg, Operand(esp, kPointerSize));
5833 __ mov(result_reg, Operand(esp, 0));
5835 __ add(esp, Immediate(kDoubleSize));
5839 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5840 Register hi_reg = ToRegister(instr->hi());
5841 Register lo_reg = ToRegister(instr->lo());
5842 X87Register result_reg = ToX87Register(instr->result());
5843 // Follow below pattern to write a x87 fp register.
5844 X87PrepareToWrite(result_reg);
5845 __ sub(esp, Immediate(kDoubleSize));
5846 __ mov(Operand(esp, 0), lo_reg);
5847 __ mov(Operand(esp, kPointerSize), hi_reg);
5848 __ fld_d(Operand(esp, 0));
5849 __ add(esp, Immediate(kDoubleSize));
5850 X87CommitWrite(result_reg);
5854 void LCodeGen::DoAllocate(LAllocate* instr) {
5855 class DeferredAllocate final : public LDeferredCode {
5857 DeferredAllocate(LCodeGen* codegen,
5859 const X87Stack& x87_stack)
5860 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5861 void Generate() override { codegen()->DoDeferredAllocate(instr_); }
5862 LInstruction* instr() override { return instr_; }
5868 DeferredAllocate* deferred =
5869 new(zone()) DeferredAllocate(this, instr, x87_stack_);
5871 Register result = ToRegister(instr->result());
5872 Register temp = ToRegister(instr->temp());
5874 // Allocate memory for the object.
5875 AllocationFlags flags = TAG_OBJECT;
5876 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5877 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5879 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5880 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5881 flags = static_cast<AllocationFlags>(flags | PRETENURE);
5884 if (instr->size()->IsConstantOperand()) {
5885 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5886 if (size <= Page::kMaxRegularHeapObjectSize) {
5887 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5889 __ jmp(deferred->entry());
5892 Register size = ToRegister(instr->size());
5893 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5896 __ bind(deferred->exit());
5898 if (instr->hydrogen()->MustPrefillWithFiller()) {
5899 if (instr->size()->IsConstantOperand()) {
5900 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5901 __ mov(temp, (size / kPointerSize) - 1);
5903 temp = ToRegister(instr->size());
5904 __ shr(temp, kPointerSizeLog2);
5909 __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5910 isolate()->factory()->one_pointer_filler_map());
5912 __ j(not_zero, &loop);
5917 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5918 Register result = ToRegister(instr->result());
5920 // TODO(3095996): Get rid of this. For now, we need to make the
5921 // result register contain a valid pointer because it is already
5922 // contained in the register pointer map.
5923 __ Move(result, Immediate(Smi::FromInt(0)));
5925 PushSafepointRegistersScope scope(this);
5926 if (instr->size()->IsRegister()) {
5927 Register size = ToRegister(instr->size());
5928 DCHECK(!size.is(result));
5929 __ SmiTag(ToRegister(instr->size()));
5932 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5933 if (size >= 0 && size <= Smi::kMaxValue) {
5934 __ push(Immediate(Smi::FromInt(size)));
5936 // We should never get here at runtime => abort
5942 int flags = AllocateDoubleAlignFlag::encode(
5943 instr->hydrogen()->MustAllocateDoubleAligned());
5944 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5945 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5946 flags = AllocateTargetSpace::update(flags, OLD_SPACE);
5948 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5950 __ push(Immediate(Smi::FromInt(flags)));
5952 CallRuntimeFromDeferred(
5953 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5954 __ StoreToSafepointRegisterSlot(result, eax);
5958 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5959 DCHECK(ToRegister(instr->value()).is(eax));
5961 CallRuntime(Runtime::kToFastProperties, 1, instr);
5965 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5966 DCHECK(ToRegister(instr->context()).is(esi));
5968 // Registers will be used as follows:
5969 // ecx = literals array.
5970 // ebx = regexp literal.
5971 // eax = regexp literal clone.
5973 int literal_offset =
5974 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5975 __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5976 __ mov(ebx, FieldOperand(ecx, literal_offset));
5977 __ cmp(ebx, factory()->undefined_value());
5978 __ j(not_equal, &materialized, Label::kNear);
5980 // Create regexp literal using runtime function
5981 // Result will be in eax.
5983 __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5984 __ push(Immediate(instr->hydrogen()->pattern()));
5985 __ push(Immediate(instr->hydrogen()->flags()));
5986 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5989 __ bind(&materialized);
5990 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5991 Label allocated, runtime_allocate;
5992 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5993 __ jmp(&allocated, Label::kNear);
5995 __ bind(&runtime_allocate);
5997 __ push(Immediate(Smi::FromInt(size)));
5998 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
6001 __ bind(&allocated);
6002 // Copy the content into the newly allocated memory.
6003 // (Unroll copy loop once for better throughput).
6004 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
6005 __ mov(edx, FieldOperand(ebx, i));
6006 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
6007 __ mov(FieldOperand(eax, i), edx);
6008 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
6010 if ((size % (2 * kPointerSize)) != 0) {
6011 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
6012 __ mov(FieldOperand(eax, size - kPointerSize), edx);
6017 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
6018 DCHECK(ToRegister(instr->context()).is(esi));
6019 // Use the fast case closure allocation code that allocates in new
6020 // space for nested functions that don't need literals cloning.
6021 bool pretenure = instr->hydrogen()->pretenure();
6022 if (!pretenure && instr->hydrogen()->has_no_literals()) {
6023 FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
6024 instr->hydrogen()->kind());
6025 __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
6026 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
6029 __ push(Immediate(instr->hydrogen()->shared_info()));
6030 __ push(Immediate(pretenure ? factory()->true_value()
6031 : factory()->false_value()));
6032 CallRuntime(Runtime::kNewClosure, 3, instr);
6037 void LCodeGen::DoTypeof(LTypeof* instr) {
6038 DCHECK(ToRegister(instr->context()).is(esi));
6039 DCHECK(ToRegister(instr->value()).is(ebx));
6041 Register value_register = ToRegister(instr->value());
6042 __ JumpIfNotSmi(value_register, &do_call);
6043 __ mov(eax, Immediate(isolate()->factory()->number_string()));
6046 TypeofStub stub(isolate());
6047 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
6052 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
6053 Register input = ToRegister(instr->value());
6054 Condition final_branch_condition = EmitTypeofIs(instr, input);
6055 if (final_branch_condition != no_condition) {
6056 EmitBranch(instr, final_branch_condition);
6061 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
6062 Label* true_label = instr->TrueLabel(chunk_);
6063 Label* false_label = instr->FalseLabel(chunk_);
6064 Handle<String> type_name = instr->type_literal();
6065 int left_block = instr->TrueDestination(chunk_);
6066 int right_block = instr->FalseDestination(chunk_);
6067 int next_block = GetNextEmittedBlock();
6069 Label::Distance true_distance = left_block == next_block ? Label::kNear
6071 Label::Distance false_distance = right_block == next_block ? Label::kNear
6073 Condition final_branch_condition = no_condition;
6074 if (String::Equals(type_name, factory()->number_string())) {
6075 __ JumpIfSmi(input, true_label, true_distance);
6076 __ cmp(FieldOperand(input, HeapObject::kMapOffset),
6077 factory()->heap_number_map());
6078 final_branch_condition = equal;
6080 } else if (String::Equals(type_name, factory()->string_string())) {
6081 __ JumpIfSmi(input, false_label, false_distance);
6082 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
6083 __ j(above_equal, false_label, false_distance);
6084 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6085 1 << Map::kIsUndetectable);
6086 final_branch_condition = zero;
6088 } else if (String::Equals(type_name, factory()->symbol_string())) {
6089 __ JumpIfSmi(input, false_label, false_distance);
6090 __ CmpObjectType(input, SYMBOL_TYPE, input);
6091 final_branch_condition = equal;
6093 } else if (String::Equals(type_name, factory()->boolean_string())) {
6094 __ cmp(input, factory()->true_value());
6095 __ j(equal, true_label, true_distance);
6096 __ cmp(input, factory()->false_value());
6097 final_branch_condition = equal;
6099 } else if (String::Equals(type_name, factory()->undefined_string())) {
6100 __ cmp(input, factory()->undefined_value());
6101 __ j(equal, true_label, true_distance);
6102 __ JumpIfSmi(input, false_label, false_distance);
6103 // Check for undetectable objects => true.
6104 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
6105 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6106 1 << Map::kIsUndetectable);
6107 final_branch_condition = not_zero;
6109 } else if (String::Equals(type_name, factory()->function_string())) {
6110 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
6111 __ JumpIfSmi(input, false_label, false_distance);
6112 __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
6113 __ j(equal, true_label, true_distance);
6114 __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
6115 final_branch_condition = equal;
6117 } else if (String::Equals(type_name, factory()->object_string())) {
6118 __ JumpIfSmi(input, false_label, false_distance);
6119 __ cmp(input, factory()->null_value());
6120 __ j(equal, true_label, true_distance);
6121 __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
6122 __ j(below, false_label, false_distance);
6123 __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
6124 __ j(above, false_label, false_distance);
6125 // Check for undetectable objects => false.
6126 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
6127 1 << Map::kIsUndetectable);
6128 final_branch_condition = zero;
6130 } else if (String::Equals(type_name, factory()->float32x4_string())) {
6131 __ JumpIfSmi(input, false_label, false_distance);
6132 __ CmpObjectType(input, FLOAT32X4_TYPE, input);
6133 final_branch_condition = equal;
6136 __ jmp(false_label, false_distance);
6138 return final_branch_condition;
6142 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
6143 Register temp = ToRegister(instr->temp());
6145 EmitIsConstructCall(temp);
6146 EmitBranch(instr, equal);
6150 void LCodeGen::EmitIsConstructCall(Register temp) {
6151 // Get the frame pointer for the calling frame.
6152 __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
6154 // Skip the arguments adaptor frame if it exists.
6155 Label check_frame_marker;
6156 __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
6157 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
6158 __ j(not_equal, &check_frame_marker, Label::kNear);
6159 __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
6161 // Check the marker in the calling frame.
6162 __ bind(&check_frame_marker);
6163 __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
6164 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
6168 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
6169 if (!info()->IsStub()) {
6170 // Ensure that we have enough space after the previous lazy-bailout
6171 // instruction for patching the code here.
6172 int current_pc = masm()->pc_offset();
6173 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
6174 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
6175 __ Nop(padding_size);
6178 last_lazy_deopt_pc_ = masm()->pc_offset();
6182 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
6183 last_lazy_deopt_pc_ = masm()->pc_offset();
6184 DCHECK(instr->HasEnvironment());
6185 LEnvironment* env = instr->environment();
6186 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6187 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6191 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
6192 Deoptimizer::BailoutType type = instr->hydrogen()->type();
6193 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
6194 // needed return address), even though the implementation of LAZY and EAGER is
6195 // now identical. When LAZY is eventually completely folded into EAGER, remove
6196 // the special case below.
6197 if (info()->IsStub() && type == Deoptimizer::EAGER) {
6198 type = Deoptimizer::LAZY;
6200 DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
6204 void LCodeGen::DoDummy(LDummy* instr) {
6205 // Nothing to see here, move on!
6209 void LCodeGen::DoDummyUse(LDummyUse* instr) {
6210 // Nothing to see here, move on!
6214 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
6215 PushSafepointRegistersScope scope(this);
6216 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
6217 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
6218 RecordSafepointWithLazyDeopt(
6219 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
6220 DCHECK(instr->HasEnvironment());
6221 LEnvironment* env = instr->environment();
6222 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
6226 void LCodeGen::DoStackCheck(LStackCheck* instr) {
6227 class DeferredStackCheck final : public LDeferredCode {
6229 DeferredStackCheck(LCodeGen* codegen,
6231 const X87Stack& x87_stack)
6232 : LDeferredCode(codegen, x87_stack), instr_(instr) { }
6233 void Generate() override { codegen()->DoDeferredStackCheck(instr_); }
6234 LInstruction* instr() override { return instr_; }
6237 LStackCheck* instr_;
6240 DCHECK(instr->HasEnvironment());
6241 LEnvironment* env = instr->environment();
6242 // There is no LLazyBailout instruction for stack-checks. We have to
6243 // prepare for lazy deoptimization explicitly here.
6244 if (instr->hydrogen()->is_function_entry()) {
6245 // Perform stack overflow check.
6247 ExternalReference stack_limit =
6248 ExternalReference::address_of_stack_limit(isolate());
6249 __ cmp(esp, Operand::StaticVariable(stack_limit));
6250 __ j(above_equal, &done, Label::kNear);
6252 DCHECK(instr->context()->IsRegister());
6253 DCHECK(ToRegister(instr->context()).is(esi));
6254 CallCode(isolate()->builtins()->StackCheck(),
6255 RelocInfo::CODE_TARGET,
6259 DCHECK(instr->hydrogen()->is_backwards_branch());
6260 // Perform stack overflow check if this goto needs it before jumping.
6261 DeferredStackCheck* deferred_stack_check =
6262 new(zone()) DeferredStackCheck(this, instr, x87_stack_);
6263 ExternalReference stack_limit =
6264 ExternalReference::address_of_stack_limit(isolate());
6265 __ cmp(esp, Operand::StaticVariable(stack_limit));
6266 __ j(below, deferred_stack_check->entry());
6267 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
6268 __ bind(instr->done_label());
6269 deferred_stack_check->SetExit(instr->done_label());
6270 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
6271 // Don't record a deoptimization index for the safepoint here.
6272 // This will be done explicitly when emitting call and the safepoint in
6273 // the deferred code.
6278 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
6279 // This is a pseudo-instruction that ensures that the environment here is
6280 // properly registered for deoptimization and records the assembler's PC
6282 LEnvironment* environment = instr->environment();
6284 // If the environment were already registered, we would have no way of
6285 // backpatching it with the spill slot operands.
6286 DCHECK(!environment->HasBeenRegistered());
6287 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
6289 GenerateOsrPrologue();
6293 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
6294 DCHECK(ToRegister(instr->context()).is(esi));
6295 __ test(eax, Immediate(kSmiTagMask));
6296 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
6298 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
6299 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
6300 DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
6302 Label use_cache, call_runtime;
6303 __ CheckEnumCache(&call_runtime);
6305 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
6306 __ jmp(&use_cache, Label::kNear);
6308 // Get the set of properties to enumerate.
6309 __ bind(&call_runtime);
6311 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
6313 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
6314 isolate()->factory()->meta_map());
6315 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
6316 __ bind(&use_cache);
6320 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
6321 Register map = ToRegister(instr->map());
6322 Register result = ToRegister(instr->result());
6323 Label load_cache, done;
6324 __ EnumLength(result, map);
6325 __ cmp(result, Immediate(Smi::FromInt(0)));
6326 __ j(not_equal, &load_cache, Label::kNear);
6327 __ mov(result, isolate()->factory()->empty_fixed_array());
6328 __ jmp(&done, Label::kNear);
6330 __ bind(&load_cache);
6331 __ LoadInstanceDescriptors(map, result);
6333 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
6335 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
6337 __ test(result, result);
6338 DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
6342 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
6343 Register object = ToRegister(instr->value());
6344 __ cmp(ToRegister(instr->map()),
6345 FieldOperand(object, HeapObject::kMapOffset));
6346 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
6350 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
6353 PushSafepointRegistersScope scope(this);
6357 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
6358 RecordSafepointWithRegisters(
6359 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
6360 __ StoreToSafepointRegisterSlot(object, eax);
6364 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
6365 class DeferredLoadMutableDouble final : public LDeferredCode {
6367 DeferredLoadMutableDouble(LCodeGen* codegen,
6368 LLoadFieldByIndex* instr,
6371 const X87Stack& x87_stack)
6372 : LDeferredCode(codegen, x87_stack),
6377 void Generate() override {
6378 codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
6380 LInstruction* instr() override { return instr_; }
6383 LLoadFieldByIndex* instr_;
6388 Register object = ToRegister(instr->object());
6389 Register index = ToRegister(instr->index());
6391 DeferredLoadMutableDouble* deferred;
6392 deferred = new(zone()) DeferredLoadMutableDouble(
6393 this, instr, object, index, x87_stack_);
6395 Label out_of_object, done;
6396 __ test(index, Immediate(Smi::FromInt(1)));
6397 __ j(not_zero, deferred->entry());
6401 __ cmp(index, Immediate(0));
6402 __ j(less, &out_of_object, Label::kNear);
6403 __ mov(object, FieldOperand(object,
6405 times_half_pointer_size,
6406 JSObject::kHeaderSize));
6407 __ jmp(&done, Label::kNear);
6409 __ bind(&out_of_object);
6410 __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
6412 // Index is now equal to out of object property index plus 1.
6413 __ mov(object, FieldOperand(object,
6415 times_half_pointer_size,
6416 FixedArray::kHeaderSize - kPointerSize));
6417 __ bind(deferred->exit());
6422 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
6423 Register context = ToRegister(instr->context());
6424 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
6428 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
6429 Handle<ScopeInfo> scope_info = instr->scope_info();
6430 __ Push(scope_info);
6431 __ push(ToRegister(instr->function()));
6432 CallRuntime(Runtime::kPushBlockContext, 2, instr);
6433 RecordSafepoint(Safepoint::kNoLazyDeopt);
6439 } // namespace internal
6442 #endif // V8_TARGET_ARCH_X87