1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #if V8_TARGET_ARCH_IA32
9 #include "src/base/bits.h"
10 #include "src/code-factory.h"
11 #include "src/code-stubs.h"
12 #include "src/codegen.h"
13 #include "src/cpu-profiler.h"
14 #include "src/deoptimizer.h"
15 #include "src/hydrogen-osr.h"
16 #include "src/ia32/lithium-codegen-ia32.h"
17 #include "src/ic/ic.h"
18 #include "src/ic/stub-cache.h"
23 // When invoking builtins, we need to record the safepoint in the middle of
24 // the invoke instruction sequence generated by the macro assembler.
25 class SafepointGenerator final : public CallWrapper {
27 SafepointGenerator(LCodeGen* codegen,
28 LPointerMap* pointers,
29 Safepoint::DeoptMode mode)
33 virtual ~SafepointGenerator() {}
35 void BeforeCall(int call_size) const override {}
37 void AfterCall() const override {
38 codegen_->RecordSafepoint(pointers_, deopt_mode_);
43 LPointerMap* pointers_;
44 Safepoint::DeoptMode deopt_mode_;
50 bool LCodeGen::GenerateCode() {
51 LPhase phase("Z_Code generation", chunk());
55 // Open a frame scope to indicate that there is a frame on the stack. The
56 // MANUAL indicates that the scope shouldn't actually generate code to set up
57 // the frame (that is done in GeneratePrologue).
58 FrameScope frame_scope(masm_, StackFrame::MANUAL);
60 support_aligned_spilled_doubles_ = info()->IsOptimizing();
62 dynamic_frame_alignment_ = info()->IsOptimizing() &&
63 ((chunk()->num_double_slots() > 2 &&
64 !chunk()->graph()->is_recursive()) ||
65 !info()->osr_ast_id().IsNone());
67 return GeneratePrologue() &&
69 GenerateDeferredCode() &&
70 GenerateJumpTable() &&
71 GenerateSafepointTable();
75 void LCodeGen::FinishCode(Handle<Code> code) {
77 code->set_stack_slots(GetStackSlotCount());
78 code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
79 PopulateDeoptimizationData(code);
80 if (!info()->IsStub()) {
81 Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(code);
87 void LCodeGen::MakeSureStackPagesMapped(int offset) {
88 const int kPageSize = 4 * KB;
89 for (offset -= kPageSize; offset > 0; offset -= kPageSize) {
90 __ mov(Operand(esp, offset), eax);
96 void LCodeGen::SaveCallerDoubles() {
97 DCHECK(info()->saves_caller_doubles());
98 DCHECK(NeedsEagerFrame());
99 Comment(";;; Save clobbered callee double registers");
101 BitVector* doubles = chunk()->allocated_double_registers();
102 BitVector::Iterator save_iterator(doubles);
103 while (!save_iterator.Done()) {
104 __ movsd(MemOperand(esp, count * kDoubleSize),
105 XMMRegister::FromAllocationIndex(save_iterator.Current()));
106 save_iterator.Advance();
112 void LCodeGen::RestoreCallerDoubles() {
113 DCHECK(info()->saves_caller_doubles());
114 DCHECK(NeedsEagerFrame());
115 Comment(";;; Restore clobbered callee double registers");
116 BitVector* doubles = chunk()->allocated_double_registers();
117 BitVector::Iterator save_iterator(doubles);
119 while (!save_iterator.Done()) {
120 __ movsd(XMMRegister::FromAllocationIndex(save_iterator.Current()),
121 MemOperand(esp, count * kDoubleSize));
122 save_iterator.Advance();
128 bool LCodeGen::GeneratePrologue() {
129 DCHECK(is_generating());
131 if (info()->IsOptimizing()) {
132 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
135 if (strlen(FLAG_stop_at) > 0 &&
136 info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
141 // Sloppy mode functions and builtins need to replace the receiver with the
142 // global proxy when called as functions (without an explicit receiver
144 if (is_sloppy(info()->language_mode()) && info()->MayUseThis() &&
145 !info()->is_native() && info()->scope()->has_this_declaration()) {
147 // +1 for return address.
148 int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
149 __ mov(ecx, Operand(esp, receiver_offset));
151 __ cmp(ecx, isolate()->factory()->undefined_value());
152 __ j(not_equal, &ok, Label::kNear);
154 __ mov(ecx, GlobalObjectOperand());
155 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
157 __ mov(Operand(esp, receiver_offset), ecx);
162 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
163 // Move state of dynamic frame alignment into edx.
164 __ Move(edx, Immediate(kNoAlignmentPadding));
166 Label do_not_pad, align_loop;
167 STATIC_ASSERT(kDoubleSize == 2 * kPointerSize);
168 // Align esp + 4 to a multiple of 2 * kPointerSize.
169 __ test(esp, Immediate(kPointerSize));
170 __ j(not_zero, &do_not_pad, Label::kNear);
171 __ push(Immediate(0));
173 __ mov(edx, Immediate(kAlignmentPaddingPushed));
174 // Copy arguments, receiver, and return address.
175 __ mov(ecx, Immediate(scope()->num_parameters() + 2));
177 __ bind(&align_loop);
178 __ mov(eax, Operand(ebx, 1 * kPointerSize));
179 __ mov(Operand(ebx, 0), eax);
180 __ add(Operand(ebx), Immediate(kPointerSize));
182 __ j(not_zero, &align_loop, Label::kNear);
183 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
184 __ bind(&do_not_pad);
188 info()->set_prologue_offset(masm_->pc_offset());
189 if (NeedsEagerFrame()) {
190 DCHECK(!frame_is_built_);
191 frame_is_built_ = true;
192 if (info()->IsStub()) {
195 __ Prologue(info()->IsCodePreAgingActive());
197 info()->AddNoFrameRange(0, masm_->pc_offset());
200 if (info()->IsOptimizing() &&
201 dynamic_frame_alignment_ &&
203 __ test(esp, Immediate(kPointerSize));
204 __ Assert(zero, kFrameIsExpectedToBeAligned);
207 // Reserve space for the stack slots needed by the code.
208 int slots = GetStackSlotCount();
209 DCHECK(slots != 0 || !info()->IsOptimizing());
212 if (dynamic_frame_alignment_) {
215 __ push(Immediate(kNoAlignmentPadding));
218 if (FLAG_debug_code) {
219 __ sub(Operand(esp), Immediate(slots * kPointerSize));
221 MakeSureStackPagesMapped(slots * kPointerSize);
224 __ mov(Operand(eax), Immediate(slots));
227 __ mov(MemOperand(esp, eax, times_4, 0),
228 Immediate(kSlotsZapValue));
230 __ j(not_zero, &loop);
233 __ sub(Operand(esp), Immediate(slots * kPointerSize));
235 MakeSureStackPagesMapped(slots * kPointerSize);
239 if (support_aligned_spilled_doubles_) {
240 Comment(";;; Store dynamic frame alignment tag for spilled doubles");
241 // Store dynamic frame alignment state in the first local.
242 int offset = JavaScriptFrameConstants::kDynamicAlignmentStateOffset;
243 if (dynamic_frame_alignment_) {
244 __ mov(Operand(ebp, offset), edx);
246 __ mov(Operand(ebp, offset), Immediate(kNoAlignmentPadding));
251 if (info()->saves_caller_doubles()) SaveCallerDoubles();
254 // Possibly allocate a local context.
255 int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
256 if (heap_slots > 0) {
257 Comment(";;; Allocate local context");
258 bool need_write_barrier = true;
259 // Argument to NewContext is the function, which is still in edi.
260 DCHECK(!info()->scope()->is_script_scope());
261 if (heap_slots <= FastNewContextStub::kMaximumSlots) {
262 FastNewContextStub stub(isolate(), heap_slots);
264 // Result of FastNewContextStub is always in new space.
265 need_write_barrier = false;
268 __ CallRuntime(Runtime::kNewFunctionContext, 1);
270 RecordSafepoint(Safepoint::kNoLazyDeopt);
271 // Context is returned in eax. It replaces the context passed to us.
272 // It's saved in the stack and kept live in esi.
274 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
276 // Copy parameters into context if necessary.
277 int num_parameters = scope()->num_parameters();
278 int first_parameter = scope()->has_this_declaration() ? -1 : 0;
279 for (int i = first_parameter; i < num_parameters; i++) {
280 Variable* var = (i == -1) ? scope()->receiver() : scope()->parameter(i);
281 if (var->IsContextSlot()) {
282 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
283 (num_parameters - 1 - i) * kPointerSize;
284 // Load parameter from stack.
285 __ mov(eax, Operand(ebp, parameter_offset));
286 // Store it in the context.
287 int context_offset = Context::SlotOffset(var->index());
288 __ mov(Operand(esi, context_offset), eax);
289 // Update the write barrier. This clobbers eax and ebx.
290 if (need_write_barrier) {
291 __ RecordWriteContextSlot(esi,
296 } else if (FLAG_debug_code) {
298 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
299 __ Abort(kExpectedNewSpaceObject);
304 Comment(";;; End allocate local context");
308 if (FLAG_trace && info()->IsOptimizing()) {
309 // We have not executed any compiled code yet, so esi still holds the
311 __ CallRuntime(Runtime::kTraceEnter, 0);
313 return !is_aborted();
317 void LCodeGen::GenerateOsrPrologue() {
318 // Generate the OSR entry prologue at the first unknown OSR value, or if there
319 // are none, at the OSR entrypoint instruction.
320 if (osr_pc_offset_ >= 0) return;
322 osr_pc_offset_ = masm()->pc_offset();
324 // Move state of dynamic frame alignment into edx.
325 __ Move(edx, Immediate(kNoAlignmentPadding));
327 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
328 Label do_not_pad, align_loop;
329 // Align ebp + 4 to a multiple of 2 * kPointerSize.
330 __ test(ebp, Immediate(kPointerSize));
331 __ j(zero, &do_not_pad, Label::kNear);
332 __ push(Immediate(0));
334 __ mov(edx, Immediate(kAlignmentPaddingPushed));
336 // Move all parts of the frame over one word. The frame consists of:
337 // unoptimized frame slots, alignment state, context, frame pointer, return
338 // address, receiver, and the arguments.
339 __ mov(ecx, Immediate(scope()->num_parameters() +
340 5 + graph()->osr()->UnoptimizedFrameSlots()));
342 __ bind(&align_loop);
343 __ mov(eax, Operand(ebx, 1 * kPointerSize));
344 __ mov(Operand(ebx, 0), eax);
345 __ add(Operand(ebx), Immediate(kPointerSize));
347 __ j(not_zero, &align_loop, Label::kNear);
348 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
349 __ sub(Operand(ebp), Immediate(kPointerSize));
350 __ bind(&do_not_pad);
353 // Save the first local, which is overwritten by the alignment state.
354 Operand alignment_loc = MemOperand(ebp, -3 * kPointerSize);
355 __ push(alignment_loc);
357 // Set the dynamic frame alignment state.
358 __ mov(alignment_loc, edx);
360 // Adjust the frame size, subsuming the unoptimized frame into the
362 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
364 __ sub(esp, Immediate((slots - 1) * kPointerSize));
368 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
369 if (instr->IsCall()) {
370 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
372 if (!instr->IsLazyBailout() && !instr->IsGap()) {
373 safepoints_.BumpLastLazySafepointIndex();
378 void LCodeGen::GenerateBodyInstructionPost(LInstruction* instr) { }
381 bool LCodeGen::GenerateJumpTable() {
382 if (!jump_table_.length()) return !is_aborted();
385 Comment(";;; -------------------- Jump table --------------------");
387 for (int i = 0; i < jump_table_.length(); i++) {
388 Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
389 __ bind(&table_entry->label);
390 Address entry = table_entry->address;
391 DeoptComment(table_entry->deopt_info);
392 if (table_entry->needs_frame) {
393 DCHECK(!info()->saves_caller_doubles());
394 __ push(Immediate(ExternalReference::ForDeoptEntry(entry)));
395 __ call(&needs_frame);
397 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
398 __ call(entry, RelocInfo::RUNTIME_ENTRY);
400 info()->LogDeoptCallPosition(masm()->pc_offset(),
401 table_entry->deopt_info.inlining_id);
403 if (needs_frame.is_linked()) {
404 __ bind(&needs_frame);
407 3: return address <-- esp
412 __ sub(esp, Immediate(kPointerSize)); // Reserve space for stub marker.
413 __ push(MemOperand(esp, kPointerSize)); // Copy return address.
414 __ push(MemOperand(esp, 3 * kPointerSize)); // Copy entry address.
421 0: entry address <-- esp
423 __ mov(MemOperand(esp, 4 * kPointerSize), ebp); // Save ebp.
425 __ mov(ebp, MemOperand(ebp, StandardFrameConstants::kContextOffset));
426 __ mov(MemOperand(esp, 3 * kPointerSize), ebp);
427 // Fill ebp with the right stack frame address.
428 __ lea(ebp, MemOperand(esp, 4 * kPointerSize));
429 // This variant of deopt can only be used with stubs. Since we don't
430 // have a function pointer to install in the stack frame that we're
431 // building, install a special marker there instead.
432 DCHECK(info()->IsStub());
433 __ mov(MemOperand(esp, 2 * kPointerSize),
434 Immediate(Smi::FromInt(StackFrame::STUB)));
441 0: entry address <-- esp
443 __ ret(0); // Call the continuation without clobbering registers.
445 return !is_aborted();
449 bool LCodeGen::GenerateDeferredCode() {
450 DCHECK(is_generating());
451 if (deferred_.length() > 0) {
452 for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
453 LDeferredCode* code = deferred_[i];
456 instructions_->at(code->instruction_index())->hydrogen_value();
457 RecordAndWritePosition(
458 chunk()->graph()->SourcePositionToScriptPosition(value->position()));
460 Comment(";;; <@%d,#%d> "
461 "-------------------- Deferred %s --------------------",
462 code->instruction_index(),
463 code->instr()->hydrogen_value()->id(),
464 code->instr()->Mnemonic());
465 __ bind(code->entry());
466 if (NeedsDeferredFrame()) {
467 Comment(";;; Build frame");
468 DCHECK(!frame_is_built_);
469 DCHECK(info()->IsStub());
470 frame_is_built_ = true;
471 // Build the frame in such a way that esi isn't trashed.
472 __ push(ebp); // Caller's frame pointer.
473 __ push(Operand(ebp, StandardFrameConstants::kContextOffset));
474 __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
475 __ lea(ebp, Operand(esp, 2 * kPointerSize));
476 Comment(";;; Deferred code");
479 if (NeedsDeferredFrame()) {
480 __ bind(code->done());
481 Comment(";;; Destroy frame");
482 DCHECK(frame_is_built_);
483 frame_is_built_ = false;
487 __ jmp(code->exit());
491 // Deferred code is the last part of the instruction sequence. Mark
492 // the generated code as done unless we bailed out.
493 if (!is_aborted()) status_ = DONE;
494 return !is_aborted();
498 bool LCodeGen::GenerateSafepointTable() {
500 if (!info()->IsStub()) {
501 // For lazy deoptimization we need space to patch a call after every call.
502 // Ensure there is always space for such patching, even if the code ends
504 int target_offset = masm()->pc_offset() + Deoptimizer::patch_size();
505 while (masm()->pc_offset() < target_offset) {
509 safepoints_.Emit(masm(), GetStackSlotCount());
510 return !is_aborted();
514 Register LCodeGen::ToRegister(int index) const {
515 return Register::FromAllocationIndex(index);
519 XMMRegister LCodeGen::ToDoubleRegister(int index) const {
520 return XMMRegister::FromAllocationIndex(index);
524 Register LCodeGen::ToRegister(LOperand* op) const {
525 DCHECK(op->IsRegister());
526 return ToRegister(op->index());
530 XMMRegister LCodeGen::ToDoubleRegister(LOperand* op) const {
531 DCHECK(op->IsDoubleRegister());
532 return ToDoubleRegister(op->index());
536 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
537 return ToRepresentation(op, Representation::Integer32());
541 int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
542 const Representation& r) const {
543 HConstant* constant = chunk_->LookupConstant(op);
544 int32_t value = constant->Integer32Value();
545 if (r.IsInteger32()) return value;
546 DCHECK(r.IsSmiOrTagged());
547 return reinterpret_cast<int32_t>(Smi::FromInt(value));
551 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
552 HConstant* constant = chunk_->LookupConstant(op);
553 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
554 return constant->handle(isolate());
558 double LCodeGen::ToDouble(LConstantOperand* op) const {
559 HConstant* constant = chunk_->LookupConstant(op);
560 DCHECK(constant->HasDoubleValue());
561 return constant->DoubleValue();
565 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
566 HConstant* constant = chunk_->LookupConstant(op);
567 DCHECK(constant->HasExternalReferenceValue());
568 return constant->ExternalReferenceValue();
572 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
573 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
577 bool LCodeGen::IsSmi(LConstantOperand* op) const {
578 return chunk_->LookupLiteralRepresentation(op).IsSmi();
582 static int ArgumentsOffsetWithoutFrame(int index) {
584 return -(index + 1) * kPointerSize + kPCOnStackSize;
588 Operand LCodeGen::ToOperand(LOperand* op) const {
589 if (op->IsRegister()) return Operand(ToRegister(op));
590 if (op->IsDoubleRegister()) return Operand(ToDoubleRegister(op));
591 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
592 if (NeedsEagerFrame()) {
593 return Operand(ebp, StackSlotOffset(op->index()));
595 // Retrieve parameter without eager stack-frame relative to the
597 return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
602 Operand LCodeGen::HighOperand(LOperand* op) {
603 DCHECK(op->IsDoubleStackSlot());
604 if (NeedsEagerFrame()) {
605 return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
607 // Retrieve parameter without eager stack-frame relative to the
610 esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
615 void LCodeGen::WriteTranslation(LEnvironment* environment,
616 Translation* translation) {
617 if (environment == NULL) return;
619 // The translation includes one command per value in the environment.
620 int translation_size = environment->translation_size();
621 // The output frame height does not include the parameters.
622 int height = translation_size - environment->parameter_count();
624 WriteTranslation(environment->outer(), translation);
625 bool has_closure_id = !info()->closure().is_null() &&
626 !info()->closure().is_identical_to(environment->closure());
627 int closure_id = has_closure_id
628 ? DefineDeoptimizationLiteral(environment->closure())
629 : Translation::kSelfLiteralId;
630 switch (environment->frame_type()) {
632 translation->BeginJSFrame(environment->ast_id(), closure_id, height);
635 translation->BeginConstructStubFrame(closure_id, translation_size);
638 DCHECK(translation_size == 1);
640 translation->BeginGetterStubFrame(closure_id);
643 DCHECK(translation_size == 2);
645 translation->BeginSetterStubFrame(closure_id);
647 case ARGUMENTS_ADAPTOR:
648 translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
651 translation->BeginCompiledStubFrame(translation_size);
657 int object_index = 0;
658 int dematerialized_index = 0;
659 for (int i = 0; i < translation_size; ++i) {
660 LOperand* value = environment->values()->at(i);
661 AddToTranslation(environment,
664 environment->HasTaggedValueAt(i),
665 environment->HasUint32ValueAt(i),
667 &dematerialized_index);
672 void LCodeGen::AddToTranslation(LEnvironment* environment,
673 Translation* translation,
677 int* object_index_pointer,
678 int* dematerialized_index_pointer) {
679 if (op == LEnvironment::materialization_marker()) {
680 int object_index = (*object_index_pointer)++;
681 if (environment->ObjectIsDuplicateAt(object_index)) {
682 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
683 translation->DuplicateObject(dupe_of);
686 int object_length = environment->ObjectLengthAt(object_index);
687 if (environment->ObjectIsArgumentsAt(object_index)) {
688 translation->BeginArgumentsObject(object_length);
690 translation->BeginCapturedObject(object_length);
692 int dematerialized_index = *dematerialized_index_pointer;
693 int env_offset = environment->translation_size() + dematerialized_index;
694 *dematerialized_index_pointer += object_length;
695 for (int i = 0; i < object_length; ++i) {
696 LOperand* value = environment->values()->at(env_offset + i);
697 AddToTranslation(environment,
700 environment->HasTaggedValueAt(env_offset + i),
701 environment->HasUint32ValueAt(env_offset + i),
702 object_index_pointer,
703 dematerialized_index_pointer);
708 if (op->IsStackSlot()) {
710 translation->StoreStackSlot(op->index());
711 } else if (is_uint32) {
712 translation->StoreUint32StackSlot(op->index());
714 translation->StoreInt32StackSlot(op->index());
716 } else if (op->IsDoubleStackSlot()) {
717 translation->StoreDoubleStackSlot(op->index());
718 } else if (op->IsRegister()) {
719 Register reg = ToRegister(op);
721 translation->StoreRegister(reg);
722 } else if (is_uint32) {
723 translation->StoreUint32Register(reg);
725 translation->StoreInt32Register(reg);
727 } else if (op->IsDoubleRegister()) {
728 XMMRegister reg = ToDoubleRegister(op);
729 translation->StoreDoubleRegister(reg);
730 } else if (op->IsConstantOperand()) {
731 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
732 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
733 translation->StoreLiteral(src_index);
740 void LCodeGen::CallCodeGeneric(Handle<Code> code,
741 RelocInfo::Mode mode,
743 SafepointMode safepoint_mode) {
744 DCHECK(instr != NULL);
746 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
748 // Signal that we don't inline smi code before these stubs in the
749 // optimizing code generator.
750 if (code->kind() == Code::BINARY_OP_IC ||
751 code->kind() == Code::COMPARE_IC) {
757 void LCodeGen::CallCode(Handle<Code> code,
758 RelocInfo::Mode mode,
759 LInstruction* instr) {
760 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
764 void LCodeGen::CallRuntime(const Runtime::Function* fun,
767 SaveFPRegsMode save_doubles) {
768 DCHECK(instr != NULL);
769 DCHECK(instr->HasPointerMap());
771 __ CallRuntime(fun, argc, save_doubles);
773 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
775 DCHECK(info()->is_calling());
779 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
780 if (context->IsRegister()) {
781 if (!ToRegister(context).is(esi)) {
782 __ mov(esi, ToRegister(context));
784 } else if (context->IsStackSlot()) {
785 __ mov(esi, ToOperand(context));
786 } else if (context->IsConstantOperand()) {
787 HConstant* constant =
788 chunk_->LookupConstant(LConstantOperand::cast(context));
789 __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
795 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
799 LoadContextFromDeferred(context);
801 __ CallRuntimeSaveDoubles(id);
802 RecordSafepointWithRegisters(
803 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
805 DCHECK(info()->is_calling());
809 void LCodeGen::RegisterEnvironmentForDeoptimization(
810 LEnvironment* environment, Safepoint::DeoptMode mode) {
811 environment->set_has_been_used();
812 if (!environment->HasBeenRegistered()) {
813 // Physical stack frame layout:
814 // -x ............. -4 0 ..................................... y
815 // [incoming arguments] [spill slots] [pushed outgoing arguments]
817 // Layout of the environment:
818 // 0 ..................................................... size-1
819 // [parameters] [locals] [expression stack including arguments]
821 // Layout of the translation:
822 // 0 ........................................................ size - 1 + 4
823 // [expression stack including arguments] [locals] [4 words] [parameters]
824 // |>------------ translation_size ------------<|
827 int jsframe_count = 0;
828 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
830 if (e->frame_type() == JS_FUNCTION) {
834 Translation translation(&translations_, frame_count, jsframe_count, zone());
835 WriteTranslation(environment, &translation);
836 int deoptimization_index = deoptimizations_.length();
837 int pc_offset = masm()->pc_offset();
838 environment->Register(deoptimization_index,
840 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
841 deoptimizations_.Add(environment, zone());
846 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
847 Deoptimizer::DeoptReason deopt_reason,
848 Deoptimizer::BailoutType bailout_type) {
849 LEnvironment* environment = instr->environment();
850 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
851 DCHECK(environment->HasBeenRegistered());
852 int id = environment->deoptimization_index();
853 DCHECK(info()->IsOptimizing() || info()->IsStub());
855 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
857 Abort(kBailoutWasNotPrepared);
861 if (DeoptEveryNTimes()) {
862 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
866 __ mov(eax, Operand::StaticVariable(count));
867 __ sub(eax, Immediate(1));
868 __ j(not_zero, &no_deopt, Label::kNear);
869 if (FLAG_trap_on_deopt) __ int3();
870 __ mov(eax, Immediate(FLAG_deopt_every_n_times));
871 __ mov(Operand::StaticVariable(count), eax);
874 DCHECK(frame_is_built_);
875 __ call(entry, RelocInfo::RUNTIME_ENTRY);
877 __ mov(Operand::StaticVariable(count), eax);
882 if (info()->ShouldTrapOnDeopt()) {
884 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
889 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);
891 DCHECK(info()->IsStub() || frame_is_built_);
892 if (cc == no_condition && frame_is_built_) {
893 DeoptComment(deopt_info);
894 __ call(entry, RelocInfo::RUNTIME_ENTRY);
895 info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
897 Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
899 // We often have several deopts to the same entry, reuse the last
900 // jump entry if this is the case.
901 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
902 jump_table_.is_empty() ||
903 !table_entry.IsEquivalentTo(jump_table_.last())) {
904 jump_table_.Add(table_entry, zone());
906 if (cc == no_condition) {
907 __ jmp(&jump_table_.last().label);
909 __ j(cc, &jump_table_.last().label);
915 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
916 Deoptimizer::DeoptReason deopt_reason) {
917 Deoptimizer::BailoutType bailout_type = info()->IsStub()
919 : Deoptimizer::EAGER;
920 DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
924 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
925 int length = deoptimizations_.length();
926 if (length == 0) return;
927 Handle<DeoptimizationInputData> data =
928 DeoptimizationInputData::New(isolate(), length, TENURED);
930 Handle<ByteArray> translations =
931 translations_.CreateByteArray(isolate()->factory());
932 data->SetTranslationByteArray(*translations);
933 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
934 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
935 if (info_->IsOptimizing()) {
936 // Reference to shared function info does not change between phases.
937 AllowDeferredHandleDereference allow_handle_dereference;
938 data->SetSharedFunctionInfo(*info_->shared_info());
940 data->SetSharedFunctionInfo(Smi::FromInt(0));
942 data->SetWeakCellCache(Smi::FromInt(0));
944 Handle<FixedArray> literals =
945 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
946 { AllowDeferredHandleDereference copy_handles;
947 for (int i = 0; i < deoptimization_literals_.length(); i++) {
948 literals->set(i, *deoptimization_literals_[i]);
950 data->SetLiteralArray(*literals);
953 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
954 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
956 // Populate the deoptimization entries.
957 for (int i = 0; i < length; i++) {
958 LEnvironment* env = deoptimizations_[i];
959 data->SetAstId(i, env->ast_id());
960 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
961 data->SetArgumentsStackHeight(i,
962 Smi::FromInt(env->arguments_stack_height()));
963 data->SetPc(i, Smi::FromInt(env->pc_offset()));
965 code->set_deoptimization_data(*data);
969 int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
970 int result = deoptimization_literals_.length();
971 for (int i = 0; i < deoptimization_literals_.length(); ++i) {
972 if (deoptimization_literals_[i].is_identical_to(literal)) return i;
974 deoptimization_literals_.Add(literal, zone());
979 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
980 DCHECK_EQ(0, deoptimization_literals_.length());
981 for (auto function : chunk()->inlined_functions()) {
982 DefineDeoptimizationLiteral(function);
984 inlined_function_count_ = deoptimization_literals_.length();
988 void LCodeGen::RecordSafepointWithLazyDeopt(
989 LInstruction* instr, SafepointMode safepoint_mode) {
990 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
991 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
993 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
994 RecordSafepointWithRegisters(
995 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
1000 void LCodeGen::RecordSafepoint(
1001 LPointerMap* pointers,
1002 Safepoint::Kind kind,
1004 Safepoint::DeoptMode deopt_mode) {
1005 DCHECK(kind == expected_safepoint_kind_);
1006 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
1007 Safepoint safepoint =
1008 safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
1009 for (int i = 0; i < operands->length(); i++) {
1010 LOperand* pointer = operands->at(i);
1011 if (pointer->IsStackSlot()) {
1012 safepoint.DefinePointerSlot(pointer->index(), zone());
1013 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
1014 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
1020 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
1021 Safepoint::DeoptMode mode) {
1022 RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
1026 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
1027 LPointerMap empty_pointers(zone());
1028 RecordSafepoint(&empty_pointers, mode);
1032 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
1034 Safepoint::DeoptMode mode) {
1035 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1039 void LCodeGen::RecordAndWritePosition(int position) {
1040 if (position == RelocInfo::kNoPosition) return;
1041 masm()->positions_recorder()->RecordPosition(position);
1042 masm()->positions_recorder()->WriteRecordedPositions();
1046 static const char* LabelType(LLabel* label) {
1047 if (label->is_loop_header()) return " (loop header)";
1048 if (label->is_osr_entry()) return " (OSR entry)";
1053 void LCodeGen::DoLabel(LLabel* label) {
1054 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1055 current_instruction_,
1056 label->hydrogen_value()->id(),
1059 __ bind(label->label());
1060 current_block_ = label->block_id();
1065 void LCodeGen::DoParallelMove(LParallelMove* move) {
1066 resolver_.Resolve(move);
1070 void LCodeGen::DoGap(LGap* gap) {
1071 for (int i = LGap::FIRST_INNER_POSITION;
1072 i <= LGap::LAST_INNER_POSITION;
1074 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1075 LParallelMove* move = gap->GetParallelMove(inner_pos);
1076 if (move != NULL) DoParallelMove(move);
1081 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1086 void LCodeGen::DoParameter(LParameter* instr) {
1091 void LCodeGen::DoCallStub(LCallStub* instr) {
1092 DCHECK(ToRegister(instr->context()).is(esi));
1093 DCHECK(ToRegister(instr->result()).is(eax));
1094 switch (instr->hydrogen()->major_key()) {
1095 case CodeStub::RegExpExec: {
1096 RegExpExecStub stub(isolate());
1097 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1100 case CodeStub::SubString: {
1101 SubStringStub stub(isolate());
1102 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1105 case CodeStub::StringCompare: {
1106 StringCompareStub stub(isolate());
1107 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1116 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1117 GenerateOsrPrologue();
1121 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1122 Register dividend = ToRegister(instr->dividend());
1123 int32_t divisor = instr->divisor();
1124 DCHECK(dividend.is(ToRegister(instr->result())));
1126 // Theoretically, a variation of the branch-free code for integer division by
1127 // a power of 2 (calculating the remainder via an additional multiplication
1128 // (which gets simplified to an 'and') and subtraction) should be faster, and
1129 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1130 // indicate that positive dividends are heavily favored, so the branching
1131 // version performs better.
1132 HMod* hmod = instr->hydrogen();
1133 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1134 Label dividend_is_not_negative, done;
1135 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1136 __ test(dividend, dividend);
1137 __ j(not_sign, ÷nd_is_not_negative, Label::kNear);
1138 // Note that this is correct even for kMinInt operands.
1140 __ and_(dividend, mask);
1142 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1143 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1145 __ jmp(&done, Label::kNear);
1148 __ bind(÷nd_is_not_negative);
1149 __ and_(dividend, mask);
1154 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1155 Register dividend = ToRegister(instr->dividend());
1156 int32_t divisor = instr->divisor();
1157 DCHECK(ToRegister(instr->result()).is(eax));
1160 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1164 __ TruncatingDiv(dividend, Abs(divisor));
1165 __ imul(edx, edx, Abs(divisor));
1166 __ mov(eax, dividend);
1169 // Check for negative zero.
1170 HMod* hmod = instr->hydrogen();
1171 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1172 Label remainder_not_zero;
1173 __ j(not_zero, &remainder_not_zero, Label::kNear);
1174 __ cmp(dividend, Immediate(0));
1175 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1176 __ bind(&remainder_not_zero);
1181 void LCodeGen::DoModI(LModI* instr) {
1182 HMod* hmod = instr->hydrogen();
1184 Register left_reg = ToRegister(instr->left());
1185 DCHECK(left_reg.is(eax));
1186 Register right_reg = ToRegister(instr->right());
1187 DCHECK(!right_reg.is(eax));
1188 DCHECK(!right_reg.is(edx));
1189 Register result_reg = ToRegister(instr->result());
1190 DCHECK(result_reg.is(edx));
1193 // Check for x % 0, idiv would signal a divide error. We have to
1194 // deopt in this case because we can't return a NaN.
1195 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1196 __ test(right_reg, Operand(right_reg));
1197 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1200 // Check for kMinInt % -1, idiv would signal a divide error. We
1201 // have to deopt if we care about -0, because we can't return that.
1202 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1203 Label no_overflow_possible;
1204 __ cmp(left_reg, kMinInt);
1205 __ j(not_equal, &no_overflow_possible, Label::kNear);
1206 __ cmp(right_reg, -1);
1207 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1208 DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1210 __ j(not_equal, &no_overflow_possible, Label::kNear);
1211 __ Move(result_reg, Immediate(0));
1212 __ jmp(&done, Label::kNear);
1214 __ bind(&no_overflow_possible);
1217 // Sign extend dividend in eax into edx:eax.
1220 // If we care about -0, test if the dividend is <0 and the result is 0.
1221 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1222 Label positive_left;
1223 __ test(left_reg, Operand(left_reg));
1224 __ j(not_sign, &positive_left, Label::kNear);
1226 __ test(result_reg, Operand(result_reg));
1227 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1228 __ jmp(&done, Label::kNear);
1229 __ bind(&positive_left);
1236 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1237 Register dividend = ToRegister(instr->dividend());
1238 int32_t divisor = instr->divisor();
1239 Register result = ToRegister(instr->result());
1240 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1241 DCHECK(!result.is(dividend));
1243 // Check for (0 / -x) that will produce negative zero.
1244 HDiv* hdiv = instr->hydrogen();
1245 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1246 __ test(dividend, dividend);
1247 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1249 // Check for (kMinInt / -1).
1250 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1251 __ cmp(dividend, kMinInt);
1252 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1254 // Deoptimize if remainder will not be 0.
1255 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1256 divisor != 1 && divisor != -1) {
1257 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1258 __ test(dividend, Immediate(mask));
1259 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1261 __ Move(result, dividend);
1262 int32_t shift = WhichPowerOf2Abs(divisor);
1264 // The arithmetic shift is always OK, the 'if' is an optimization only.
1265 if (shift > 1) __ sar(result, 31);
1266 __ shr(result, 32 - shift);
1267 __ add(result, dividend);
1268 __ sar(result, shift);
1270 if (divisor < 0) __ neg(result);
1274 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1275 Register dividend = ToRegister(instr->dividend());
1276 int32_t divisor = instr->divisor();
1277 DCHECK(ToRegister(instr->result()).is(edx));
1280 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1284 // Check for (0 / -x) that will produce negative zero.
1285 HDiv* hdiv = instr->hydrogen();
1286 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1287 __ test(dividend, dividend);
1288 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1291 __ TruncatingDiv(dividend, Abs(divisor));
1292 if (divisor < 0) __ neg(edx);
1294 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1296 __ imul(eax, eax, divisor);
1297 __ sub(eax, dividend);
1298 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1303 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1304 void LCodeGen::DoDivI(LDivI* instr) {
1305 HBinaryOperation* hdiv = instr->hydrogen();
1306 Register dividend = ToRegister(instr->dividend());
1307 Register divisor = ToRegister(instr->divisor());
1308 Register remainder = ToRegister(instr->temp());
1309 DCHECK(dividend.is(eax));
1310 DCHECK(remainder.is(edx));
1311 DCHECK(ToRegister(instr->result()).is(eax));
1312 DCHECK(!divisor.is(eax));
1313 DCHECK(!divisor.is(edx));
1316 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1317 __ test(divisor, divisor);
1318 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1321 // Check for (0 / -x) that will produce negative zero.
1322 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1323 Label dividend_not_zero;
1324 __ test(dividend, dividend);
1325 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1326 __ test(divisor, divisor);
1327 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1328 __ bind(÷nd_not_zero);
1331 // Check for (kMinInt / -1).
1332 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1333 Label dividend_not_min_int;
1334 __ cmp(dividend, kMinInt);
1335 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1336 __ cmp(divisor, -1);
1337 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1338 __ bind(÷nd_not_min_int);
1341 // Sign extend to edx (= remainder).
1345 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1346 // Deoptimize if remainder is not 0.
1347 __ test(remainder, remainder);
1348 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1353 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1354 Register dividend = ToRegister(instr->dividend());
1355 int32_t divisor = instr->divisor();
1356 DCHECK(dividend.is(ToRegister(instr->result())));
1358 // If the divisor is positive, things are easy: There can be no deopts and we
1359 // can simply do an arithmetic right shift.
1360 if (divisor == 1) return;
1361 int32_t shift = WhichPowerOf2Abs(divisor);
1363 __ sar(dividend, shift);
1367 // If the divisor is negative, we have to negate and handle edge cases.
1369 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1370 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1373 // Dividing by -1 is basically negation, unless we overflow.
1374 if (divisor == -1) {
1375 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1376 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1381 // If the negation could not overflow, simply shifting is OK.
1382 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1383 __ sar(dividend, shift);
1387 Label not_kmin_int, done;
1388 __ j(no_overflow, ¬_kmin_int, Label::kNear);
1389 __ mov(dividend, Immediate(kMinInt / divisor));
1390 __ jmp(&done, Label::kNear);
1391 __ bind(¬_kmin_int);
1392 __ sar(dividend, shift);
1397 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1398 Register dividend = ToRegister(instr->dividend());
1399 int32_t divisor = instr->divisor();
1400 DCHECK(ToRegister(instr->result()).is(edx));
1403 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1407 // Check for (0 / -x) that will produce negative zero.
1408 HMathFloorOfDiv* hdiv = instr->hydrogen();
1409 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1410 __ test(dividend, dividend);
1411 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1414 // Easy case: We need no dynamic check for the dividend and the flooring
1415 // division is the same as the truncating division.
1416 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1417 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1418 __ TruncatingDiv(dividend, Abs(divisor));
1419 if (divisor < 0) __ neg(edx);
1423 // In the general case we may need to adjust before and after the truncating
1424 // division to get a flooring division.
1425 Register temp = ToRegister(instr->temp3());
1426 DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1427 Label needs_adjustment, done;
1428 __ cmp(dividend, Immediate(0));
1429 __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1430 __ TruncatingDiv(dividend, Abs(divisor));
1431 if (divisor < 0) __ neg(edx);
1432 __ jmp(&done, Label::kNear);
1433 __ bind(&needs_adjustment);
1434 __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1435 __ TruncatingDiv(temp, Abs(divisor));
1436 if (divisor < 0) __ neg(edx);
1442 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1443 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1444 HBinaryOperation* hdiv = instr->hydrogen();
1445 Register dividend = ToRegister(instr->dividend());
1446 Register divisor = ToRegister(instr->divisor());
1447 Register remainder = ToRegister(instr->temp());
1448 Register result = ToRegister(instr->result());
1449 DCHECK(dividend.is(eax));
1450 DCHECK(remainder.is(edx));
1451 DCHECK(result.is(eax));
1452 DCHECK(!divisor.is(eax));
1453 DCHECK(!divisor.is(edx));
1456 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1457 __ test(divisor, divisor);
1458 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1461 // Check for (0 / -x) that will produce negative zero.
1462 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1463 Label dividend_not_zero;
1464 __ test(dividend, dividend);
1465 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1466 __ test(divisor, divisor);
1467 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1468 __ bind(÷nd_not_zero);
1471 // Check for (kMinInt / -1).
1472 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1473 Label dividend_not_min_int;
1474 __ cmp(dividend, kMinInt);
1475 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1476 __ cmp(divisor, -1);
1477 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1478 __ bind(÷nd_not_min_int);
1481 // Sign extend to edx (= remainder).
1486 __ test(remainder, remainder);
1487 __ j(zero, &done, Label::kNear);
1488 __ xor_(remainder, divisor);
1489 __ sar(remainder, 31);
1490 __ add(result, remainder);
1495 void LCodeGen::DoMulI(LMulI* instr) {
1496 Register left = ToRegister(instr->left());
1497 LOperand* right = instr->right();
1499 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1500 __ mov(ToRegister(instr->temp()), left);
1503 if (right->IsConstantOperand()) {
1504 // Try strength reductions on the multiplication.
1505 // All replacement instructions are at most as long as the imul
1506 // and have better latency.
1507 int constant = ToInteger32(LConstantOperand::cast(right));
1508 if (constant == -1) {
1510 } else if (constant == 0) {
1511 __ xor_(left, Operand(left));
1512 } else if (constant == 2) {
1513 __ add(left, Operand(left));
1514 } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1515 // If we know that the multiplication can't overflow, it's safe to
1516 // use instructions that don't set the overflow flag for the
1523 __ lea(left, Operand(left, left, times_2, 0));
1529 __ lea(left, Operand(left, left, times_4, 0));
1535 __ lea(left, Operand(left, left, times_8, 0));
1541 __ imul(left, left, constant);
1545 __ imul(left, left, constant);
1548 if (instr->hydrogen()->representation().IsSmi()) {
1551 __ imul(left, ToOperand(right));
1554 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1555 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1558 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1559 // Bail out if the result is supposed to be negative zero.
1561 __ test(left, Operand(left));
1562 __ j(not_zero, &done, Label::kNear);
1563 if (right->IsConstantOperand()) {
1564 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1565 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1566 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1567 __ cmp(ToRegister(instr->temp()), Immediate(0));
1568 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1571 // Test the non-zero operand for negative sign.
1572 __ or_(ToRegister(instr->temp()), ToOperand(right));
1573 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1580 void LCodeGen::DoBitI(LBitI* instr) {
1581 LOperand* left = instr->left();
1582 LOperand* right = instr->right();
1583 DCHECK(left->Equals(instr->result()));
1584 DCHECK(left->IsRegister());
1586 if (right->IsConstantOperand()) {
1587 int32_t right_operand =
1588 ToRepresentation(LConstantOperand::cast(right),
1589 instr->hydrogen()->representation());
1590 switch (instr->op()) {
1591 case Token::BIT_AND:
1592 __ and_(ToRegister(left), right_operand);
1595 __ or_(ToRegister(left), right_operand);
1597 case Token::BIT_XOR:
1598 if (right_operand == int32_t(~0)) {
1599 __ not_(ToRegister(left));
1601 __ xor_(ToRegister(left), right_operand);
1609 switch (instr->op()) {
1610 case Token::BIT_AND:
1611 __ and_(ToRegister(left), ToOperand(right));
1614 __ or_(ToRegister(left), ToOperand(right));
1616 case Token::BIT_XOR:
1617 __ xor_(ToRegister(left), ToOperand(right));
1627 void LCodeGen::DoShiftI(LShiftI* instr) {
1628 LOperand* left = instr->left();
1629 LOperand* right = instr->right();
1630 DCHECK(left->Equals(instr->result()));
1631 DCHECK(left->IsRegister());
1632 if (right->IsRegister()) {
1633 DCHECK(ToRegister(right).is(ecx));
1635 switch (instr->op()) {
1637 __ ror_cl(ToRegister(left));
1640 __ sar_cl(ToRegister(left));
1643 __ shr_cl(ToRegister(left));
1644 if (instr->can_deopt()) {
1645 __ test(ToRegister(left), ToRegister(left));
1646 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1650 __ shl_cl(ToRegister(left));
1657 int value = ToInteger32(LConstantOperand::cast(right));
1658 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1659 switch (instr->op()) {
1661 if (shift_count == 0 && instr->can_deopt()) {
1662 __ test(ToRegister(left), ToRegister(left));
1663 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1665 __ ror(ToRegister(left), shift_count);
1669 if (shift_count != 0) {
1670 __ sar(ToRegister(left), shift_count);
1674 if (shift_count != 0) {
1675 __ shr(ToRegister(left), shift_count);
1676 } else if (instr->can_deopt()) {
1677 __ test(ToRegister(left), ToRegister(left));
1678 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1682 if (shift_count != 0) {
1683 if (instr->hydrogen_value()->representation().IsSmi() &&
1684 instr->can_deopt()) {
1685 if (shift_count != 1) {
1686 __ shl(ToRegister(left), shift_count - 1);
1688 __ SmiTag(ToRegister(left));
1689 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1691 __ shl(ToRegister(left), shift_count);
1703 void LCodeGen::DoSubI(LSubI* instr) {
1704 LOperand* left = instr->left();
1705 LOperand* right = instr->right();
1706 DCHECK(left->Equals(instr->result()));
1708 if (right->IsConstantOperand()) {
1709 __ sub(ToOperand(left),
1710 ToImmediate(right, instr->hydrogen()->representation()));
1712 __ sub(ToRegister(left), ToOperand(right));
1714 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1715 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1720 void LCodeGen::DoConstantI(LConstantI* instr) {
1721 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1725 void LCodeGen::DoConstantS(LConstantS* instr) {
1726 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1730 void LCodeGen::DoConstantD(LConstantD* instr) {
1731 uint64_t const bits = instr->bits();
1732 uint32_t const lower = static_cast<uint32_t>(bits);
1733 uint32_t const upper = static_cast<uint32_t>(bits >> 32);
1734 DCHECK(instr->result()->IsDoubleRegister());
1736 XMMRegister result = ToDoubleRegister(instr->result());
1738 __ xorps(result, result);
1740 Register temp = ToRegister(instr->temp());
1741 if (CpuFeatures::IsSupported(SSE4_1)) {
1742 CpuFeatureScope scope2(masm(), SSE4_1);
1744 __ Move(temp, Immediate(lower));
1745 __ movd(result, Operand(temp));
1746 __ Move(temp, Immediate(upper));
1747 __ pinsrd(result, Operand(temp), 1);
1749 __ xorps(result, result);
1750 __ Move(temp, Immediate(upper));
1751 __ pinsrd(result, Operand(temp), 1);
1754 __ Move(temp, Immediate(upper));
1755 __ movd(result, Operand(temp));
1756 __ psllq(result, 32);
1758 XMMRegister xmm_scratch = double_scratch0();
1759 __ Move(temp, Immediate(lower));
1760 __ movd(xmm_scratch, Operand(temp));
1761 __ orps(result, xmm_scratch);
1768 void LCodeGen::DoConstantE(LConstantE* instr) {
1769 __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
1773 void LCodeGen::DoConstantT(LConstantT* instr) {
1774 Register reg = ToRegister(instr->result());
1775 Handle<Object> object = instr->value(isolate());
1776 AllowDeferredHandleDereference smi_check;
1777 __ LoadObject(reg, object);
1781 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
1782 Register result = ToRegister(instr->result());
1783 Register map = ToRegister(instr->value());
1784 __ EnumLength(result, map);
1788 void LCodeGen::DoDateField(LDateField* instr) {
1789 Register object = ToRegister(instr->date());
1790 Register result = ToRegister(instr->result());
1791 Register scratch = ToRegister(instr->temp());
1792 Smi* index = instr->index();
1793 DCHECK(object.is(result));
1794 DCHECK(object.is(eax));
1796 if (index->value() == 0) {
1797 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
1799 Label runtime, done;
1800 if (index->value() < JSDate::kFirstUncachedField) {
1801 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
1802 __ mov(scratch, Operand::StaticVariable(stamp));
1803 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
1804 __ j(not_equal, &runtime, Label::kNear);
1805 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
1806 kPointerSize * index->value()));
1807 __ jmp(&done, Label::kNear);
1810 __ PrepareCallCFunction(2, scratch);
1811 __ mov(Operand(esp, 0), object);
1812 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
1813 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
1819 Operand LCodeGen::BuildSeqStringOperand(Register string,
1821 String::Encoding encoding) {
1822 if (index->IsConstantOperand()) {
1823 int offset = ToRepresentation(LConstantOperand::cast(index),
1824 Representation::Integer32());
1825 if (encoding == String::TWO_BYTE_ENCODING) {
1826 offset *= kUC16Size;
1828 STATIC_ASSERT(kCharSize == 1);
1829 return FieldOperand(string, SeqString::kHeaderSize + offset);
1831 return FieldOperand(
1832 string, ToRegister(index),
1833 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
1834 SeqString::kHeaderSize);
1838 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
1839 String::Encoding encoding = instr->hydrogen()->encoding();
1840 Register result = ToRegister(instr->result());
1841 Register string = ToRegister(instr->string());
1843 if (FLAG_debug_code) {
1845 __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
1846 __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
1848 __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
1849 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1850 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1851 __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
1852 ? one_byte_seq_type : two_byte_seq_type));
1853 __ Check(equal, kUnexpectedStringType);
1857 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1858 if (encoding == String::ONE_BYTE_ENCODING) {
1859 __ movzx_b(result, operand);
1861 __ movzx_w(result, operand);
1866 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
1867 String::Encoding encoding = instr->hydrogen()->encoding();
1868 Register string = ToRegister(instr->string());
1870 if (FLAG_debug_code) {
1871 Register value = ToRegister(instr->value());
1872 Register index = ToRegister(instr->index());
1873 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1874 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1876 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
1877 ? one_byte_seq_type : two_byte_seq_type;
1878 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
1881 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1882 if (instr->value()->IsConstantOperand()) {
1883 int value = ToRepresentation(LConstantOperand::cast(instr->value()),
1884 Representation::Integer32());
1885 DCHECK_LE(0, value);
1886 if (encoding == String::ONE_BYTE_ENCODING) {
1887 DCHECK_LE(value, String::kMaxOneByteCharCode);
1888 __ mov_b(operand, static_cast<int8_t>(value));
1890 DCHECK_LE(value, String::kMaxUtf16CodeUnit);
1891 __ mov_w(operand, static_cast<int16_t>(value));
1894 Register value = ToRegister(instr->value());
1895 if (encoding == String::ONE_BYTE_ENCODING) {
1896 __ mov_b(operand, value);
1898 __ mov_w(operand, value);
1904 void LCodeGen::DoAddI(LAddI* instr) {
1905 LOperand* left = instr->left();
1906 LOperand* right = instr->right();
1908 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
1909 if (right->IsConstantOperand()) {
1910 int32_t offset = ToRepresentation(LConstantOperand::cast(right),
1911 instr->hydrogen()->representation());
1912 __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
1914 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
1915 __ lea(ToRegister(instr->result()), address);
1918 if (right->IsConstantOperand()) {
1919 __ add(ToOperand(left),
1920 ToImmediate(right, instr->hydrogen()->representation()));
1922 __ add(ToRegister(left), ToOperand(right));
1924 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1925 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1931 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
1932 LOperand* left = instr->left();
1933 LOperand* right = instr->right();
1934 DCHECK(left->Equals(instr->result()));
1935 HMathMinMax::Operation operation = instr->hydrogen()->operation();
1936 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
1938 Condition condition = (operation == HMathMinMax::kMathMin)
1941 if (right->IsConstantOperand()) {
1942 Operand left_op = ToOperand(left);
1943 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
1944 instr->hydrogen()->representation());
1945 __ cmp(left_op, immediate);
1946 __ j(condition, &return_left, Label::kNear);
1947 __ mov(left_op, immediate);
1949 Register left_reg = ToRegister(left);
1950 Operand right_op = ToOperand(right);
1951 __ cmp(left_reg, right_op);
1952 __ j(condition, &return_left, Label::kNear);
1953 __ mov(left_reg, right_op);
1955 __ bind(&return_left);
1957 DCHECK(instr->hydrogen()->representation().IsDouble());
1958 Label check_nan_left, check_zero, return_left, return_right;
1959 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
1960 XMMRegister left_reg = ToDoubleRegister(left);
1961 XMMRegister right_reg = ToDoubleRegister(right);
1962 __ ucomisd(left_reg, right_reg);
1963 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
1964 __ j(equal, &check_zero, Label::kNear); // left == right.
1965 __ j(condition, &return_left, Label::kNear);
1966 __ jmp(&return_right, Label::kNear);
1968 __ bind(&check_zero);
1969 XMMRegister xmm_scratch = double_scratch0();
1970 __ xorps(xmm_scratch, xmm_scratch);
1971 __ ucomisd(left_reg, xmm_scratch);
1972 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
1973 // At this point, both left and right are either 0 or -0.
1974 if (operation == HMathMinMax::kMathMin) {
1975 __ orpd(left_reg, right_reg);
1977 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
1978 __ addsd(left_reg, right_reg);
1980 __ jmp(&return_left, Label::kNear);
1982 __ bind(&check_nan_left);
1983 __ ucomisd(left_reg, left_reg); // NaN check.
1984 __ j(parity_even, &return_left, Label::kNear); // left == NaN.
1985 __ bind(&return_right);
1986 __ movaps(left_reg, right_reg);
1988 __ bind(&return_left);
1993 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
1994 XMMRegister left = ToDoubleRegister(instr->left());
1995 XMMRegister right = ToDoubleRegister(instr->right());
1996 XMMRegister result = ToDoubleRegister(instr->result());
1997 switch (instr->op()) {
1999 if (CpuFeatures::IsSupported(AVX)) {
2000 CpuFeatureScope scope(masm(), AVX);
2001 __ vaddsd(result, left, right);
2003 DCHECK(result.is(left));
2004 __ addsd(left, right);
2008 if (CpuFeatures::IsSupported(AVX)) {
2009 CpuFeatureScope scope(masm(), AVX);
2010 __ vsubsd(result, left, right);
2012 DCHECK(result.is(left));
2013 __ subsd(left, right);
2017 if (CpuFeatures::IsSupported(AVX)) {
2018 CpuFeatureScope scope(masm(), AVX);
2019 __ vmulsd(result, left, right);
2021 DCHECK(result.is(left));
2022 __ mulsd(left, right);
2026 if (CpuFeatures::IsSupported(AVX)) {
2027 CpuFeatureScope scope(masm(), AVX);
2028 __ vdivsd(result, left, right);
2030 DCHECK(result.is(left));
2031 __ divsd(left, right);
2033 // Don't delete this mov. It may improve performance on some CPUs,
2034 // when there is a (v)mulsd depending on the result
2035 __ movaps(result, result);
2038 // Pass two doubles as arguments on the stack.
2039 __ PrepareCallCFunction(4, eax);
2040 __ movsd(Operand(esp, 0 * kDoubleSize), left);
2041 __ movsd(Operand(esp, 1 * kDoubleSize), right);
2043 ExternalReference::mod_two_doubles_operation(isolate()),
2046 // Return value is in st(0) on ia32.
2047 // Store it into the result register.
2048 __ sub(Operand(esp), Immediate(kDoubleSize));
2049 __ fstp_d(Operand(esp, 0));
2050 __ movsd(result, Operand(esp, 0));
2051 __ add(Operand(esp), Immediate(kDoubleSize));
2061 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2062 DCHECK(ToRegister(instr->context()).is(esi));
2063 DCHECK(ToRegister(instr->left()).is(edx));
2064 DCHECK(ToRegister(instr->right()).is(eax));
2065 DCHECK(ToRegister(instr->result()).is(eax));
2068 CodeFactory::BinaryOpIC(isolate(), instr->op(), instr->strength()).code();
2069 CallCode(code, RelocInfo::CODE_TARGET, instr);
2073 template<class InstrType>
2074 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2075 int left_block = instr->TrueDestination(chunk_);
2076 int right_block = instr->FalseDestination(chunk_);
2078 int next_block = GetNextEmittedBlock();
2080 if (right_block == left_block || cc == no_condition) {
2081 EmitGoto(left_block);
2082 } else if (left_block == next_block) {
2083 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2084 } else if (right_block == next_block) {
2085 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2087 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2088 __ jmp(chunk_->GetAssemblyLabel(right_block));
2093 template<class InstrType>
2094 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2095 int false_block = instr->FalseDestination(chunk_);
2096 if (cc == no_condition) {
2097 __ jmp(chunk_->GetAssemblyLabel(false_block));
2099 __ j(cc, chunk_->GetAssemblyLabel(false_block));
2104 void LCodeGen::DoBranch(LBranch* instr) {
2105 Representation r = instr->hydrogen()->value()->representation();
2106 if (r.IsSmiOrInteger32()) {
2107 Register reg = ToRegister(instr->value());
2108 __ test(reg, Operand(reg));
2109 EmitBranch(instr, not_zero);
2110 } else if (r.IsDouble()) {
2111 DCHECK(!info()->IsStub());
2112 XMMRegister reg = ToDoubleRegister(instr->value());
2113 XMMRegister xmm_scratch = double_scratch0();
2114 __ xorps(xmm_scratch, xmm_scratch);
2115 __ ucomisd(reg, xmm_scratch);
2116 EmitBranch(instr, not_equal);
2118 DCHECK(r.IsTagged());
2119 Register reg = ToRegister(instr->value());
2120 HType type = instr->hydrogen()->value()->type();
2121 if (type.IsBoolean()) {
2122 DCHECK(!info()->IsStub());
2123 __ cmp(reg, factory()->true_value());
2124 EmitBranch(instr, equal);
2125 } else if (type.IsSmi()) {
2126 DCHECK(!info()->IsStub());
2127 __ test(reg, Operand(reg));
2128 EmitBranch(instr, not_equal);
2129 } else if (type.IsJSArray()) {
2130 DCHECK(!info()->IsStub());
2131 EmitBranch(instr, no_condition);
2132 } else if (type.IsHeapNumber()) {
2133 DCHECK(!info()->IsStub());
2134 XMMRegister xmm_scratch = double_scratch0();
2135 __ xorps(xmm_scratch, xmm_scratch);
2136 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2137 EmitBranch(instr, not_equal);
2138 } else if (type.IsString()) {
2139 DCHECK(!info()->IsStub());
2140 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2141 EmitBranch(instr, not_equal);
2143 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2144 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2146 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2147 // undefined -> false.
2148 __ cmp(reg, factory()->undefined_value());
2149 __ j(equal, instr->FalseLabel(chunk_));
2151 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2153 __ cmp(reg, factory()->true_value());
2154 __ j(equal, instr->TrueLabel(chunk_));
2156 __ cmp(reg, factory()->false_value());
2157 __ j(equal, instr->FalseLabel(chunk_));
2159 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2161 __ cmp(reg, factory()->null_value());
2162 __ j(equal, instr->FalseLabel(chunk_));
2165 if (expected.Contains(ToBooleanStub::SMI)) {
2166 // Smis: 0 -> false, all other -> true.
2167 __ test(reg, Operand(reg));
2168 __ j(equal, instr->FalseLabel(chunk_));
2169 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2170 } else if (expected.NeedsMap()) {
2171 // If we need a map later and have a Smi -> deopt.
2172 __ test(reg, Immediate(kSmiTagMask));
2173 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2176 Register map = no_reg; // Keep the compiler happy.
2177 if (expected.NeedsMap()) {
2178 map = ToRegister(instr->temp());
2179 DCHECK(!map.is(reg));
2180 __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2182 if (expected.CanBeUndetectable()) {
2183 // Undetectable -> false.
2184 __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2185 1 << Map::kIsUndetectable);
2186 __ j(not_zero, instr->FalseLabel(chunk_));
2190 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2191 // spec object -> true.
2192 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2193 __ j(above_equal, instr->TrueLabel(chunk_));
2196 if (expected.Contains(ToBooleanStub::STRING)) {
2197 // String value -> false iff empty.
2199 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2200 __ j(above_equal, ¬_string, Label::kNear);
2201 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2202 __ j(not_zero, instr->TrueLabel(chunk_));
2203 __ jmp(instr->FalseLabel(chunk_));
2204 __ bind(¬_string);
2207 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2208 // Symbol value -> true.
2209 __ CmpInstanceType(map, SYMBOL_TYPE);
2210 __ j(equal, instr->TrueLabel(chunk_));
2213 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2214 // heap number -> false iff +0, -0, or NaN.
2215 Label not_heap_number;
2216 __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2217 factory()->heap_number_map());
2218 __ j(not_equal, ¬_heap_number, Label::kNear);
2219 XMMRegister xmm_scratch = double_scratch0();
2220 __ xorps(xmm_scratch, xmm_scratch);
2221 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2222 __ j(zero, instr->FalseLabel(chunk_));
2223 __ jmp(instr->TrueLabel(chunk_));
2224 __ bind(¬_heap_number);
2227 if (!expected.IsGeneric()) {
2228 // We've seen something for the first time -> deopt.
2229 // This can only happen if we are not generic already.
2230 DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2237 void LCodeGen::EmitGoto(int block) {
2238 if (!IsNextEmittedBlock(block)) {
2239 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2244 void LCodeGen::DoGoto(LGoto* instr) {
2245 EmitGoto(instr->block_id());
2249 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2250 Condition cond = no_condition;
2253 case Token::EQ_STRICT:
2257 case Token::NE_STRICT:
2261 cond = is_unsigned ? below : less;
2264 cond = is_unsigned ? above : greater;
2267 cond = is_unsigned ? below_equal : less_equal;
2270 cond = is_unsigned ? above_equal : greater_equal;
2273 case Token::INSTANCEOF:
2281 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2282 LOperand* left = instr->left();
2283 LOperand* right = instr->right();
2285 instr->is_double() ||
2286 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2287 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2288 Condition cc = TokenToCondition(instr->op(), is_unsigned);
2290 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2291 // We can statically evaluate the comparison.
2292 double left_val = ToDouble(LConstantOperand::cast(left));
2293 double right_val = ToDouble(LConstantOperand::cast(right));
2294 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2295 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2296 EmitGoto(next_block);
2298 if (instr->is_double()) {
2299 __ ucomisd(ToDoubleRegister(left), ToDoubleRegister(right));
2300 // Don't base result on EFLAGS when a NaN is involved. Instead
2301 // jump to the false block.
2302 __ j(parity_even, instr->FalseLabel(chunk_));
2304 if (right->IsConstantOperand()) {
2305 __ cmp(ToOperand(left),
2306 ToImmediate(right, instr->hydrogen()->representation()));
2307 } else if (left->IsConstantOperand()) {
2308 __ cmp(ToOperand(right),
2309 ToImmediate(left, instr->hydrogen()->representation()));
2310 // We commuted the operands, so commute the condition.
2311 cc = CommuteCondition(cc);
2313 __ cmp(ToRegister(left), ToOperand(right));
2316 EmitBranch(instr, cc);
2321 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2322 Register left = ToRegister(instr->left());
2324 if (instr->right()->IsConstantOperand()) {
2325 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2326 __ CmpObject(left, right);
2328 Operand right = ToOperand(instr->right());
2329 __ cmp(left, right);
2331 EmitBranch(instr, equal);
2335 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2336 if (instr->hydrogen()->representation().IsTagged()) {
2337 Register input_reg = ToRegister(instr->object());
2338 __ cmp(input_reg, factory()->the_hole_value());
2339 EmitBranch(instr, equal);
2343 XMMRegister input_reg = ToDoubleRegister(instr->object());
2344 __ ucomisd(input_reg, input_reg);
2345 EmitFalseBranch(instr, parity_odd);
2347 __ sub(esp, Immediate(kDoubleSize));
2348 __ movsd(MemOperand(esp, 0), input_reg);
2350 __ add(esp, Immediate(kDoubleSize));
2351 int offset = sizeof(kHoleNanUpper32);
2352 __ cmp(MemOperand(esp, -offset), Immediate(kHoleNanUpper32));
2353 EmitBranch(instr, equal);
2357 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2358 Representation rep = instr->hydrogen()->value()->representation();
2359 DCHECK(!rep.IsInteger32());
2360 Register scratch = ToRegister(instr->temp());
2362 if (rep.IsDouble()) {
2363 XMMRegister value = ToDoubleRegister(instr->value());
2364 XMMRegister xmm_scratch = double_scratch0();
2365 __ xorps(xmm_scratch, xmm_scratch);
2366 __ ucomisd(xmm_scratch, value);
2367 EmitFalseBranch(instr, not_equal);
2368 __ movmskpd(scratch, value);
2369 __ test(scratch, Immediate(1));
2370 EmitBranch(instr, not_zero);
2372 Register value = ToRegister(instr->value());
2373 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2374 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2375 __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2377 EmitFalseBranch(instr, no_overflow);
2378 __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2379 Immediate(0x00000000));
2380 EmitBranch(instr, equal);
2385 Condition LCodeGen::EmitIsObject(Register input,
2387 Label* is_not_object,
2389 __ JumpIfSmi(input, is_not_object);
2391 __ cmp(input, isolate()->factory()->null_value());
2392 __ j(equal, is_object);
2394 __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
2395 // Undetectable objects behave like undefined.
2396 __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
2397 1 << Map::kIsUndetectable);
2398 __ j(not_zero, is_not_object);
2400 __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
2401 __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2402 __ j(below, is_not_object);
2403 __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2408 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2409 Register reg = ToRegister(instr->value());
2410 Register temp = ToRegister(instr->temp());
2412 Condition true_cond = EmitIsObject(
2413 reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2415 EmitBranch(instr, true_cond);
2419 Condition LCodeGen::EmitIsString(Register input,
2421 Label* is_not_string,
2422 SmiCheck check_needed = INLINE_SMI_CHECK) {
2423 if (check_needed == INLINE_SMI_CHECK) {
2424 __ JumpIfSmi(input, is_not_string);
2427 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2433 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2434 Register reg = ToRegister(instr->value());
2435 Register temp = ToRegister(instr->temp());
2437 SmiCheck check_needed =
2438 instr->hydrogen()->value()->type().IsHeapObject()
2439 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2441 Condition true_cond = EmitIsString(
2442 reg, temp, instr->FalseLabel(chunk_), check_needed);
2444 EmitBranch(instr, true_cond);
2448 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2449 Operand input = ToOperand(instr->value());
2451 __ test(input, Immediate(kSmiTagMask));
2452 EmitBranch(instr, zero);
2456 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2457 Register input = ToRegister(instr->value());
2458 Register temp = ToRegister(instr->temp());
2460 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2461 STATIC_ASSERT(kSmiTag == 0);
2462 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2464 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2465 __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2466 1 << Map::kIsUndetectable);
2467 EmitBranch(instr, not_zero);
2471 static Condition ComputeCompareCondition(Token::Value op) {
2473 case Token::EQ_STRICT:
2483 return greater_equal;
2486 return no_condition;
2491 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2492 Token::Value op = instr->op();
2495 CodeFactory::CompareIC(isolate(), op, Strength::WEAK).code();
2496 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2498 Condition condition = ComputeCompareCondition(op);
2499 __ test(eax, Operand(eax));
2501 EmitBranch(instr, condition);
2505 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2506 InstanceType from = instr->from();
2507 InstanceType to = instr->to();
2508 if (from == FIRST_TYPE) return to;
2509 DCHECK(from == to || to == LAST_TYPE);
2514 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2515 InstanceType from = instr->from();
2516 InstanceType to = instr->to();
2517 if (from == to) return equal;
2518 if (to == LAST_TYPE) return above_equal;
2519 if (from == FIRST_TYPE) return below_equal;
2525 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2526 Register input = ToRegister(instr->value());
2527 Register temp = ToRegister(instr->temp());
2529 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2530 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2533 __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2534 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2538 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2539 Register input = ToRegister(instr->value());
2540 Register result = ToRegister(instr->result());
2542 __ AssertString(input);
2544 __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2545 __ IndexFromHash(result, result);
2549 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2550 LHasCachedArrayIndexAndBranch* instr) {
2551 Register input = ToRegister(instr->value());
2553 __ test(FieldOperand(input, String::kHashFieldOffset),
2554 Immediate(String::kContainsCachedArrayIndexMask));
2555 EmitBranch(instr, equal);
2559 // Branches to a label or falls through with the answer in the z flag. Trashes
2560 // the temp registers, but not the input.
2561 void LCodeGen::EmitClassOfTest(Label* is_true,
2563 Handle<String>class_name,
2567 DCHECK(!input.is(temp));
2568 DCHECK(!input.is(temp2));
2569 DCHECK(!temp.is(temp2));
2570 __ JumpIfSmi(input, is_false);
2572 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2573 // Assuming the following assertions, we can use the same compares to test
2574 // for both being a function type and being in the object type range.
2575 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2576 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2577 FIRST_SPEC_OBJECT_TYPE + 1);
2578 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2579 LAST_SPEC_OBJECT_TYPE - 1);
2580 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2581 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2582 __ j(below, is_false);
2583 __ j(equal, is_true);
2584 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2585 __ j(equal, is_true);
2587 // Faster code path to avoid two compares: subtract lower bound from the
2588 // actual type and do a signed compare with the width of the type range.
2589 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2590 __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2591 __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2592 __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2593 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2594 __ j(above, is_false);
2597 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2598 // Check if the constructor in the map is a function.
2599 __ GetMapConstructor(temp, temp, temp2);
2600 // Objects with a non-function constructor have class 'Object'.
2601 __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2602 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2603 __ j(not_equal, is_true);
2605 __ j(not_equal, is_false);
2608 // temp now contains the constructor function. Grab the
2609 // instance class name from there.
2610 __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2611 __ mov(temp, FieldOperand(temp,
2612 SharedFunctionInfo::kInstanceClassNameOffset));
2613 // The class name we are testing against is internalized since it's a literal.
2614 // The name in the constructor is internalized because of the way the context
2615 // is booted. This routine isn't expected to work for random API-created
2616 // classes and it doesn't have to because you can't access it with natives
2617 // syntax. Since both sides are internalized it is sufficient to use an
2618 // identity comparison.
2619 __ cmp(temp, class_name);
2620 // End with the answer in the z flag.
2624 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2625 Register input = ToRegister(instr->value());
2626 Register temp = ToRegister(instr->temp());
2627 Register temp2 = ToRegister(instr->temp2());
2629 Handle<String> class_name = instr->hydrogen()->class_name();
2631 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2632 class_name, input, temp, temp2);
2634 EmitBranch(instr, equal);
2638 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2639 Register reg = ToRegister(instr->value());
2640 __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2641 EmitBranch(instr, equal);
2645 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2646 // Object and function are in fixed registers defined by the stub.
2647 DCHECK(ToRegister(instr->context()).is(esi));
2648 InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2649 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2651 Label true_value, done;
2652 __ test(eax, Operand(eax));
2653 __ j(zero, &true_value, Label::kNear);
2654 __ mov(ToRegister(instr->result()), factory()->false_value());
2655 __ jmp(&done, Label::kNear);
2656 __ bind(&true_value);
2657 __ mov(ToRegister(instr->result()), factory()->true_value());
2662 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2663 class DeferredInstanceOfKnownGlobal final : public LDeferredCode {
2665 DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2666 LInstanceOfKnownGlobal* instr)
2667 : LDeferredCode(codegen), instr_(instr) { }
2668 void Generate() override {
2669 codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2671 LInstruction* instr() override { return instr_; }
2672 Label* map_check() { return &map_check_; }
2674 LInstanceOfKnownGlobal* instr_;
2678 DeferredInstanceOfKnownGlobal* deferred;
2679 deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr);
2681 Label done, false_result;
2682 Register object = ToRegister(instr->value());
2683 Register temp = ToRegister(instr->temp());
2685 // A Smi is not an instance of anything.
2686 __ JumpIfSmi(object, &false_result, Label::kNear);
2688 // This is the inlined call site instanceof cache. The two occurences of the
2689 // hole value will be patched to the last map/result pair generated by the
2692 Register map = ToRegister(instr->temp());
2693 __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2694 __ bind(deferred->map_check()); // Label for calculating code patching.
2695 Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2696 __ cmp(map, Operand::ForCell(cache_cell)); // Patched to cached map.
2697 __ j(not_equal, &cache_miss, Label::kNear);
2698 __ mov(eax, factory()->the_hole_value()); // Patched to either true or false.
2699 __ jmp(&done, Label::kNear);
2701 // The inlined call site cache did not match. Check for null and string
2702 // before calling the deferred code.
2703 __ bind(&cache_miss);
2704 // Null is not an instance of anything.
2705 __ cmp(object, factory()->null_value());
2706 __ j(equal, &false_result, Label::kNear);
2708 // String values are not instances of anything.
2709 Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2710 __ j(is_string, &false_result, Label::kNear);
2712 // Go to the deferred code.
2713 __ jmp(deferred->entry());
2715 __ bind(&false_result);
2716 __ mov(ToRegister(instr->result()), factory()->false_value());
2718 // Here result has either true or false. Deferred code also produces true or
2720 __ bind(deferred->exit());
2725 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
2727 PushSafepointRegistersScope scope(this);
2729 InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
2730 flags = static_cast<InstanceofStub::Flags>(
2731 flags | InstanceofStub::kArgsInRegisters);
2732 flags = static_cast<InstanceofStub::Flags>(
2733 flags | InstanceofStub::kCallSiteInlineCheck);
2734 flags = static_cast<InstanceofStub::Flags>(
2735 flags | InstanceofStub::kReturnTrueFalseObject);
2736 InstanceofStub stub(isolate(), flags);
2738 // Get the temp register reserved by the instruction. This needs to be a
2739 // register which is pushed last by PushSafepointRegisters as top of the
2740 // stack is used to pass the offset to the location of the map check to
2742 Register temp = ToRegister(instr->temp());
2743 DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
2744 __ LoadHeapObject(InstanceofStub::right(), instr->function());
2745 static const int kAdditionalDelta = 13;
2746 int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
2747 __ mov(temp, Immediate(delta));
2748 __ StoreToSafepointRegisterSlot(temp, temp);
2749 CallCodeGeneric(stub.GetCode(),
2750 RelocInfo::CODE_TARGET,
2752 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
2753 // Get the deoptimization index of the LLazyBailout-environment that
2754 // corresponds to this instruction.
2755 LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
2756 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
2758 // Put the result value into the eax slot and restore all registers.
2759 __ StoreToSafepointRegisterSlot(eax, eax);
2763 void LCodeGen::DoCmpT(LCmpT* instr) {
2764 Token::Value op = instr->op();
2767 CodeFactory::CompareIC(isolate(), op, instr->strength()).code();
2768 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2770 Condition condition = ComputeCompareCondition(op);
2771 Label true_value, done;
2772 __ test(eax, Operand(eax));
2773 __ j(condition, &true_value, Label::kNear);
2774 __ mov(ToRegister(instr->result()), factory()->false_value());
2775 __ jmp(&done, Label::kNear);
2776 __ bind(&true_value);
2777 __ mov(ToRegister(instr->result()), factory()->true_value());
2782 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
2783 int extra_value_count = dynamic_frame_alignment ? 2 : 1;
2785 if (instr->has_constant_parameter_count()) {
2786 int parameter_count = ToInteger32(instr->constant_parameter_count());
2787 if (dynamic_frame_alignment && FLAG_debug_code) {
2789 (parameter_count + extra_value_count) * kPointerSize),
2790 Immediate(kAlignmentZapValue));
2791 __ Assert(equal, kExpectedAlignmentMarker);
2793 __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
2795 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
2796 Register reg = ToRegister(instr->parameter_count());
2797 // The argument count parameter is a smi
2799 Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
2800 if (dynamic_frame_alignment && FLAG_debug_code) {
2801 DCHECK(extra_value_count == 2);
2802 __ cmp(Operand(esp, reg, times_pointer_size,
2803 extra_value_count * kPointerSize),
2804 Immediate(kAlignmentZapValue));
2805 __ Assert(equal, kExpectedAlignmentMarker);
2808 // emit code to restore stack based on instr->parameter_count()
2809 __ pop(return_addr_reg); // save return address
2810 if (dynamic_frame_alignment) {
2811 __ inc(reg); // 1 more for alignment
2814 __ shl(reg, kPointerSizeLog2);
2816 __ jmp(return_addr_reg);
2821 void LCodeGen::DoReturn(LReturn* instr) {
2822 if (FLAG_trace && info()->IsOptimizing()) {
2823 // Preserve the return value on the stack and rely on the runtime call
2824 // to return the value in the same register. We're leaving the code
2825 // managed by the register allocator and tearing down the frame, it's
2826 // safe to write to the context register.
2828 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2829 __ CallRuntime(Runtime::kTraceExit, 1);
2831 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
2832 if (dynamic_frame_alignment_) {
2833 // Fetch the state of the dynamic frame alignment.
2834 __ mov(edx, Operand(ebp,
2835 JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
2837 int no_frame_start = -1;
2838 if (NeedsEagerFrame()) {
2841 no_frame_start = masm_->pc_offset();
2843 if (dynamic_frame_alignment_) {
2845 __ cmp(edx, Immediate(kNoAlignmentPadding));
2846 __ j(equal, &no_padding, Label::kNear);
2848 EmitReturn(instr, true);
2849 __ bind(&no_padding);
2852 EmitReturn(instr, false);
2853 if (no_frame_start != -1) {
2854 info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
2860 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
2861 Register vector_register = ToRegister(instr->temp_vector());
2862 Register slot_register = LoadWithVectorDescriptor::SlotRegister();
2863 DCHECK(vector_register.is(LoadWithVectorDescriptor::VectorRegister()));
2864 DCHECK(slot_register.is(eax));
2866 AllowDeferredHandleDereference vector_structure_check;
2867 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
2868 __ mov(vector_register, vector);
2869 // No need to allocate this register.
2870 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
2871 int index = vector->GetIndex(slot);
2872 __ mov(slot_register, Immediate(Smi::FromInt(index)));
2876 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
2877 DCHECK(ToRegister(instr->context()).is(esi));
2878 DCHECK(ToRegister(instr->global_object())
2879 .is(LoadDescriptor::ReceiverRegister()));
2880 DCHECK(ToRegister(instr->result()).is(eax));
2882 __ mov(LoadDescriptor::NameRegister(), instr->name());
2883 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
2884 ContextualMode mode = instr->for_typeof() ? NOT_CONTEXTUAL : CONTEXTUAL;
2885 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(isolate(), mode,
2886 PREMONOMORPHIC).code();
2887 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2891 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
2892 Register context = ToRegister(instr->context());
2893 Register result = ToRegister(instr->result());
2894 __ mov(result, ContextOperand(context, instr->slot_index()));
2896 if (instr->hydrogen()->RequiresHoleCheck()) {
2897 __ cmp(result, factory()->the_hole_value());
2898 if (instr->hydrogen()->DeoptimizesOnHole()) {
2899 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2902 __ j(not_equal, &is_not_hole, Label::kNear);
2903 __ mov(result, factory()->undefined_value());
2904 __ bind(&is_not_hole);
2910 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
2911 Register context = ToRegister(instr->context());
2912 Register value = ToRegister(instr->value());
2914 Label skip_assignment;
2916 Operand target = ContextOperand(context, instr->slot_index());
2917 if (instr->hydrogen()->RequiresHoleCheck()) {
2918 __ cmp(target, factory()->the_hole_value());
2919 if (instr->hydrogen()->DeoptimizesOnHole()) {
2920 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2922 __ j(not_equal, &skip_assignment, Label::kNear);
2926 __ mov(target, value);
2927 if (instr->hydrogen()->NeedsWriteBarrier()) {
2928 SmiCheck check_needed =
2929 instr->hydrogen()->value()->type().IsHeapObject()
2930 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2931 Register temp = ToRegister(instr->temp());
2932 int offset = Context::SlotOffset(instr->slot_index());
2933 __ RecordWriteContextSlot(context,
2938 EMIT_REMEMBERED_SET,
2942 __ bind(&skip_assignment);
2946 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
2947 HObjectAccess access = instr->hydrogen()->access();
2948 int offset = access.offset();
2950 if (access.IsExternalMemory()) {
2951 Register result = ToRegister(instr->result());
2952 MemOperand operand = instr->object()->IsConstantOperand()
2953 ? MemOperand::StaticVariable(ToExternalReference(
2954 LConstantOperand::cast(instr->object())))
2955 : MemOperand(ToRegister(instr->object()), offset);
2956 __ Load(result, operand, access.representation());
2960 Register object = ToRegister(instr->object());
2961 if (instr->hydrogen()->representation().IsDouble()) {
2962 XMMRegister result = ToDoubleRegister(instr->result());
2963 __ movsd(result, FieldOperand(object, offset));
2967 Register result = ToRegister(instr->result());
2968 if (!access.IsInobject()) {
2969 __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
2972 __ Load(result, FieldOperand(object, offset), access.representation());
2976 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
2977 DCHECK(!operand->IsDoubleRegister());
2978 if (operand->IsConstantOperand()) {
2979 Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
2980 AllowDeferredHandleDereference smi_check;
2981 if (object->IsSmi()) {
2982 __ Push(Handle<Smi>::cast(object));
2984 __ PushHeapObject(Handle<HeapObject>::cast(object));
2986 } else if (operand->IsRegister()) {
2987 __ push(ToRegister(operand));
2989 __ push(ToOperand(operand));
2994 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
2995 DCHECK(ToRegister(instr->context()).is(esi));
2996 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
2997 DCHECK(ToRegister(instr->result()).is(eax));
2999 __ mov(LoadDescriptor::NameRegister(), instr->name());
3000 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3001 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(
3002 isolate(), NOT_CONTEXTUAL,
3003 instr->hydrogen()->initialization_state()).code();
3004 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3008 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3009 Register function = ToRegister(instr->function());
3010 Register temp = ToRegister(instr->temp());
3011 Register result = ToRegister(instr->result());
3013 // Get the prototype or initial map from the function.
3015 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
3017 // Check that the function has a prototype or an initial map.
3018 __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3019 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3021 // If the function does not have an initial map, we're done.
3023 __ CmpObjectType(result, MAP_TYPE, temp);
3024 __ j(not_equal, &done, Label::kNear);
3026 // Get the prototype from the initial map.
3027 __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3034 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3035 Register result = ToRegister(instr->result());
3036 __ LoadRoot(result, instr->index());
3040 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3041 Register arguments = ToRegister(instr->arguments());
3042 Register result = ToRegister(instr->result());
3043 if (instr->length()->IsConstantOperand() &&
3044 instr->index()->IsConstantOperand()) {
3045 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3046 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3047 int index = (const_length - const_index) + 1;
3048 __ mov(result, Operand(arguments, index * kPointerSize));
3050 Register length = ToRegister(instr->length());
3051 Operand index = ToOperand(instr->index());
3052 // There are two words between the frame pointer and the last argument.
3053 // Subtracting from length accounts for one of them add one more.
3054 __ sub(length, index);
3055 __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3060 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3061 ElementsKind elements_kind = instr->elements_kind();
3062 LOperand* key = instr->key();
3063 if (!key->IsConstantOperand() &&
3064 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3066 __ SmiUntag(ToRegister(key));
3068 Operand operand(BuildFastArrayOperand(
3071 instr->hydrogen()->key()->representation(),
3073 instr->base_offset()));
3074 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
3075 elements_kind == FLOAT32_ELEMENTS) {
3076 XMMRegister result(ToDoubleRegister(instr->result()));
3077 __ movss(result, operand);
3078 __ cvtss2sd(result, result);
3079 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
3080 elements_kind == FLOAT64_ELEMENTS) {
3081 __ movsd(ToDoubleRegister(instr->result()), operand);
3083 Register result(ToRegister(instr->result()));
3084 switch (elements_kind) {
3085 case EXTERNAL_INT8_ELEMENTS:
3087 __ movsx_b(result, operand);
3089 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3090 case EXTERNAL_UINT8_ELEMENTS:
3091 case UINT8_ELEMENTS:
3092 case UINT8_CLAMPED_ELEMENTS:
3093 __ movzx_b(result, operand);
3095 case EXTERNAL_INT16_ELEMENTS:
3096 case INT16_ELEMENTS:
3097 __ movsx_w(result, operand);
3099 case EXTERNAL_UINT16_ELEMENTS:
3100 case UINT16_ELEMENTS:
3101 __ movzx_w(result, operand);
3103 case EXTERNAL_INT32_ELEMENTS:
3104 case INT32_ELEMENTS:
3105 __ mov(result, operand);
3107 case EXTERNAL_UINT32_ELEMENTS:
3108 case UINT32_ELEMENTS:
3109 __ mov(result, operand);
3110 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3111 __ test(result, Operand(result));
3112 DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3115 case EXTERNAL_FLOAT32_ELEMENTS:
3116 case EXTERNAL_FLOAT64_ELEMENTS:
3117 case FLOAT32_ELEMENTS:
3118 case FLOAT64_ELEMENTS:
3119 case FAST_SMI_ELEMENTS:
3121 case FAST_DOUBLE_ELEMENTS:
3122 case FAST_HOLEY_SMI_ELEMENTS:
3123 case FAST_HOLEY_ELEMENTS:
3124 case FAST_HOLEY_DOUBLE_ELEMENTS:
3125 case DICTIONARY_ELEMENTS:
3126 case SLOPPY_ARGUMENTS_ELEMENTS:
3134 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3135 if (instr->hydrogen()->RequiresHoleCheck()) {
3136 Operand hole_check_operand = BuildFastArrayOperand(
3137 instr->elements(), instr->key(),
3138 instr->hydrogen()->key()->representation(),
3139 FAST_DOUBLE_ELEMENTS,
3140 instr->base_offset() + sizeof(kHoleNanLower32));
3141 __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3142 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3145 Operand double_load_operand = BuildFastArrayOperand(
3148 instr->hydrogen()->key()->representation(),
3149 FAST_DOUBLE_ELEMENTS,
3150 instr->base_offset());
3151 XMMRegister result = ToDoubleRegister(instr->result());
3152 __ movsd(result, double_load_operand);
3156 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3157 Register result = ToRegister(instr->result());
3161 BuildFastArrayOperand(instr->elements(), instr->key(),
3162 instr->hydrogen()->key()->representation(),
3163 FAST_ELEMENTS, instr->base_offset()));
3165 // Check for the hole value.
3166 if (instr->hydrogen()->RequiresHoleCheck()) {
3167 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3168 __ test(result, Immediate(kSmiTagMask));
3169 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3171 __ cmp(result, factory()->the_hole_value());
3172 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3174 } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3175 DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
3177 __ cmp(result, factory()->the_hole_value());
3178 __ j(not_equal, &done);
3179 if (info()->IsStub()) {
3180 // A stub can safely convert the hole to undefined only if the array
3181 // protector cell contains (Smi) Isolate::kArrayProtectorValid. Otherwise
3182 // it needs to bail out.
3183 __ mov(result, isolate()->factory()->array_protector());
3184 __ cmp(FieldOperand(result, PropertyCell::kValueOffset),
3185 Immediate(Smi::FromInt(Isolate::kArrayProtectorValid)));
3186 DeoptimizeIf(not_equal, instr, Deoptimizer::kHole);
3188 __ mov(result, isolate()->factory()->undefined_value());
3194 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3195 if (instr->is_typed_elements()) {
3196 DoLoadKeyedExternalArray(instr);
3197 } else if (instr->hydrogen()->representation().IsDouble()) {
3198 DoLoadKeyedFixedDoubleArray(instr);
3200 DoLoadKeyedFixedArray(instr);
3205 Operand LCodeGen::BuildFastArrayOperand(
3206 LOperand* elements_pointer,
3208 Representation key_representation,
3209 ElementsKind elements_kind,
3210 uint32_t base_offset) {
3211 Register elements_pointer_reg = ToRegister(elements_pointer);
3212 int element_shift_size = ElementsKindToShiftSize(elements_kind);
3213 int shift_size = element_shift_size;
3214 if (key->IsConstantOperand()) {
3215 int constant_value = ToInteger32(LConstantOperand::cast(key));
3216 if (constant_value & 0xF0000000) {
3217 Abort(kArrayIndexConstantValueTooBig);
3219 return Operand(elements_pointer_reg,
3220 ((constant_value) << shift_size)
3223 // Take the tag bit into account while computing the shift size.
3224 if (key_representation.IsSmi() && (shift_size >= 1)) {
3225 shift_size -= kSmiTagSize;
3227 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3228 return Operand(elements_pointer_reg,
3236 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3237 DCHECK(ToRegister(instr->context()).is(esi));
3238 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3239 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3241 if (instr->hydrogen()->HasVectorAndSlot()) {
3242 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3246 CodeFactory::KeyedLoadICInOptimizedCode(
3247 isolate(), instr->hydrogen()->initialization_state()).code();
3248 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3252 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3253 Register result = ToRegister(instr->result());
3255 if (instr->hydrogen()->from_inlined()) {
3256 __ lea(result, Operand(esp, -2 * kPointerSize));
3258 // Check for arguments adapter frame.
3259 Label done, adapted;
3260 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3261 __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3262 __ cmp(Operand(result),
3263 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3264 __ j(equal, &adapted, Label::kNear);
3266 // No arguments adaptor frame.
3267 __ mov(result, Operand(ebp));
3268 __ jmp(&done, Label::kNear);
3270 // Arguments adaptor frame present.
3272 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3274 // Result is the frame pointer for the frame if not adapted and for the real
3275 // frame below the adaptor frame if adapted.
3281 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3282 Operand elem = ToOperand(instr->elements());
3283 Register result = ToRegister(instr->result());
3287 // If no arguments adaptor frame the number of arguments is fixed.
3289 __ mov(result, Immediate(scope()->num_parameters()));
3290 __ j(equal, &done, Label::kNear);
3292 // Arguments adaptor frame present. Get argument length from there.
3293 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3294 __ mov(result, Operand(result,
3295 ArgumentsAdaptorFrameConstants::kLengthOffset));
3296 __ SmiUntag(result);
3298 // Argument length is in result register.
3303 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3304 Register receiver = ToRegister(instr->receiver());
3305 Register function = ToRegister(instr->function());
3307 // If the receiver is null or undefined, we have to pass the global
3308 // object as a receiver to normal functions. Values have to be
3309 // passed unchanged to builtins and strict-mode functions.
3310 Label receiver_ok, global_object;
3311 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3312 Register scratch = ToRegister(instr->temp());
3314 if (!instr->hydrogen()->known_function()) {
3315 // Do not transform the receiver to object for strict mode
3318 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3319 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3320 1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3321 __ j(not_equal, &receiver_ok, dist);
3323 // Do not transform the receiver to object for builtins.
3324 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3325 1 << SharedFunctionInfo::kNativeBitWithinByte);
3326 __ j(not_equal, &receiver_ok, dist);
3329 // Normal function. Replace undefined or null with global receiver.
3330 __ cmp(receiver, factory()->null_value());
3331 __ j(equal, &global_object, Label::kNear);
3332 __ cmp(receiver, factory()->undefined_value());
3333 __ j(equal, &global_object, Label::kNear);
3335 // The receiver should be a JS object.
3336 __ test(receiver, Immediate(kSmiTagMask));
3337 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3338 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3339 DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3341 __ jmp(&receiver_ok, Label::kNear);
3342 __ bind(&global_object);
3343 __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3344 const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3345 __ mov(receiver, Operand(receiver, global_offset));
3346 const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3347 __ mov(receiver, FieldOperand(receiver, proxy_offset));
3348 __ bind(&receiver_ok);
3352 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3353 Register receiver = ToRegister(instr->receiver());
3354 Register function = ToRegister(instr->function());
3355 Register length = ToRegister(instr->length());
3356 Register elements = ToRegister(instr->elements());
3357 DCHECK(receiver.is(eax)); // Used for parameter count.
3358 DCHECK(function.is(edi)); // Required by InvokeFunction.
3359 DCHECK(ToRegister(instr->result()).is(eax));
3361 // Copy the arguments to this function possibly from the
3362 // adaptor frame below it.
3363 const uint32_t kArgumentsLimit = 1 * KB;
3364 __ cmp(length, kArgumentsLimit);
3365 DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3368 __ mov(receiver, length);
3370 // Loop through the arguments pushing them onto the execution
3373 // length is a small non-negative integer, due to the test above.
3374 __ test(length, Operand(length));
3375 __ j(zero, &invoke, Label::kNear);
3377 __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3379 __ j(not_zero, &loop);
3381 // Invoke the function.
3383 DCHECK(instr->HasPointerMap());
3384 LPointerMap* pointers = instr->pointer_map();
3385 SafepointGenerator safepoint_generator(
3386 this, pointers, Safepoint::kLazyDeopt);
3387 ParameterCount actual(eax);
3388 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3392 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3397 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3398 LOperand* argument = instr->value();
3399 EmitPushTaggedOperand(argument);
3403 void LCodeGen::DoDrop(LDrop* instr) {
3404 __ Drop(instr->count());
3408 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3409 Register result = ToRegister(instr->result());
3410 __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3414 void LCodeGen::DoContext(LContext* instr) {
3415 Register result = ToRegister(instr->result());
3416 if (info()->IsOptimizing()) {
3417 __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3419 // If there is no frame, the context must be in esi.
3420 DCHECK(result.is(esi));
3425 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3426 DCHECK(ToRegister(instr->context()).is(esi));
3427 __ push(esi); // The context is the first argument.
3428 __ push(Immediate(instr->hydrogen()->pairs()));
3429 __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3430 CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3434 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3435 int formal_parameter_count, int arity,
3436 LInstruction* instr) {
3437 bool dont_adapt_arguments =
3438 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3439 bool can_invoke_directly =
3440 dont_adapt_arguments || formal_parameter_count == arity;
3442 Register function_reg = edi;
3444 if (can_invoke_directly) {
3446 __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3448 // Set eax to arguments count if adaption is not needed. Assumes that eax
3449 // is available to write to at this point.
3450 if (dont_adapt_arguments) {
3454 // Invoke function directly.
3455 if (function.is_identical_to(info()->closure())) {
3458 __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3460 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3462 // We need to adapt arguments.
3463 LPointerMap* pointers = instr->pointer_map();
3464 SafepointGenerator generator(
3465 this, pointers, Safepoint::kLazyDeopt);
3466 ParameterCount count(arity);
3467 ParameterCount expected(formal_parameter_count);
3468 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3473 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3474 DCHECK(ToRegister(instr->result()).is(eax));
3476 if (instr->hydrogen()->IsTailCall()) {
3477 if (NeedsEagerFrame()) __ leave();
3479 if (instr->target()->IsConstantOperand()) {
3480 LConstantOperand* target = LConstantOperand::cast(instr->target());
3481 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3482 __ jmp(code, RelocInfo::CODE_TARGET);
3484 DCHECK(instr->target()->IsRegister());
3485 Register target = ToRegister(instr->target());
3486 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3490 LPointerMap* pointers = instr->pointer_map();
3491 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3493 if (instr->target()->IsConstantOperand()) {
3494 LConstantOperand* target = LConstantOperand::cast(instr->target());
3495 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3496 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3497 __ call(code, RelocInfo::CODE_TARGET);
3499 DCHECK(instr->target()->IsRegister());
3500 Register target = ToRegister(instr->target());
3501 generator.BeforeCall(__ CallSize(Operand(target)));
3502 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3505 generator.AfterCall();
3510 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3511 DCHECK(ToRegister(instr->function()).is(edi));
3512 DCHECK(ToRegister(instr->result()).is(eax));
3514 if (instr->hydrogen()->pass_argument_count()) {
3515 __ mov(eax, instr->arity());
3519 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3521 bool is_self_call = false;
3522 if (instr->hydrogen()->function()->IsConstant()) {
3523 HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3524 Handle<JSFunction> jsfun =
3525 Handle<JSFunction>::cast(fun_const->handle(isolate()));
3526 is_self_call = jsfun.is_identical_to(info()->closure());
3532 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3535 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3539 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3540 Register input_reg = ToRegister(instr->value());
3541 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3542 factory()->heap_number_map());
3543 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3545 Label slow, allocated, done;
3546 Register tmp = input_reg.is(eax) ? ecx : eax;
3547 Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3549 // Preserve the value of all registers.
3550 PushSafepointRegistersScope scope(this);
3552 __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3553 // Check the sign of the argument. If the argument is positive, just
3554 // return it. We do not need to patch the stack since |input| and
3555 // |result| are the same register and |input| will be restored
3556 // unchanged by popping safepoint registers.
3557 __ test(tmp, Immediate(HeapNumber::kSignMask));
3558 __ j(zero, &done, Label::kNear);
3560 __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3561 __ jmp(&allocated, Label::kNear);
3563 // Slow case: Call the runtime system to do the number allocation.
3565 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3566 instr, instr->context());
3567 // Set the pointer to the new heap number in tmp.
3568 if (!tmp.is(eax)) __ mov(tmp, eax);
3569 // Restore input_reg after call to runtime.
3570 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3572 __ bind(&allocated);
3573 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3574 __ and_(tmp2, ~HeapNumber::kSignMask);
3575 __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3576 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3577 __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3578 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3584 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3585 Register input_reg = ToRegister(instr->value());
3586 __ test(input_reg, Operand(input_reg));
3588 __ j(not_sign, &is_positive, Label::kNear);
3589 __ neg(input_reg); // Sets flags.
3590 DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3591 __ bind(&is_positive);
3595 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3596 // Class for deferred case.
3597 class DeferredMathAbsTaggedHeapNumber final : public LDeferredCode {
3599 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3601 : LDeferredCode(codegen), instr_(instr) { }
3602 void Generate() override {
3603 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3605 LInstruction* instr() override { return instr_; }
3611 DCHECK(instr->value()->Equals(instr->result()));
3612 Representation r = instr->hydrogen()->value()->representation();
3615 XMMRegister scratch = double_scratch0();
3616 XMMRegister input_reg = ToDoubleRegister(instr->value());
3617 __ xorps(scratch, scratch);
3618 __ subsd(scratch, input_reg);
3619 __ andps(input_reg, scratch);
3620 } else if (r.IsSmiOrInteger32()) {
3621 EmitIntegerMathAbs(instr);
3622 } else { // Tagged case.
3623 DeferredMathAbsTaggedHeapNumber* deferred =
3624 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
3625 Register input_reg = ToRegister(instr->value());
3627 __ JumpIfNotSmi(input_reg, deferred->entry());
3628 EmitIntegerMathAbs(instr);
3629 __ bind(deferred->exit());
3634 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3635 XMMRegister xmm_scratch = double_scratch0();
3636 Register output_reg = ToRegister(instr->result());
3637 XMMRegister input_reg = ToDoubleRegister(instr->value());
3639 if (CpuFeatures::IsSupported(SSE4_1)) {
3640 CpuFeatureScope scope(masm(), SSE4_1);
3641 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3642 // Deoptimize on negative zero.
3644 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3645 __ ucomisd(input_reg, xmm_scratch);
3646 __ j(not_equal, &non_zero, Label::kNear);
3647 __ movmskpd(output_reg, input_reg);
3648 __ test(output_reg, Immediate(1));
3649 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3652 __ roundsd(xmm_scratch, input_reg, kRoundDown);
3653 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3654 // Overflow is signalled with minint.
3655 __ cmp(output_reg, 0x1);
3656 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3658 Label negative_sign, done;
3659 // Deoptimize on unordered.
3660 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3661 __ ucomisd(input_reg, xmm_scratch);
3662 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3663 __ j(below, &negative_sign, Label::kNear);
3665 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3666 // Check for negative zero.
3667 Label positive_sign;
3668 __ j(above, &positive_sign, Label::kNear);
3669 __ movmskpd(output_reg, input_reg);
3670 __ test(output_reg, Immediate(1));
3671 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3672 __ Move(output_reg, Immediate(0));
3673 __ jmp(&done, Label::kNear);
3674 __ bind(&positive_sign);
3677 // Use truncating instruction (OK because input is positive).
3678 __ cvttsd2si(output_reg, Operand(input_reg));
3679 // Overflow is signalled with minint.
3680 __ cmp(output_reg, 0x1);
3681 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3682 __ jmp(&done, Label::kNear);
3684 // Non-zero negative reaches here.
3685 __ bind(&negative_sign);
3686 // Truncate, then compare and compensate.
3687 __ cvttsd2si(output_reg, Operand(input_reg));
3688 __ Cvtsi2sd(xmm_scratch, output_reg);
3689 __ ucomisd(input_reg, xmm_scratch);
3690 __ j(equal, &done, Label::kNear);
3691 __ sub(output_reg, Immediate(1));
3692 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3699 void LCodeGen::DoMathRound(LMathRound* instr) {
3700 Register output_reg = ToRegister(instr->result());
3701 XMMRegister input_reg = ToDoubleRegister(instr->value());
3702 XMMRegister xmm_scratch = double_scratch0();
3703 XMMRegister input_temp = ToDoubleRegister(instr->temp());
3704 ExternalReference one_half = ExternalReference::address_of_one_half();
3705 ExternalReference minus_one_half =
3706 ExternalReference::address_of_minus_one_half();
3708 Label done, round_to_zero, below_one_half, do_not_compensate;
3709 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3711 __ movsd(xmm_scratch, Operand::StaticVariable(one_half));
3712 __ ucomisd(xmm_scratch, input_reg);
3713 __ j(above, &below_one_half, Label::kNear);
3715 // CVTTSD2SI rounds towards zero, since 0.5 <= x, we use floor(0.5 + x).
3716 __ addsd(xmm_scratch, input_reg);
3717 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3718 // Overflow is signalled with minint.
3719 __ cmp(output_reg, 0x1);
3720 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3721 __ jmp(&done, dist);
3723 __ bind(&below_one_half);
3724 __ movsd(xmm_scratch, Operand::StaticVariable(minus_one_half));
3725 __ ucomisd(xmm_scratch, input_reg);
3726 __ j(below_equal, &round_to_zero, Label::kNear);
3728 // CVTTSD2SI rounds towards zero, we use ceil(x - (-0.5)) and then
3729 // compare and compensate.
3730 __ movaps(input_temp, input_reg); // Do not alter input_reg.
3731 __ subsd(input_temp, xmm_scratch);
3732 __ cvttsd2si(output_reg, Operand(input_temp));
3733 // Catch minint due to overflow, and to prevent overflow when compensating.
3734 __ cmp(output_reg, 0x1);
3735 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3737 __ Cvtsi2sd(xmm_scratch, output_reg);
3738 __ ucomisd(xmm_scratch, input_temp);
3739 __ j(equal, &done, dist);
3740 __ sub(output_reg, Immediate(1));
3741 // No overflow because we already ruled out minint.
3742 __ jmp(&done, dist);
3744 __ bind(&round_to_zero);
3745 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3746 // we can ignore the difference between a result of -0 and +0.
3747 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3748 // If the sign is positive, we return +0.
3749 __ movmskpd(output_reg, input_reg);
3750 __ test(output_reg, Immediate(1));
3751 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3753 __ Move(output_reg, Immediate(0));
3758 void LCodeGen::DoMathFround(LMathFround* instr) {
3759 XMMRegister input_reg = ToDoubleRegister(instr->value());
3760 XMMRegister output_reg = ToDoubleRegister(instr->result());
3761 __ cvtsd2ss(output_reg, input_reg);
3762 __ cvtss2sd(output_reg, output_reg);
3766 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3767 Operand input = ToOperand(instr->value());
3768 XMMRegister output = ToDoubleRegister(instr->result());
3769 __ sqrtsd(output, input);
3773 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3774 XMMRegister xmm_scratch = double_scratch0();
3775 XMMRegister input_reg = ToDoubleRegister(instr->value());
3776 Register scratch = ToRegister(instr->temp());
3777 DCHECK(ToDoubleRegister(instr->result()).is(input_reg));
3779 // Note that according to ECMA-262 15.8.2.13:
3780 // Math.pow(-Infinity, 0.5) == Infinity
3781 // Math.sqrt(-Infinity) == NaN
3783 // Check base for -Infinity. According to IEEE-754, single-precision
3784 // -Infinity has the highest 9 bits set and the lowest 23 bits cleared.
3785 __ mov(scratch, 0xFF800000);
3786 __ movd(xmm_scratch, scratch);
3787 __ cvtss2sd(xmm_scratch, xmm_scratch);
3788 __ ucomisd(input_reg, xmm_scratch);
3789 // Comparing -Infinity with NaN results in "unordered", which sets the
3790 // zero flag as if both were equal. However, it also sets the carry flag.
3791 __ j(not_equal, &sqrt, Label::kNear);
3792 __ j(carry, &sqrt, Label::kNear);
3793 // If input is -Infinity, return Infinity.
3794 __ xorps(input_reg, input_reg);
3795 __ subsd(input_reg, xmm_scratch);
3796 __ jmp(&done, Label::kNear);
3800 __ xorps(xmm_scratch, xmm_scratch);
3801 __ addsd(input_reg, xmm_scratch); // Convert -0 to +0.
3802 __ sqrtsd(input_reg, input_reg);
3807 void LCodeGen::DoPower(LPower* instr) {
3808 Representation exponent_type = instr->hydrogen()->right()->representation();
3809 // Having marked this as a call, we can use any registers.
3810 // Just make sure that the input/output registers are the expected ones.
3811 Register tagged_exponent = MathPowTaggedDescriptor::exponent();
3812 DCHECK(!instr->right()->IsDoubleRegister() ||
3813 ToDoubleRegister(instr->right()).is(xmm1));
3814 DCHECK(!instr->right()->IsRegister() ||
3815 ToRegister(instr->right()).is(tagged_exponent));
3816 DCHECK(ToDoubleRegister(instr->left()).is(xmm2));
3817 DCHECK(ToDoubleRegister(instr->result()).is(xmm3));
3819 if (exponent_type.IsSmi()) {
3820 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3822 } else if (exponent_type.IsTagged()) {
3824 __ JumpIfSmi(tagged_exponent, &no_deopt);
3825 DCHECK(!ecx.is(tagged_exponent));
3826 __ CmpObjectType(tagged_exponent, HEAP_NUMBER_TYPE, ecx);
3827 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3829 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3831 } else if (exponent_type.IsInteger32()) {
3832 MathPowStub stub(isolate(), MathPowStub::INTEGER);
3835 DCHECK(exponent_type.IsDouble());
3836 MathPowStub stub(isolate(), MathPowStub::DOUBLE);
3842 void LCodeGen::DoMathLog(LMathLog* instr) {
3843 DCHECK(instr->value()->Equals(instr->result()));
3844 XMMRegister input_reg = ToDoubleRegister(instr->value());
3845 XMMRegister xmm_scratch = double_scratch0();
3846 Label positive, done, zero;
3847 __ xorps(xmm_scratch, xmm_scratch);
3848 __ ucomisd(input_reg, xmm_scratch);
3849 __ j(above, &positive, Label::kNear);
3850 __ j(not_carry, &zero, Label::kNear);
3851 __ pcmpeqd(input_reg, input_reg);
3852 __ jmp(&done, Label::kNear);
3854 ExternalReference ninf =
3855 ExternalReference::address_of_negative_infinity();
3856 __ movsd(input_reg, Operand::StaticVariable(ninf));
3857 __ jmp(&done, Label::kNear);
3860 __ sub(Operand(esp), Immediate(kDoubleSize));
3861 __ movsd(Operand(esp, 0), input_reg);
3862 __ fld_d(Operand(esp, 0));
3864 __ fstp_d(Operand(esp, 0));
3865 __ movsd(input_reg, Operand(esp, 0));
3866 __ add(Operand(esp), Immediate(kDoubleSize));
3871 void LCodeGen::DoMathClz32(LMathClz32* instr) {
3872 Register input = ToRegister(instr->value());
3873 Register result = ToRegister(instr->result());
3875 __ Lzcnt(result, input);
3879 void LCodeGen::DoMathExp(LMathExp* instr) {
3880 XMMRegister input = ToDoubleRegister(instr->value());
3881 XMMRegister result = ToDoubleRegister(instr->result());
3882 XMMRegister temp0 = double_scratch0();
3883 Register temp1 = ToRegister(instr->temp1());
3884 Register temp2 = ToRegister(instr->temp2());
3886 MathExpGenerator::EmitMathExp(masm(), input, result, temp0, temp1, temp2);
3890 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
3891 DCHECK(ToRegister(instr->context()).is(esi));
3892 DCHECK(ToRegister(instr->function()).is(edi));
3893 DCHECK(instr->HasPointerMap());
3895 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
3896 if (known_function.is_null()) {
3897 LPointerMap* pointers = instr->pointer_map();
3898 SafepointGenerator generator(
3899 this, pointers, Safepoint::kLazyDeopt);
3900 ParameterCount count(instr->arity());
3901 __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
3903 CallKnownFunction(known_function,
3904 instr->hydrogen()->formal_parameter_count(),
3905 instr->arity(), instr);
3910 void LCodeGen::DoCallFunction(LCallFunction* instr) {
3911 DCHECK(ToRegister(instr->context()).is(esi));
3912 DCHECK(ToRegister(instr->function()).is(edi));
3913 DCHECK(ToRegister(instr->result()).is(eax));
3915 int arity = instr->arity();
3916 CallFunctionFlags flags = instr->hydrogen()->function_flags();
3917 if (instr->hydrogen()->HasVectorAndSlot()) {
3918 Register slot_register = ToRegister(instr->temp_slot());
3919 Register vector_register = ToRegister(instr->temp_vector());
3920 DCHECK(slot_register.is(edx));
3921 DCHECK(vector_register.is(ebx));
3923 AllowDeferredHandleDereference vector_structure_check;
3924 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3925 int index = vector->GetIndex(instr->hydrogen()->slot());
3927 __ mov(vector_register, vector);
3928 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3930 CallICState::CallType call_type =
3931 (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
3934 CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
3935 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3937 CallFunctionStub stub(isolate(), arity, flags);
3938 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3943 void LCodeGen::DoCallNew(LCallNew* instr) {
3944 DCHECK(ToRegister(instr->context()).is(esi));
3945 DCHECK(ToRegister(instr->constructor()).is(edi));
3946 DCHECK(ToRegister(instr->result()).is(eax));
3948 // No cell in ebx for construct type feedback in optimized code
3949 __ mov(ebx, isolate()->factory()->undefined_value());
3950 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
3951 __ Move(eax, Immediate(instr->arity()));
3952 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3956 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
3957 DCHECK(ToRegister(instr->context()).is(esi));
3958 DCHECK(ToRegister(instr->constructor()).is(edi));
3959 DCHECK(ToRegister(instr->result()).is(eax));
3961 __ Move(eax, Immediate(instr->arity()));
3962 if (instr->arity() == 1) {
3963 // We only need the allocation site for the case we have a length argument.
3964 // The case may bail out to the runtime, which will determine the correct
3965 // elements kind with the site.
3966 __ mov(ebx, instr->hydrogen()->site());
3968 __ mov(ebx, isolate()->factory()->undefined_value());
3971 ElementsKind kind = instr->hydrogen()->elements_kind();
3972 AllocationSiteOverrideMode override_mode =
3973 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
3974 ? DISABLE_ALLOCATION_SITES
3977 if (instr->arity() == 0) {
3978 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
3979 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3980 } else if (instr->arity() == 1) {
3982 if (IsFastPackedElementsKind(kind)) {
3984 // We might need a change here
3985 // look at the first argument
3986 __ mov(ecx, Operand(esp, 0));
3988 __ j(zero, &packed_case, Label::kNear);
3990 ElementsKind holey_kind = GetHoleyElementsKind(kind);
3991 ArraySingleArgumentConstructorStub stub(isolate(),
3994 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
3995 __ jmp(&done, Label::kNear);
3996 __ bind(&packed_case);
3999 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
4000 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4003 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
4004 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4009 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4010 DCHECK(ToRegister(instr->context()).is(esi));
4011 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
4015 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4016 Register function = ToRegister(instr->function());
4017 Register code_object = ToRegister(instr->code_object());
4018 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4019 __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4023 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4024 Register result = ToRegister(instr->result());
4025 Register base = ToRegister(instr->base_object());
4026 if (instr->offset()->IsConstantOperand()) {
4027 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4028 __ lea(result, Operand(base, ToInteger32(offset)));
4030 Register offset = ToRegister(instr->offset());
4031 __ lea(result, Operand(base, offset, times_1, 0));
4036 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4037 Representation representation = instr->hydrogen()->field_representation();
4039 HObjectAccess access = instr->hydrogen()->access();
4040 int offset = access.offset();
4042 if (access.IsExternalMemory()) {
4043 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4044 MemOperand operand = instr->object()->IsConstantOperand()
4045 ? MemOperand::StaticVariable(
4046 ToExternalReference(LConstantOperand::cast(instr->object())))
4047 : MemOperand(ToRegister(instr->object()), offset);
4048 if (instr->value()->IsConstantOperand()) {
4049 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4050 __ mov(operand, Immediate(ToInteger32(operand_value)));
4052 Register value = ToRegister(instr->value());
4053 __ Store(value, operand, representation);
4058 Register object = ToRegister(instr->object());
4059 __ AssertNotSmi(object);
4061 DCHECK(!representation.IsSmi() ||
4062 !instr->value()->IsConstantOperand() ||
4063 IsSmi(LConstantOperand::cast(instr->value())));
4064 if (representation.IsDouble()) {
4065 DCHECK(access.IsInobject());
4066 DCHECK(!instr->hydrogen()->has_transition());
4067 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4068 XMMRegister value = ToDoubleRegister(instr->value());
4069 __ movsd(FieldOperand(object, offset), value);
4073 if (instr->hydrogen()->has_transition()) {
4074 Handle<Map> transition = instr->hydrogen()->transition_map();
4075 AddDeprecationDependency(transition);
4076 __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4077 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4078 Register temp = ToRegister(instr->temp());
4079 Register temp_map = ToRegister(instr->temp_map());
4080 // Update the write barrier for the map field.
4081 __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4086 Register write_register = object;
4087 if (!access.IsInobject()) {
4088 write_register = ToRegister(instr->temp());
4089 __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4092 MemOperand operand = FieldOperand(write_register, offset);
4093 if (instr->value()->IsConstantOperand()) {
4094 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4095 if (operand_value->IsRegister()) {
4096 Register value = ToRegister(operand_value);
4097 __ Store(value, operand, representation);
4098 } else if (representation.IsInteger32()) {
4099 Immediate immediate = ToImmediate(operand_value, representation);
4100 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4101 __ mov(operand, immediate);
4103 Handle<Object> handle_value = ToHandle(operand_value);
4104 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4105 __ mov(operand, handle_value);
4108 Register value = ToRegister(instr->value());
4109 __ Store(value, operand, representation);
4112 if (instr->hydrogen()->NeedsWriteBarrier()) {
4113 Register value = ToRegister(instr->value());
4114 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4115 // Update the write barrier for the object for in-object properties.
4116 __ RecordWriteField(write_register,
4121 EMIT_REMEMBERED_SET,
4122 instr->hydrogen()->SmiCheckForWriteBarrier(),
4123 instr->hydrogen()->PointersToHereCheckForValue());
4128 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4129 DCHECK(ToRegister(instr->context()).is(esi));
4130 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4131 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4133 __ mov(StoreDescriptor::NameRegister(), instr->name());
4135 StoreIC::initialize_stub(isolate(), instr->language_mode(),
4136 instr->hydrogen()->initialization_state());
4137 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4141 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4142 Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4143 if (instr->index()->IsConstantOperand()) {
4144 __ cmp(ToOperand(instr->length()),
4145 ToImmediate(LConstantOperand::cast(instr->index()),
4146 instr->hydrogen()->length()->representation()));
4147 cc = CommuteCondition(cc);
4148 } else if (instr->length()->IsConstantOperand()) {
4149 __ cmp(ToOperand(instr->index()),
4150 ToImmediate(LConstantOperand::cast(instr->length()),
4151 instr->hydrogen()->index()->representation()));
4153 __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4155 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4157 __ j(NegateCondition(cc), &done, Label::kNear);
4161 DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4166 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4167 ElementsKind elements_kind = instr->elements_kind();
4168 LOperand* key = instr->key();
4169 if (!key->IsConstantOperand() &&
4170 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4172 __ SmiUntag(ToRegister(key));
4174 Operand operand(BuildFastArrayOperand(
4177 instr->hydrogen()->key()->representation(),
4179 instr->base_offset()));
4180 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
4181 elements_kind == FLOAT32_ELEMENTS) {
4182 XMMRegister xmm_scratch = double_scratch0();
4183 __ cvtsd2ss(xmm_scratch, ToDoubleRegister(instr->value()));
4184 __ movss(operand, xmm_scratch);
4185 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
4186 elements_kind == FLOAT64_ELEMENTS) {
4187 __ movsd(operand, ToDoubleRegister(instr->value()));
4189 Register value = ToRegister(instr->value());
4190 switch (elements_kind) {
4191 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
4192 case EXTERNAL_UINT8_ELEMENTS:
4193 case EXTERNAL_INT8_ELEMENTS:
4194 case UINT8_ELEMENTS:
4196 case UINT8_CLAMPED_ELEMENTS:
4197 __ mov_b(operand, value);
4199 case EXTERNAL_INT16_ELEMENTS:
4200 case EXTERNAL_UINT16_ELEMENTS:
4201 case UINT16_ELEMENTS:
4202 case INT16_ELEMENTS:
4203 __ mov_w(operand, value);
4205 case EXTERNAL_INT32_ELEMENTS:
4206 case EXTERNAL_UINT32_ELEMENTS:
4207 case UINT32_ELEMENTS:
4208 case INT32_ELEMENTS:
4209 __ mov(operand, value);
4211 case EXTERNAL_FLOAT32_ELEMENTS:
4212 case EXTERNAL_FLOAT64_ELEMENTS:
4213 case FLOAT32_ELEMENTS:
4214 case FLOAT64_ELEMENTS:
4215 case FAST_SMI_ELEMENTS:
4217 case FAST_DOUBLE_ELEMENTS:
4218 case FAST_HOLEY_SMI_ELEMENTS:
4219 case FAST_HOLEY_ELEMENTS:
4220 case FAST_HOLEY_DOUBLE_ELEMENTS:
4221 case DICTIONARY_ELEMENTS:
4222 case SLOPPY_ARGUMENTS_ELEMENTS:
4230 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4231 Operand double_store_operand = BuildFastArrayOperand(
4234 instr->hydrogen()->key()->representation(),
4235 FAST_DOUBLE_ELEMENTS,
4236 instr->base_offset());
4238 XMMRegister value = ToDoubleRegister(instr->value());
4240 if (instr->NeedsCanonicalization()) {
4241 XMMRegister xmm_scratch = double_scratch0();
4242 // Turn potential sNaN value into qNaN.
4243 __ xorps(xmm_scratch, xmm_scratch);
4244 __ subsd(value, xmm_scratch);
4247 __ movsd(double_store_operand, value);
4251 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4252 Register elements = ToRegister(instr->elements());
4253 Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4255 Operand operand = BuildFastArrayOperand(
4258 instr->hydrogen()->key()->representation(),
4260 instr->base_offset());
4261 if (instr->value()->IsRegister()) {
4262 __ mov(operand, ToRegister(instr->value()));
4264 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4265 if (IsSmi(operand_value)) {
4266 Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4267 __ mov(operand, immediate);
4269 DCHECK(!IsInteger32(operand_value));
4270 Handle<Object> handle_value = ToHandle(operand_value);
4271 __ mov(operand, handle_value);
4275 if (instr->hydrogen()->NeedsWriteBarrier()) {
4276 DCHECK(instr->value()->IsRegister());
4277 Register value = ToRegister(instr->value());
4278 DCHECK(!instr->key()->IsConstantOperand());
4279 SmiCheck check_needed =
4280 instr->hydrogen()->value()->type().IsHeapObject()
4281 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4282 // Compute address of modified element and store it into key register.
4283 __ lea(key, operand);
4284 __ RecordWrite(elements,
4288 EMIT_REMEMBERED_SET,
4290 instr->hydrogen()->PointersToHereCheckForValue());
4295 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4296 // By cases...external, fast-double, fast
4297 if (instr->is_typed_elements()) {
4298 DoStoreKeyedExternalArray(instr);
4299 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4300 DoStoreKeyedFixedDoubleArray(instr);
4302 DoStoreKeyedFixedArray(instr);
4307 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4308 DCHECK(ToRegister(instr->context()).is(esi));
4309 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4310 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4311 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4313 Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
4314 isolate(), instr->language_mode(),
4315 instr->hydrogen()->initialization_state()).code();
4316 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4320 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4321 Register object = ToRegister(instr->object());
4322 Register temp = ToRegister(instr->temp());
4323 Label no_memento_found;
4324 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4325 DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4326 __ bind(&no_memento_found);
4330 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
4331 class DeferredMaybeGrowElements final : public LDeferredCode {
4333 DeferredMaybeGrowElements(LCodeGen* codegen, LMaybeGrowElements* instr)
4334 : LDeferredCode(codegen), instr_(instr) {}
4335 void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
4336 LInstruction* instr() override { return instr_; }
4339 LMaybeGrowElements* instr_;
4342 Register result = eax;
4343 DeferredMaybeGrowElements* deferred =
4344 new (zone()) DeferredMaybeGrowElements(this, instr);
4345 LOperand* key = instr->key();
4346 LOperand* current_capacity = instr->current_capacity();
4348 DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
4349 DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
4350 DCHECK(key->IsConstantOperand() || key->IsRegister());
4351 DCHECK(current_capacity->IsConstantOperand() ||
4352 current_capacity->IsRegister());
4354 if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
4355 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4356 int32_t constant_capacity =
4357 ToInteger32(LConstantOperand::cast(current_capacity));
4358 if (constant_key >= constant_capacity) {
4360 __ jmp(deferred->entry());
4362 } else if (key->IsConstantOperand()) {
4363 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
4364 __ cmp(ToOperand(current_capacity), Immediate(constant_key));
4365 __ j(less_equal, deferred->entry());
4366 } else if (current_capacity->IsConstantOperand()) {
4367 int32_t constant_capacity =
4368 ToInteger32(LConstantOperand::cast(current_capacity));
4369 __ cmp(ToRegister(key), Immediate(constant_capacity));
4370 __ j(greater_equal, deferred->entry());
4372 __ cmp(ToRegister(key), ToRegister(current_capacity));
4373 __ j(greater_equal, deferred->entry());
4376 __ mov(result, ToOperand(instr->elements()));
4377 __ bind(deferred->exit());
4381 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
4382 // TODO(3095996): Get rid of this. For now, we need to make the
4383 // result register contain a valid pointer because it is already
4384 // contained in the register pointer map.
4385 Register result = eax;
4386 __ Move(result, Immediate(0));
4388 // We have to call a stub.
4390 PushSafepointRegistersScope scope(this);
4391 if (instr->object()->IsRegister()) {
4392 __ Move(result, ToRegister(instr->object()));
4394 __ mov(result, ToOperand(instr->object()));
4397 LOperand* key = instr->key();
4398 if (key->IsConstantOperand()) {
4399 __ mov(ebx, ToImmediate(key, Representation::Smi()));
4401 __ Move(ebx, ToRegister(key));
4405 GrowArrayElementsStub stub(isolate(), instr->hydrogen()->is_js_array(),
4406 instr->hydrogen()->kind());
4408 RecordSafepointWithLazyDeopt(
4409 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4410 __ StoreToSafepointRegisterSlot(result, result);
4413 // Deopt on smi, which means the elements array changed to dictionary mode.
4414 __ test(result, Immediate(kSmiTagMask));
4415 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
4419 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4420 Register object_reg = ToRegister(instr->object());
4422 Handle<Map> from_map = instr->original_map();
4423 Handle<Map> to_map = instr->transitioned_map();
4424 ElementsKind from_kind = instr->from_kind();
4425 ElementsKind to_kind = instr->to_kind();
4427 Label not_applicable;
4428 bool is_simple_map_transition =
4429 IsSimpleMapChangeTransition(from_kind, to_kind);
4430 Label::Distance branch_distance =
4431 is_simple_map_transition ? Label::kNear : Label::kFar;
4432 __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4433 __ j(not_equal, ¬_applicable, branch_distance);
4434 if (is_simple_map_transition) {
4435 Register new_map_reg = ToRegister(instr->new_map_temp());
4436 __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4439 DCHECK_NOT_NULL(instr->temp());
4440 __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4441 ToRegister(instr->temp()),
4444 DCHECK(ToRegister(instr->context()).is(esi));
4445 DCHECK(object_reg.is(eax));
4446 PushSafepointRegistersScope scope(this);
4447 __ mov(ebx, to_map);
4448 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4449 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4451 RecordSafepointWithLazyDeopt(instr,
4452 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4454 __ bind(¬_applicable);
4458 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4459 class DeferredStringCharCodeAt final : public LDeferredCode {
4461 DeferredStringCharCodeAt(LCodeGen* codegen,
4462 LStringCharCodeAt* instr)
4463 : LDeferredCode(codegen), instr_(instr) { }
4464 void Generate() override { codegen()->DoDeferredStringCharCodeAt(instr_); }
4465 LInstruction* instr() override { return instr_; }
4468 LStringCharCodeAt* instr_;
4471 DeferredStringCharCodeAt* deferred =
4472 new(zone()) DeferredStringCharCodeAt(this, instr);
4474 StringCharLoadGenerator::Generate(masm(),
4476 ToRegister(instr->string()),
4477 ToRegister(instr->index()),
4478 ToRegister(instr->result()),
4480 __ bind(deferred->exit());
4484 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4485 Register string = ToRegister(instr->string());
4486 Register result = ToRegister(instr->result());
4488 // TODO(3095996): Get rid of this. For now, we need to make the
4489 // result register contain a valid pointer because it is already
4490 // contained in the register pointer map.
4491 __ Move(result, Immediate(0));
4493 PushSafepointRegistersScope scope(this);
4495 // Push the index as a smi. This is safe because of the checks in
4496 // DoStringCharCodeAt above.
4497 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4498 if (instr->index()->IsConstantOperand()) {
4499 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4500 Representation::Smi());
4503 Register index = ToRegister(instr->index());
4507 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4508 instr, instr->context());
4511 __ StoreToSafepointRegisterSlot(result, eax);
4515 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4516 class DeferredStringCharFromCode final : public LDeferredCode {
4518 DeferredStringCharFromCode(LCodeGen* codegen,
4519 LStringCharFromCode* instr)
4520 : LDeferredCode(codegen), instr_(instr) { }
4521 void Generate() override {
4522 codegen()->DoDeferredStringCharFromCode(instr_);
4524 LInstruction* instr() override { return instr_; }
4527 LStringCharFromCode* instr_;
4530 DeferredStringCharFromCode* deferred =
4531 new(zone()) DeferredStringCharFromCode(this, instr);
4533 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4534 Register char_code = ToRegister(instr->char_code());
4535 Register result = ToRegister(instr->result());
4536 DCHECK(!char_code.is(result));
4538 __ cmp(char_code, String::kMaxOneByteCharCode);
4539 __ j(above, deferred->entry());
4540 __ Move(result, Immediate(factory()->single_character_string_cache()));
4541 __ mov(result, FieldOperand(result,
4542 char_code, times_pointer_size,
4543 FixedArray::kHeaderSize));
4544 __ cmp(result, factory()->undefined_value());
4545 __ j(equal, deferred->entry());
4546 __ bind(deferred->exit());
4550 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4551 Register char_code = ToRegister(instr->char_code());
4552 Register result = ToRegister(instr->result());
4554 // TODO(3095996): Get rid of this. For now, we need to make the
4555 // result register contain a valid pointer because it is already
4556 // contained in the register pointer map.
4557 __ Move(result, Immediate(0));
4559 PushSafepointRegistersScope scope(this);
4560 __ SmiTag(char_code);
4562 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4563 __ StoreToSafepointRegisterSlot(result, eax);
4567 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4568 DCHECK(ToRegister(instr->context()).is(esi));
4569 DCHECK(ToRegister(instr->left()).is(edx));
4570 DCHECK(ToRegister(instr->right()).is(eax));
4571 StringAddStub stub(isolate(),
4572 instr->hydrogen()->flags(),
4573 instr->hydrogen()->pretenure_flag());
4574 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4578 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4579 LOperand* input = instr->value();
4580 LOperand* output = instr->result();
4581 DCHECK(input->IsRegister() || input->IsStackSlot());
4582 DCHECK(output->IsDoubleRegister());
4583 __ Cvtsi2sd(ToDoubleRegister(output), ToOperand(input));
4587 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4588 LOperand* input = instr->value();
4589 LOperand* output = instr->result();
4590 __ LoadUint32(ToDoubleRegister(output), ToRegister(input));
4594 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4595 class DeferredNumberTagI final : public LDeferredCode {
4597 DeferredNumberTagI(LCodeGen* codegen,
4599 : LDeferredCode(codegen), instr_(instr) { }
4600 void Generate() override {
4601 codegen()->DoDeferredNumberTagIU(
4602 instr_, instr_->value(), instr_->temp(), SIGNED_INT32);
4604 LInstruction* instr() override { return instr_; }
4607 LNumberTagI* instr_;
4610 LOperand* input = instr->value();
4611 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4612 Register reg = ToRegister(input);
4614 DeferredNumberTagI* deferred =
4615 new(zone()) DeferredNumberTagI(this, instr);
4617 __ j(overflow, deferred->entry());
4618 __ bind(deferred->exit());
4622 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4623 class DeferredNumberTagU final : public LDeferredCode {
4625 DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4626 : LDeferredCode(codegen), instr_(instr) { }
4627 void Generate() override {
4628 codegen()->DoDeferredNumberTagIU(
4629 instr_, instr_->value(), instr_->temp(), UNSIGNED_INT32);
4631 LInstruction* instr() override { return instr_; }
4634 LNumberTagU* instr_;
4637 LOperand* input = instr->value();
4638 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4639 Register reg = ToRegister(input);
4641 DeferredNumberTagU* deferred =
4642 new(zone()) DeferredNumberTagU(this, instr);
4643 __ cmp(reg, Immediate(Smi::kMaxValue));
4644 __ j(above, deferred->entry());
4646 __ bind(deferred->exit());
4650 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
4653 IntegerSignedness signedness) {
4655 Register reg = ToRegister(value);
4656 Register tmp = ToRegister(temp);
4657 XMMRegister xmm_scratch = double_scratch0();
4659 if (signedness == SIGNED_INT32) {
4660 // There was overflow, so bits 30 and 31 of the original integer
4661 // disagree. Try to allocate a heap number in new space and store
4662 // the value in there. If that fails, call the runtime system.
4664 __ xor_(reg, 0x80000000);
4665 __ Cvtsi2sd(xmm_scratch, Operand(reg));
4667 __ LoadUint32(xmm_scratch, reg);
4670 if (FLAG_inline_new) {
4671 __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
4672 __ jmp(&done, Label::kNear);
4675 // Slow case: Call the runtime system to do the number allocation.
4678 // TODO(3095996): Put a valid pointer value in the stack slot where the
4679 // result register is stored, as this register is in the pointer map, but
4680 // contains an integer value.
4681 __ Move(reg, Immediate(0));
4683 // Preserve the value of all registers.
4684 PushSafepointRegistersScope scope(this);
4686 // NumberTagI and NumberTagD use the context from the frame, rather than
4687 // the environment's HContext or HInlinedContext value.
4688 // They only call Runtime::kAllocateHeapNumber.
4689 // The corresponding HChange instructions are added in a phase that does
4690 // not have easy access to the local context.
4691 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4692 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4693 RecordSafepointWithRegisters(
4694 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4695 __ StoreToSafepointRegisterSlot(reg, eax);
4698 // Done. Put the value in xmm_scratch into the value of the allocated heap
4701 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), xmm_scratch);
4705 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4706 class DeferredNumberTagD final : public LDeferredCode {
4708 DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4709 : LDeferredCode(codegen), instr_(instr) { }
4710 void Generate() override { codegen()->DoDeferredNumberTagD(instr_); }
4711 LInstruction* instr() override { return instr_; }
4714 LNumberTagD* instr_;
4717 Register reg = ToRegister(instr->result());
4719 DeferredNumberTagD* deferred =
4720 new(zone()) DeferredNumberTagD(this, instr);
4721 if (FLAG_inline_new) {
4722 Register tmp = ToRegister(instr->temp());
4723 __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
4725 __ jmp(deferred->entry());
4727 __ bind(deferred->exit());
4728 XMMRegister input_reg = ToDoubleRegister(instr->value());
4729 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg);
4733 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4734 // TODO(3095996): Get rid of this. For now, we need to make the
4735 // result register contain a valid pointer because it is already
4736 // contained in the register pointer map.
4737 Register reg = ToRegister(instr->result());
4738 __ Move(reg, Immediate(0));
4740 PushSafepointRegistersScope scope(this);
4741 // NumberTagI and NumberTagD use the context from the frame, rather than
4742 // the environment's HContext or HInlinedContext value.
4743 // They only call Runtime::kAllocateHeapNumber.
4744 // The corresponding HChange instructions are added in a phase that does
4745 // not have easy access to the local context.
4746 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4747 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4748 RecordSafepointWithRegisters(
4749 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4750 __ StoreToSafepointRegisterSlot(reg, eax);
4754 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4755 HChange* hchange = instr->hydrogen();
4756 Register input = ToRegister(instr->value());
4757 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4758 hchange->value()->CheckFlag(HValue::kUint32)) {
4759 __ test(input, Immediate(0xc0000000));
4760 DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
4763 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4764 !hchange->value()->CheckFlag(HValue::kUint32)) {
4765 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4770 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4771 LOperand* input = instr->value();
4772 Register result = ToRegister(input);
4773 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4774 if (instr->needs_check()) {
4775 __ test(result, Immediate(kSmiTagMask));
4776 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4778 __ AssertSmi(result);
4780 __ SmiUntag(result);
4784 void LCodeGen::EmitNumberUntagD(LNumberUntagD* instr, Register input_reg,
4785 Register temp_reg, XMMRegister result_reg,
4786 NumberUntagDMode mode) {
4787 bool can_convert_undefined_to_nan =
4788 instr->hydrogen()->can_convert_undefined_to_nan();
4789 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
4791 Label convert, load_smi, done;
4793 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4795 __ JumpIfSmi(input_reg, &load_smi, Label::kNear);
4797 // Heap number map check.
4798 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4799 factory()->heap_number_map());
4800 if (can_convert_undefined_to_nan) {
4801 __ j(not_equal, &convert, Label::kNear);
4803 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4806 // Heap number to XMM conversion.
4807 __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset));
4809 if (deoptimize_on_minus_zero) {
4810 XMMRegister xmm_scratch = double_scratch0();
4811 __ xorps(xmm_scratch, xmm_scratch);
4812 __ ucomisd(result_reg, xmm_scratch);
4813 __ j(not_zero, &done, Label::kNear);
4814 __ movmskpd(temp_reg, result_reg);
4815 __ test_b(temp_reg, 1);
4816 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4818 __ jmp(&done, Label::kNear);
4820 if (can_convert_undefined_to_nan) {
4823 // Convert undefined to NaN.
4824 __ cmp(input_reg, factory()->undefined_value());
4825 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
4827 __ pcmpeqd(result_reg, result_reg);
4828 __ jmp(&done, Label::kNear);
4831 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4835 // Smi to XMM conversion. Clobbering a temp is faster than re-tagging the
4836 // input register since we avoid dependencies.
4837 __ mov(temp_reg, input_reg);
4838 __ SmiUntag(temp_reg); // Untag smi before converting to float.
4839 __ Cvtsi2sd(result_reg, Operand(temp_reg));
4844 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
4845 Register input_reg = ToRegister(instr->value());
4847 // The input was optimistically untagged; revert it.
4848 STATIC_ASSERT(kSmiTagSize == 1);
4849 __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
4851 if (instr->truncating()) {
4852 Label no_heap_number, check_bools, check_false;
4854 // Heap number map check.
4855 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4856 factory()->heap_number_map());
4857 __ j(not_equal, &no_heap_number, Label::kNear);
4858 __ TruncateHeapNumberToI(input_reg, input_reg);
4861 __ bind(&no_heap_number);
4862 // Check for Oddballs. Undefined/False is converted to zero and True to one
4863 // for truncating conversions.
4864 __ cmp(input_reg, factory()->undefined_value());
4865 __ j(not_equal, &check_bools, Label::kNear);
4866 __ Move(input_reg, Immediate(0));
4869 __ bind(&check_bools);
4870 __ cmp(input_reg, factory()->true_value());
4871 __ j(not_equal, &check_false, Label::kNear);
4872 __ Move(input_reg, Immediate(1));
4875 __ bind(&check_false);
4876 __ cmp(input_reg, factory()->false_value());
4877 DeoptimizeIf(not_equal, instr,
4878 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
4879 __ Move(input_reg, Immediate(0));
4881 XMMRegister scratch = ToDoubleRegister(instr->temp());
4882 DCHECK(!scratch.is(xmm0));
4883 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4884 isolate()->factory()->heap_number_map());
4885 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4886 __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
4887 __ cvttsd2si(input_reg, Operand(xmm0));
4888 __ Cvtsi2sd(scratch, Operand(input_reg));
4889 __ ucomisd(xmm0, scratch);
4890 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
4891 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
4892 if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
4893 __ test(input_reg, Operand(input_reg));
4894 __ j(not_zero, done);
4895 __ movmskpd(input_reg, xmm0);
4896 __ and_(input_reg, 1);
4897 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4903 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
4904 class DeferredTaggedToI final : public LDeferredCode {
4906 DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
4907 : LDeferredCode(codegen), instr_(instr) { }
4908 void Generate() override { codegen()->DoDeferredTaggedToI(instr_, done()); }
4909 LInstruction* instr() override { return instr_; }
4915 LOperand* input = instr->value();
4916 DCHECK(input->IsRegister());
4917 Register input_reg = ToRegister(input);
4918 DCHECK(input_reg.is(ToRegister(instr->result())));
4920 if (instr->hydrogen()->value()->representation().IsSmi()) {
4921 __ SmiUntag(input_reg);
4923 DeferredTaggedToI* deferred =
4924 new(zone()) DeferredTaggedToI(this, instr);
4925 // Optimistically untag the input.
4926 // If the input is a HeapObject, SmiUntag will set the carry flag.
4927 STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
4928 __ SmiUntag(input_reg);
4929 // Branch to deferred code if the input was tagged.
4930 // The deferred code will take care of restoring the tag.
4931 __ j(carry, deferred->entry());
4932 __ bind(deferred->exit());
4937 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4938 LOperand* input = instr->value();
4939 DCHECK(input->IsRegister());
4940 LOperand* temp = instr->temp();
4941 DCHECK(temp->IsRegister());
4942 LOperand* result = instr->result();
4943 DCHECK(result->IsDoubleRegister());
4945 Register input_reg = ToRegister(input);
4946 Register temp_reg = ToRegister(temp);
4948 HValue* value = instr->hydrogen()->value();
4949 NumberUntagDMode mode = value->representation().IsSmi()
4950 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4952 XMMRegister result_reg = ToDoubleRegister(result);
4953 EmitNumberUntagD(instr, input_reg, temp_reg, result_reg, mode);
4957 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
4958 LOperand* input = instr->value();
4959 DCHECK(input->IsDoubleRegister());
4960 LOperand* result = instr->result();
4961 DCHECK(result->IsRegister());
4962 Register result_reg = ToRegister(result);
4964 if (instr->truncating()) {
4965 XMMRegister input_reg = ToDoubleRegister(input);
4966 __ TruncateDoubleToI(result_reg, input_reg);
4968 Label lost_precision, is_nan, minus_zero, done;
4969 XMMRegister input_reg = ToDoubleRegister(input);
4970 XMMRegister xmm_scratch = double_scratch0();
4971 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4972 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4973 instr->hydrogen()->GetMinusZeroMode(), &lost_precision,
4974 &is_nan, &minus_zero, dist);
4975 __ jmp(&done, dist);
4976 __ bind(&lost_precision);
4977 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4979 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4980 __ bind(&minus_zero);
4981 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4987 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
4988 LOperand* input = instr->value();
4989 DCHECK(input->IsDoubleRegister());
4990 LOperand* result = instr->result();
4991 DCHECK(result->IsRegister());
4992 Register result_reg = ToRegister(result);
4994 Label lost_precision, is_nan, minus_zero, done;
4995 XMMRegister input_reg = ToDoubleRegister(input);
4996 XMMRegister xmm_scratch = double_scratch0();
4997 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4998 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4999 instr->hydrogen()->GetMinusZeroMode(), &lost_precision, &is_nan,
5001 __ jmp(&done, dist);
5002 __ bind(&lost_precision);
5003 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5005 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5006 __ bind(&minus_zero);
5007 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
5009 __ SmiTag(result_reg);
5010 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
5014 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
5015 LOperand* input = instr->value();
5016 __ test(ToOperand(input), Immediate(kSmiTagMask));
5017 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
5021 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5022 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
5023 LOperand* input = instr->value();
5024 __ test(ToOperand(input), Immediate(kSmiTagMask));
5025 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5030 void LCodeGen::DoCheckArrayBufferNotNeutered(
5031 LCheckArrayBufferNotNeutered* instr) {
5032 Register view = ToRegister(instr->view());
5033 Register scratch = ToRegister(instr->scratch());
5035 __ mov(scratch, FieldOperand(view, JSArrayBufferView::kBufferOffset));
5036 __ test_b(FieldOperand(scratch, JSArrayBuffer::kBitFieldOffset),
5037 1 << JSArrayBuffer::WasNeutered::kShift);
5038 DeoptimizeIf(not_zero, instr, Deoptimizer::kOutOfBounds);
5042 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
5043 Register input = ToRegister(instr->value());
5044 Register temp = ToRegister(instr->temp());
5046 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
5048 if (instr->hydrogen()->is_interval_check()) {
5051 instr->hydrogen()->GetCheckInterval(&first, &last);
5053 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5054 static_cast<int8_t>(first));
5056 // If there is only one type in the interval check for equality.
5057 if (first == last) {
5058 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5060 DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
5061 // Omit check for the last type.
5062 if (last != LAST_TYPE) {
5063 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5064 static_cast<int8_t>(last));
5065 DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5071 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5073 if (base::bits::IsPowerOfTwo32(mask)) {
5074 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5075 __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5076 DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5077 Deoptimizer::kWrongInstanceType);
5079 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5080 __ and_(temp, mask);
5082 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5088 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5089 Handle<HeapObject> object = instr->hydrogen()->object().handle();
5090 if (instr->hydrogen()->object_in_new_space()) {
5091 Register reg = ToRegister(instr->value());
5092 Handle<Cell> cell = isolate()->factory()->NewCell(object);
5093 __ cmp(reg, Operand::ForCell(cell));
5095 Operand operand = ToOperand(instr->value());
5096 __ cmp(operand, object);
5098 DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5102 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5104 PushSafepointRegistersScope scope(this);
5107 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5108 RecordSafepointWithRegisters(
5109 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5111 __ test(eax, Immediate(kSmiTagMask));
5113 DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5117 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5118 class DeferredCheckMaps final : public LDeferredCode {
5120 DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr, Register object)
5121 : LDeferredCode(codegen), instr_(instr), object_(object) {
5122 SetExit(check_maps());
5124 void Generate() override {
5125 codegen()->DoDeferredInstanceMigration(instr_, object_);
5127 Label* check_maps() { return &check_maps_; }
5128 LInstruction* instr() override { return instr_; }
5136 if (instr->hydrogen()->IsStabilityCheck()) {
5137 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5138 for (int i = 0; i < maps->size(); ++i) {
5139 AddStabilityDependency(maps->at(i).handle());
5144 LOperand* input = instr->value();
5145 DCHECK(input->IsRegister());
5146 Register reg = ToRegister(input);
5148 DeferredCheckMaps* deferred = NULL;
5149 if (instr->hydrogen()->HasMigrationTarget()) {
5150 deferred = new(zone()) DeferredCheckMaps(this, instr, reg);
5151 __ bind(deferred->check_maps());
5154 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5156 for (int i = 0; i < maps->size() - 1; i++) {
5157 Handle<Map> map = maps->at(i).handle();
5158 __ CompareMap(reg, map);
5159 __ j(equal, &success, Label::kNear);
5162 Handle<Map> map = maps->at(maps->size() - 1).handle();
5163 __ CompareMap(reg, map);
5164 if (instr->hydrogen()->HasMigrationTarget()) {
5165 __ j(not_equal, deferred->entry());
5167 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5174 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5175 XMMRegister value_reg = ToDoubleRegister(instr->unclamped());
5176 XMMRegister xmm_scratch = double_scratch0();
5177 Register result_reg = ToRegister(instr->result());
5178 __ ClampDoubleToUint8(value_reg, xmm_scratch, result_reg);
5182 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5183 DCHECK(instr->unclamped()->Equals(instr->result()));
5184 Register value_reg = ToRegister(instr->result());
5185 __ ClampUint8(value_reg);
5189 void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
5190 DCHECK(instr->unclamped()->Equals(instr->result()));
5191 Register input_reg = ToRegister(instr->unclamped());
5192 XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm());
5193 XMMRegister xmm_scratch = double_scratch0();
5194 Label is_smi, done, heap_number;
5196 __ JumpIfSmi(input_reg, &is_smi);
5198 // Check for heap number
5199 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5200 factory()->heap_number_map());
5201 __ j(equal, &heap_number, Label::kNear);
5203 // Check for undefined. Undefined is converted to zero for clamping
5205 __ cmp(input_reg, factory()->undefined_value());
5206 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5207 __ mov(input_reg, 0);
5208 __ jmp(&done, Label::kNear);
5211 __ bind(&heap_number);
5212 __ movsd(xmm_scratch, FieldOperand(input_reg, HeapNumber::kValueOffset));
5213 __ ClampDoubleToUint8(xmm_scratch, temp_xmm_reg, input_reg);
5214 __ jmp(&done, Label::kNear);
5218 __ SmiUntag(input_reg);
5219 __ ClampUint8(input_reg);
5224 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5225 XMMRegister value_reg = ToDoubleRegister(instr->value());
5226 Register result_reg = ToRegister(instr->result());
5227 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5228 if (CpuFeatures::IsSupported(SSE4_1)) {
5229 CpuFeatureScope scope2(masm(), SSE4_1);
5230 __ pextrd(result_reg, value_reg, 1);
5232 XMMRegister xmm_scratch = double_scratch0();
5233 __ pshufd(xmm_scratch, value_reg, 1);
5234 __ movd(result_reg, xmm_scratch);
5237 __ movd(result_reg, value_reg);
5242 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5243 Register hi_reg = ToRegister(instr->hi());
5244 Register lo_reg = ToRegister(instr->lo());
5245 XMMRegister result_reg = ToDoubleRegister(instr->result());
5247 if (CpuFeatures::IsSupported(SSE4_1)) {
5248 CpuFeatureScope scope2(masm(), SSE4_1);
5249 __ movd(result_reg, lo_reg);
5250 __ pinsrd(result_reg, hi_reg, 1);
5252 XMMRegister xmm_scratch = double_scratch0();
5253 __ movd(result_reg, hi_reg);
5254 __ psllq(result_reg, 32);
5255 __ movd(xmm_scratch, lo_reg);
5256 __ orps(result_reg, xmm_scratch);
5261 void LCodeGen::DoAllocate(LAllocate* instr) {
5262 class DeferredAllocate final : public LDeferredCode {
5264 DeferredAllocate(LCodeGen* codegen, LAllocate* instr)
5265 : LDeferredCode(codegen), instr_(instr) { }
5266 void Generate() override { codegen()->DoDeferredAllocate(instr_); }
5267 LInstruction* instr() override { return instr_; }
5273 DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr);
5275 Register result = ToRegister(instr->result());
5276 Register temp = ToRegister(instr->temp());
5278 // Allocate memory for the object.
5279 AllocationFlags flags = TAG_OBJECT;
5280 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5281 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5283 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5284 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5285 flags = static_cast<AllocationFlags>(flags | PRETENURE);
5288 if (instr->size()->IsConstantOperand()) {
5289 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5290 if (size <= Page::kMaxRegularHeapObjectSize) {
5291 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5293 __ jmp(deferred->entry());
5296 Register size = ToRegister(instr->size());
5297 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5300 __ bind(deferred->exit());
5302 if (instr->hydrogen()->MustPrefillWithFiller()) {
5303 if (instr->size()->IsConstantOperand()) {
5304 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5305 __ mov(temp, (size / kPointerSize) - 1);
5307 temp = ToRegister(instr->size());
5308 __ shr(temp, kPointerSizeLog2);
5313 __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5314 isolate()->factory()->one_pointer_filler_map());
5316 __ j(not_zero, &loop);
5321 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5322 Register result = ToRegister(instr->result());
5324 // TODO(3095996): Get rid of this. For now, we need to make the
5325 // result register contain a valid pointer because it is already
5326 // contained in the register pointer map.
5327 __ Move(result, Immediate(Smi::FromInt(0)));
5329 PushSafepointRegistersScope scope(this);
5330 if (instr->size()->IsRegister()) {
5331 Register size = ToRegister(instr->size());
5332 DCHECK(!size.is(result));
5333 __ SmiTag(ToRegister(instr->size()));
5336 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5337 if (size >= 0 && size <= Smi::kMaxValue) {
5338 __ push(Immediate(Smi::FromInt(size)));
5340 // We should never get here at runtime => abort
5346 int flags = AllocateDoubleAlignFlag::encode(
5347 instr->hydrogen()->MustAllocateDoubleAligned());
5348 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5349 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5350 flags = AllocateTargetSpace::update(flags, OLD_SPACE);
5352 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5354 __ push(Immediate(Smi::FromInt(flags)));
5356 CallRuntimeFromDeferred(
5357 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5358 __ StoreToSafepointRegisterSlot(result, eax);
5362 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5363 DCHECK(ToRegister(instr->value()).is(eax));
5365 CallRuntime(Runtime::kToFastProperties, 1, instr);
5369 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5370 DCHECK(ToRegister(instr->context()).is(esi));
5372 // Registers will be used as follows:
5373 // ecx = literals array.
5374 // ebx = regexp literal.
5375 // eax = regexp literal clone.
5377 int literal_offset =
5378 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5379 __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5380 __ mov(ebx, FieldOperand(ecx, literal_offset));
5381 __ cmp(ebx, factory()->undefined_value());
5382 __ j(not_equal, &materialized, Label::kNear);
5384 // Create regexp literal using runtime function
5385 // Result will be in eax.
5387 __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5388 __ push(Immediate(instr->hydrogen()->pattern()));
5389 __ push(Immediate(instr->hydrogen()->flags()));
5390 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5393 __ bind(&materialized);
5394 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5395 Label allocated, runtime_allocate;
5396 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5397 __ jmp(&allocated, Label::kNear);
5399 __ bind(&runtime_allocate);
5401 __ push(Immediate(Smi::FromInt(size)));
5402 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5405 __ bind(&allocated);
5406 // Copy the content into the newly allocated memory.
5407 // (Unroll copy loop once for better throughput).
5408 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5409 __ mov(edx, FieldOperand(ebx, i));
5410 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5411 __ mov(FieldOperand(eax, i), edx);
5412 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5414 if ((size % (2 * kPointerSize)) != 0) {
5415 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5416 __ mov(FieldOperand(eax, size - kPointerSize), edx);
5421 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5422 DCHECK(ToRegister(instr->context()).is(esi));
5423 // Use the fast case closure allocation code that allocates in new
5424 // space for nested functions that don't need literals cloning.
5425 bool pretenure = instr->hydrogen()->pretenure();
5426 if (!pretenure && instr->hydrogen()->has_no_literals()) {
5427 FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
5428 instr->hydrogen()->kind());
5429 __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
5430 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5433 __ push(Immediate(instr->hydrogen()->shared_info()));
5434 __ push(Immediate(pretenure ? factory()->true_value()
5435 : factory()->false_value()));
5436 CallRuntime(Runtime::kNewClosure, 3, instr);
5441 void LCodeGen::DoTypeof(LTypeof* instr) {
5442 DCHECK(ToRegister(instr->context()).is(esi));
5443 DCHECK(ToRegister(instr->value()).is(ebx));
5445 Register value_register = ToRegister(instr->value());
5446 __ JumpIfNotSmi(value_register, &do_call);
5447 __ mov(eax, Immediate(isolate()->factory()->number_string()));
5450 TypeofStub stub(isolate());
5451 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5456 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5457 Register input = ToRegister(instr->value());
5458 Condition final_branch_condition = EmitTypeofIs(instr, input);
5459 if (final_branch_condition != no_condition) {
5460 EmitBranch(instr, final_branch_condition);
5465 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
5466 Label* true_label = instr->TrueLabel(chunk_);
5467 Label* false_label = instr->FalseLabel(chunk_);
5468 Handle<String> type_name = instr->type_literal();
5469 int left_block = instr->TrueDestination(chunk_);
5470 int right_block = instr->FalseDestination(chunk_);
5471 int next_block = GetNextEmittedBlock();
5473 Label::Distance true_distance = left_block == next_block ? Label::kNear
5475 Label::Distance false_distance = right_block == next_block ? Label::kNear
5477 Condition final_branch_condition = no_condition;
5478 if (String::Equals(type_name, factory()->number_string())) {
5479 __ JumpIfSmi(input, true_label, true_distance);
5480 __ cmp(FieldOperand(input, HeapObject::kMapOffset),
5481 factory()->heap_number_map());
5482 final_branch_condition = equal;
5484 } else if (String::Equals(type_name, factory()->string_string())) {
5485 __ JumpIfSmi(input, false_label, false_distance);
5486 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
5487 __ j(above_equal, false_label, false_distance);
5488 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5489 1 << Map::kIsUndetectable);
5490 final_branch_condition = zero;
5492 } else if (String::Equals(type_name, factory()->symbol_string())) {
5493 __ JumpIfSmi(input, false_label, false_distance);
5494 __ CmpObjectType(input, SYMBOL_TYPE, input);
5495 final_branch_condition = equal;
5497 } else if (String::Equals(type_name, factory()->boolean_string())) {
5498 __ cmp(input, factory()->true_value());
5499 __ j(equal, true_label, true_distance);
5500 __ cmp(input, factory()->false_value());
5501 final_branch_condition = equal;
5503 } else if (String::Equals(type_name, factory()->undefined_string())) {
5504 __ cmp(input, factory()->undefined_value());
5505 __ j(equal, true_label, true_distance);
5506 __ JumpIfSmi(input, false_label, false_distance);
5507 // Check for undetectable objects => true.
5508 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
5509 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5510 1 << Map::kIsUndetectable);
5511 final_branch_condition = not_zero;
5513 } else if (String::Equals(type_name, factory()->function_string())) {
5514 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5515 __ JumpIfSmi(input, false_label, false_distance);
5516 __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
5517 __ j(equal, true_label, true_distance);
5518 __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
5519 final_branch_condition = equal;
5521 } else if (String::Equals(type_name, factory()->object_string())) {
5522 __ JumpIfSmi(input, false_label, false_distance);
5523 __ cmp(input, factory()->null_value());
5524 __ j(equal, true_label, true_distance);
5525 __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
5526 __ j(below, false_label, false_distance);
5527 __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5528 __ j(above, false_label, false_distance);
5529 // Check for undetectable objects => false.
5530 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5531 1 << Map::kIsUndetectable);
5532 final_branch_condition = zero;
5535 __ jmp(false_label, false_distance);
5537 return final_branch_condition;
5541 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
5542 Register temp = ToRegister(instr->temp());
5544 EmitIsConstructCall(temp);
5545 EmitBranch(instr, equal);
5549 void LCodeGen::EmitIsConstructCall(Register temp) {
5550 // Get the frame pointer for the calling frame.
5551 __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
5553 // Skip the arguments adaptor frame if it exists.
5554 Label check_frame_marker;
5555 __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
5556 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
5557 __ j(not_equal, &check_frame_marker, Label::kNear);
5558 __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
5560 // Check the marker in the calling frame.
5561 __ bind(&check_frame_marker);
5562 __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
5563 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
5567 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
5568 if (!info()->IsStub()) {
5569 // Ensure that we have enough space after the previous lazy-bailout
5570 // instruction for patching the code here.
5571 int current_pc = masm()->pc_offset();
5572 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
5573 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
5574 __ Nop(padding_size);
5577 last_lazy_deopt_pc_ = masm()->pc_offset();
5581 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
5582 last_lazy_deopt_pc_ = masm()->pc_offset();
5583 DCHECK(instr->HasEnvironment());
5584 LEnvironment* env = instr->environment();
5585 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5586 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5590 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
5591 Deoptimizer::BailoutType type = instr->hydrogen()->type();
5592 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
5593 // needed return address), even though the implementation of LAZY and EAGER is
5594 // now identical. When LAZY is eventually completely folded into EAGER, remove
5595 // the special case below.
5596 if (info()->IsStub() && type == Deoptimizer::EAGER) {
5597 type = Deoptimizer::LAZY;
5599 DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
5603 void LCodeGen::DoDummy(LDummy* instr) {
5604 // Nothing to see here, move on!
5608 void LCodeGen::DoDummyUse(LDummyUse* instr) {
5609 // Nothing to see here, move on!
5613 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5614 PushSafepointRegistersScope scope(this);
5615 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5616 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5617 RecordSafepointWithLazyDeopt(
5618 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5619 DCHECK(instr->HasEnvironment());
5620 LEnvironment* env = instr->environment();
5621 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5625 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5626 class DeferredStackCheck final : public LDeferredCode {
5628 DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5629 : LDeferredCode(codegen), instr_(instr) { }
5630 void Generate() override { codegen()->DoDeferredStackCheck(instr_); }
5631 LInstruction* instr() override { return instr_; }
5634 LStackCheck* instr_;
5637 DCHECK(instr->HasEnvironment());
5638 LEnvironment* env = instr->environment();
5639 // There is no LLazyBailout instruction for stack-checks. We have to
5640 // prepare for lazy deoptimization explicitly here.
5641 if (instr->hydrogen()->is_function_entry()) {
5642 // Perform stack overflow check.
5644 ExternalReference stack_limit =
5645 ExternalReference::address_of_stack_limit(isolate());
5646 __ cmp(esp, Operand::StaticVariable(stack_limit));
5647 __ j(above_equal, &done, Label::kNear);
5649 DCHECK(instr->context()->IsRegister());
5650 DCHECK(ToRegister(instr->context()).is(esi));
5651 CallCode(isolate()->builtins()->StackCheck(),
5652 RelocInfo::CODE_TARGET,
5656 DCHECK(instr->hydrogen()->is_backwards_branch());
5657 // Perform stack overflow check if this goto needs it before jumping.
5658 DeferredStackCheck* deferred_stack_check =
5659 new(zone()) DeferredStackCheck(this, instr);
5660 ExternalReference stack_limit =
5661 ExternalReference::address_of_stack_limit(isolate());
5662 __ cmp(esp, Operand::StaticVariable(stack_limit));
5663 __ j(below, deferred_stack_check->entry());
5664 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5665 __ bind(instr->done_label());
5666 deferred_stack_check->SetExit(instr->done_label());
5667 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5668 // Don't record a deoptimization index for the safepoint here.
5669 // This will be done explicitly when emitting call and the safepoint in
5670 // the deferred code.
5675 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
5676 // This is a pseudo-instruction that ensures that the environment here is
5677 // properly registered for deoptimization and records the assembler's PC
5679 LEnvironment* environment = instr->environment();
5681 // If the environment were already registered, we would have no way of
5682 // backpatching it with the spill slot operands.
5683 DCHECK(!environment->HasBeenRegistered());
5684 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
5686 GenerateOsrPrologue();
5690 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
5691 DCHECK(ToRegister(instr->context()).is(esi));
5692 __ test(eax, Immediate(kSmiTagMask));
5693 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5695 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
5696 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
5697 DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
5699 Label use_cache, call_runtime;
5700 __ CheckEnumCache(&call_runtime);
5702 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
5703 __ jmp(&use_cache, Label::kNear);
5705 // Get the set of properties to enumerate.
5706 __ bind(&call_runtime);
5708 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
5710 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
5711 isolate()->factory()->meta_map());
5712 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5713 __ bind(&use_cache);
5717 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
5718 Register map = ToRegister(instr->map());
5719 Register result = ToRegister(instr->result());
5720 Label load_cache, done;
5721 __ EnumLength(result, map);
5722 __ cmp(result, Immediate(Smi::FromInt(0)));
5723 __ j(not_equal, &load_cache, Label::kNear);
5724 __ mov(result, isolate()->factory()->empty_fixed_array());
5725 __ jmp(&done, Label::kNear);
5727 __ bind(&load_cache);
5728 __ LoadInstanceDescriptors(map, result);
5730 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
5732 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
5734 __ test(result, result);
5735 DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
5739 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
5740 Register object = ToRegister(instr->value());
5741 __ cmp(ToRegister(instr->map()),
5742 FieldOperand(object, HeapObject::kMapOffset));
5743 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5747 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
5750 PushSafepointRegistersScope scope(this);
5754 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
5755 RecordSafepointWithRegisters(
5756 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
5757 __ StoreToSafepointRegisterSlot(object, eax);
5761 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
5762 class DeferredLoadMutableDouble final : public LDeferredCode {
5764 DeferredLoadMutableDouble(LCodeGen* codegen,
5765 LLoadFieldByIndex* instr,
5768 : LDeferredCode(codegen),
5773 void Generate() override {
5774 codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
5776 LInstruction* instr() override { return instr_; }
5779 LLoadFieldByIndex* instr_;
5784 Register object = ToRegister(instr->object());
5785 Register index = ToRegister(instr->index());
5787 DeferredLoadMutableDouble* deferred;
5788 deferred = new(zone()) DeferredLoadMutableDouble(
5789 this, instr, object, index);
5791 Label out_of_object, done;
5792 __ test(index, Immediate(Smi::FromInt(1)));
5793 __ j(not_zero, deferred->entry());
5797 __ cmp(index, Immediate(0));
5798 __ j(less, &out_of_object, Label::kNear);
5799 __ mov(object, FieldOperand(object,
5801 times_half_pointer_size,
5802 JSObject::kHeaderSize));
5803 __ jmp(&done, Label::kNear);
5805 __ bind(&out_of_object);
5806 __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
5808 // Index is now equal to out of object property index plus 1.
5809 __ mov(object, FieldOperand(object,
5811 times_half_pointer_size,
5812 FixedArray::kHeaderSize - kPointerSize));
5813 __ bind(deferred->exit());
5818 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
5819 Register context = ToRegister(instr->context());
5820 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
5824 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
5825 Handle<ScopeInfo> scope_info = instr->scope_info();
5826 __ Push(scope_info);
5827 __ push(ToRegister(instr->function()));
5828 CallRuntime(Runtime::kPushBlockContext, 2, instr);
5829 RecordSafepoint(Safepoint::kNoLazyDeopt);
5835 } // namespace internal
5838 #endif // V8_TARGET_ARCH_IA32