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/deoptimizer.h"
14 #include "src/hydrogen-osr.h"
15 #include "src/ia32/lithium-codegen-ia32.h"
16 #include "src/ic/ic.h"
17 #include "src/ic/stub-cache.h"
22 // When invoking builtins, we need to record the safepoint in the middle of
23 // the invoke instruction sequence generated by the macro assembler.
24 class SafepointGenerator FINAL : public CallWrapper {
26 SafepointGenerator(LCodeGen* codegen,
27 LPointerMap* pointers,
28 Safepoint::DeoptMode mode)
32 virtual ~SafepointGenerator() {}
34 void BeforeCall(int call_size) const OVERRIDE {}
36 void AfterCall() const OVERRIDE {
37 codegen_->RecordSafepoint(pointers_, deopt_mode_);
42 LPointerMap* pointers_;
43 Safepoint::DeoptMode deopt_mode_;
49 bool LCodeGen::GenerateCode() {
50 LPhase phase("Z_Code generation", chunk());
54 // Open a frame scope to indicate that there is a frame on the stack. The
55 // MANUAL indicates that the scope shouldn't actually generate code to set up
56 // the frame (that is done in GeneratePrologue).
57 FrameScope frame_scope(masm_, StackFrame::MANUAL);
59 support_aligned_spilled_doubles_ = info()->IsOptimizing();
61 dynamic_frame_alignment_ = info()->IsOptimizing() &&
62 ((chunk()->num_double_slots() > 2 &&
63 !chunk()->graph()->is_recursive()) ||
64 !info()->osr_ast_id().IsNone());
66 return GeneratePrologue() &&
68 GenerateDeferredCode() &&
69 GenerateJumpTable() &&
70 GenerateSafepointTable();
74 void LCodeGen::FinishCode(Handle<Code> code) {
76 code->set_stack_slots(GetStackSlotCount());
77 code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
78 PopulateDeoptimizationData(code);
79 if (!info()->IsStub()) {
80 Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(code);
86 void LCodeGen::MakeSureStackPagesMapped(int offset) {
87 const int kPageSize = 4 * KB;
88 for (offset -= kPageSize; offset > 0; offset -= kPageSize) {
89 __ mov(Operand(esp, offset), eax);
95 void LCodeGen::SaveCallerDoubles() {
96 DCHECK(info()->saves_caller_doubles());
97 DCHECK(NeedsEagerFrame());
98 Comment(";;; Save clobbered callee double registers");
100 BitVector* doubles = chunk()->allocated_double_registers();
101 BitVector::Iterator save_iterator(doubles);
102 while (!save_iterator.Done()) {
103 __ movsd(MemOperand(esp, count * kDoubleSize),
104 XMMRegister::FromAllocationIndex(save_iterator.Current()));
105 save_iterator.Advance();
111 void LCodeGen::RestoreCallerDoubles() {
112 DCHECK(info()->saves_caller_doubles());
113 DCHECK(NeedsEagerFrame());
114 Comment(";;; Restore clobbered callee double registers");
115 BitVector* doubles = chunk()->allocated_double_registers();
116 BitVector::Iterator save_iterator(doubles);
118 while (!save_iterator.Done()) {
119 __ movsd(XMMRegister::FromAllocationIndex(save_iterator.Current()),
120 MemOperand(esp, count * kDoubleSize));
121 save_iterator.Advance();
127 bool LCodeGen::GeneratePrologue() {
128 DCHECK(is_generating());
130 if (info()->IsOptimizing()) {
131 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
134 if (strlen(FLAG_stop_at) > 0 &&
135 info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
140 // Sloppy mode functions and builtins need to replace the receiver with the
141 // global proxy when called as functions (without an explicit receiver
143 if (info_->this_has_uses() && is_sloppy(info_->language_mode()) &&
144 !info_->is_native()) {
146 // +1 for return address.
147 int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
148 __ mov(ecx, Operand(esp, receiver_offset));
150 __ cmp(ecx, isolate()->factory()->undefined_value());
151 __ j(not_equal, &ok, Label::kNear);
153 __ mov(ecx, GlobalObjectOperand());
154 __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
156 __ mov(Operand(esp, receiver_offset), ecx);
161 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
162 // Move state of dynamic frame alignment into edx.
163 __ Move(edx, Immediate(kNoAlignmentPadding));
165 Label do_not_pad, align_loop;
166 STATIC_ASSERT(kDoubleSize == 2 * kPointerSize);
167 // Align esp + 4 to a multiple of 2 * kPointerSize.
168 __ test(esp, Immediate(kPointerSize));
169 __ j(not_zero, &do_not_pad, Label::kNear);
170 __ push(Immediate(0));
172 __ mov(edx, Immediate(kAlignmentPaddingPushed));
173 // Copy arguments, receiver, and return address.
174 __ mov(ecx, Immediate(scope()->num_parameters() + 2));
176 __ bind(&align_loop);
177 __ mov(eax, Operand(ebx, 1 * kPointerSize));
178 __ mov(Operand(ebx, 0), eax);
179 __ add(Operand(ebx), Immediate(kPointerSize));
181 __ j(not_zero, &align_loop, Label::kNear);
182 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
183 __ bind(&do_not_pad);
187 info()->set_prologue_offset(masm_->pc_offset());
188 if (NeedsEagerFrame()) {
189 DCHECK(!frame_is_built_);
190 frame_is_built_ = true;
191 if (info()->IsStub()) {
194 __ Prologue(info()->IsCodePreAgingActive());
196 info()->AddNoFrameRange(0, masm_->pc_offset());
199 if (info()->IsOptimizing() &&
200 dynamic_frame_alignment_ &&
202 __ test(esp, Immediate(kPointerSize));
203 __ Assert(zero, kFrameIsExpectedToBeAligned);
206 // Reserve space for the stack slots needed by the code.
207 int slots = GetStackSlotCount();
208 DCHECK(slots != 0 || !info()->IsOptimizing());
211 if (dynamic_frame_alignment_) {
214 __ push(Immediate(kNoAlignmentPadding));
217 if (FLAG_debug_code) {
218 __ sub(Operand(esp), Immediate(slots * kPointerSize));
220 MakeSureStackPagesMapped(slots * kPointerSize);
223 __ mov(Operand(eax), Immediate(slots));
226 __ mov(MemOperand(esp, eax, times_4, 0),
227 Immediate(kSlotsZapValue));
229 __ j(not_zero, &loop);
232 __ sub(Operand(esp), Immediate(slots * kPointerSize));
234 MakeSureStackPagesMapped(slots * kPointerSize);
238 if (support_aligned_spilled_doubles_) {
239 Comment(";;; Store dynamic frame alignment tag for spilled doubles");
240 // Store dynamic frame alignment state in the first local.
241 int offset = JavaScriptFrameConstants::kDynamicAlignmentStateOffset;
242 if (dynamic_frame_alignment_) {
243 __ mov(Operand(ebp, offset), edx);
245 __ mov(Operand(ebp, offset), Immediate(kNoAlignmentPadding));
250 if (info()->saves_caller_doubles()) SaveCallerDoubles();
253 // Possibly allocate a local context.
254 int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
255 if (heap_slots > 0) {
256 Comment(";;; Allocate local context");
257 bool need_write_barrier = true;
258 // Argument to NewContext is the function, which is still in edi.
259 if (heap_slots <= FastNewContextStub::kMaximumSlots) {
260 FastNewContextStub stub(isolate(), heap_slots);
262 // Result of FastNewContextStub is always in new space.
263 need_write_barrier = false;
266 __ CallRuntime(Runtime::kNewFunctionContext, 1);
268 RecordSafepoint(Safepoint::kNoLazyDeopt);
269 // Context is returned in eax. It replaces the context passed to us.
270 // It's saved in the stack and kept live in esi.
272 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);
274 // Copy parameters into context if necessary.
275 int num_parameters = scope()->num_parameters();
276 for (int i = 0; i < num_parameters; i++) {
277 Variable* var = scope()->parameter(i);
278 if (var->IsContextSlot()) {
279 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
280 (num_parameters - 1 - i) * kPointerSize;
281 // Load parameter from stack.
282 __ mov(eax, Operand(ebp, parameter_offset));
283 // Store it in the context.
284 int context_offset = Context::SlotOffset(var->index());
285 __ mov(Operand(esi, context_offset), eax);
286 // Update the write barrier. This clobbers eax and ebx.
287 if (need_write_barrier) {
288 __ RecordWriteContextSlot(esi,
293 } else if (FLAG_debug_code) {
295 __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
296 __ Abort(kExpectedNewSpaceObject);
301 Comment(";;; End allocate local context");
305 if (FLAG_trace && info()->IsOptimizing()) {
306 // We have not executed any compiled code yet, so esi still holds the
308 __ CallRuntime(Runtime::kTraceEnter, 0);
310 return !is_aborted();
314 void LCodeGen::GenerateOsrPrologue() {
315 // Generate the OSR entry prologue at the first unknown OSR value, or if there
316 // are none, at the OSR entrypoint instruction.
317 if (osr_pc_offset_ >= 0) return;
319 osr_pc_offset_ = masm()->pc_offset();
321 // Move state of dynamic frame alignment into edx.
322 __ Move(edx, Immediate(kNoAlignmentPadding));
324 if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
325 Label do_not_pad, align_loop;
326 // Align ebp + 4 to a multiple of 2 * kPointerSize.
327 __ test(ebp, Immediate(kPointerSize));
328 __ j(zero, &do_not_pad, Label::kNear);
329 __ push(Immediate(0));
331 __ mov(edx, Immediate(kAlignmentPaddingPushed));
333 // Move all parts of the frame over one word. The frame consists of:
334 // unoptimized frame slots, alignment state, context, frame pointer, return
335 // address, receiver, and the arguments.
336 __ mov(ecx, Immediate(scope()->num_parameters() +
337 5 + graph()->osr()->UnoptimizedFrameSlots()));
339 __ bind(&align_loop);
340 __ mov(eax, Operand(ebx, 1 * kPointerSize));
341 __ mov(Operand(ebx, 0), eax);
342 __ add(Operand(ebx), Immediate(kPointerSize));
344 __ j(not_zero, &align_loop, Label::kNear);
345 __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
346 __ sub(Operand(ebp), Immediate(kPointerSize));
347 __ bind(&do_not_pad);
350 // Save the first local, which is overwritten by the alignment state.
351 Operand alignment_loc = MemOperand(ebp, -3 * kPointerSize);
352 __ push(alignment_loc);
354 // Set the dynamic frame alignment state.
355 __ mov(alignment_loc, edx);
357 // Adjust the frame size, subsuming the unoptimized frame into the
359 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
361 __ sub(esp, Immediate((slots - 1) * kPointerSize));
365 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
366 if (instr->IsCall()) {
367 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
369 if (!instr->IsLazyBailout() && !instr->IsGap()) {
370 safepoints_.BumpLastLazySafepointIndex();
375 void LCodeGen::GenerateBodyInstructionPost(LInstruction* instr) { }
378 bool LCodeGen::GenerateJumpTable() {
380 if (jump_table_.length() > 0) {
381 Comment(";;; -------------------- Jump table --------------------");
383 for (int i = 0; i < jump_table_.length(); i++) {
384 Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
385 __ bind(&table_entry->label);
386 Address entry = table_entry->address;
387 DeoptComment(table_entry->deopt_info);
388 if (table_entry->needs_frame) {
389 DCHECK(!info()->saves_caller_doubles());
390 __ push(Immediate(ExternalReference::ForDeoptEntry(entry)));
391 if (needs_frame.is_bound()) {
392 __ jmp(&needs_frame);
394 __ bind(&needs_frame);
395 __ push(MemOperand(ebp, StandardFrameConstants::kContextOffset));
396 // This variant of deopt can only be used with stubs. Since we don't
397 // have a function pointer to install in the stack frame that we're
398 // building, install a special marker there instead.
399 DCHECK(info()->IsStub());
400 __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
401 // Push a PC inside the function so that the deopt code can find where
402 // the deopt comes from. It doesn't have to be the precise return
403 // address of a "calling" LAZY deopt, it only has to be somewhere
404 // inside the code body.
405 Label push_approx_pc;
406 __ call(&push_approx_pc);
407 __ bind(&push_approx_pc);
408 // Push the continuation which was stashed were the ebp should
409 // be. Replace it with the saved ebp.
410 __ push(MemOperand(esp, 3 * kPointerSize));
411 __ mov(MemOperand(esp, 4 * kPointerSize), ebp);
412 __ lea(ebp, MemOperand(esp, 4 * kPointerSize));
413 __ ret(0); // Call the continuation without clobbering registers.
416 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
417 __ call(entry, RelocInfo::RUNTIME_ENTRY);
420 return !is_aborted();
424 bool LCodeGen::GenerateDeferredCode() {
425 DCHECK(is_generating());
426 if (deferred_.length() > 0) {
427 for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
428 LDeferredCode* code = deferred_[i];
431 instructions_->at(code->instruction_index())->hydrogen_value();
432 RecordAndWritePosition(
433 chunk()->graph()->SourcePositionToScriptPosition(value->position()));
435 Comment(";;; <@%d,#%d> "
436 "-------------------- Deferred %s --------------------",
437 code->instruction_index(),
438 code->instr()->hydrogen_value()->id(),
439 code->instr()->Mnemonic());
440 __ bind(code->entry());
441 if (NeedsDeferredFrame()) {
442 Comment(";;; Build frame");
443 DCHECK(!frame_is_built_);
444 DCHECK(info()->IsStub());
445 frame_is_built_ = true;
446 // Build the frame in such a way that esi isn't trashed.
447 __ push(ebp); // Caller's frame pointer.
448 __ push(Operand(ebp, StandardFrameConstants::kContextOffset));
449 __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
450 __ lea(ebp, Operand(esp, 2 * kPointerSize));
451 Comment(";;; Deferred code");
454 if (NeedsDeferredFrame()) {
455 __ bind(code->done());
456 Comment(";;; Destroy frame");
457 DCHECK(frame_is_built_);
458 frame_is_built_ = false;
462 __ jmp(code->exit());
466 // Deferred code is the last part of the instruction sequence. Mark
467 // the generated code as done unless we bailed out.
468 if (!is_aborted()) status_ = DONE;
469 return !is_aborted();
473 bool LCodeGen::GenerateSafepointTable() {
475 if (!info()->IsStub()) {
476 // For lazy deoptimization we need space to patch a call after every call.
477 // Ensure there is always space for such patching, even if the code ends
479 int target_offset = masm()->pc_offset() + Deoptimizer::patch_size();
480 while (masm()->pc_offset() < target_offset) {
484 safepoints_.Emit(masm(), GetStackSlotCount());
485 return !is_aborted();
489 Register LCodeGen::ToRegister(int index) const {
490 return Register::FromAllocationIndex(index);
494 XMMRegister LCodeGen::ToDoubleRegister(int index) const {
495 return XMMRegister::FromAllocationIndex(index);
499 Register LCodeGen::ToRegister(LOperand* op) const {
500 DCHECK(op->IsRegister());
501 return ToRegister(op->index());
505 XMMRegister LCodeGen::ToDoubleRegister(LOperand* op) const {
506 DCHECK(op->IsDoubleRegister());
507 return ToDoubleRegister(op->index());
511 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
512 return ToRepresentation(op, Representation::Integer32());
516 int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
517 const Representation& r) const {
518 HConstant* constant = chunk_->LookupConstant(op);
519 int32_t value = constant->Integer32Value();
520 if (r.IsInteger32()) return value;
521 DCHECK(r.IsSmiOrTagged());
522 return reinterpret_cast<int32_t>(Smi::FromInt(value));
526 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
527 HConstant* constant = chunk_->LookupConstant(op);
528 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
529 return constant->handle(isolate());
533 double LCodeGen::ToDouble(LConstantOperand* op) const {
534 HConstant* constant = chunk_->LookupConstant(op);
535 DCHECK(constant->HasDoubleValue());
536 return constant->DoubleValue();
540 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
541 HConstant* constant = chunk_->LookupConstant(op);
542 DCHECK(constant->HasExternalReferenceValue());
543 return constant->ExternalReferenceValue();
547 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
548 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
552 bool LCodeGen::IsSmi(LConstantOperand* op) const {
553 return chunk_->LookupLiteralRepresentation(op).IsSmi();
557 static int ArgumentsOffsetWithoutFrame(int index) {
559 return -(index + 1) * kPointerSize + kPCOnStackSize;
563 Operand LCodeGen::ToOperand(LOperand* op) const {
564 if (op->IsRegister()) return Operand(ToRegister(op));
565 if (op->IsDoubleRegister()) return Operand(ToDoubleRegister(op));
566 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
567 if (NeedsEagerFrame()) {
568 return Operand(ebp, StackSlotOffset(op->index()));
570 // Retrieve parameter without eager stack-frame relative to the
572 return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
577 Operand LCodeGen::HighOperand(LOperand* op) {
578 DCHECK(op->IsDoubleStackSlot());
579 if (NeedsEagerFrame()) {
580 return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
582 // Retrieve parameter without eager stack-frame relative to the
585 esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
590 void LCodeGen::WriteTranslation(LEnvironment* environment,
591 Translation* translation) {
592 if (environment == NULL) return;
594 // The translation includes one command per value in the environment.
595 int translation_size = environment->translation_size();
596 // The output frame height does not include the parameters.
597 int height = translation_size - environment->parameter_count();
599 WriteTranslation(environment->outer(), translation);
600 bool has_closure_id = !info()->closure().is_null() &&
601 !info()->closure().is_identical_to(environment->closure());
602 int closure_id = has_closure_id
603 ? DefineDeoptimizationLiteral(environment->closure())
604 : Translation::kSelfLiteralId;
605 switch (environment->frame_type()) {
607 translation->BeginJSFrame(environment->ast_id(), closure_id, height);
610 translation->BeginConstructStubFrame(closure_id, translation_size);
613 DCHECK(translation_size == 1);
615 translation->BeginGetterStubFrame(closure_id);
618 DCHECK(translation_size == 2);
620 translation->BeginSetterStubFrame(closure_id);
622 case ARGUMENTS_ADAPTOR:
623 translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
626 translation->BeginCompiledStubFrame();
632 int object_index = 0;
633 int dematerialized_index = 0;
634 for (int i = 0; i < translation_size; ++i) {
635 LOperand* value = environment->values()->at(i);
636 AddToTranslation(environment,
639 environment->HasTaggedValueAt(i),
640 environment->HasUint32ValueAt(i),
642 &dematerialized_index);
647 void LCodeGen::AddToTranslation(LEnvironment* environment,
648 Translation* translation,
652 int* object_index_pointer,
653 int* dematerialized_index_pointer) {
654 if (op == LEnvironment::materialization_marker()) {
655 int object_index = (*object_index_pointer)++;
656 if (environment->ObjectIsDuplicateAt(object_index)) {
657 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
658 translation->DuplicateObject(dupe_of);
661 int object_length = environment->ObjectLengthAt(object_index);
662 if (environment->ObjectIsArgumentsAt(object_index)) {
663 translation->BeginArgumentsObject(object_length);
665 translation->BeginCapturedObject(object_length);
667 int dematerialized_index = *dematerialized_index_pointer;
668 int env_offset = environment->translation_size() + dematerialized_index;
669 *dematerialized_index_pointer += object_length;
670 for (int i = 0; i < object_length; ++i) {
671 LOperand* value = environment->values()->at(env_offset + i);
672 AddToTranslation(environment,
675 environment->HasTaggedValueAt(env_offset + i),
676 environment->HasUint32ValueAt(env_offset + i),
677 object_index_pointer,
678 dematerialized_index_pointer);
683 if (op->IsStackSlot()) {
685 translation->StoreStackSlot(op->index());
686 } else if (is_uint32) {
687 translation->StoreUint32StackSlot(op->index());
689 translation->StoreInt32StackSlot(op->index());
691 } else if (op->IsDoubleStackSlot()) {
692 translation->StoreDoubleStackSlot(op->index());
693 } else if (op->IsRegister()) {
694 Register reg = ToRegister(op);
696 translation->StoreRegister(reg);
697 } else if (is_uint32) {
698 translation->StoreUint32Register(reg);
700 translation->StoreInt32Register(reg);
702 } else if (op->IsDoubleRegister()) {
703 XMMRegister reg = ToDoubleRegister(op);
704 translation->StoreDoubleRegister(reg);
705 } else if (op->IsConstantOperand()) {
706 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
707 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
708 translation->StoreLiteral(src_index);
715 void LCodeGen::CallCodeGeneric(Handle<Code> code,
716 RelocInfo::Mode mode,
718 SafepointMode safepoint_mode) {
719 DCHECK(instr != NULL);
721 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
723 // Signal that we don't inline smi code before these stubs in the
724 // optimizing code generator.
725 if (code->kind() == Code::BINARY_OP_IC ||
726 code->kind() == Code::COMPARE_IC) {
732 void LCodeGen::CallCode(Handle<Code> code,
733 RelocInfo::Mode mode,
734 LInstruction* instr) {
735 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
739 void LCodeGen::CallRuntime(const Runtime::Function* fun,
742 SaveFPRegsMode save_doubles) {
743 DCHECK(instr != NULL);
744 DCHECK(instr->HasPointerMap());
746 __ CallRuntime(fun, argc, save_doubles);
748 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
750 DCHECK(info()->is_calling());
754 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
755 if (context->IsRegister()) {
756 if (!ToRegister(context).is(esi)) {
757 __ mov(esi, ToRegister(context));
759 } else if (context->IsStackSlot()) {
760 __ mov(esi, ToOperand(context));
761 } else if (context->IsConstantOperand()) {
762 HConstant* constant =
763 chunk_->LookupConstant(LConstantOperand::cast(context));
764 __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
770 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
774 LoadContextFromDeferred(context);
776 __ CallRuntimeSaveDoubles(id);
777 RecordSafepointWithRegisters(
778 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
780 DCHECK(info()->is_calling());
784 void LCodeGen::RegisterEnvironmentForDeoptimization(
785 LEnvironment* environment, Safepoint::DeoptMode mode) {
786 environment->set_has_been_used();
787 if (!environment->HasBeenRegistered()) {
788 // Physical stack frame layout:
789 // -x ............. -4 0 ..................................... y
790 // [incoming arguments] [spill slots] [pushed outgoing arguments]
792 // Layout of the environment:
793 // 0 ..................................................... size-1
794 // [parameters] [locals] [expression stack including arguments]
796 // Layout of the translation:
797 // 0 ........................................................ size - 1 + 4
798 // [expression stack including arguments] [locals] [4 words] [parameters]
799 // |>------------ translation_size ------------<|
802 int jsframe_count = 0;
803 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
805 if (e->frame_type() == JS_FUNCTION) {
809 Translation translation(&translations_, frame_count, jsframe_count, zone());
810 WriteTranslation(environment, &translation);
811 int deoptimization_index = deoptimizations_.length();
812 int pc_offset = masm()->pc_offset();
813 environment->Register(deoptimization_index,
815 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
816 deoptimizations_.Add(environment, zone());
821 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
822 Deoptimizer::DeoptReason deopt_reason,
823 Deoptimizer::BailoutType bailout_type) {
824 LEnvironment* environment = instr->environment();
825 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
826 DCHECK(environment->HasBeenRegistered());
827 int id = environment->deoptimization_index();
828 DCHECK(info()->IsOptimizing() || info()->IsStub());
830 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
832 Abort(kBailoutWasNotPrepared);
836 if (DeoptEveryNTimes()) {
837 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
841 __ mov(eax, Operand::StaticVariable(count));
842 __ sub(eax, Immediate(1));
843 __ j(not_zero, &no_deopt, Label::kNear);
844 if (FLAG_trap_on_deopt) __ int3();
845 __ mov(eax, Immediate(FLAG_deopt_every_n_times));
846 __ mov(Operand::StaticVariable(count), eax);
849 DCHECK(frame_is_built_);
850 __ call(entry, RelocInfo::RUNTIME_ENTRY);
852 __ mov(Operand::StaticVariable(count), eax);
857 if (info()->ShouldTrapOnDeopt()) {
859 if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
864 Deoptimizer::DeoptInfo deopt_info(instr->hydrogen_value()->position().raw(),
865 instr->Mnemonic(), deopt_reason);
866 DCHECK(info()->IsStub() || frame_is_built_);
867 if (cc == no_condition && frame_is_built_) {
868 DeoptComment(deopt_info);
869 __ call(entry, RelocInfo::RUNTIME_ENTRY);
871 Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
873 // We often have several deopts to the same entry, reuse the last
874 // jump entry if this is the case.
875 if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
876 jump_table_.is_empty() ||
877 !table_entry.IsEquivalentTo(jump_table_.last())) {
878 jump_table_.Add(table_entry, zone());
880 if (cc == no_condition) {
881 __ jmp(&jump_table_.last().label);
883 __ j(cc, &jump_table_.last().label);
889 void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
890 Deoptimizer::DeoptReason deopt_reason) {
891 Deoptimizer::BailoutType bailout_type = info()->IsStub()
893 : Deoptimizer::EAGER;
894 DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
898 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
899 int length = deoptimizations_.length();
900 if (length == 0) return;
901 Handle<DeoptimizationInputData> data =
902 DeoptimizationInputData::New(isolate(), length, TENURED);
904 Handle<ByteArray> translations =
905 translations_.CreateByteArray(isolate()->factory());
906 data->SetTranslationByteArray(*translations);
907 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
908 data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
909 if (info_->IsOptimizing()) {
910 // Reference to shared function info does not change between phases.
911 AllowDeferredHandleDereference allow_handle_dereference;
912 data->SetSharedFunctionInfo(*info_->shared_info());
914 data->SetSharedFunctionInfo(Smi::FromInt(0));
916 data->SetWeakCellCache(Smi::FromInt(0));
918 Handle<FixedArray> literals =
919 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
920 { AllowDeferredHandleDereference copy_handles;
921 for (int i = 0; i < deoptimization_literals_.length(); i++) {
922 literals->set(i, *deoptimization_literals_[i]);
924 data->SetLiteralArray(*literals);
927 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
928 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
930 // Populate the deoptimization entries.
931 for (int i = 0; i < length; i++) {
932 LEnvironment* env = deoptimizations_[i];
933 data->SetAstId(i, env->ast_id());
934 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
935 data->SetArgumentsStackHeight(i,
936 Smi::FromInt(env->arguments_stack_height()));
937 data->SetPc(i, Smi::FromInt(env->pc_offset()));
939 code->set_deoptimization_data(*data);
943 int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
944 int result = deoptimization_literals_.length();
945 for (int i = 0; i < deoptimization_literals_.length(); ++i) {
946 if (deoptimization_literals_[i].is_identical_to(literal)) return i;
948 deoptimization_literals_.Add(literal, zone());
953 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
954 DCHECK(deoptimization_literals_.length() == 0);
956 const ZoneList<Handle<JSFunction> >* inlined_closures =
957 chunk()->inlined_closures();
959 for (int i = 0, length = inlined_closures->length();
962 DefineDeoptimizationLiteral(inlined_closures->at(i));
965 inlined_function_count_ = deoptimization_literals_.length();
969 void LCodeGen::RecordSafepointWithLazyDeopt(
970 LInstruction* instr, SafepointMode safepoint_mode) {
971 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
972 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
974 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
975 RecordSafepointWithRegisters(
976 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
981 void LCodeGen::RecordSafepoint(
982 LPointerMap* pointers,
983 Safepoint::Kind kind,
985 Safepoint::DeoptMode deopt_mode) {
986 DCHECK(kind == expected_safepoint_kind_);
987 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
988 Safepoint safepoint =
989 safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
990 for (int i = 0; i < operands->length(); i++) {
991 LOperand* pointer = operands->at(i);
992 if (pointer->IsStackSlot()) {
993 safepoint.DefinePointerSlot(pointer->index(), zone());
994 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
995 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
1001 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
1002 Safepoint::DeoptMode mode) {
1003 RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
1007 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
1008 LPointerMap empty_pointers(zone());
1009 RecordSafepoint(&empty_pointers, mode);
1013 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
1015 Safepoint::DeoptMode mode) {
1016 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
1020 void LCodeGen::RecordAndWritePosition(int position) {
1021 if (position == RelocInfo::kNoPosition) return;
1022 masm()->positions_recorder()->RecordPosition(position);
1023 masm()->positions_recorder()->WriteRecordedPositions();
1027 static const char* LabelType(LLabel* label) {
1028 if (label->is_loop_header()) return " (loop header)";
1029 if (label->is_osr_entry()) return " (OSR entry)";
1034 void LCodeGen::DoLabel(LLabel* label) {
1035 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
1036 current_instruction_,
1037 label->hydrogen_value()->id(),
1040 __ bind(label->label());
1041 current_block_ = label->block_id();
1046 void LCodeGen::DoParallelMove(LParallelMove* move) {
1047 resolver_.Resolve(move);
1051 void LCodeGen::DoGap(LGap* gap) {
1052 for (int i = LGap::FIRST_INNER_POSITION;
1053 i <= LGap::LAST_INNER_POSITION;
1055 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
1056 LParallelMove* move = gap->GetParallelMove(inner_pos);
1057 if (move != NULL) DoParallelMove(move);
1062 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
1067 void LCodeGen::DoParameter(LParameter* instr) {
1072 void LCodeGen::DoCallStub(LCallStub* instr) {
1073 DCHECK(ToRegister(instr->context()).is(esi));
1074 DCHECK(ToRegister(instr->result()).is(eax));
1075 switch (instr->hydrogen()->major_key()) {
1076 case CodeStub::RegExpExec: {
1077 RegExpExecStub stub(isolate());
1078 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1081 case CodeStub::SubString: {
1082 SubStringStub stub(isolate());
1083 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1086 case CodeStub::StringCompare: {
1087 StringCompareStub stub(isolate());
1088 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
1097 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
1098 GenerateOsrPrologue();
1102 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
1103 Register dividend = ToRegister(instr->dividend());
1104 int32_t divisor = instr->divisor();
1105 DCHECK(dividend.is(ToRegister(instr->result())));
1107 // Theoretically, a variation of the branch-free code for integer division by
1108 // a power of 2 (calculating the remainder via an additional multiplication
1109 // (which gets simplified to an 'and') and subtraction) should be faster, and
1110 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
1111 // indicate that positive dividends are heavily favored, so the branching
1112 // version performs better.
1113 HMod* hmod = instr->hydrogen();
1114 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1115 Label dividend_is_not_negative, done;
1116 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
1117 __ test(dividend, dividend);
1118 __ j(not_sign, ÷nd_is_not_negative, Label::kNear);
1119 // Note that this is correct even for kMinInt operands.
1121 __ and_(dividend, mask);
1123 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1124 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1126 __ jmp(&done, Label::kNear);
1129 __ bind(÷nd_is_not_negative);
1130 __ and_(dividend, mask);
1135 void LCodeGen::DoModByConstI(LModByConstI* instr) {
1136 Register dividend = ToRegister(instr->dividend());
1137 int32_t divisor = instr->divisor();
1138 DCHECK(ToRegister(instr->result()).is(eax));
1141 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1145 __ TruncatingDiv(dividend, Abs(divisor));
1146 __ imul(edx, edx, Abs(divisor));
1147 __ mov(eax, dividend);
1150 // Check for negative zero.
1151 HMod* hmod = instr->hydrogen();
1152 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1153 Label remainder_not_zero;
1154 __ j(not_zero, &remainder_not_zero, Label::kNear);
1155 __ cmp(dividend, Immediate(0));
1156 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1157 __ bind(&remainder_not_zero);
1162 void LCodeGen::DoModI(LModI* instr) {
1163 HMod* hmod = instr->hydrogen();
1165 Register left_reg = ToRegister(instr->left());
1166 DCHECK(left_reg.is(eax));
1167 Register right_reg = ToRegister(instr->right());
1168 DCHECK(!right_reg.is(eax));
1169 DCHECK(!right_reg.is(edx));
1170 Register result_reg = ToRegister(instr->result());
1171 DCHECK(result_reg.is(edx));
1174 // Check for x % 0, idiv would signal a divide error. We have to
1175 // deopt in this case because we can't return a NaN.
1176 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1177 __ test(right_reg, Operand(right_reg));
1178 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1181 // Check for kMinInt % -1, idiv would signal a divide error. We
1182 // have to deopt if we care about -0, because we can't return that.
1183 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1184 Label no_overflow_possible;
1185 __ cmp(left_reg, kMinInt);
1186 __ j(not_equal, &no_overflow_possible, Label::kNear);
1187 __ cmp(right_reg, -1);
1188 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1189 DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
1191 __ j(not_equal, &no_overflow_possible, Label::kNear);
1192 __ Move(result_reg, Immediate(0));
1193 __ jmp(&done, Label::kNear);
1195 __ bind(&no_overflow_possible);
1198 // Sign extend dividend in eax into edx:eax.
1201 // If we care about -0, test if the dividend is <0 and the result is 0.
1202 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1203 Label positive_left;
1204 __ test(left_reg, Operand(left_reg));
1205 __ j(not_sign, &positive_left, Label::kNear);
1207 __ test(result_reg, Operand(result_reg));
1208 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1209 __ jmp(&done, Label::kNear);
1210 __ bind(&positive_left);
1217 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1218 Register dividend = ToRegister(instr->dividend());
1219 int32_t divisor = instr->divisor();
1220 Register result = ToRegister(instr->result());
1221 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1222 DCHECK(!result.is(dividend));
1224 // Check for (0 / -x) that will produce negative zero.
1225 HDiv* hdiv = instr->hydrogen();
1226 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1227 __ test(dividend, dividend);
1228 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1230 // Check for (kMinInt / -1).
1231 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1232 __ cmp(dividend, kMinInt);
1233 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1235 // Deoptimize if remainder will not be 0.
1236 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1237 divisor != 1 && divisor != -1) {
1238 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1239 __ test(dividend, Immediate(mask));
1240 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1242 __ Move(result, dividend);
1243 int32_t shift = WhichPowerOf2Abs(divisor);
1245 // The arithmetic shift is always OK, the 'if' is an optimization only.
1246 if (shift > 1) __ sar(result, 31);
1247 __ shr(result, 32 - shift);
1248 __ add(result, dividend);
1249 __ sar(result, shift);
1251 if (divisor < 0) __ neg(result);
1255 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1256 Register dividend = ToRegister(instr->dividend());
1257 int32_t divisor = instr->divisor();
1258 DCHECK(ToRegister(instr->result()).is(edx));
1261 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1265 // Check for (0 / -x) that will produce negative zero.
1266 HDiv* hdiv = instr->hydrogen();
1267 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1268 __ test(dividend, dividend);
1269 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1272 __ TruncatingDiv(dividend, Abs(divisor));
1273 if (divisor < 0) __ neg(edx);
1275 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1277 __ imul(eax, eax, divisor);
1278 __ sub(eax, dividend);
1279 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
1284 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
1285 void LCodeGen::DoDivI(LDivI* instr) {
1286 HBinaryOperation* hdiv = instr->hydrogen();
1287 Register dividend = ToRegister(instr->dividend());
1288 Register divisor = ToRegister(instr->divisor());
1289 Register remainder = ToRegister(instr->temp());
1290 DCHECK(dividend.is(eax));
1291 DCHECK(remainder.is(edx));
1292 DCHECK(ToRegister(instr->result()).is(eax));
1293 DCHECK(!divisor.is(eax));
1294 DCHECK(!divisor.is(edx));
1297 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1298 __ test(divisor, divisor);
1299 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1302 // Check for (0 / -x) that will produce negative zero.
1303 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1304 Label dividend_not_zero;
1305 __ test(dividend, dividend);
1306 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1307 __ test(divisor, divisor);
1308 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1309 __ bind(÷nd_not_zero);
1312 // Check for (kMinInt / -1).
1313 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1314 Label dividend_not_min_int;
1315 __ cmp(dividend, kMinInt);
1316 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1317 __ cmp(divisor, -1);
1318 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1319 __ bind(÷nd_not_min_int);
1322 // Sign extend to edx (= remainder).
1326 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1327 // Deoptimize if remainder is not 0.
1328 __ test(remainder, remainder);
1329 DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
1334 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1335 Register dividend = ToRegister(instr->dividend());
1336 int32_t divisor = instr->divisor();
1337 DCHECK(dividend.is(ToRegister(instr->result())));
1339 // If the divisor is positive, things are easy: There can be no deopts and we
1340 // can simply do an arithmetic right shift.
1341 if (divisor == 1) return;
1342 int32_t shift = WhichPowerOf2Abs(divisor);
1344 __ sar(dividend, shift);
1348 // If the divisor is negative, we have to negate and handle edge cases.
1350 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1351 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1354 // Dividing by -1 is basically negation, unless we overflow.
1355 if (divisor == -1) {
1356 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1357 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1362 // If the negation could not overflow, simply shifting is OK.
1363 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1364 __ sar(dividend, shift);
1368 Label not_kmin_int, done;
1369 __ j(no_overflow, ¬_kmin_int, Label::kNear);
1370 __ mov(dividend, Immediate(kMinInt / divisor));
1371 __ jmp(&done, Label::kNear);
1372 __ bind(¬_kmin_int);
1373 __ sar(dividend, shift);
1378 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1379 Register dividend = ToRegister(instr->dividend());
1380 int32_t divisor = instr->divisor();
1381 DCHECK(ToRegister(instr->result()).is(edx));
1384 DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
1388 // Check for (0 / -x) that will produce negative zero.
1389 HMathFloorOfDiv* hdiv = instr->hydrogen();
1390 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1391 __ test(dividend, dividend);
1392 DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
1395 // Easy case: We need no dynamic check for the dividend and the flooring
1396 // division is the same as the truncating division.
1397 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1398 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1399 __ TruncatingDiv(dividend, Abs(divisor));
1400 if (divisor < 0) __ neg(edx);
1404 // In the general case we may need to adjust before and after the truncating
1405 // division to get a flooring division.
1406 Register temp = ToRegister(instr->temp3());
1407 DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
1408 Label needs_adjustment, done;
1409 __ cmp(dividend, Immediate(0));
1410 __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
1411 __ TruncatingDiv(dividend, Abs(divisor));
1412 if (divisor < 0) __ neg(edx);
1413 __ jmp(&done, Label::kNear);
1414 __ bind(&needs_adjustment);
1415 __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
1416 __ TruncatingDiv(temp, Abs(divisor));
1417 if (divisor < 0) __ neg(edx);
1423 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
1424 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1425 HBinaryOperation* hdiv = instr->hydrogen();
1426 Register dividend = ToRegister(instr->dividend());
1427 Register divisor = ToRegister(instr->divisor());
1428 Register remainder = ToRegister(instr->temp());
1429 Register result = ToRegister(instr->result());
1430 DCHECK(dividend.is(eax));
1431 DCHECK(remainder.is(edx));
1432 DCHECK(result.is(eax));
1433 DCHECK(!divisor.is(eax));
1434 DCHECK(!divisor.is(edx));
1437 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1438 __ test(divisor, divisor);
1439 DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
1442 // Check for (0 / -x) that will produce negative zero.
1443 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1444 Label dividend_not_zero;
1445 __ test(dividend, dividend);
1446 __ j(not_zero, ÷nd_not_zero, Label::kNear);
1447 __ test(divisor, divisor);
1448 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1449 __ bind(÷nd_not_zero);
1452 // Check for (kMinInt / -1).
1453 if (hdiv->CheckFlag(HValue::kCanOverflow)) {
1454 Label dividend_not_min_int;
1455 __ cmp(dividend, kMinInt);
1456 __ j(not_zero, ÷nd_not_min_int, Label::kNear);
1457 __ cmp(divisor, -1);
1458 DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
1459 __ bind(÷nd_not_min_int);
1462 // Sign extend to edx (= remainder).
1467 __ test(remainder, remainder);
1468 __ j(zero, &done, Label::kNear);
1469 __ xor_(remainder, divisor);
1470 __ sar(remainder, 31);
1471 __ add(result, remainder);
1476 void LCodeGen::DoMulI(LMulI* instr) {
1477 Register left = ToRegister(instr->left());
1478 LOperand* right = instr->right();
1480 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1481 __ mov(ToRegister(instr->temp()), left);
1484 if (right->IsConstantOperand()) {
1485 // Try strength reductions on the multiplication.
1486 // All replacement instructions are at most as long as the imul
1487 // and have better latency.
1488 int constant = ToInteger32(LConstantOperand::cast(right));
1489 if (constant == -1) {
1491 } else if (constant == 0) {
1492 __ xor_(left, Operand(left));
1493 } else if (constant == 2) {
1494 __ add(left, Operand(left));
1495 } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1496 // If we know that the multiplication can't overflow, it's safe to
1497 // use instructions that don't set the overflow flag for the
1504 __ lea(left, Operand(left, left, times_2, 0));
1510 __ lea(left, Operand(left, left, times_4, 0));
1516 __ lea(left, Operand(left, left, times_8, 0));
1522 __ imul(left, left, constant);
1526 __ imul(left, left, constant);
1529 if (instr->hydrogen()->representation().IsSmi()) {
1532 __ imul(left, ToOperand(right));
1535 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1536 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1539 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1540 // Bail out if the result is supposed to be negative zero.
1542 __ test(left, Operand(left));
1543 __ j(not_zero, &done, Label::kNear);
1544 if (right->IsConstantOperand()) {
1545 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1546 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
1547 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1548 __ cmp(ToRegister(instr->temp()), Immediate(0));
1549 DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
1552 // Test the non-zero operand for negative sign.
1553 __ or_(ToRegister(instr->temp()), ToOperand(right));
1554 DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
1561 void LCodeGen::DoBitI(LBitI* instr) {
1562 LOperand* left = instr->left();
1563 LOperand* right = instr->right();
1564 DCHECK(left->Equals(instr->result()));
1565 DCHECK(left->IsRegister());
1567 if (right->IsConstantOperand()) {
1568 int32_t right_operand =
1569 ToRepresentation(LConstantOperand::cast(right),
1570 instr->hydrogen()->representation());
1571 switch (instr->op()) {
1572 case Token::BIT_AND:
1573 __ and_(ToRegister(left), right_operand);
1576 __ or_(ToRegister(left), right_operand);
1578 case Token::BIT_XOR:
1579 if (right_operand == int32_t(~0)) {
1580 __ not_(ToRegister(left));
1582 __ xor_(ToRegister(left), right_operand);
1590 switch (instr->op()) {
1591 case Token::BIT_AND:
1592 __ and_(ToRegister(left), ToOperand(right));
1595 __ or_(ToRegister(left), ToOperand(right));
1597 case Token::BIT_XOR:
1598 __ xor_(ToRegister(left), ToOperand(right));
1608 void LCodeGen::DoShiftI(LShiftI* instr) {
1609 LOperand* left = instr->left();
1610 LOperand* right = instr->right();
1611 DCHECK(left->Equals(instr->result()));
1612 DCHECK(left->IsRegister());
1613 if (right->IsRegister()) {
1614 DCHECK(ToRegister(right).is(ecx));
1616 switch (instr->op()) {
1618 __ ror_cl(ToRegister(left));
1621 __ sar_cl(ToRegister(left));
1624 __ shr_cl(ToRegister(left));
1625 if (instr->can_deopt()) {
1626 __ test(ToRegister(left), ToRegister(left));
1627 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1631 __ shl_cl(ToRegister(left));
1638 int value = ToInteger32(LConstantOperand::cast(right));
1639 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1640 switch (instr->op()) {
1642 if (shift_count == 0 && instr->can_deopt()) {
1643 __ test(ToRegister(left), ToRegister(left));
1644 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1646 __ ror(ToRegister(left), shift_count);
1650 if (shift_count != 0) {
1651 __ sar(ToRegister(left), shift_count);
1655 if (shift_count != 0) {
1656 __ shr(ToRegister(left), shift_count);
1657 } else if (instr->can_deopt()) {
1658 __ test(ToRegister(left), ToRegister(left));
1659 DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
1663 if (shift_count != 0) {
1664 if (instr->hydrogen_value()->representation().IsSmi() &&
1665 instr->can_deopt()) {
1666 if (shift_count != 1) {
1667 __ shl(ToRegister(left), shift_count - 1);
1669 __ SmiTag(ToRegister(left));
1670 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1672 __ shl(ToRegister(left), shift_count);
1684 void LCodeGen::DoSubI(LSubI* instr) {
1685 LOperand* left = instr->left();
1686 LOperand* right = instr->right();
1687 DCHECK(left->Equals(instr->result()));
1689 if (right->IsConstantOperand()) {
1690 __ sub(ToOperand(left),
1691 ToImmediate(right, instr->hydrogen()->representation()));
1693 __ sub(ToRegister(left), ToOperand(right));
1695 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1696 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1701 void LCodeGen::DoConstantI(LConstantI* instr) {
1702 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1706 void LCodeGen::DoConstantS(LConstantS* instr) {
1707 __ Move(ToRegister(instr->result()), Immediate(instr->value()));
1711 void LCodeGen::DoConstantD(LConstantD* instr) {
1712 uint64_t const bits = instr->bits();
1713 uint32_t const lower = static_cast<uint32_t>(bits);
1714 uint32_t const upper = static_cast<uint32_t>(bits >> 32);
1715 DCHECK(instr->result()->IsDoubleRegister());
1717 XMMRegister result = ToDoubleRegister(instr->result());
1719 __ xorps(result, result);
1721 Register temp = ToRegister(instr->temp());
1722 if (CpuFeatures::IsSupported(SSE4_1)) {
1723 CpuFeatureScope scope2(masm(), SSE4_1);
1725 __ Move(temp, Immediate(lower));
1726 __ movd(result, Operand(temp));
1727 __ Move(temp, Immediate(upper));
1728 __ pinsrd(result, Operand(temp), 1);
1730 __ xorps(result, result);
1731 __ Move(temp, Immediate(upper));
1732 __ pinsrd(result, Operand(temp), 1);
1735 __ Move(temp, Immediate(upper));
1736 __ movd(result, Operand(temp));
1737 __ psllq(result, 32);
1739 XMMRegister xmm_scratch = double_scratch0();
1740 __ Move(temp, Immediate(lower));
1741 __ movd(xmm_scratch, Operand(temp));
1742 __ orps(result, xmm_scratch);
1749 void LCodeGen::DoConstantE(LConstantE* instr) {
1750 __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
1754 void LCodeGen::DoConstantT(LConstantT* instr) {
1755 Register reg = ToRegister(instr->result());
1756 Handle<Object> object = instr->value(isolate());
1757 AllowDeferredHandleDereference smi_check;
1758 __ LoadObject(reg, object);
1762 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
1763 Register result = ToRegister(instr->result());
1764 Register map = ToRegister(instr->value());
1765 __ EnumLength(result, map);
1769 void LCodeGen::DoDateField(LDateField* instr) {
1770 Register object = ToRegister(instr->date());
1771 Register result = ToRegister(instr->result());
1772 Register scratch = ToRegister(instr->temp());
1773 Smi* index = instr->index();
1774 Label runtime, done;
1775 DCHECK(object.is(result));
1776 DCHECK(object.is(eax));
1778 __ test(object, Immediate(kSmiTagMask));
1779 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
1780 __ CmpObjectType(object, JS_DATE_TYPE, scratch);
1781 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotADateObject);
1783 if (index->value() == 0) {
1784 __ mov(result, FieldOperand(object, JSDate::kValueOffset));
1786 if (index->value() < JSDate::kFirstUncachedField) {
1787 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
1788 __ mov(scratch, Operand::StaticVariable(stamp));
1789 __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
1790 __ j(not_equal, &runtime, Label::kNear);
1791 __ mov(result, FieldOperand(object, JSDate::kValueOffset +
1792 kPointerSize * index->value()));
1793 __ jmp(&done, Label::kNear);
1796 __ PrepareCallCFunction(2, scratch);
1797 __ mov(Operand(esp, 0), object);
1798 __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
1799 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
1805 Operand LCodeGen::BuildSeqStringOperand(Register string,
1807 String::Encoding encoding) {
1808 if (index->IsConstantOperand()) {
1809 int offset = ToRepresentation(LConstantOperand::cast(index),
1810 Representation::Integer32());
1811 if (encoding == String::TWO_BYTE_ENCODING) {
1812 offset *= kUC16Size;
1814 STATIC_ASSERT(kCharSize == 1);
1815 return FieldOperand(string, SeqString::kHeaderSize + offset);
1817 return FieldOperand(
1818 string, ToRegister(index),
1819 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
1820 SeqString::kHeaderSize);
1824 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
1825 String::Encoding encoding = instr->hydrogen()->encoding();
1826 Register result = ToRegister(instr->result());
1827 Register string = ToRegister(instr->string());
1829 if (FLAG_debug_code) {
1831 __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
1832 __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));
1834 __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
1835 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1836 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1837 __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
1838 ? one_byte_seq_type : two_byte_seq_type));
1839 __ Check(equal, kUnexpectedStringType);
1843 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1844 if (encoding == String::ONE_BYTE_ENCODING) {
1845 __ movzx_b(result, operand);
1847 __ movzx_w(result, operand);
1852 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
1853 String::Encoding encoding = instr->hydrogen()->encoding();
1854 Register string = ToRegister(instr->string());
1856 if (FLAG_debug_code) {
1857 Register value = ToRegister(instr->value());
1858 Register index = ToRegister(instr->index());
1859 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1860 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1862 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
1863 ? one_byte_seq_type : two_byte_seq_type;
1864 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
1867 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1868 if (instr->value()->IsConstantOperand()) {
1869 int value = ToRepresentation(LConstantOperand::cast(instr->value()),
1870 Representation::Integer32());
1871 DCHECK_LE(0, value);
1872 if (encoding == String::ONE_BYTE_ENCODING) {
1873 DCHECK_LE(value, String::kMaxOneByteCharCode);
1874 __ mov_b(operand, static_cast<int8_t>(value));
1876 DCHECK_LE(value, String::kMaxUtf16CodeUnit);
1877 __ mov_w(operand, static_cast<int16_t>(value));
1880 Register value = ToRegister(instr->value());
1881 if (encoding == String::ONE_BYTE_ENCODING) {
1882 __ mov_b(operand, value);
1884 __ mov_w(operand, value);
1890 void LCodeGen::DoAddI(LAddI* instr) {
1891 LOperand* left = instr->left();
1892 LOperand* right = instr->right();
1894 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
1895 if (right->IsConstantOperand()) {
1896 int32_t offset = ToRepresentation(LConstantOperand::cast(right),
1897 instr->hydrogen()->representation());
1898 __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
1900 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
1901 __ lea(ToRegister(instr->result()), address);
1904 if (right->IsConstantOperand()) {
1905 __ add(ToOperand(left),
1906 ToImmediate(right, instr->hydrogen()->representation()));
1908 __ add(ToRegister(left), ToOperand(right));
1910 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1911 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1917 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
1918 LOperand* left = instr->left();
1919 LOperand* right = instr->right();
1920 DCHECK(left->Equals(instr->result()));
1921 HMathMinMax::Operation operation = instr->hydrogen()->operation();
1922 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
1924 Condition condition = (operation == HMathMinMax::kMathMin)
1927 if (right->IsConstantOperand()) {
1928 Operand left_op = ToOperand(left);
1929 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
1930 instr->hydrogen()->representation());
1931 __ cmp(left_op, immediate);
1932 __ j(condition, &return_left, Label::kNear);
1933 __ mov(left_op, immediate);
1935 Register left_reg = ToRegister(left);
1936 Operand right_op = ToOperand(right);
1937 __ cmp(left_reg, right_op);
1938 __ j(condition, &return_left, Label::kNear);
1939 __ mov(left_reg, right_op);
1941 __ bind(&return_left);
1943 DCHECK(instr->hydrogen()->representation().IsDouble());
1944 Label check_nan_left, check_zero, return_left, return_right;
1945 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
1946 XMMRegister left_reg = ToDoubleRegister(left);
1947 XMMRegister right_reg = ToDoubleRegister(right);
1948 __ ucomisd(left_reg, right_reg);
1949 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
1950 __ j(equal, &check_zero, Label::kNear); // left == right.
1951 __ j(condition, &return_left, Label::kNear);
1952 __ jmp(&return_right, Label::kNear);
1954 __ bind(&check_zero);
1955 XMMRegister xmm_scratch = double_scratch0();
1956 __ xorps(xmm_scratch, xmm_scratch);
1957 __ ucomisd(left_reg, xmm_scratch);
1958 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
1959 // At this point, both left and right are either 0 or -0.
1960 if (operation == HMathMinMax::kMathMin) {
1961 __ orpd(left_reg, right_reg);
1963 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
1964 __ addsd(left_reg, right_reg);
1966 __ jmp(&return_left, Label::kNear);
1968 __ bind(&check_nan_left);
1969 __ ucomisd(left_reg, left_reg); // NaN check.
1970 __ j(parity_even, &return_left, Label::kNear); // left == NaN.
1971 __ bind(&return_right);
1972 __ movaps(left_reg, right_reg);
1974 __ bind(&return_left);
1979 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
1980 XMMRegister left = ToDoubleRegister(instr->left());
1981 XMMRegister right = ToDoubleRegister(instr->right());
1982 XMMRegister result = ToDoubleRegister(instr->result());
1983 switch (instr->op()) {
1985 if (CpuFeatures::IsSupported(AVX)) {
1986 CpuFeatureScope scope(masm(), AVX);
1987 __ vaddsd(result, left, right);
1989 DCHECK(result.is(left));
1990 __ addsd(left, right);
1994 if (CpuFeatures::IsSupported(AVX)) {
1995 CpuFeatureScope scope(masm(), AVX);
1996 __ vsubsd(result, left, right);
1998 DCHECK(result.is(left));
1999 __ subsd(left, right);
2003 if (CpuFeatures::IsSupported(AVX)) {
2004 CpuFeatureScope scope(masm(), AVX);
2005 __ vmulsd(result, left, right);
2007 DCHECK(result.is(left));
2008 __ mulsd(left, right);
2012 if (CpuFeatures::IsSupported(AVX)) {
2013 CpuFeatureScope scope(masm(), AVX);
2014 __ vdivsd(result, left, right);
2016 DCHECK(result.is(left));
2017 __ divsd(left, right);
2018 // Don't delete this mov. It may improve performance on some CPUs,
2019 // when there is a mulsd depending on the result
2020 __ movaps(left, left);
2024 // Pass two doubles as arguments on the stack.
2025 __ PrepareCallCFunction(4, eax);
2026 __ movsd(Operand(esp, 0 * kDoubleSize), left);
2027 __ movsd(Operand(esp, 1 * kDoubleSize), right);
2029 ExternalReference::mod_two_doubles_operation(isolate()),
2032 // Return value is in st(0) on ia32.
2033 // Store it into the result register.
2034 __ sub(Operand(esp), Immediate(kDoubleSize));
2035 __ fstp_d(Operand(esp, 0));
2036 __ movsd(result, Operand(esp, 0));
2037 __ add(Operand(esp), Immediate(kDoubleSize));
2047 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2048 DCHECK(ToRegister(instr->context()).is(esi));
2049 DCHECK(ToRegister(instr->left()).is(edx));
2050 DCHECK(ToRegister(instr->right()).is(eax));
2051 DCHECK(ToRegister(instr->result()).is(eax));
2053 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), instr->op()).code();
2054 CallCode(code, RelocInfo::CODE_TARGET, instr);
2058 template<class InstrType>
2059 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
2060 int left_block = instr->TrueDestination(chunk_);
2061 int right_block = instr->FalseDestination(chunk_);
2063 int next_block = GetNextEmittedBlock();
2065 if (right_block == left_block || cc == no_condition) {
2066 EmitGoto(left_block);
2067 } else if (left_block == next_block) {
2068 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
2069 } else if (right_block == next_block) {
2070 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2072 __ j(cc, chunk_->GetAssemblyLabel(left_block));
2073 __ jmp(chunk_->GetAssemblyLabel(right_block));
2078 template<class InstrType>
2079 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
2080 int false_block = instr->FalseDestination(chunk_);
2081 if (cc == no_condition) {
2082 __ jmp(chunk_->GetAssemblyLabel(false_block));
2084 __ j(cc, chunk_->GetAssemblyLabel(false_block));
2089 void LCodeGen::DoBranch(LBranch* instr) {
2090 Representation r = instr->hydrogen()->value()->representation();
2091 if (r.IsSmiOrInteger32()) {
2092 Register reg = ToRegister(instr->value());
2093 __ test(reg, Operand(reg));
2094 EmitBranch(instr, not_zero);
2095 } else if (r.IsDouble()) {
2096 DCHECK(!info()->IsStub());
2097 XMMRegister reg = ToDoubleRegister(instr->value());
2098 XMMRegister xmm_scratch = double_scratch0();
2099 __ xorps(xmm_scratch, xmm_scratch);
2100 __ ucomisd(reg, xmm_scratch);
2101 EmitBranch(instr, not_equal);
2103 DCHECK(r.IsTagged());
2104 Register reg = ToRegister(instr->value());
2105 HType type = instr->hydrogen()->value()->type();
2106 if (type.IsBoolean()) {
2107 DCHECK(!info()->IsStub());
2108 __ cmp(reg, factory()->true_value());
2109 EmitBranch(instr, equal);
2110 } else if (type.IsSmi()) {
2111 DCHECK(!info()->IsStub());
2112 __ test(reg, Operand(reg));
2113 EmitBranch(instr, not_equal);
2114 } else if (type.IsJSArray()) {
2115 DCHECK(!info()->IsStub());
2116 EmitBranch(instr, no_condition);
2117 } else if (type.IsHeapNumber()) {
2118 DCHECK(!info()->IsStub());
2119 XMMRegister xmm_scratch = double_scratch0();
2120 __ xorps(xmm_scratch, xmm_scratch);
2121 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2122 EmitBranch(instr, not_equal);
2123 } else if (type.IsString()) {
2124 DCHECK(!info()->IsStub());
2125 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2126 EmitBranch(instr, not_equal);
2128 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2129 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2131 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2132 // undefined -> false.
2133 __ cmp(reg, factory()->undefined_value());
2134 __ j(equal, instr->FalseLabel(chunk_));
2136 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2138 __ cmp(reg, factory()->true_value());
2139 __ j(equal, instr->TrueLabel(chunk_));
2141 __ cmp(reg, factory()->false_value());
2142 __ j(equal, instr->FalseLabel(chunk_));
2144 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2146 __ cmp(reg, factory()->null_value());
2147 __ j(equal, instr->FalseLabel(chunk_));
2150 if (expected.Contains(ToBooleanStub::SMI)) {
2151 // Smis: 0 -> false, all other -> true.
2152 __ test(reg, Operand(reg));
2153 __ j(equal, instr->FalseLabel(chunk_));
2154 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2155 } else if (expected.NeedsMap()) {
2156 // If we need a map later and have a Smi -> deopt.
2157 __ test(reg, Immediate(kSmiTagMask));
2158 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
2161 Register map = no_reg; // Keep the compiler happy.
2162 if (expected.NeedsMap()) {
2163 map = ToRegister(instr->temp());
2164 DCHECK(!map.is(reg));
2165 __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));
2167 if (expected.CanBeUndetectable()) {
2168 // Undetectable -> false.
2169 __ test_b(FieldOperand(map, Map::kBitFieldOffset),
2170 1 << Map::kIsUndetectable);
2171 __ j(not_zero, instr->FalseLabel(chunk_));
2175 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2176 // spec object -> true.
2177 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2178 __ j(above_equal, instr->TrueLabel(chunk_));
2181 if (expected.Contains(ToBooleanStub::STRING)) {
2182 // String value -> false iff empty.
2184 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2185 __ j(above_equal, ¬_string, Label::kNear);
2186 __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2187 __ j(not_zero, instr->TrueLabel(chunk_));
2188 __ jmp(instr->FalseLabel(chunk_));
2189 __ bind(¬_string);
2192 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2193 // Symbol value -> true.
2194 __ CmpInstanceType(map, SYMBOL_TYPE);
2195 __ j(equal, instr->TrueLabel(chunk_));
2198 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2199 // heap number -> false iff +0, -0, or NaN.
2200 Label not_heap_number;
2201 __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
2202 factory()->heap_number_map());
2203 __ j(not_equal, ¬_heap_number, Label::kNear);
2204 XMMRegister xmm_scratch = double_scratch0();
2205 __ xorps(xmm_scratch, xmm_scratch);
2206 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2207 __ j(zero, instr->FalseLabel(chunk_));
2208 __ jmp(instr->TrueLabel(chunk_));
2209 __ bind(¬_heap_number);
2212 if (!expected.IsGeneric()) {
2213 // We've seen something for the first time -> deopt.
2214 // This can only happen if we are not generic already.
2215 DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
2222 void LCodeGen::EmitGoto(int block) {
2223 if (!IsNextEmittedBlock(block)) {
2224 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2229 void LCodeGen::DoGoto(LGoto* instr) {
2230 EmitGoto(instr->block_id());
2234 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2235 Condition cond = no_condition;
2238 case Token::EQ_STRICT:
2242 case Token::NE_STRICT:
2246 cond = is_unsigned ? below : less;
2249 cond = is_unsigned ? above : greater;
2252 cond = is_unsigned ? below_equal : less_equal;
2255 cond = is_unsigned ? above_equal : greater_equal;
2258 case Token::INSTANCEOF:
2266 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2267 LOperand* left = instr->left();
2268 LOperand* right = instr->right();
2270 instr->is_double() ||
2271 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2272 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2273 Condition cc = TokenToCondition(instr->op(), is_unsigned);
2275 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2276 // We can statically evaluate the comparison.
2277 double left_val = ToDouble(LConstantOperand::cast(left));
2278 double right_val = ToDouble(LConstantOperand::cast(right));
2279 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2280 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2281 EmitGoto(next_block);
2283 if (instr->is_double()) {
2284 __ ucomisd(ToDoubleRegister(left), ToDoubleRegister(right));
2285 // Don't base result on EFLAGS when a NaN is involved. Instead
2286 // jump to the false block.
2287 __ j(parity_even, instr->FalseLabel(chunk_));
2289 if (right->IsConstantOperand()) {
2290 __ cmp(ToOperand(left),
2291 ToImmediate(right, instr->hydrogen()->representation()));
2292 } else if (left->IsConstantOperand()) {
2293 __ cmp(ToOperand(right),
2294 ToImmediate(left, instr->hydrogen()->representation()));
2295 // We commuted the operands, so commute the condition.
2296 cc = CommuteCondition(cc);
2298 __ cmp(ToRegister(left), ToOperand(right));
2301 EmitBranch(instr, cc);
2306 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2307 Register left = ToRegister(instr->left());
2309 if (instr->right()->IsConstantOperand()) {
2310 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2311 __ CmpObject(left, right);
2313 Operand right = ToOperand(instr->right());
2314 __ cmp(left, right);
2316 EmitBranch(instr, equal);
2320 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2321 if (instr->hydrogen()->representation().IsTagged()) {
2322 Register input_reg = ToRegister(instr->object());
2323 __ cmp(input_reg, factory()->the_hole_value());
2324 EmitBranch(instr, equal);
2328 XMMRegister input_reg = ToDoubleRegister(instr->object());
2329 __ ucomisd(input_reg, input_reg);
2330 EmitFalseBranch(instr, parity_odd);
2332 __ sub(esp, Immediate(kDoubleSize));
2333 __ movsd(MemOperand(esp, 0), input_reg);
2335 __ add(esp, Immediate(kDoubleSize));
2336 int offset = sizeof(kHoleNanUpper32);
2337 __ cmp(MemOperand(esp, -offset), Immediate(kHoleNanUpper32));
2338 EmitBranch(instr, equal);
2342 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2343 Representation rep = instr->hydrogen()->value()->representation();
2344 DCHECK(!rep.IsInteger32());
2345 Register scratch = ToRegister(instr->temp());
2347 if (rep.IsDouble()) {
2348 XMMRegister value = ToDoubleRegister(instr->value());
2349 XMMRegister xmm_scratch = double_scratch0();
2350 __ xorps(xmm_scratch, xmm_scratch);
2351 __ ucomisd(xmm_scratch, value);
2352 EmitFalseBranch(instr, not_equal);
2353 __ movmskpd(scratch, value);
2354 __ test(scratch, Immediate(1));
2355 EmitBranch(instr, not_zero);
2357 Register value = ToRegister(instr->value());
2358 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2359 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2360 __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
2362 EmitFalseBranch(instr, no_overflow);
2363 __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
2364 Immediate(0x00000000));
2365 EmitBranch(instr, equal);
2370 Condition LCodeGen::EmitIsObject(Register input,
2372 Label* is_not_object,
2374 __ JumpIfSmi(input, is_not_object);
2376 __ cmp(input, isolate()->factory()->null_value());
2377 __ j(equal, is_object);
2379 __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
2380 // Undetectable objects behave like undefined.
2381 __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
2382 1 << Map::kIsUndetectable);
2383 __ j(not_zero, is_not_object);
2385 __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
2386 __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
2387 __ j(below, is_not_object);
2388 __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
2393 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2394 Register reg = ToRegister(instr->value());
2395 Register temp = ToRegister(instr->temp());
2397 Condition true_cond = EmitIsObject(
2398 reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2400 EmitBranch(instr, true_cond);
2404 Condition LCodeGen::EmitIsString(Register input,
2406 Label* is_not_string,
2407 SmiCheck check_needed = INLINE_SMI_CHECK) {
2408 if (check_needed == INLINE_SMI_CHECK) {
2409 __ JumpIfSmi(input, is_not_string);
2412 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2418 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2419 Register reg = ToRegister(instr->value());
2420 Register temp = ToRegister(instr->temp());
2422 SmiCheck check_needed =
2423 instr->hydrogen()->value()->type().IsHeapObject()
2424 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2426 Condition true_cond = EmitIsString(
2427 reg, temp, instr->FalseLabel(chunk_), check_needed);
2429 EmitBranch(instr, true_cond);
2433 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2434 Operand input = ToOperand(instr->value());
2436 __ test(input, Immediate(kSmiTagMask));
2437 EmitBranch(instr, zero);
2441 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2442 Register input = ToRegister(instr->value());
2443 Register temp = ToRegister(instr->temp());
2445 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2446 STATIC_ASSERT(kSmiTag == 0);
2447 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2449 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2450 __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
2451 1 << Map::kIsUndetectable);
2452 EmitBranch(instr, not_zero);
2456 static Condition ComputeCompareCondition(Token::Value op) {
2458 case Token::EQ_STRICT:
2468 return greater_equal;
2471 return no_condition;
2476 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2477 Token::Value op = instr->op();
2479 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
2480 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2482 Condition condition = ComputeCompareCondition(op);
2483 __ test(eax, Operand(eax));
2485 EmitBranch(instr, condition);
2489 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2490 InstanceType from = instr->from();
2491 InstanceType to = instr->to();
2492 if (from == FIRST_TYPE) return to;
2493 DCHECK(from == to || to == LAST_TYPE);
2498 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2499 InstanceType from = instr->from();
2500 InstanceType to = instr->to();
2501 if (from == to) return equal;
2502 if (to == LAST_TYPE) return above_equal;
2503 if (from == FIRST_TYPE) return below_equal;
2509 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2510 Register input = ToRegister(instr->value());
2511 Register temp = ToRegister(instr->temp());
2513 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2514 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2517 __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
2518 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2522 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2523 Register input = ToRegister(instr->value());
2524 Register result = ToRegister(instr->result());
2526 __ AssertString(input);
2528 __ mov(result, FieldOperand(input, String::kHashFieldOffset));
2529 __ IndexFromHash(result, result);
2533 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2534 LHasCachedArrayIndexAndBranch* instr) {
2535 Register input = ToRegister(instr->value());
2537 __ test(FieldOperand(input, String::kHashFieldOffset),
2538 Immediate(String::kContainsCachedArrayIndexMask));
2539 EmitBranch(instr, equal);
2543 // Branches to a label or falls through with the answer in the z flag. Trashes
2544 // the temp registers, but not the input.
2545 void LCodeGen::EmitClassOfTest(Label* is_true,
2547 Handle<String>class_name,
2551 DCHECK(!input.is(temp));
2552 DCHECK(!input.is(temp2));
2553 DCHECK(!temp.is(temp2));
2554 __ JumpIfSmi(input, is_false);
2556 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2557 // Assuming the following assertions, we can use the same compares to test
2558 // for both being a function type and being in the object type range.
2559 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2560 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2561 FIRST_SPEC_OBJECT_TYPE + 1);
2562 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2563 LAST_SPEC_OBJECT_TYPE - 1);
2564 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2565 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2566 __ j(below, is_false);
2567 __ j(equal, is_true);
2568 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2569 __ j(equal, is_true);
2571 // Faster code path to avoid two compares: subtract lower bound from the
2572 // actual type and do a signed compare with the width of the type range.
2573 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
2574 __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2575 __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2576 __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2577 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2578 __ j(above, is_false);
2581 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2582 // Check if the constructor in the map is a function.
2583 __ mov(temp, FieldOperand(temp, Map::kConstructorOffset));
2584 // Objects with a non-function constructor have class 'Object'.
2585 __ CmpObjectType(temp, JS_FUNCTION_TYPE, temp2);
2586 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2587 __ j(not_equal, is_true);
2589 __ j(not_equal, is_false);
2592 // temp now contains the constructor function. Grab the
2593 // instance class name from there.
2594 __ mov(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2595 __ mov(temp, FieldOperand(temp,
2596 SharedFunctionInfo::kInstanceClassNameOffset));
2597 // The class name we are testing against is internalized since it's a literal.
2598 // The name in the constructor is internalized because of the way the context
2599 // is booted. This routine isn't expected to work for random API-created
2600 // classes and it doesn't have to because you can't access it with natives
2601 // syntax. Since both sides are internalized it is sufficient to use an
2602 // identity comparison.
2603 __ cmp(temp, class_name);
2604 // End with the answer in the z flag.
2608 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2609 Register input = ToRegister(instr->value());
2610 Register temp = ToRegister(instr->temp());
2611 Register temp2 = ToRegister(instr->temp2());
2613 Handle<String> class_name = instr->hydrogen()->class_name();
2615 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2616 class_name, input, temp, temp2);
2618 EmitBranch(instr, equal);
2622 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2623 Register reg = ToRegister(instr->value());
2624 __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2625 EmitBranch(instr, equal);
2629 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2630 // Object and function are in fixed registers defined by the stub.
2631 DCHECK(ToRegister(instr->context()).is(esi));
2632 InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
2633 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
2635 Label true_value, done;
2636 __ test(eax, Operand(eax));
2637 __ j(zero, &true_value, Label::kNear);
2638 __ mov(ToRegister(instr->result()), factory()->false_value());
2639 __ jmp(&done, Label::kNear);
2640 __ bind(&true_value);
2641 __ mov(ToRegister(instr->result()), factory()->true_value());
2646 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2647 class DeferredInstanceOfKnownGlobal FINAL : public LDeferredCode {
2649 DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2650 LInstanceOfKnownGlobal* instr)
2651 : LDeferredCode(codegen), instr_(instr) { }
2652 void Generate() OVERRIDE {
2653 codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2655 LInstruction* instr() OVERRIDE { return instr_; }
2656 Label* map_check() { return &map_check_; }
2658 LInstanceOfKnownGlobal* instr_;
2662 DeferredInstanceOfKnownGlobal* deferred;
2663 deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr);
2665 Label done, false_result;
2666 Register object = ToRegister(instr->value());
2667 Register temp = ToRegister(instr->temp());
2669 // A Smi is not an instance of anything.
2670 __ JumpIfSmi(object, &false_result, Label::kNear);
2672 // This is the inlined call site instanceof cache. The two occurences of the
2673 // hole value will be patched to the last map/result pair generated by the
2676 Register map = ToRegister(instr->temp());
2677 __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
2678 __ bind(deferred->map_check()); // Label for calculating code patching.
2679 Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2680 __ cmp(map, Operand::ForCell(cache_cell)); // Patched to cached map.
2681 __ j(not_equal, &cache_miss, Label::kNear);
2682 __ mov(eax, factory()->the_hole_value()); // Patched to either true or false.
2683 __ jmp(&done, Label::kNear);
2685 // The inlined call site cache did not match. Check for null and string
2686 // before calling the deferred code.
2687 __ bind(&cache_miss);
2688 // Null is not an instance of anything.
2689 __ cmp(object, factory()->null_value());
2690 __ j(equal, &false_result, Label::kNear);
2692 // String values are not instances of anything.
2693 Condition is_string = masm_->IsObjectStringType(object, temp, temp);
2694 __ j(is_string, &false_result, Label::kNear);
2696 // Go to the deferred code.
2697 __ jmp(deferred->entry());
2699 __ bind(&false_result);
2700 __ mov(ToRegister(instr->result()), factory()->false_value());
2702 // Here result has either true or false. Deferred code also produces true or
2704 __ bind(deferred->exit());
2709 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
2711 PushSafepointRegistersScope scope(this);
2713 InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
2714 flags = static_cast<InstanceofStub::Flags>(
2715 flags | InstanceofStub::kArgsInRegisters);
2716 flags = static_cast<InstanceofStub::Flags>(
2717 flags | InstanceofStub::kCallSiteInlineCheck);
2718 flags = static_cast<InstanceofStub::Flags>(
2719 flags | InstanceofStub::kReturnTrueFalseObject);
2720 InstanceofStub stub(isolate(), flags);
2722 // Get the temp register reserved by the instruction. This needs to be a
2723 // register which is pushed last by PushSafepointRegisters as top of the
2724 // stack is used to pass the offset to the location of the map check to
2726 Register temp = ToRegister(instr->temp());
2727 DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
2728 __ LoadHeapObject(InstanceofStub::right(), instr->function());
2729 static const int kAdditionalDelta = 13;
2730 int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
2731 __ mov(temp, Immediate(delta));
2732 __ StoreToSafepointRegisterSlot(temp, temp);
2733 CallCodeGeneric(stub.GetCode(),
2734 RelocInfo::CODE_TARGET,
2736 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
2737 // Get the deoptimization index of the LLazyBailout-environment that
2738 // corresponds to this instruction.
2739 LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
2740 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
2742 // Put the result value into the eax slot and restore all registers.
2743 __ StoreToSafepointRegisterSlot(eax, eax);
2747 void LCodeGen::DoCmpT(LCmpT* instr) {
2748 Token::Value op = instr->op();
2750 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
2751 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2753 Condition condition = ComputeCompareCondition(op);
2754 Label true_value, done;
2755 __ test(eax, Operand(eax));
2756 __ j(condition, &true_value, Label::kNear);
2757 __ mov(ToRegister(instr->result()), factory()->false_value());
2758 __ jmp(&done, Label::kNear);
2759 __ bind(&true_value);
2760 __ mov(ToRegister(instr->result()), factory()->true_value());
2765 void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
2766 int extra_value_count = dynamic_frame_alignment ? 2 : 1;
2768 if (instr->has_constant_parameter_count()) {
2769 int parameter_count = ToInteger32(instr->constant_parameter_count());
2770 if (dynamic_frame_alignment && FLAG_debug_code) {
2772 (parameter_count + extra_value_count) * kPointerSize),
2773 Immediate(kAlignmentZapValue));
2774 __ Assert(equal, kExpectedAlignmentMarker);
2776 __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
2778 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
2779 Register reg = ToRegister(instr->parameter_count());
2780 // The argument count parameter is a smi
2782 Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
2783 if (dynamic_frame_alignment && FLAG_debug_code) {
2784 DCHECK(extra_value_count == 2);
2785 __ cmp(Operand(esp, reg, times_pointer_size,
2786 extra_value_count * kPointerSize),
2787 Immediate(kAlignmentZapValue));
2788 __ Assert(equal, kExpectedAlignmentMarker);
2791 // emit code to restore stack based on instr->parameter_count()
2792 __ pop(return_addr_reg); // save return address
2793 if (dynamic_frame_alignment) {
2794 __ inc(reg); // 1 more for alignment
2797 __ shl(reg, kPointerSizeLog2);
2799 __ jmp(return_addr_reg);
2804 void LCodeGen::DoReturn(LReturn* instr) {
2805 if (FLAG_trace && info()->IsOptimizing()) {
2806 // Preserve the return value on the stack and rely on the runtime call
2807 // to return the value in the same register. We're leaving the code
2808 // managed by the register allocator and tearing down the frame, it's
2809 // safe to write to the context register.
2811 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
2812 __ CallRuntime(Runtime::kTraceExit, 1);
2814 if (info()->saves_caller_doubles()) RestoreCallerDoubles();
2815 if (dynamic_frame_alignment_) {
2816 // Fetch the state of the dynamic frame alignment.
2817 __ mov(edx, Operand(ebp,
2818 JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
2820 int no_frame_start = -1;
2821 if (NeedsEagerFrame()) {
2824 no_frame_start = masm_->pc_offset();
2826 if (dynamic_frame_alignment_) {
2828 __ cmp(edx, Immediate(kNoAlignmentPadding));
2829 __ j(equal, &no_padding, Label::kNear);
2831 EmitReturn(instr, true);
2832 __ bind(&no_padding);
2835 EmitReturn(instr, false);
2836 if (no_frame_start != -1) {
2837 info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
2842 void LCodeGen::DoLoadGlobalCell(LLoadGlobalCell* instr) {
2843 Register result = ToRegister(instr->result());
2844 __ mov(result, Operand::ForCell(instr->hydrogen()->cell().handle()));
2845 if (instr->hydrogen()->RequiresHoleCheck()) {
2846 __ cmp(result, factory()->the_hole_value());
2847 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2853 void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
2854 DCHECK(FLAG_vector_ics);
2855 Register vector_register = ToRegister(instr->temp_vector());
2856 Register slot_register = VectorLoadICDescriptor::SlotRegister();
2857 DCHECK(vector_register.is(VectorLoadICDescriptor::VectorRegister()));
2858 DCHECK(slot_register.is(eax));
2860 AllowDeferredHandleDereference vector_structure_check;
2861 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
2862 __ mov(vector_register, vector);
2863 // No need to allocate this register.
2864 FeedbackVectorICSlot slot = instr->hydrogen()->slot();
2865 int index = vector->GetIndex(slot);
2866 __ mov(slot_register, Immediate(Smi::FromInt(index)));
2870 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
2871 DCHECK(ToRegister(instr->context()).is(esi));
2872 DCHECK(ToRegister(instr->global_object())
2873 .is(LoadDescriptor::ReceiverRegister()));
2874 DCHECK(ToRegister(instr->result()).is(eax));
2876 __ mov(LoadDescriptor::NameRegister(), instr->name());
2877 if (FLAG_vector_ics) {
2878 EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
2880 ContextualMode mode = instr->for_typeof() ? NOT_CONTEXTUAL : CONTEXTUAL;
2881 Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(isolate(), mode).code();
2882 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2886 void LCodeGen::DoStoreGlobalCell(LStoreGlobalCell* instr) {
2887 Register value = ToRegister(instr->value());
2888 Handle<PropertyCell> cell_handle = instr->hydrogen()->cell().handle();
2890 // If the cell we are storing to contains the hole it could have
2891 // been deleted from the property dictionary. In that case, we need
2892 // to update the property details in the property dictionary to mark
2893 // it as no longer deleted. We deoptimize in that case.
2894 if (instr->hydrogen()->RequiresHoleCheck()) {
2895 __ cmp(Operand::ForCell(cell_handle), factory()->the_hole_value());
2896 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2900 __ mov(Operand::ForCell(cell_handle), value);
2901 // Cells are always rescanned, so no write barrier here.
2905 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
2906 Register context = ToRegister(instr->context());
2907 Register result = ToRegister(instr->result());
2908 __ mov(result, ContextOperand(context, instr->slot_index()));
2910 if (instr->hydrogen()->RequiresHoleCheck()) {
2911 __ cmp(result, factory()->the_hole_value());
2912 if (instr->hydrogen()->DeoptimizesOnHole()) {
2913 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2916 __ j(not_equal, &is_not_hole, Label::kNear);
2917 __ mov(result, factory()->undefined_value());
2918 __ bind(&is_not_hole);
2924 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
2925 Register context = ToRegister(instr->context());
2926 Register value = ToRegister(instr->value());
2928 Label skip_assignment;
2930 Operand target = ContextOperand(context, instr->slot_index());
2931 if (instr->hydrogen()->RequiresHoleCheck()) {
2932 __ cmp(target, factory()->the_hole_value());
2933 if (instr->hydrogen()->DeoptimizesOnHole()) {
2934 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
2936 __ j(not_equal, &skip_assignment, Label::kNear);
2940 __ mov(target, value);
2941 if (instr->hydrogen()->NeedsWriteBarrier()) {
2942 SmiCheck check_needed =
2943 instr->hydrogen()->value()->type().IsHeapObject()
2944 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2945 Register temp = ToRegister(instr->temp());
2946 int offset = Context::SlotOffset(instr->slot_index());
2947 __ RecordWriteContextSlot(context,
2952 EMIT_REMEMBERED_SET,
2956 __ bind(&skip_assignment);
2960 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
2961 HObjectAccess access = instr->hydrogen()->access();
2962 int offset = access.offset();
2964 if (access.IsExternalMemory()) {
2965 Register result = ToRegister(instr->result());
2966 MemOperand operand = instr->object()->IsConstantOperand()
2967 ? MemOperand::StaticVariable(ToExternalReference(
2968 LConstantOperand::cast(instr->object())))
2969 : MemOperand(ToRegister(instr->object()), offset);
2970 __ Load(result, operand, access.representation());
2974 Register object = ToRegister(instr->object());
2975 if (instr->hydrogen()->representation().IsDouble()) {
2976 XMMRegister result = ToDoubleRegister(instr->result());
2977 __ movsd(result, FieldOperand(object, offset));
2981 Register result = ToRegister(instr->result());
2982 if (!access.IsInobject()) {
2983 __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
2986 __ Load(result, FieldOperand(object, offset), access.representation());
2990 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
2991 DCHECK(!operand->IsDoubleRegister());
2992 if (operand->IsConstantOperand()) {
2993 Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
2994 AllowDeferredHandleDereference smi_check;
2995 if (object->IsSmi()) {
2996 __ Push(Handle<Smi>::cast(object));
2998 __ PushHeapObject(Handle<HeapObject>::cast(object));
3000 } else if (operand->IsRegister()) {
3001 __ push(ToRegister(operand));
3003 __ push(ToOperand(operand));
3008 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3009 DCHECK(ToRegister(instr->context()).is(esi));
3010 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3011 DCHECK(ToRegister(instr->result()).is(eax));
3013 __ mov(LoadDescriptor::NameRegister(), instr->name());
3014 if (FLAG_vector_ics) {
3015 EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3018 CodeFactory::LoadICInOptimizedCode(isolate(), NOT_CONTEXTUAL).code();
3019 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3023 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
3024 Register function = ToRegister(instr->function());
3025 Register temp = ToRegister(instr->temp());
3026 Register result = ToRegister(instr->result());
3028 // Get the prototype or initial map from the function.
3030 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
3032 // Check that the function has a prototype or an initial map.
3033 __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3034 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3036 // If the function does not have an initial map, we're done.
3038 __ CmpObjectType(result, MAP_TYPE, temp);
3039 __ j(not_equal, &done, Label::kNear);
3041 // Get the prototype from the initial map.
3042 __ mov(result, FieldOperand(result, Map::kPrototypeOffset));
3049 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
3050 Register result = ToRegister(instr->result());
3051 __ LoadRoot(result, instr->index());
3055 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
3056 Register arguments = ToRegister(instr->arguments());
3057 Register result = ToRegister(instr->result());
3058 if (instr->length()->IsConstantOperand() &&
3059 instr->index()->IsConstantOperand()) {
3060 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
3061 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
3062 int index = (const_length - const_index) + 1;
3063 __ mov(result, Operand(arguments, index * kPointerSize));
3065 Register length = ToRegister(instr->length());
3066 Operand index = ToOperand(instr->index());
3067 // There are two words between the frame pointer and the last argument.
3068 // Subtracting from length accounts for one of them add one more.
3069 __ sub(length, index);
3070 __ mov(result, Operand(arguments, length, times_4, kPointerSize));
3075 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
3076 ElementsKind elements_kind = instr->elements_kind();
3077 LOperand* key = instr->key();
3078 if (!key->IsConstantOperand() &&
3079 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
3081 __ SmiUntag(ToRegister(key));
3083 Operand operand(BuildFastArrayOperand(
3086 instr->hydrogen()->key()->representation(),
3088 instr->base_offset()));
3089 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
3090 elements_kind == FLOAT32_ELEMENTS) {
3091 XMMRegister result(ToDoubleRegister(instr->result()));
3092 __ movss(result, operand);
3093 __ cvtss2sd(result, result);
3094 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
3095 elements_kind == FLOAT64_ELEMENTS) {
3096 __ movsd(ToDoubleRegister(instr->result()), operand);
3098 Register result(ToRegister(instr->result()));
3099 switch (elements_kind) {
3100 case EXTERNAL_INT8_ELEMENTS:
3102 __ movsx_b(result, operand);
3104 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3105 case EXTERNAL_UINT8_ELEMENTS:
3106 case UINT8_ELEMENTS:
3107 case UINT8_CLAMPED_ELEMENTS:
3108 __ movzx_b(result, operand);
3110 case EXTERNAL_INT16_ELEMENTS:
3111 case INT16_ELEMENTS:
3112 __ movsx_w(result, operand);
3114 case EXTERNAL_UINT16_ELEMENTS:
3115 case UINT16_ELEMENTS:
3116 __ movzx_w(result, operand);
3118 case EXTERNAL_INT32_ELEMENTS:
3119 case INT32_ELEMENTS:
3120 __ mov(result, operand);
3122 case EXTERNAL_UINT32_ELEMENTS:
3123 case UINT32_ELEMENTS:
3124 __ mov(result, operand);
3125 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
3126 __ test(result, Operand(result));
3127 DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
3130 case EXTERNAL_FLOAT32_ELEMENTS:
3131 case EXTERNAL_FLOAT64_ELEMENTS:
3132 case FLOAT32_ELEMENTS:
3133 case FLOAT64_ELEMENTS:
3134 case FAST_SMI_ELEMENTS:
3136 case FAST_DOUBLE_ELEMENTS:
3137 case FAST_HOLEY_SMI_ELEMENTS:
3138 case FAST_HOLEY_ELEMENTS:
3139 case FAST_HOLEY_DOUBLE_ELEMENTS:
3140 case DICTIONARY_ELEMENTS:
3141 case SLOPPY_ARGUMENTS_ELEMENTS:
3149 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3150 if (instr->hydrogen()->RequiresHoleCheck()) {
3151 Operand hole_check_operand = BuildFastArrayOperand(
3152 instr->elements(), instr->key(),
3153 instr->hydrogen()->key()->representation(),
3154 FAST_DOUBLE_ELEMENTS,
3155 instr->base_offset() + sizeof(kHoleNanLower32));
3156 __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3157 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3160 Operand double_load_operand = BuildFastArrayOperand(
3163 instr->hydrogen()->key()->representation(),
3164 FAST_DOUBLE_ELEMENTS,
3165 instr->base_offset());
3166 XMMRegister result = ToDoubleRegister(instr->result());
3167 __ movsd(result, double_load_operand);
3171 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3172 Register result = ToRegister(instr->result());
3176 BuildFastArrayOperand(instr->elements(), instr->key(),
3177 instr->hydrogen()->key()->representation(),
3178 FAST_ELEMENTS, instr->base_offset()));
3180 // Check for the hole value.
3181 if (instr->hydrogen()->RequiresHoleCheck()) {
3182 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3183 __ test(result, Immediate(kSmiTagMask));
3184 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
3186 __ cmp(result, factory()->the_hole_value());
3187 DeoptimizeIf(equal, instr, Deoptimizer::kHole);
3193 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3194 if (instr->is_typed_elements()) {
3195 DoLoadKeyedExternalArray(instr);
3196 } else if (instr->hydrogen()->representation().IsDouble()) {
3197 DoLoadKeyedFixedDoubleArray(instr);
3199 DoLoadKeyedFixedArray(instr);
3204 Operand LCodeGen::BuildFastArrayOperand(
3205 LOperand* elements_pointer,
3207 Representation key_representation,
3208 ElementsKind elements_kind,
3209 uint32_t base_offset) {
3210 Register elements_pointer_reg = ToRegister(elements_pointer);
3211 int element_shift_size = ElementsKindToShiftSize(elements_kind);
3212 int shift_size = element_shift_size;
3213 if (key->IsConstantOperand()) {
3214 int constant_value = ToInteger32(LConstantOperand::cast(key));
3215 if (constant_value & 0xF0000000) {
3216 Abort(kArrayIndexConstantValueTooBig);
3218 return Operand(elements_pointer_reg,
3219 ((constant_value) << shift_size)
3222 // Take the tag bit into account while computing the shift size.
3223 if (key_representation.IsSmi() && (shift_size >= 1)) {
3224 shift_size -= kSmiTagSize;
3226 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3227 return Operand(elements_pointer_reg,
3235 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3236 DCHECK(ToRegister(instr->context()).is(esi));
3237 DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3238 DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
3240 if (FLAG_vector_ics) {
3241 EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3244 Handle<Code> ic = CodeFactory::KeyedLoadICInOptimizedCode(isolate()).code();
3245 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3249 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3250 Register result = ToRegister(instr->result());
3252 if (instr->hydrogen()->from_inlined()) {
3253 __ lea(result, Operand(esp, -2 * kPointerSize));
3255 // Check for arguments adapter frame.
3256 Label done, adapted;
3257 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3258 __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
3259 __ cmp(Operand(result),
3260 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3261 __ j(equal, &adapted, Label::kNear);
3263 // No arguments adaptor frame.
3264 __ mov(result, Operand(ebp));
3265 __ jmp(&done, Label::kNear);
3267 // Arguments adaptor frame present.
3269 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3271 // Result is the frame pointer for the frame if not adapted and for the real
3272 // frame below the adaptor frame if adapted.
3278 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3279 Operand elem = ToOperand(instr->elements());
3280 Register result = ToRegister(instr->result());
3284 // If no arguments adaptor frame the number of arguments is fixed.
3286 __ mov(result, Immediate(scope()->num_parameters()));
3287 __ j(equal, &done, Label::kNear);
3289 // Arguments adaptor frame present. Get argument length from there.
3290 __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3291 __ mov(result, Operand(result,
3292 ArgumentsAdaptorFrameConstants::kLengthOffset));
3293 __ SmiUntag(result);
3295 // Argument length is in result register.
3300 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3301 Register receiver = ToRegister(instr->receiver());
3302 Register function = ToRegister(instr->function());
3304 // If the receiver is null or undefined, we have to pass the global
3305 // object as a receiver to normal functions. Values have to be
3306 // passed unchanged to builtins and strict-mode functions.
3307 Label receiver_ok, global_object;
3308 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3309 Register scratch = ToRegister(instr->temp());
3311 if (!instr->hydrogen()->known_function()) {
3312 // Do not transform the receiver to object for strict mode
3315 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3316 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
3317 1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3318 __ j(not_equal, &receiver_ok, dist);
3320 // Do not transform the receiver to object for builtins.
3321 __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
3322 1 << SharedFunctionInfo::kNativeBitWithinByte);
3323 __ j(not_equal, &receiver_ok, dist);
3326 // Normal function. Replace undefined or null with global receiver.
3327 __ cmp(receiver, factory()->null_value());
3328 __ j(equal, &global_object, Label::kNear);
3329 __ cmp(receiver, factory()->undefined_value());
3330 __ j(equal, &global_object, Label::kNear);
3332 // The receiver should be a JS object.
3333 __ test(receiver, Immediate(kSmiTagMask));
3334 DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
3335 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3336 DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
3338 __ jmp(&receiver_ok, Label::kNear);
3339 __ bind(&global_object);
3340 __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
3341 const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
3342 __ mov(receiver, Operand(receiver, global_offset));
3343 const int proxy_offset = GlobalObject::kGlobalProxyOffset;
3344 __ mov(receiver, FieldOperand(receiver, proxy_offset));
3345 __ bind(&receiver_ok);
3349 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3350 Register receiver = ToRegister(instr->receiver());
3351 Register function = ToRegister(instr->function());
3352 Register length = ToRegister(instr->length());
3353 Register elements = ToRegister(instr->elements());
3354 DCHECK(receiver.is(eax)); // Used for parameter count.
3355 DCHECK(function.is(edi)); // Required by InvokeFunction.
3356 DCHECK(ToRegister(instr->result()).is(eax));
3358 // Copy the arguments to this function possibly from the
3359 // adaptor frame below it.
3360 const uint32_t kArgumentsLimit = 1 * KB;
3361 __ cmp(length, kArgumentsLimit);
3362 DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
3365 __ mov(receiver, length);
3367 // Loop through the arguments pushing them onto the execution
3370 // length is a small non-negative integer, due to the test above.
3371 __ test(length, Operand(length));
3372 __ j(zero, &invoke, Label::kNear);
3374 __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
3376 __ j(not_zero, &loop);
3378 // Invoke the function.
3380 DCHECK(instr->HasPointerMap());
3381 LPointerMap* pointers = instr->pointer_map();
3382 SafepointGenerator safepoint_generator(
3383 this, pointers, Safepoint::kLazyDeopt);
3384 ParameterCount actual(eax);
3385 __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
3389 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
3394 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3395 LOperand* argument = instr->value();
3396 EmitPushTaggedOperand(argument);
3400 void LCodeGen::DoDrop(LDrop* instr) {
3401 __ Drop(instr->count());
3405 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3406 Register result = ToRegister(instr->result());
3407 __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
3411 void LCodeGen::DoContext(LContext* instr) {
3412 Register result = ToRegister(instr->result());
3413 if (info()->IsOptimizing()) {
3414 __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
3416 // If there is no frame, the context must be in esi.
3417 DCHECK(result.is(esi));
3422 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3423 DCHECK(ToRegister(instr->context()).is(esi));
3424 __ push(esi); // The context is the first argument.
3425 __ push(Immediate(instr->hydrogen()->pairs()));
3426 __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3427 CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3431 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3432 int formal_parameter_count, int arity,
3433 LInstruction* instr) {
3434 bool dont_adapt_arguments =
3435 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3436 bool can_invoke_directly =
3437 dont_adapt_arguments || formal_parameter_count == arity;
3439 Register function_reg = edi;
3441 if (can_invoke_directly) {
3443 __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
3445 // Set eax to arguments count if adaption is not needed. Assumes that eax
3446 // is available to write to at this point.
3447 if (dont_adapt_arguments) {
3451 // Invoke function directly.
3452 if (function.is_identical_to(info()->closure())) {
3455 __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
3457 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3459 // We need to adapt arguments.
3460 LPointerMap* pointers = instr->pointer_map();
3461 SafepointGenerator generator(
3462 this, pointers, Safepoint::kLazyDeopt);
3463 ParameterCount count(arity);
3464 ParameterCount expected(formal_parameter_count);
3465 __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
3470 void LCodeGen::DoTailCallThroughMegamorphicCache(
3471 LTailCallThroughMegamorphicCache* instr) {
3472 Register receiver = ToRegister(instr->receiver());
3473 Register name = ToRegister(instr->name());
3474 DCHECK(receiver.is(LoadDescriptor::ReceiverRegister()));
3475 DCHECK(name.is(LoadDescriptor::NameRegister()));
3476 Register slot = FLAG_vector_ics ? ToRegister(instr->slot()) : no_reg;
3477 Register vector = FLAG_vector_ics ? ToRegister(instr->vector()) : no_reg;
3479 Register scratch = ebx;
3480 Register extra = edi;
3481 DCHECK(!extra.is(slot) && !extra.is(vector));
3482 DCHECK(!scratch.is(receiver) && !scratch.is(name));
3483 DCHECK(!extra.is(receiver) && !extra.is(name));
3485 // Important for the tail-call.
3486 bool must_teardown_frame = NeedsEagerFrame();
3488 if (!instr->hydrogen()->is_just_miss()) {
3489 if (FLAG_vector_ics) {
3494 // The probe will tail call to a handler if found.
3495 // If --vector-ics is on, then it knows to pop the two args first.
3496 DCHECK(!instr->hydrogen()->is_keyed_load());
3497 isolate()->stub_cache()->GenerateProbe(
3498 masm(), Code::LOAD_IC, instr->hydrogen()->flags(), must_teardown_frame,
3499 receiver, name, scratch, extra);
3501 if (FLAG_vector_ics) {
3507 // Tail call to miss if we ended up here.
3508 if (must_teardown_frame) __ leave();
3509 if (instr->hydrogen()->is_keyed_load()) {
3510 KeyedLoadIC::GenerateMiss(masm());
3512 LoadIC::GenerateMiss(masm());
3517 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3518 DCHECK(ToRegister(instr->result()).is(eax));
3520 if (instr->hydrogen()->IsTailCall()) {
3521 if (NeedsEagerFrame()) __ leave();
3523 if (instr->target()->IsConstantOperand()) {
3524 LConstantOperand* target = LConstantOperand::cast(instr->target());
3525 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3526 __ jmp(code, RelocInfo::CODE_TARGET);
3528 DCHECK(instr->target()->IsRegister());
3529 Register target = ToRegister(instr->target());
3530 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3534 LPointerMap* pointers = instr->pointer_map();
3535 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3537 if (instr->target()->IsConstantOperand()) {
3538 LConstantOperand* target = LConstantOperand::cast(instr->target());
3539 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3540 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3541 __ call(code, RelocInfo::CODE_TARGET);
3543 DCHECK(instr->target()->IsRegister());
3544 Register target = ToRegister(instr->target());
3545 generator.BeforeCall(__ CallSize(Operand(target)));
3546 __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
3549 generator.AfterCall();
3554 void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3555 DCHECK(ToRegister(instr->function()).is(edi));
3556 DCHECK(ToRegister(instr->result()).is(eax));
3558 if (instr->hydrogen()->pass_argument_count()) {
3559 __ mov(eax, instr->arity());
3563 __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
3565 bool is_self_call = false;
3566 if (instr->hydrogen()->function()->IsConstant()) {
3567 HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
3568 Handle<JSFunction> jsfun =
3569 Handle<JSFunction>::cast(fun_const->handle(isolate()));
3570 is_self_call = jsfun.is_identical_to(info()->closure());
3576 __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
3579 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3583 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3584 Register input_reg = ToRegister(instr->value());
3585 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
3586 factory()->heap_number_map());
3587 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3589 Label slow, allocated, done;
3590 Register tmp = input_reg.is(eax) ? ecx : eax;
3591 Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;
3593 // Preserve the value of all registers.
3594 PushSafepointRegistersScope scope(this);
3596 __ mov(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3597 // Check the sign of the argument. If the argument is positive, just
3598 // return it. We do not need to patch the stack since |input| and
3599 // |result| are the same register and |input| will be restored
3600 // unchanged by popping safepoint registers.
3601 __ test(tmp, Immediate(HeapNumber::kSignMask));
3602 __ j(zero, &done, Label::kNear);
3604 __ AllocateHeapNumber(tmp, tmp2, no_reg, &slow);
3605 __ jmp(&allocated, Label::kNear);
3607 // Slow case: Call the runtime system to do the number allocation.
3609 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
3610 instr, instr->context());
3611 // Set the pointer to the new heap number in tmp.
3612 if (!tmp.is(eax)) __ mov(tmp, eax);
3613 // Restore input_reg after call to runtime.
3614 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3616 __ bind(&allocated);
3617 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3618 __ and_(tmp2, ~HeapNumber::kSignMask);
3619 __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
3620 __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
3621 __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
3622 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3628 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3629 Register input_reg = ToRegister(instr->value());
3630 __ test(input_reg, Operand(input_reg));
3632 __ j(not_sign, &is_positive, Label::kNear);
3633 __ neg(input_reg); // Sets flags.
3634 DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
3635 __ bind(&is_positive);
3639 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3640 // Class for deferred case.
3641 class DeferredMathAbsTaggedHeapNumber FINAL : public LDeferredCode {
3643 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
3645 : LDeferredCode(codegen), instr_(instr) { }
3646 void Generate() OVERRIDE {
3647 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3649 LInstruction* instr() OVERRIDE { return instr_; }
3655 DCHECK(instr->value()->Equals(instr->result()));
3656 Representation r = instr->hydrogen()->value()->representation();
3659 XMMRegister scratch = double_scratch0();
3660 XMMRegister input_reg = ToDoubleRegister(instr->value());
3661 __ xorps(scratch, scratch);
3662 __ subsd(scratch, input_reg);
3663 __ andps(input_reg, scratch);
3664 } else if (r.IsSmiOrInteger32()) {
3665 EmitIntegerMathAbs(instr);
3666 } else { // Tagged case.
3667 DeferredMathAbsTaggedHeapNumber* deferred =
3668 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
3669 Register input_reg = ToRegister(instr->value());
3671 __ JumpIfNotSmi(input_reg, deferred->entry());
3672 EmitIntegerMathAbs(instr);
3673 __ bind(deferred->exit());
3678 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3679 XMMRegister xmm_scratch = double_scratch0();
3680 Register output_reg = ToRegister(instr->result());
3681 XMMRegister input_reg = ToDoubleRegister(instr->value());
3683 if (CpuFeatures::IsSupported(SSE4_1)) {
3684 CpuFeatureScope scope(masm(), SSE4_1);
3685 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3686 // Deoptimize on negative zero.
3688 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3689 __ ucomisd(input_reg, xmm_scratch);
3690 __ j(not_equal, &non_zero, Label::kNear);
3691 __ movmskpd(output_reg, input_reg);
3692 __ test(output_reg, Immediate(1));
3693 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3696 __ roundsd(xmm_scratch, input_reg, Assembler::kRoundDown);
3697 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3698 // Overflow is signalled with minint.
3699 __ cmp(output_reg, 0x1);
3700 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3702 Label negative_sign, done;
3703 // Deoptimize on unordered.
3704 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3705 __ ucomisd(input_reg, xmm_scratch);
3706 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3707 __ j(below, &negative_sign, Label::kNear);
3709 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3710 // Check for negative zero.
3711 Label positive_sign;
3712 __ j(above, &positive_sign, Label::kNear);
3713 __ movmskpd(output_reg, input_reg);
3714 __ test(output_reg, Immediate(1));
3715 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3716 __ Move(output_reg, Immediate(0));
3717 __ jmp(&done, Label::kNear);
3718 __ bind(&positive_sign);
3721 // Use truncating instruction (OK because input is positive).
3722 __ cvttsd2si(output_reg, Operand(input_reg));
3723 // Overflow is signalled with minint.
3724 __ cmp(output_reg, 0x1);
3725 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3726 __ jmp(&done, Label::kNear);
3728 // Non-zero negative reaches here.
3729 __ bind(&negative_sign);
3730 // Truncate, then compare and compensate.
3731 __ cvttsd2si(output_reg, Operand(input_reg));
3732 __ Cvtsi2sd(xmm_scratch, output_reg);
3733 __ ucomisd(input_reg, xmm_scratch);
3734 __ j(equal, &done, Label::kNear);
3735 __ sub(output_reg, Immediate(1));
3736 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3743 void LCodeGen::DoMathRound(LMathRound* instr) {
3744 Register output_reg = ToRegister(instr->result());
3745 XMMRegister input_reg = ToDoubleRegister(instr->value());
3746 XMMRegister xmm_scratch = double_scratch0();
3747 XMMRegister input_temp = ToDoubleRegister(instr->temp());
3748 ExternalReference one_half = ExternalReference::address_of_one_half();
3749 ExternalReference minus_one_half =
3750 ExternalReference::address_of_minus_one_half();
3752 Label done, round_to_zero, below_one_half, do_not_compensate;
3753 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3755 __ movsd(xmm_scratch, Operand::StaticVariable(one_half));
3756 __ ucomisd(xmm_scratch, input_reg);
3757 __ j(above, &below_one_half, Label::kNear);
3759 // CVTTSD2SI rounds towards zero, since 0.5 <= x, we use floor(0.5 + x).
3760 __ addsd(xmm_scratch, input_reg);
3761 __ cvttsd2si(output_reg, Operand(xmm_scratch));
3762 // Overflow is signalled with minint.
3763 __ cmp(output_reg, 0x1);
3764 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3765 __ jmp(&done, dist);
3767 __ bind(&below_one_half);
3768 __ movsd(xmm_scratch, Operand::StaticVariable(minus_one_half));
3769 __ ucomisd(xmm_scratch, input_reg);
3770 __ j(below_equal, &round_to_zero, Label::kNear);
3772 // CVTTSD2SI rounds towards zero, we use ceil(x - (-0.5)) and then
3773 // compare and compensate.
3774 __ movaps(input_temp, input_reg); // Do not alter input_reg.
3775 __ subsd(input_temp, xmm_scratch);
3776 __ cvttsd2si(output_reg, Operand(input_temp));
3777 // Catch minint due to overflow, and to prevent overflow when compensating.
3778 __ cmp(output_reg, 0x1);
3779 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
3781 __ Cvtsi2sd(xmm_scratch, output_reg);
3782 __ ucomisd(xmm_scratch, input_temp);
3783 __ j(equal, &done, dist);
3784 __ sub(output_reg, Immediate(1));
3785 // No overflow because we already ruled out minint.
3786 __ jmp(&done, dist);
3788 __ bind(&round_to_zero);
3789 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3790 // we can ignore the difference between a result of -0 and +0.
3791 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3792 // If the sign is positive, we return +0.
3793 __ movmskpd(output_reg, input_reg);
3794 __ test(output_reg, Immediate(1));
3795 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3797 __ Move(output_reg, Immediate(0));
3802 void LCodeGen::DoMathFround(LMathFround* instr) {
3803 XMMRegister input_reg = ToDoubleRegister(instr->value());
3804 XMMRegister output_reg = ToDoubleRegister(instr->result());
3805 __ cvtsd2ss(output_reg, input_reg);
3806 __ cvtss2sd(output_reg, output_reg);
3810 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3811 Operand input = ToOperand(instr->value());
3812 XMMRegister output = ToDoubleRegister(instr->result());
3813 __ sqrtsd(output, input);
3817 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3818 XMMRegister xmm_scratch = double_scratch0();
3819 XMMRegister input_reg = ToDoubleRegister(instr->value());
3820 Register scratch = ToRegister(instr->temp());
3821 DCHECK(ToDoubleRegister(instr->result()).is(input_reg));
3823 // Note that according to ECMA-262 15.8.2.13:
3824 // Math.pow(-Infinity, 0.5) == Infinity
3825 // Math.sqrt(-Infinity) == NaN
3827 // Check base for -Infinity. According to IEEE-754, single-precision
3828 // -Infinity has the highest 9 bits set and the lowest 23 bits cleared.
3829 __ mov(scratch, 0xFF800000);
3830 __ movd(xmm_scratch, scratch);
3831 __ cvtss2sd(xmm_scratch, xmm_scratch);
3832 __ ucomisd(input_reg, xmm_scratch);
3833 // Comparing -Infinity with NaN results in "unordered", which sets the
3834 // zero flag as if both were equal. However, it also sets the carry flag.
3835 __ j(not_equal, &sqrt, Label::kNear);
3836 __ j(carry, &sqrt, Label::kNear);
3837 // If input is -Infinity, return Infinity.
3838 __ xorps(input_reg, input_reg);
3839 __ subsd(input_reg, xmm_scratch);
3840 __ jmp(&done, Label::kNear);
3844 __ xorps(xmm_scratch, xmm_scratch);
3845 __ addsd(input_reg, xmm_scratch); // Convert -0 to +0.
3846 __ sqrtsd(input_reg, input_reg);
3851 void LCodeGen::DoPower(LPower* instr) {
3852 Representation exponent_type = instr->hydrogen()->right()->representation();
3853 // Having marked this as a call, we can use any registers.
3854 // Just make sure that the input/output registers are the expected ones.
3855 Register tagged_exponent = MathPowTaggedDescriptor::exponent();
3856 DCHECK(!instr->right()->IsDoubleRegister() ||
3857 ToDoubleRegister(instr->right()).is(xmm1));
3858 DCHECK(!instr->right()->IsRegister() ||
3859 ToRegister(instr->right()).is(tagged_exponent));
3860 DCHECK(ToDoubleRegister(instr->left()).is(xmm2));
3861 DCHECK(ToDoubleRegister(instr->result()).is(xmm3));
3863 if (exponent_type.IsSmi()) {
3864 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3866 } else if (exponent_type.IsTagged()) {
3868 __ JumpIfSmi(tagged_exponent, &no_deopt);
3869 DCHECK(!ecx.is(tagged_exponent));
3870 __ CmpObjectType(tagged_exponent, HEAP_NUMBER_TYPE, ecx);
3871 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
3873 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3875 } else if (exponent_type.IsInteger32()) {
3876 MathPowStub stub(isolate(), MathPowStub::INTEGER);
3879 DCHECK(exponent_type.IsDouble());
3880 MathPowStub stub(isolate(), MathPowStub::DOUBLE);
3886 void LCodeGen::DoMathLog(LMathLog* instr) {
3887 DCHECK(instr->value()->Equals(instr->result()));
3888 XMMRegister input_reg = ToDoubleRegister(instr->value());
3889 XMMRegister xmm_scratch = double_scratch0();
3890 Label positive, done, zero;
3891 __ xorps(xmm_scratch, xmm_scratch);
3892 __ ucomisd(input_reg, xmm_scratch);
3893 __ j(above, &positive, Label::kNear);
3894 __ j(not_carry, &zero, Label::kNear);
3895 __ pcmpeqd(input_reg, input_reg);
3896 __ jmp(&done, Label::kNear);
3898 ExternalReference ninf =
3899 ExternalReference::address_of_negative_infinity();
3900 __ movsd(input_reg, Operand::StaticVariable(ninf));
3901 __ jmp(&done, Label::kNear);
3904 __ sub(Operand(esp), Immediate(kDoubleSize));
3905 __ movsd(Operand(esp, 0), input_reg);
3906 __ fld_d(Operand(esp, 0));
3908 __ fstp_d(Operand(esp, 0));
3909 __ movsd(input_reg, Operand(esp, 0));
3910 __ add(Operand(esp), Immediate(kDoubleSize));
3915 void LCodeGen::DoMathClz32(LMathClz32* instr) {
3916 Register input = ToRegister(instr->value());
3917 Register result = ToRegister(instr->result());
3918 Label not_zero_input;
3919 __ bsr(result, input);
3921 __ j(not_zero, ¬_zero_input);
3922 __ Move(result, Immediate(63)); // 63^31 == 32
3924 __ bind(¬_zero_input);
3925 __ xor_(result, Immediate(31)); // for x in [0..31], 31^x == 31-x.
3929 void LCodeGen::DoMathExp(LMathExp* instr) {
3930 XMMRegister input = ToDoubleRegister(instr->value());
3931 XMMRegister result = ToDoubleRegister(instr->result());
3932 XMMRegister temp0 = double_scratch0();
3933 Register temp1 = ToRegister(instr->temp1());
3934 Register temp2 = ToRegister(instr->temp2());
3936 MathExpGenerator::EmitMathExp(masm(), input, result, temp0, temp1, temp2);
3940 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
3941 DCHECK(ToRegister(instr->context()).is(esi));
3942 DCHECK(ToRegister(instr->function()).is(edi));
3943 DCHECK(instr->HasPointerMap());
3945 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
3946 if (known_function.is_null()) {
3947 LPointerMap* pointers = instr->pointer_map();
3948 SafepointGenerator generator(
3949 this, pointers, Safepoint::kLazyDeopt);
3950 ParameterCount count(instr->arity());
3951 __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
3953 CallKnownFunction(known_function,
3954 instr->hydrogen()->formal_parameter_count(),
3955 instr->arity(), instr);
3960 void LCodeGen::DoCallFunction(LCallFunction* instr) {
3961 DCHECK(ToRegister(instr->context()).is(esi));
3962 DCHECK(ToRegister(instr->function()).is(edi));
3963 DCHECK(ToRegister(instr->result()).is(eax));
3965 int arity = instr->arity();
3966 CallFunctionFlags flags = instr->hydrogen()->function_flags();
3967 if (instr->hydrogen()->HasVectorAndSlot()) {
3968 Register slot_register = ToRegister(instr->temp_slot());
3969 Register vector_register = ToRegister(instr->temp_vector());
3970 DCHECK(slot_register.is(edx));
3971 DCHECK(vector_register.is(ebx));
3973 AllowDeferredHandleDereference vector_structure_check;
3974 Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
3975 int index = vector->GetIndex(instr->hydrogen()->slot());
3977 __ mov(vector_register, vector);
3978 __ mov(slot_register, Immediate(Smi::FromInt(index)));
3980 CallICState::CallType call_type =
3981 (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
3984 CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
3985 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3987 CallFunctionStub stub(isolate(), arity, flags);
3988 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3993 void LCodeGen::DoCallNew(LCallNew* instr) {
3994 DCHECK(ToRegister(instr->context()).is(esi));
3995 DCHECK(ToRegister(instr->constructor()).is(edi));
3996 DCHECK(ToRegister(instr->result()).is(eax));
3998 // No cell in ebx for construct type feedback in optimized code
3999 __ mov(ebx, isolate()->factory()->undefined_value());
4000 CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
4001 __ Move(eax, Immediate(instr->arity()));
4002 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4006 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
4007 DCHECK(ToRegister(instr->context()).is(esi));
4008 DCHECK(ToRegister(instr->constructor()).is(edi));
4009 DCHECK(ToRegister(instr->result()).is(eax));
4011 __ Move(eax, Immediate(instr->arity()));
4012 __ mov(ebx, isolate()->factory()->undefined_value());
4013 ElementsKind kind = instr->hydrogen()->elements_kind();
4014 AllocationSiteOverrideMode override_mode =
4015 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
4016 ? DISABLE_ALLOCATION_SITES
4019 if (instr->arity() == 0) {
4020 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
4021 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4022 } else if (instr->arity() == 1) {
4024 if (IsFastPackedElementsKind(kind)) {
4026 // We might need a change here
4027 // look at the first argument
4028 __ mov(ecx, Operand(esp, 0));
4030 __ j(zero, &packed_case, Label::kNear);
4032 ElementsKind holey_kind = GetHoleyElementsKind(kind);
4033 ArraySingleArgumentConstructorStub stub(isolate(),
4036 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4037 __ jmp(&done, Label::kNear);
4038 __ bind(&packed_case);
4041 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
4042 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4045 ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
4046 CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
4051 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4052 DCHECK(ToRegister(instr->context()).is(esi));
4053 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
4057 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
4058 Register function = ToRegister(instr->function());
4059 Register code_object = ToRegister(instr->code_object());
4060 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
4061 __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
4065 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
4066 Register result = ToRegister(instr->result());
4067 Register base = ToRegister(instr->base_object());
4068 if (instr->offset()->IsConstantOperand()) {
4069 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
4070 __ lea(result, Operand(base, ToInteger32(offset)));
4072 Register offset = ToRegister(instr->offset());
4073 __ lea(result, Operand(base, offset, times_1, 0));
4078 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
4079 Representation representation = instr->hydrogen()->field_representation();
4081 HObjectAccess access = instr->hydrogen()->access();
4082 int offset = access.offset();
4084 if (access.IsExternalMemory()) {
4085 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4086 MemOperand operand = instr->object()->IsConstantOperand()
4087 ? MemOperand::StaticVariable(
4088 ToExternalReference(LConstantOperand::cast(instr->object())))
4089 : MemOperand(ToRegister(instr->object()), offset);
4090 if (instr->value()->IsConstantOperand()) {
4091 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4092 __ mov(operand, Immediate(ToInteger32(operand_value)));
4094 Register value = ToRegister(instr->value());
4095 __ Store(value, operand, representation);
4100 Register object = ToRegister(instr->object());
4101 __ AssertNotSmi(object);
4103 DCHECK(!representation.IsSmi() ||
4104 !instr->value()->IsConstantOperand() ||
4105 IsSmi(LConstantOperand::cast(instr->value())));
4106 if (representation.IsDouble()) {
4107 DCHECK(access.IsInobject());
4108 DCHECK(!instr->hydrogen()->has_transition());
4109 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4110 XMMRegister value = ToDoubleRegister(instr->value());
4111 __ movsd(FieldOperand(object, offset), value);
4115 if (instr->hydrogen()->has_transition()) {
4116 Handle<Map> transition = instr->hydrogen()->transition_map();
4117 AddDeprecationDependency(transition);
4118 __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
4119 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
4120 Register temp = ToRegister(instr->temp());
4121 Register temp_map = ToRegister(instr->temp_map());
4122 // Update the write barrier for the map field.
4123 __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
4128 Register write_register = object;
4129 if (!access.IsInobject()) {
4130 write_register = ToRegister(instr->temp());
4131 __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4134 MemOperand operand = FieldOperand(write_register, offset);
4135 if (instr->value()->IsConstantOperand()) {
4136 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4137 if (operand_value->IsRegister()) {
4138 Register value = ToRegister(operand_value);
4139 __ Store(value, operand, representation);
4140 } else if (representation.IsInteger32()) {
4141 Immediate immediate = ToImmediate(operand_value, representation);
4142 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4143 __ mov(operand, immediate);
4145 Handle<Object> handle_value = ToHandle(operand_value);
4146 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
4147 __ mov(operand, handle_value);
4150 Register value = ToRegister(instr->value());
4151 __ Store(value, operand, representation);
4154 if (instr->hydrogen()->NeedsWriteBarrier()) {
4155 Register value = ToRegister(instr->value());
4156 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4157 // Update the write barrier for the object for in-object properties.
4158 __ RecordWriteField(write_register,
4163 EMIT_REMEMBERED_SET,
4164 instr->hydrogen()->SmiCheckForWriteBarrier(),
4165 instr->hydrogen()->PointersToHereCheckForValue());
4170 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4171 DCHECK(ToRegister(instr->context()).is(esi));
4172 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4173 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4175 __ mov(StoreDescriptor::NameRegister(), instr->name());
4176 Handle<Code> ic = StoreIC::initialize_stub(isolate(), instr->language_mode());
4177 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4181 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4182 Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
4183 if (instr->index()->IsConstantOperand()) {
4184 __ cmp(ToOperand(instr->length()),
4185 ToImmediate(LConstantOperand::cast(instr->index()),
4186 instr->hydrogen()->length()->representation()));
4187 cc = CommuteCondition(cc);
4188 } else if (instr->length()->IsConstantOperand()) {
4189 __ cmp(ToOperand(instr->index()),
4190 ToImmediate(LConstantOperand::cast(instr->length()),
4191 instr->hydrogen()->index()->representation()));
4193 __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
4195 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
4197 __ j(NegateCondition(cc), &done, Label::kNear);
4201 DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
4206 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4207 ElementsKind elements_kind = instr->elements_kind();
4208 LOperand* key = instr->key();
4209 if (!key->IsConstantOperand() &&
4210 ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
4212 __ SmiUntag(ToRegister(key));
4214 Operand operand(BuildFastArrayOperand(
4217 instr->hydrogen()->key()->representation(),
4219 instr->base_offset()));
4220 if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
4221 elements_kind == FLOAT32_ELEMENTS) {
4222 XMMRegister xmm_scratch = double_scratch0();
4223 __ cvtsd2ss(xmm_scratch, ToDoubleRegister(instr->value()));
4224 __ movss(operand, xmm_scratch);
4225 } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
4226 elements_kind == FLOAT64_ELEMENTS) {
4227 __ movsd(operand, ToDoubleRegister(instr->value()));
4229 Register value = ToRegister(instr->value());
4230 switch (elements_kind) {
4231 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
4232 case EXTERNAL_UINT8_ELEMENTS:
4233 case EXTERNAL_INT8_ELEMENTS:
4234 case UINT8_ELEMENTS:
4236 case UINT8_CLAMPED_ELEMENTS:
4237 __ mov_b(operand, value);
4239 case EXTERNAL_INT16_ELEMENTS:
4240 case EXTERNAL_UINT16_ELEMENTS:
4241 case UINT16_ELEMENTS:
4242 case INT16_ELEMENTS:
4243 __ mov_w(operand, value);
4245 case EXTERNAL_INT32_ELEMENTS:
4246 case EXTERNAL_UINT32_ELEMENTS:
4247 case UINT32_ELEMENTS:
4248 case INT32_ELEMENTS:
4249 __ mov(operand, value);
4251 case EXTERNAL_FLOAT32_ELEMENTS:
4252 case EXTERNAL_FLOAT64_ELEMENTS:
4253 case FLOAT32_ELEMENTS:
4254 case FLOAT64_ELEMENTS:
4255 case FAST_SMI_ELEMENTS:
4257 case FAST_DOUBLE_ELEMENTS:
4258 case FAST_HOLEY_SMI_ELEMENTS:
4259 case FAST_HOLEY_ELEMENTS:
4260 case FAST_HOLEY_DOUBLE_ELEMENTS:
4261 case DICTIONARY_ELEMENTS:
4262 case SLOPPY_ARGUMENTS_ELEMENTS:
4270 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4271 Operand double_store_operand = BuildFastArrayOperand(
4274 instr->hydrogen()->key()->representation(),
4275 FAST_DOUBLE_ELEMENTS,
4276 instr->base_offset());
4278 XMMRegister value = ToDoubleRegister(instr->value());
4280 if (instr->NeedsCanonicalization()) {
4281 XMMRegister xmm_scratch = double_scratch0();
4282 // Turn potential sNaN value into qNaN.
4283 __ xorps(xmm_scratch, xmm_scratch);
4284 __ subsd(value, xmm_scratch);
4287 __ movsd(double_store_operand, value);
4291 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4292 Register elements = ToRegister(instr->elements());
4293 Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;
4295 Operand operand = BuildFastArrayOperand(
4298 instr->hydrogen()->key()->representation(),
4300 instr->base_offset());
4301 if (instr->value()->IsRegister()) {
4302 __ mov(operand, ToRegister(instr->value()));
4304 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4305 if (IsSmi(operand_value)) {
4306 Immediate immediate = ToImmediate(operand_value, Representation::Smi());
4307 __ mov(operand, immediate);
4309 DCHECK(!IsInteger32(operand_value));
4310 Handle<Object> handle_value = ToHandle(operand_value);
4311 __ mov(operand, handle_value);
4315 if (instr->hydrogen()->NeedsWriteBarrier()) {
4316 DCHECK(instr->value()->IsRegister());
4317 Register value = ToRegister(instr->value());
4318 DCHECK(!instr->key()->IsConstantOperand());
4319 SmiCheck check_needed =
4320 instr->hydrogen()->value()->type().IsHeapObject()
4321 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4322 // Compute address of modified element and store it into key register.
4323 __ lea(key, operand);
4324 __ RecordWrite(elements,
4328 EMIT_REMEMBERED_SET,
4330 instr->hydrogen()->PointersToHereCheckForValue());
4335 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4336 // By cases...external, fast-double, fast
4337 if (instr->is_typed_elements()) {
4338 DoStoreKeyedExternalArray(instr);
4339 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4340 DoStoreKeyedFixedDoubleArray(instr);
4342 DoStoreKeyedFixedArray(instr);
4347 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4348 DCHECK(ToRegister(instr->context()).is(esi));
4349 DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
4350 DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
4351 DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
4354 CodeFactory::KeyedStoreIC(isolate(), instr->language_mode()).code();
4355 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4359 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4360 Register object = ToRegister(instr->object());
4361 Register temp = ToRegister(instr->temp());
4362 Label no_memento_found;
4363 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4364 DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
4365 __ bind(&no_memento_found);
4369 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4370 Register object_reg = ToRegister(instr->object());
4372 Handle<Map> from_map = instr->original_map();
4373 Handle<Map> to_map = instr->transitioned_map();
4374 ElementsKind from_kind = instr->from_kind();
4375 ElementsKind to_kind = instr->to_kind();
4377 Label not_applicable;
4378 bool is_simple_map_transition =
4379 IsSimpleMapChangeTransition(from_kind, to_kind);
4380 Label::Distance branch_distance =
4381 is_simple_map_transition ? Label::kNear : Label::kFar;
4382 __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4383 __ j(not_equal, ¬_applicable, branch_distance);
4384 if (is_simple_map_transition) {
4385 Register new_map_reg = ToRegister(instr->new_map_temp());
4386 __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
4389 DCHECK_NOT_NULL(instr->temp());
4390 __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4391 ToRegister(instr->temp()),
4394 DCHECK(ToRegister(instr->context()).is(esi));
4395 DCHECK(object_reg.is(eax));
4396 PushSafepointRegistersScope scope(this);
4397 __ mov(ebx, to_map);
4398 bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
4399 TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
4401 RecordSafepointWithLazyDeopt(instr,
4402 RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4404 __ bind(¬_applicable);
4408 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4409 class DeferredStringCharCodeAt FINAL : public LDeferredCode {
4411 DeferredStringCharCodeAt(LCodeGen* codegen,
4412 LStringCharCodeAt* instr)
4413 : LDeferredCode(codegen), instr_(instr) { }
4414 void Generate() OVERRIDE { codegen()->DoDeferredStringCharCodeAt(instr_); }
4415 LInstruction* instr() OVERRIDE { return instr_; }
4418 LStringCharCodeAt* instr_;
4421 DeferredStringCharCodeAt* deferred =
4422 new(zone()) DeferredStringCharCodeAt(this, instr);
4424 StringCharLoadGenerator::Generate(masm(),
4426 ToRegister(instr->string()),
4427 ToRegister(instr->index()),
4428 ToRegister(instr->result()),
4430 __ bind(deferred->exit());
4434 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4435 Register string = ToRegister(instr->string());
4436 Register result = ToRegister(instr->result());
4438 // TODO(3095996): Get rid of this. For now, we need to make the
4439 // result register contain a valid pointer because it is already
4440 // contained in the register pointer map.
4441 __ Move(result, Immediate(0));
4443 PushSafepointRegistersScope scope(this);
4445 // Push the index as a smi. This is safe because of the checks in
4446 // DoStringCharCodeAt above.
4447 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4448 if (instr->index()->IsConstantOperand()) {
4449 Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
4450 Representation::Smi());
4453 Register index = ToRegister(instr->index());
4457 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
4458 instr, instr->context());
4461 __ StoreToSafepointRegisterSlot(result, eax);
4465 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4466 class DeferredStringCharFromCode FINAL : public LDeferredCode {
4468 DeferredStringCharFromCode(LCodeGen* codegen,
4469 LStringCharFromCode* instr)
4470 : LDeferredCode(codegen), instr_(instr) { }
4471 void Generate() OVERRIDE {
4472 codegen()->DoDeferredStringCharFromCode(instr_);
4474 LInstruction* instr() OVERRIDE { return instr_; }
4477 LStringCharFromCode* instr_;
4480 DeferredStringCharFromCode* deferred =
4481 new(zone()) DeferredStringCharFromCode(this, instr);
4483 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4484 Register char_code = ToRegister(instr->char_code());
4485 Register result = ToRegister(instr->result());
4486 DCHECK(!char_code.is(result));
4488 __ cmp(char_code, String::kMaxOneByteCharCode);
4489 __ j(above, deferred->entry());
4490 __ Move(result, Immediate(factory()->single_character_string_cache()));
4491 __ mov(result, FieldOperand(result,
4492 char_code, times_pointer_size,
4493 FixedArray::kHeaderSize));
4494 __ cmp(result, factory()->undefined_value());
4495 __ j(equal, deferred->entry());
4496 __ bind(deferred->exit());
4500 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4501 Register char_code = ToRegister(instr->char_code());
4502 Register result = ToRegister(instr->result());
4504 // TODO(3095996): Get rid of this. For now, we need to make the
4505 // result register contain a valid pointer because it is already
4506 // contained in the register pointer map.
4507 __ Move(result, Immediate(0));
4509 PushSafepointRegistersScope scope(this);
4510 __ SmiTag(char_code);
4512 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4513 __ StoreToSafepointRegisterSlot(result, eax);
4517 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4518 DCHECK(ToRegister(instr->context()).is(esi));
4519 DCHECK(ToRegister(instr->left()).is(edx));
4520 DCHECK(ToRegister(instr->right()).is(eax));
4521 StringAddStub stub(isolate(),
4522 instr->hydrogen()->flags(),
4523 instr->hydrogen()->pretenure_flag());
4524 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4528 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4529 LOperand* input = instr->value();
4530 LOperand* output = instr->result();
4531 DCHECK(input->IsRegister() || input->IsStackSlot());
4532 DCHECK(output->IsDoubleRegister());
4533 __ Cvtsi2sd(ToDoubleRegister(output), ToOperand(input));
4537 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4538 LOperand* input = instr->value();
4539 LOperand* output = instr->result();
4540 __ LoadUint32(ToDoubleRegister(output), ToRegister(input));
4544 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4545 class DeferredNumberTagI FINAL : public LDeferredCode {
4547 DeferredNumberTagI(LCodeGen* codegen,
4549 : LDeferredCode(codegen), instr_(instr) { }
4550 void Generate() OVERRIDE {
4551 codegen()->DoDeferredNumberTagIU(
4552 instr_, instr_->value(), instr_->temp(), SIGNED_INT32);
4554 LInstruction* instr() OVERRIDE { return instr_; }
4557 LNumberTagI* instr_;
4560 LOperand* input = instr->value();
4561 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4562 Register reg = ToRegister(input);
4564 DeferredNumberTagI* deferred =
4565 new(zone()) DeferredNumberTagI(this, instr);
4567 __ j(overflow, deferred->entry());
4568 __ bind(deferred->exit());
4572 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4573 class DeferredNumberTagU FINAL : public LDeferredCode {
4575 DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4576 : LDeferredCode(codegen), instr_(instr) { }
4577 void Generate() OVERRIDE {
4578 codegen()->DoDeferredNumberTagIU(
4579 instr_, instr_->value(), instr_->temp(), UNSIGNED_INT32);
4581 LInstruction* instr() OVERRIDE { return instr_; }
4584 LNumberTagU* instr_;
4587 LOperand* input = instr->value();
4588 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4589 Register reg = ToRegister(input);
4591 DeferredNumberTagU* deferred =
4592 new(zone()) DeferredNumberTagU(this, instr);
4593 __ cmp(reg, Immediate(Smi::kMaxValue));
4594 __ j(above, deferred->entry());
4596 __ bind(deferred->exit());
4600 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
4603 IntegerSignedness signedness) {
4605 Register reg = ToRegister(value);
4606 Register tmp = ToRegister(temp);
4607 XMMRegister xmm_scratch = double_scratch0();
4609 if (signedness == SIGNED_INT32) {
4610 // There was overflow, so bits 30 and 31 of the original integer
4611 // disagree. Try to allocate a heap number in new space and store
4612 // the value in there. If that fails, call the runtime system.
4614 __ xor_(reg, 0x80000000);
4615 __ Cvtsi2sd(xmm_scratch, Operand(reg));
4617 __ LoadUint32(xmm_scratch, reg);
4620 if (FLAG_inline_new) {
4621 __ AllocateHeapNumber(reg, tmp, no_reg, &slow);
4622 __ jmp(&done, Label::kNear);
4625 // Slow case: Call the runtime system to do the number allocation.
4628 // TODO(3095996): Put a valid pointer value in the stack slot where the
4629 // result register is stored, as this register is in the pointer map, but
4630 // contains an integer value.
4631 __ Move(reg, Immediate(0));
4633 // Preserve the value of all registers.
4634 PushSafepointRegistersScope scope(this);
4636 // NumberTagI and NumberTagD use the context from the frame, rather than
4637 // the environment's HContext or HInlinedContext value.
4638 // They only call Runtime::kAllocateHeapNumber.
4639 // The corresponding HChange instructions are added in a phase that does
4640 // not have easy access to the local context.
4641 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4642 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4643 RecordSafepointWithRegisters(
4644 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4645 __ StoreToSafepointRegisterSlot(reg, eax);
4648 // Done. Put the value in xmm_scratch into the value of the allocated heap
4651 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), xmm_scratch);
4655 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4656 class DeferredNumberTagD FINAL : public LDeferredCode {
4658 DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4659 : LDeferredCode(codegen), instr_(instr) { }
4660 void Generate() OVERRIDE { codegen()->DoDeferredNumberTagD(instr_); }
4661 LInstruction* instr() OVERRIDE { return instr_; }
4664 LNumberTagD* instr_;
4667 Register reg = ToRegister(instr->result());
4669 DeferredNumberTagD* deferred =
4670 new(zone()) DeferredNumberTagD(this, instr);
4671 if (FLAG_inline_new) {
4672 Register tmp = ToRegister(instr->temp());
4673 __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
4675 __ jmp(deferred->entry());
4677 __ bind(deferred->exit());
4678 XMMRegister input_reg = ToDoubleRegister(instr->value());
4679 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg);
4683 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4684 // TODO(3095996): Get rid of this. For now, we need to make the
4685 // result register contain a valid pointer because it is already
4686 // contained in the register pointer map.
4687 Register reg = ToRegister(instr->result());
4688 __ Move(reg, Immediate(0));
4690 PushSafepointRegistersScope scope(this);
4691 // NumberTagI and NumberTagD use the context from the frame, rather than
4692 // the environment's HContext or HInlinedContext value.
4693 // They only call Runtime::kAllocateHeapNumber.
4694 // The corresponding HChange instructions are added in a phase that does
4695 // not have easy access to the local context.
4696 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
4697 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4698 RecordSafepointWithRegisters(
4699 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4700 __ StoreToSafepointRegisterSlot(reg, eax);
4704 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4705 HChange* hchange = instr->hydrogen();
4706 Register input = ToRegister(instr->value());
4707 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4708 hchange->value()->CheckFlag(HValue::kUint32)) {
4709 __ test(input, Immediate(0xc0000000));
4710 DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
4713 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4714 !hchange->value()->CheckFlag(HValue::kUint32)) {
4715 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4720 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4721 LOperand* input = instr->value();
4722 Register result = ToRegister(input);
4723 DCHECK(input->IsRegister() && input->Equals(instr->result()));
4724 if (instr->needs_check()) {
4725 __ test(result, Immediate(kSmiTagMask));
4726 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4728 __ AssertSmi(result);
4730 __ SmiUntag(result);
4734 void LCodeGen::EmitNumberUntagD(LNumberUntagD* instr, Register input_reg,
4735 Register temp_reg, XMMRegister result_reg,
4736 NumberUntagDMode mode) {
4737 bool can_convert_undefined_to_nan =
4738 instr->hydrogen()->can_convert_undefined_to_nan();
4739 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
4741 Label convert, load_smi, done;
4743 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4745 __ JumpIfSmi(input_reg, &load_smi, Label::kNear);
4747 // Heap number map check.
4748 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4749 factory()->heap_number_map());
4750 if (can_convert_undefined_to_nan) {
4751 __ j(not_equal, &convert, Label::kNear);
4753 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4756 // Heap number to XMM conversion.
4757 __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset));
4759 if (deoptimize_on_minus_zero) {
4760 XMMRegister xmm_scratch = double_scratch0();
4761 __ xorps(xmm_scratch, xmm_scratch);
4762 __ ucomisd(result_reg, xmm_scratch);
4763 __ j(not_zero, &done, Label::kNear);
4764 __ movmskpd(temp_reg, result_reg);
4765 __ test_b(temp_reg, 1);
4766 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4768 __ jmp(&done, Label::kNear);
4770 if (can_convert_undefined_to_nan) {
4773 // Convert undefined to NaN.
4774 __ cmp(input_reg, factory()->undefined_value());
4775 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
4777 __ pcmpeqd(result_reg, result_reg);
4778 __ jmp(&done, Label::kNear);
4781 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4785 // Smi to XMM conversion. Clobbering a temp is faster than re-tagging the
4786 // input register since we avoid dependencies.
4787 __ mov(temp_reg, input_reg);
4788 __ SmiUntag(temp_reg); // Untag smi before converting to float.
4789 __ Cvtsi2sd(result_reg, Operand(temp_reg));
4794 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
4795 Register input_reg = ToRegister(instr->value());
4797 // The input was optimistically untagged; revert it.
4798 STATIC_ASSERT(kSmiTagSize == 1);
4799 __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));
4801 if (instr->truncating()) {
4802 Label no_heap_number, check_bools, check_false;
4804 // Heap number map check.
4805 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4806 factory()->heap_number_map());
4807 __ j(not_equal, &no_heap_number, Label::kNear);
4808 __ TruncateHeapNumberToI(input_reg, input_reg);
4811 __ bind(&no_heap_number);
4812 // Check for Oddballs. Undefined/False is converted to zero and True to one
4813 // for truncating conversions.
4814 __ cmp(input_reg, factory()->undefined_value());
4815 __ j(not_equal, &check_bools, Label::kNear);
4816 __ Move(input_reg, Immediate(0));
4819 __ bind(&check_bools);
4820 __ cmp(input_reg, factory()->true_value());
4821 __ j(not_equal, &check_false, Label::kNear);
4822 __ Move(input_reg, Immediate(1));
4825 __ bind(&check_false);
4826 __ cmp(input_reg, factory()->false_value());
4827 DeoptimizeIf(not_equal, instr,
4828 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
4829 __ Move(input_reg, Immediate(0));
4831 XMMRegister scratch = ToDoubleRegister(instr->temp());
4832 DCHECK(!scratch.is(xmm0));
4833 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
4834 isolate()->factory()->heap_number_map());
4835 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4836 __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
4837 __ cvttsd2si(input_reg, Operand(xmm0));
4838 __ Cvtsi2sd(scratch, Operand(input_reg));
4839 __ ucomisd(xmm0, scratch);
4840 DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
4841 DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
4842 if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
4843 __ test(input_reg, Operand(input_reg));
4844 __ j(not_zero, done);
4845 __ movmskpd(input_reg, xmm0);
4846 __ and_(input_reg, 1);
4847 DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4853 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
4854 class DeferredTaggedToI FINAL : public LDeferredCode {
4856 DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
4857 : LDeferredCode(codegen), instr_(instr) { }
4858 void Generate() OVERRIDE { codegen()->DoDeferredTaggedToI(instr_, done()); }
4859 LInstruction* instr() OVERRIDE { return instr_; }
4865 LOperand* input = instr->value();
4866 DCHECK(input->IsRegister());
4867 Register input_reg = ToRegister(input);
4868 DCHECK(input_reg.is(ToRegister(instr->result())));
4870 if (instr->hydrogen()->value()->representation().IsSmi()) {
4871 __ SmiUntag(input_reg);
4873 DeferredTaggedToI* deferred =
4874 new(zone()) DeferredTaggedToI(this, instr);
4875 // Optimistically untag the input.
4876 // If the input is a HeapObject, SmiUntag will set the carry flag.
4877 STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
4878 __ SmiUntag(input_reg);
4879 // Branch to deferred code if the input was tagged.
4880 // The deferred code will take care of restoring the tag.
4881 __ j(carry, deferred->entry());
4882 __ bind(deferred->exit());
4887 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4888 LOperand* input = instr->value();
4889 DCHECK(input->IsRegister());
4890 LOperand* temp = instr->temp();
4891 DCHECK(temp->IsRegister());
4892 LOperand* result = instr->result();
4893 DCHECK(result->IsDoubleRegister());
4895 Register input_reg = ToRegister(input);
4896 Register temp_reg = ToRegister(temp);
4898 HValue* value = instr->hydrogen()->value();
4899 NumberUntagDMode mode = value->representation().IsSmi()
4900 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4902 XMMRegister result_reg = ToDoubleRegister(result);
4903 EmitNumberUntagD(instr, input_reg, temp_reg, result_reg, mode);
4907 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
4908 LOperand* input = instr->value();
4909 DCHECK(input->IsDoubleRegister());
4910 LOperand* result = instr->result();
4911 DCHECK(result->IsRegister());
4912 Register result_reg = ToRegister(result);
4914 if (instr->truncating()) {
4915 XMMRegister input_reg = ToDoubleRegister(input);
4916 __ TruncateDoubleToI(result_reg, input_reg);
4918 Label lost_precision, is_nan, minus_zero, done;
4919 XMMRegister input_reg = ToDoubleRegister(input);
4920 XMMRegister xmm_scratch = double_scratch0();
4921 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4922 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4923 instr->hydrogen()->GetMinusZeroMode(), &lost_precision,
4924 &is_nan, &minus_zero, dist);
4925 __ jmp(&done, dist);
4926 __ bind(&lost_precision);
4927 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4929 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4930 __ bind(&minus_zero);
4931 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4937 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
4938 LOperand* input = instr->value();
4939 DCHECK(input->IsDoubleRegister());
4940 LOperand* result = instr->result();
4941 DCHECK(result->IsRegister());
4942 Register result_reg = ToRegister(result);
4944 Label lost_precision, is_nan, minus_zero, done;
4945 XMMRegister input_reg = ToDoubleRegister(input);
4946 XMMRegister xmm_scratch = double_scratch0();
4947 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
4948 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4949 instr->hydrogen()->GetMinusZeroMode(), &lost_precision, &is_nan,
4951 __ jmp(&done, dist);
4952 __ bind(&lost_precision);
4953 DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
4955 DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
4956 __ bind(&minus_zero);
4957 DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
4959 __ SmiTag(result_reg);
4960 DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
4964 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
4965 LOperand* input = instr->value();
4966 __ test(ToOperand(input), Immediate(kSmiTagMask));
4967 DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
4971 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
4972 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
4973 LOperand* input = instr->value();
4974 __ test(ToOperand(input), Immediate(kSmiTagMask));
4975 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
4980 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
4981 Register input = ToRegister(instr->value());
4982 Register temp = ToRegister(instr->temp());
4984 __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
4986 if (instr->hydrogen()->is_interval_check()) {
4989 instr->hydrogen()->GetCheckInterval(&first, &last);
4991 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
4992 static_cast<int8_t>(first));
4994 // If there is only one type in the interval check for equality.
4995 if (first == last) {
4996 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
4998 DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
4999 // Omit check for the last type.
5000 if (last != LAST_TYPE) {
5001 __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
5002 static_cast<int8_t>(last));
5003 DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
5009 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
5011 if (base::bits::IsPowerOfTwo32(mask)) {
5012 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
5013 __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5014 DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
5015 Deoptimizer::kWrongInstanceType);
5017 __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
5018 __ and_(temp, mask);
5020 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
5026 void LCodeGen::DoCheckValue(LCheckValue* instr) {
5027 Handle<HeapObject> object = instr->hydrogen()->object().handle();
5028 if (instr->hydrogen()->object_in_new_space()) {
5029 Register reg = ToRegister(instr->value());
5030 Handle<Cell> cell = isolate()->factory()->NewCell(object);
5031 __ cmp(reg, Operand::ForCell(cell));
5033 Operand operand = ToOperand(instr->value());
5034 __ cmp(operand, object);
5036 DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
5040 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
5042 PushSafepointRegistersScope scope(this);
5045 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
5046 RecordSafepointWithRegisters(
5047 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
5049 __ test(eax, Immediate(kSmiTagMask));
5051 DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
5055 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5056 class DeferredCheckMaps FINAL : public LDeferredCode {
5058 DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr, Register object)
5059 : LDeferredCode(codegen), instr_(instr), object_(object) {
5060 SetExit(check_maps());
5062 void Generate() OVERRIDE {
5063 codegen()->DoDeferredInstanceMigration(instr_, object_);
5065 Label* check_maps() { return &check_maps_; }
5066 LInstruction* instr() OVERRIDE { return instr_; }
5074 if (instr->hydrogen()->IsStabilityCheck()) {
5075 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5076 for (int i = 0; i < maps->size(); ++i) {
5077 AddStabilityDependency(maps->at(i).handle());
5082 LOperand* input = instr->value();
5083 DCHECK(input->IsRegister());
5084 Register reg = ToRegister(input);
5086 DeferredCheckMaps* deferred = NULL;
5087 if (instr->hydrogen()->HasMigrationTarget()) {
5088 deferred = new(zone()) DeferredCheckMaps(this, instr, reg);
5089 __ bind(deferred->check_maps());
5092 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
5094 for (int i = 0; i < maps->size() - 1; i++) {
5095 Handle<Map> map = maps->at(i).handle();
5096 __ CompareMap(reg, map);
5097 __ j(equal, &success, Label::kNear);
5100 Handle<Map> map = maps->at(maps->size() - 1).handle();
5101 __ CompareMap(reg, map);
5102 if (instr->hydrogen()->HasMigrationTarget()) {
5103 __ j(not_equal, deferred->entry());
5105 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5112 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5113 XMMRegister value_reg = ToDoubleRegister(instr->unclamped());
5114 XMMRegister xmm_scratch = double_scratch0();
5115 Register result_reg = ToRegister(instr->result());
5116 __ ClampDoubleToUint8(value_reg, xmm_scratch, result_reg);
5120 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5121 DCHECK(instr->unclamped()->Equals(instr->result()));
5122 Register value_reg = ToRegister(instr->result());
5123 __ ClampUint8(value_reg);
5127 void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
5128 DCHECK(instr->unclamped()->Equals(instr->result()));
5129 Register input_reg = ToRegister(instr->unclamped());
5130 XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm());
5131 XMMRegister xmm_scratch = double_scratch0();
5132 Label is_smi, done, heap_number;
5134 __ JumpIfSmi(input_reg, &is_smi);
5136 // Check for heap number
5137 __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5138 factory()->heap_number_map());
5139 __ j(equal, &heap_number, Label::kNear);
5141 // Check for undefined. Undefined is converted to zero for clamping
5143 __ cmp(input_reg, factory()->undefined_value());
5144 DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
5145 __ mov(input_reg, 0);
5146 __ jmp(&done, Label::kNear);
5149 __ bind(&heap_number);
5150 __ movsd(xmm_scratch, FieldOperand(input_reg, HeapNumber::kValueOffset));
5151 __ ClampDoubleToUint8(xmm_scratch, temp_xmm_reg, input_reg);
5152 __ jmp(&done, Label::kNear);
5156 __ SmiUntag(input_reg);
5157 __ ClampUint8(input_reg);
5162 void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5163 XMMRegister value_reg = ToDoubleRegister(instr->value());
5164 Register result_reg = ToRegister(instr->result());
5165 if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
5166 if (CpuFeatures::IsSupported(SSE4_1)) {
5167 CpuFeatureScope scope2(masm(), SSE4_1);
5168 __ pextrd(result_reg, value_reg, 1);
5170 XMMRegister xmm_scratch = double_scratch0();
5171 __ pshufd(xmm_scratch, value_reg, 1);
5172 __ movd(result_reg, xmm_scratch);
5175 __ movd(result_reg, value_reg);
5180 void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5181 Register hi_reg = ToRegister(instr->hi());
5182 Register lo_reg = ToRegister(instr->lo());
5183 XMMRegister result_reg = ToDoubleRegister(instr->result());
5185 if (CpuFeatures::IsSupported(SSE4_1)) {
5186 CpuFeatureScope scope2(masm(), SSE4_1);
5187 __ movd(result_reg, lo_reg);
5188 __ pinsrd(result_reg, hi_reg, 1);
5190 XMMRegister xmm_scratch = double_scratch0();
5191 __ movd(result_reg, hi_reg);
5192 __ psllq(result_reg, 32);
5193 __ movd(xmm_scratch, lo_reg);
5194 __ orps(result_reg, xmm_scratch);
5199 void LCodeGen::DoAllocate(LAllocate* instr) {
5200 class DeferredAllocate FINAL : public LDeferredCode {
5202 DeferredAllocate(LCodeGen* codegen, LAllocate* instr)
5203 : LDeferredCode(codegen), instr_(instr) { }
5204 void Generate() OVERRIDE { codegen()->DoDeferredAllocate(instr_); }
5205 LInstruction* instr() OVERRIDE { return instr_; }
5211 DeferredAllocate* deferred = new(zone()) DeferredAllocate(this, instr);
5213 Register result = ToRegister(instr->result());
5214 Register temp = ToRegister(instr->temp());
5216 // Allocate memory for the object.
5217 AllocationFlags flags = TAG_OBJECT;
5218 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5219 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5221 if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5222 DCHECK(!instr->hydrogen()->IsOldDataSpaceAllocation());
5223 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5224 flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_POINTER_SPACE);
5225 } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5226 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5227 flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_DATA_SPACE);
5230 if (instr->size()->IsConstantOperand()) {
5231 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5232 if (size <= Page::kMaxRegularHeapObjectSize) {
5233 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5235 __ jmp(deferred->entry());
5238 Register size = ToRegister(instr->size());
5239 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5242 __ bind(deferred->exit());
5244 if (instr->hydrogen()->MustPrefillWithFiller()) {
5245 if (instr->size()->IsConstantOperand()) {
5246 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5247 __ mov(temp, (size / kPointerSize) - 1);
5249 temp = ToRegister(instr->size());
5250 __ shr(temp, kPointerSizeLog2);
5255 __ mov(FieldOperand(result, temp, times_pointer_size, 0),
5256 isolate()->factory()->one_pointer_filler_map());
5258 __ j(not_zero, &loop);
5263 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5264 Register result = ToRegister(instr->result());
5266 // TODO(3095996): Get rid of this. For now, we need to make the
5267 // result register contain a valid pointer because it is already
5268 // contained in the register pointer map.
5269 __ Move(result, Immediate(Smi::FromInt(0)));
5271 PushSafepointRegistersScope scope(this);
5272 if (instr->size()->IsRegister()) {
5273 Register size = ToRegister(instr->size());
5274 DCHECK(!size.is(result));
5275 __ SmiTag(ToRegister(instr->size()));
5278 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5279 if (size >= 0 && size <= Smi::kMaxValue) {
5280 __ push(Immediate(Smi::FromInt(size)));
5282 // We should never get here at runtime => abort
5288 int flags = AllocateDoubleAlignFlag::encode(
5289 instr->hydrogen()->MustAllocateDoubleAligned());
5290 if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5291 DCHECK(!instr->hydrogen()->IsOldDataSpaceAllocation());
5292 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5293 flags = AllocateTargetSpace::update(flags, OLD_POINTER_SPACE);
5294 } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5295 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5296 flags = AllocateTargetSpace::update(flags, OLD_DATA_SPACE);
5298 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5300 __ push(Immediate(Smi::FromInt(flags)));
5302 CallRuntimeFromDeferred(
5303 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5304 __ StoreToSafepointRegisterSlot(result, eax);
5308 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5309 DCHECK(ToRegister(instr->value()).is(eax));
5311 CallRuntime(Runtime::kToFastProperties, 1, instr);
5315 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5316 DCHECK(ToRegister(instr->context()).is(esi));
5318 // Registers will be used as follows:
5319 // ecx = literals array.
5320 // ebx = regexp literal.
5321 // eax = regexp literal clone.
5323 int literal_offset =
5324 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5325 __ LoadHeapObject(ecx, instr->hydrogen()->literals());
5326 __ mov(ebx, FieldOperand(ecx, literal_offset));
5327 __ cmp(ebx, factory()->undefined_value());
5328 __ j(not_equal, &materialized, Label::kNear);
5330 // Create regexp literal using runtime function
5331 // Result will be in eax.
5333 __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
5334 __ push(Immediate(instr->hydrogen()->pattern()));
5335 __ push(Immediate(instr->hydrogen()->flags()));
5336 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5339 __ bind(&materialized);
5340 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5341 Label allocated, runtime_allocate;
5342 __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
5343 __ jmp(&allocated, Label::kNear);
5345 __ bind(&runtime_allocate);
5347 __ push(Immediate(Smi::FromInt(size)));
5348 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5351 __ bind(&allocated);
5352 // Copy the content into the newly allocated memory.
5353 // (Unroll copy loop once for better throughput).
5354 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5355 __ mov(edx, FieldOperand(ebx, i));
5356 __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
5357 __ mov(FieldOperand(eax, i), edx);
5358 __ mov(FieldOperand(eax, i + kPointerSize), ecx);
5360 if ((size % (2 * kPointerSize)) != 0) {
5361 __ mov(edx, FieldOperand(ebx, size - kPointerSize));
5362 __ mov(FieldOperand(eax, size - kPointerSize), edx);
5367 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5368 DCHECK(ToRegister(instr->context()).is(esi));
5369 // Use the fast case closure allocation code that allocates in new
5370 // space for nested functions that don't need literals cloning.
5371 bool pretenure = instr->hydrogen()->pretenure();
5372 if (!pretenure && instr->hydrogen()->has_no_literals()) {
5373 FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
5374 instr->hydrogen()->kind());
5375 __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
5376 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
5379 __ push(Immediate(instr->hydrogen()->shared_info()));
5380 __ push(Immediate(pretenure ? factory()->true_value()
5381 : factory()->false_value()));
5382 CallRuntime(Runtime::kNewClosure, 3, instr);
5387 void LCodeGen::DoTypeof(LTypeof* instr) {
5388 DCHECK(ToRegister(instr->context()).is(esi));
5389 LOperand* input = instr->value();
5390 EmitPushTaggedOperand(input);
5391 CallRuntime(Runtime::kTypeof, 1, instr);
5395 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5396 Register input = ToRegister(instr->value());
5397 Condition final_branch_condition = EmitTypeofIs(instr, input);
5398 if (final_branch_condition != no_condition) {
5399 EmitBranch(instr, final_branch_condition);
5404 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
5405 Label* true_label = instr->TrueLabel(chunk_);
5406 Label* false_label = instr->FalseLabel(chunk_);
5407 Handle<String> type_name = instr->type_literal();
5408 int left_block = instr->TrueDestination(chunk_);
5409 int right_block = instr->FalseDestination(chunk_);
5410 int next_block = GetNextEmittedBlock();
5412 Label::Distance true_distance = left_block == next_block ? Label::kNear
5414 Label::Distance false_distance = right_block == next_block ? Label::kNear
5416 Condition final_branch_condition = no_condition;
5417 if (String::Equals(type_name, factory()->number_string())) {
5418 __ JumpIfSmi(input, true_label, true_distance);
5419 __ cmp(FieldOperand(input, HeapObject::kMapOffset),
5420 factory()->heap_number_map());
5421 final_branch_condition = equal;
5423 } else if (String::Equals(type_name, factory()->string_string())) {
5424 __ JumpIfSmi(input, false_label, false_distance);
5425 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
5426 __ j(above_equal, false_label, false_distance);
5427 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5428 1 << Map::kIsUndetectable);
5429 final_branch_condition = zero;
5431 } else if (String::Equals(type_name, factory()->symbol_string())) {
5432 __ JumpIfSmi(input, false_label, false_distance);
5433 __ CmpObjectType(input, SYMBOL_TYPE, input);
5434 final_branch_condition = equal;
5436 } else if (String::Equals(type_name, factory()->boolean_string())) {
5437 __ cmp(input, factory()->true_value());
5438 __ j(equal, true_label, true_distance);
5439 __ cmp(input, factory()->false_value());
5440 final_branch_condition = equal;
5442 } else if (String::Equals(type_name, factory()->undefined_string())) {
5443 __ cmp(input, factory()->undefined_value());
5444 __ j(equal, true_label, true_distance);
5445 __ JumpIfSmi(input, false_label, false_distance);
5446 // Check for undetectable objects => true.
5447 __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
5448 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5449 1 << Map::kIsUndetectable);
5450 final_branch_condition = not_zero;
5452 } else if (String::Equals(type_name, factory()->function_string())) {
5453 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5454 __ JumpIfSmi(input, false_label, false_distance);
5455 __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
5456 __ j(equal, true_label, true_distance);
5457 __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
5458 final_branch_condition = equal;
5460 } else if (String::Equals(type_name, factory()->object_string())) {
5461 __ JumpIfSmi(input, false_label, false_distance);
5462 __ cmp(input, factory()->null_value());
5463 __ j(equal, true_label, true_distance);
5464 __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
5465 __ j(below, false_label, false_distance);
5466 __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5467 __ j(above, false_label, false_distance);
5468 // Check for undetectable objects => false.
5469 __ test_b(FieldOperand(input, Map::kBitFieldOffset),
5470 1 << Map::kIsUndetectable);
5471 final_branch_condition = zero;
5474 __ jmp(false_label, false_distance);
5476 return final_branch_condition;
5480 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
5481 Register temp = ToRegister(instr->temp());
5483 EmitIsConstructCall(temp);
5484 EmitBranch(instr, equal);
5488 void LCodeGen::EmitIsConstructCall(Register temp) {
5489 // Get the frame pointer for the calling frame.
5490 __ mov(temp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
5492 // Skip the arguments adaptor frame if it exists.
5493 Label check_frame_marker;
5494 __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
5495 Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
5496 __ j(not_equal, &check_frame_marker, Label::kNear);
5497 __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
5499 // Check the marker in the calling frame.
5500 __ bind(&check_frame_marker);
5501 __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
5502 Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
5506 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
5507 if (!info()->IsStub()) {
5508 // Ensure that we have enough space after the previous lazy-bailout
5509 // instruction for patching the code here.
5510 int current_pc = masm()->pc_offset();
5511 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
5512 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
5513 __ Nop(padding_size);
5516 last_lazy_deopt_pc_ = masm()->pc_offset();
5520 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
5521 last_lazy_deopt_pc_ = masm()->pc_offset();
5522 DCHECK(instr->HasEnvironment());
5523 LEnvironment* env = instr->environment();
5524 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5525 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5529 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
5530 Deoptimizer::BailoutType type = instr->hydrogen()->type();
5531 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
5532 // needed return address), even though the implementation of LAZY and EAGER is
5533 // now identical. When LAZY is eventually completely folded into EAGER, remove
5534 // the special case below.
5535 if (info()->IsStub() && type == Deoptimizer::EAGER) {
5536 type = Deoptimizer::LAZY;
5538 DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
5542 void LCodeGen::DoDummy(LDummy* instr) {
5543 // Nothing to see here, move on!
5547 void LCodeGen::DoDummyUse(LDummyUse* instr) {
5548 // Nothing to see here, move on!
5552 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5553 PushSafepointRegistersScope scope(this);
5554 __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5555 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5556 RecordSafepointWithLazyDeopt(
5557 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5558 DCHECK(instr->HasEnvironment());
5559 LEnvironment* env = instr->environment();
5560 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5564 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5565 class DeferredStackCheck FINAL : public LDeferredCode {
5567 DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5568 : LDeferredCode(codegen), instr_(instr) { }
5569 void Generate() OVERRIDE { codegen()->DoDeferredStackCheck(instr_); }
5570 LInstruction* instr() OVERRIDE { return instr_; }
5573 LStackCheck* instr_;
5576 DCHECK(instr->HasEnvironment());
5577 LEnvironment* env = instr->environment();
5578 // There is no LLazyBailout instruction for stack-checks. We have to
5579 // prepare for lazy deoptimization explicitly here.
5580 if (instr->hydrogen()->is_function_entry()) {
5581 // Perform stack overflow check.
5583 ExternalReference stack_limit =
5584 ExternalReference::address_of_stack_limit(isolate());
5585 __ cmp(esp, Operand::StaticVariable(stack_limit));
5586 __ j(above_equal, &done, Label::kNear);
5588 DCHECK(instr->context()->IsRegister());
5589 DCHECK(ToRegister(instr->context()).is(esi));
5590 CallCode(isolate()->builtins()->StackCheck(),
5591 RelocInfo::CODE_TARGET,
5595 DCHECK(instr->hydrogen()->is_backwards_branch());
5596 // Perform stack overflow check if this goto needs it before jumping.
5597 DeferredStackCheck* deferred_stack_check =
5598 new(zone()) DeferredStackCheck(this, instr);
5599 ExternalReference stack_limit =
5600 ExternalReference::address_of_stack_limit(isolate());
5601 __ cmp(esp, Operand::StaticVariable(stack_limit));
5602 __ j(below, deferred_stack_check->entry());
5603 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5604 __ bind(instr->done_label());
5605 deferred_stack_check->SetExit(instr->done_label());
5606 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5607 // Don't record a deoptimization index for the safepoint here.
5608 // This will be done explicitly when emitting call and the safepoint in
5609 // the deferred code.
5614 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
5615 // This is a pseudo-instruction that ensures that the environment here is
5616 // properly registered for deoptimization and records the assembler's PC
5618 LEnvironment* environment = instr->environment();
5620 // If the environment were already registered, we would have no way of
5621 // backpatching it with the spill slot operands.
5622 DCHECK(!environment->HasBeenRegistered());
5623 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
5625 GenerateOsrPrologue();
5629 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
5630 DCHECK(ToRegister(instr->context()).is(esi));
5631 __ cmp(eax, isolate()->factory()->undefined_value());
5632 DeoptimizeIf(equal, instr, Deoptimizer::kUndefined);
5634 __ cmp(eax, isolate()->factory()->null_value());
5635 DeoptimizeIf(equal, instr, Deoptimizer::kNull);
5637 __ test(eax, Immediate(kSmiTagMask));
5638 DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
5640 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
5641 __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
5642 DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
5644 Label use_cache, call_runtime;
5645 __ CheckEnumCache(&call_runtime);
5647 __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
5648 __ jmp(&use_cache, Label::kNear);
5650 // Get the set of properties to enumerate.
5651 __ bind(&call_runtime);
5653 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
5655 __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
5656 isolate()->factory()->meta_map());
5657 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5658 __ bind(&use_cache);
5662 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
5663 Register map = ToRegister(instr->map());
5664 Register result = ToRegister(instr->result());
5665 Label load_cache, done;
5666 __ EnumLength(result, map);
5667 __ cmp(result, Immediate(Smi::FromInt(0)));
5668 __ j(not_equal, &load_cache, Label::kNear);
5669 __ mov(result, isolate()->factory()->empty_fixed_array());
5670 __ jmp(&done, Label::kNear);
5672 __ bind(&load_cache);
5673 __ LoadInstanceDescriptors(map, result);
5675 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
5677 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
5679 __ test(result, result);
5680 DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
5684 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
5685 Register object = ToRegister(instr->value());
5686 __ cmp(ToRegister(instr->map()),
5687 FieldOperand(object, HeapObject::kMapOffset));
5688 DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
5692 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
5695 PushSafepointRegistersScope scope(this);
5699 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
5700 RecordSafepointWithRegisters(
5701 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
5702 __ StoreToSafepointRegisterSlot(object, eax);
5706 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
5707 class DeferredLoadMutableDouble FINAL : public LDeferredCode {
5709 DeferredLoadMutableDouble(LCodeGen* codegen,
5710 LLoadFieldByIndex* instr,
5713 : LDeferredCode(codegen),
5718 void Generate() OVERRIDE {
5719 codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
5721 LInstruction* instr() OVERRIDE { return instr_; }
5724 LLoadFieldByIndex* instr_;
5729 Register object = ToRegister(instr->object());
5730 Register index = ToRegister(instr->index());
5732 DeferredLoadMutableDouble* deferred;
5733 deferred = new(zone()) DeferredLoadMutableDouble(
5734 this, instr, object, index);
5736 Label out_of_object, done;
5737 __ test(index, Immediate(Smi::FromInt(1)));
5738 __ j(not_zero, deferred->entry());
5742 __ cmp(index, Immediate(0));
5743 __ j(less, &out_of_object, Label::kNear);
5744 __ mov(object, FieldOperand(object,
5746 times_half_pointer_size,
5747 JSObject::kHeaderSize));
5748 __ jmp(&done, Label::kNear);
5750 __ bind(&out_of_object);
5751 __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
5753 // Index is now equal to out of object property index plus 1.
5754 __ mov(object, FieldOperand(object,
5756 times_half_pointer_size,
5757 FixedArray::kHeaderSize - kPointerSize));
5758 __ bind(deferred->exit());
5763 void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
5764 Register context = ToRegister(instr->context());
5765 __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
5769 void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
5770 Handle<ScopeInfo> scope_info = instr->scope_info();
5771 __ Push(scope_info);
5772 __ push(ToRegister(instr->function()));
5773 CallRuntime(Runtime::kPushBlockContext, 2, instr);
5774 RecordSafepoint(Safepoint::kNoLazyDeopt);
5780 } } // namespace v8::internal
5782 #endif // V8_TARGET_ARCH_IA32