1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 #include "v8.h"
29
30 #if V8_TARGET_ARCH_X64
31
32 #include "x64/lithium-codegen-x64.h"
33 #include "code-stubs.h"
34 #include "stub-cache.h"
35 #include "hydrogen-osr.h"
36
37 namespace v8 {
38 namespace internal {
39
40
41 // When invoking builtins, we need to record the safepoint in the middle of
42 // the invoke instruction sequence generated by the macro assembler.
43 class SafepointGenerator V8_FINAL : public CallWrapper {
44 public:
SafepointGenerator(LCodeGen * codegen,LPointerMap * pointers,Safepoint::DeoptMode mode)45 SafepointGenerator(LCodeGen* codegen,
46 LPointerMap* pointers,
47 Safepoint::DeoptMode mode)
48 : codegen_(codegen),
49 pointers_(pointers),
50 deopt_mode_(mode) { }
~SafepointGenerator()51 virtual ~SafepointGenerator() {}
52
BeforeCall(int call_size) const53 virtual void BeforeCall(int call_size) const V8_OVERRIDE {
54 codegen_->EnsureSpaceForLazyDeopt(Deoptimizer::patch_size() - call_size);
55 }
56
AfterCall() const57 virtual void AfterCall() const V8_OVERRIDE {
58 codegen_->RecordSafepoint(pointers_, deopt_mode_);
59 }
60
61 private:
62 LCodeGen* codegen_;
63 LPointerMap* pointers_;
64 Safepoint::DeoptMode deopt_mode_;
65 };
66
67
68 #define __ masm()->
69
GenerateCode()70 bool LCodeGen::GenerateCode() {
71 LPhase phase("Z_Code generation", chunk());
72 ASSERT(is_unused());
73 status_ = GENERATING;
74
75 // Open a frame scope to indicate that there is a frame on the stack. The
76 // MANUAL indicates that the scope shouldn't actually generate code to set up
77 // the frame (that is done in GeneratePrologue).
78 FrameScope frame_scope(masm_, StackFrame::MANUAL);
79
80 return GeneratePrologue() &&
81 GenerateBody() &&
82 GenerateDeferredCode() &&
83 GenerateJumpTable() &&
84 GenerateSafepointTable();
85 }
86
87
FinishCode(Handle<Code> code)88 void LCodeGen::FinishCode(Handle<Code> code) {
89 ASSERT(is_done());
90 code->set_stack_slots(GetStackSlotCount());
91 code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
92 RegisterDependentCodeForEmbeddedMaps(code);
93 PopulateDeoptimizationData(code);
94 info()->CommitDependencies(code);
95 }
96
97
Abort(BailoutReason reason)98 void LChunkBuilder::Abort(BailoutReason reason) {
99 info()->set_bailout_reason(reason);
100 status_ = ABORTED;
101 }
102
103
104 #ifdef _MSC_VER
MakeSureStackPagesMapped(int offset)105 void LCodeGen::MakeSureStackPagesMapped(int offset) {
106 const int kPageSize = 4 * KB;
107 for (offset -= kPageSize; offset > 0; offset -= kPageSize) {
108 __ movq(Operand(rsp, offset), rax);
109 }
110 }
111 #endif
112
113
SaveCallerDoubles()114 void LCodeGen::SaveCallerDoubles() {
115 ASSERT(info()->saves_caller_doubles());
116 ASSERT(NeedsEagerFrame());
117 Comment(";;; Save clobbered callee double registers");
118 int count = 0;
119 BitVector* doubles = chunk()->allocated_double_registers();
120 BitVector::Iterator save_iterator(doubles);
121 while (!save_iterator.Done()) {
122 __ movsd(MemOperand(rsp, count * kDoubleSize),
123 XMMRegister::FromAllocationIndex(save_iterator.Current()));
124 save_iterator.Advance();
125 count++;
126 }
127 }
128
129
RestoreCallerDoubles()130 void LCodeGen::RestoreCallerDoubles() {
131 ASSERT(info()->saves_caller_doubles());
132 ASSERT(NeedsEagerFrame());
133 Comment(";;; Restore clobbered callee double registers");
134 BitVector* doubles = chunk()->allocated_double_registers();
135 BitVector::Iterator save_iterator(doubles);
136 int count = 0;
137 while (!save_iterator.Done()) {
138 __ movsd(XMMRegister::FromAllocationIndex(save_iterator.Current()),
139 MemOperand(rsp, count * kDoubleSize));
140 save_iterator.Advance();
141 count++;
142 }
143 }
144
145
GeneratePrologue()146 bool LCodeGen::GeneratePrologue() {
147 ASSERT(is_generating());
148
149 if (info()->IsOptimizing()) {
150 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
151
152 #ifdef DEBUG
153 if (strlen(FLAG_stop_at) > 0 &&
154 info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
155 __ int3();
156 }
157 #endif
158
159 // Strict mode functions need to replace the receiver with undefined
160 // when called as functions (without an explicit receiver
161 // object). rcx is zero for method calls and non-zero for function
162 // calls.
163 if (!info_->is_classic_mode() || info_->is_native()) {
164 Label ok;
165 __ testq(rcx, rcx);
166 __ j(zero, &ok, Label::kNear);
167 StackArgumentsAccessor args(rsp, scope()->num_parameters());
168 __ LoadRoot(kScratchRegister, Heap::kUndefinedValueRootIndex);
169 __ movq(args.GetReceiverOperand(), kScratchRegister);
170 __ bind(&ok);
171 }
172 }
173
174 info()->set_prologue_offset(masm_->pc_offset());
175 if (NeedsEagerFrame()) {
176 ASSERT(!frame_is_built_);
177 frame_is_built_ = true;
178 __ Prologue(info()->IsStub() ? BUILD_STUB_FRAME : BUILD_FUNCTION_FRAME);
179 info()->AddNoFrameRange(0, masm_->pc_offset());
180 }
181
182 // Reserve space for the stack slots needed by the code.
183 int slots = GetStackSlotCount();
184 if (slots > 0) {
185 if (FLAG_debug_code) {
186 __ subq(rsp, Immediate(slots * kPointerSize));
187 #ifdef _MSC_VER
188 MakeSureStackPagesMapped(slots * kPointerSize);
189 #endif
190 __ push(rax);
191 __ Set(rax, slots);
192 __ movq(kScratchRegister, kSlotsZapValue);
193 Label loop;
194 __ bind(&loop);
195 __ movq(MemOperand(rsp, rax, times_pointer_size, 0),
196 kScratchRegister);
197 __ decl(rax);
198 __ j(not_zero, &loop);
199 __ pop(rax);
200 } else {
201 __ subq(rsp, Immediate(slots * kPointerSize));
202 #ifdef _MSC_VER
203 MakeSureStackPagesMapped(slots * kPointerSize);
204 #endif
205 }
206
207 if (info()->saves_caller_doubles()) {
208 SaveCallerDoubles();
209 }
210 }
211
212 // Possibly allocate a local context.
213 int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
214 if (heap_slots > 0) {
215 Comment(";;; Allocate local context");
216 // Argument to NewContext is the function, which is still in rdi.
217 __ push(rdi);
218 if (heap_slots <= FastNewContextStub::kMaximumSlots) {
219 FastNewContextStub stub(heap_slots);
220 __ CallStub(&stub);
221 } else {
222 __ CallRuntime(Runtime::kNewFunctionContext, 1);
223 }
224 RecordSafepoint(Safepoint::kNoLazyDeopt);
225 // Context is returned in both rax and rsi. It replaces the context
226 // passed to us. It's saved in the stack and kept live in rsi.
227 __ movq(Operand(rbp, StandardFrameConstants::kContextOffset), rsi);
228
229 // Copy any necessary parameters into the context.
230 int num_parameters = scope()->num_parameters();
231 for (int i = 0; i < num_parameters; i++) {
232 Variable* var = scope()->parameter(i);
233 if (var->IsContextSlot()) {
234 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
235 (num_parameters - 1 - i) * kPointerSize;
236 // Load parameter from stack.
237 __ movq(rax, Operand(rbp, parameter_offset));
238 // Store it in the context.
239 int context_offset = Context::SlotOffset(var->index());
240 __ movq(Operand(rsi, context_offset), rax);
241 // Update the write barrier. This clobbers rax and rbx.
242 __ RecordWriteContextSlot(rsi, context_offset, rax, rbx, kSaveFPRegs);
243 }
244 }
245 Comment(";;; End allocate local context");
246 }
247
248 // Trace the call.
249 if (FLAG_trace && info()->IsOptimizing()) {
250 __ CallRuntime(Runtime::kTraceEnter, 0);
251 }
252 return !is_aborted();
253 }
254
255
GenerateOsrPrologue()256 void LCodeGen::GenerateOsrPrologue() {
257 // Generate the OSR entry prologue at the first unknown OSR value, or if there
258 // are none, at the OSR entrypoint instruction.
259 if (osr_pc_offset_ >= 0) return;
260
261 osr_pc_offset_ = masm()->pc_offset();
262
263 // Adjust the frame size, subsuming the unoptimized frame into the
264 // optimized frame.
265 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
266 ASSERT(slots >= 0);
267 __ subq(rsp, Immediate(slots * kPointerSize));
268 }
269
270
GenerateJumpTable()271 bool LCodeGen::GenerateJumpTable() {
272 Label needs_frame;
273 if (jump_table_.length() > 0) {
274 Comment(";;; -------------------- Jump table --------------------");
275 }
276 for (int i = 0; i < jump_table_.length(); i++) {
277 __ bind(&jump_table_[i].label);
278 Address entry = jump_table_[i].address;
279 Deoptimizer::BailoutType type = jump_table_[i].bailout_type;
280 int id = Deoptimizer::GetDeoptimizationId(isolate(), entry, type);
281 if (id == Deoptimizer::kNotDeoptimizationEntry) {
282 Comment(";;; jump table entry %d.", i);
283 } else {
284 Comment(";;; jump table entry %d: deoptimization bailout %d.", i, id);
285 }
286 if (jump_table_[i].needs_frame) {
287 ASSERT(!info()->saves_caller_doubles());
288 __ Move(kScratchRegister, ExternalReference::ForDeoptEntry(entry));
289 if (needs_frame.is_bound()) {
290 __ jmp(&needs_frame);
291 } else {
292 __ bind(&needs_frame);
293 __ movq(rsi, MemOperand(rbp, StandardFrameConstants::kContextOffset));
294 __ push(rbp);
295 __ movq(rbp, rsp);
296 __ push(rsi);
297 // This variant of deopt can only be used with stubs. Since we don't
298 // have a function pointer to install in the stack frame that we're
299 // building, install a special marker there instead.
300 ASSERT(info()->IsStub());
301 __ Move(rsi, Smi::FromInt(StackFrame::STUB));
302 __ push(rsi);
303 __ movq(rsi, MemOperand(rsp, kPointerSize));
304 __ call(kScratchRegister);
305 }
306 } else {
307 if (info()->saves_caller_doubles()) {
308 ASSERT(info()->IsStub());
309 RestoreCallerDoubles();
310 }
311 __ call(entry, RelocInfo::RUNTIME_ENTRY);
312 }
313 }
314 return !is_aborted();
315 }
316
317
GenerateDeferredCode()318 bool LCodeGen::GenerateDeferredCode() {
319 ASSERT(is_generating());
320 if (deferred_.length() > 0) {
321 for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
322 LDeferredCode* code = deferred_[i];
323
324 HValue* value =
325 instructions_->at(code->instruction_index())->hydrogen_value();
326 RecordAndWritePosition(value->position());
327
328 Comment(";;; <@%d,#%d> "
329 "-------------------- Deferred %s --------------------",
330 code->instruction_index(),
331 code->instr()->hydrogen_value()->id(),
332 code->instr()->Mnemonic());
333 __ bind(code->entry());
334 if (NeedsDeferredFrame()) {
335 Comment(";;; Build frame");
336 ASSERT(!frame_is_built_);
337 ASSERT(info()->IsStub());
338 frame_is_built_ = true;
339 // Build the frame in such a way that esi isn't trashed.
340 __ push(rbp); // Caller's frame pointer.
341 __ push(Operand(rbp, StandardFrameConstants::kContextOffset));
342 __ Push(Smi::FromInt(StackFrame::STUB));
343 __ lea(rbp, Operand(rsp, 2 * kPointerSize));
344 Comment(";;; Deferred code");
345 }
346 code->Generate();
347 if (NeedsDeferredFrame()) {
348 __ bind(code->done());
349 Comment(";;; Destroy frame");
350 ASSERT(frame_is_built_);
351 frame_is_built_ = false;
352 __ movq(rsp, rbp);
353 __ pop(rbp);
354 }
355 __ jmp(code->exit());
356 }
357 }
358
359 // Deferred code is the last part of the instruction sequence. Mark
360 // the generated code as done unless we bailed out.
361 if (!is_aborted()) status_ = DONE;
362 return !is_aborted();
363 }
364
365
GenerateSafepointTable()366 bool LCodeGen::GenerateSafepointTable() {
367 ASSERT(is_done());
368 safepoints_.Emit(masm(), GetStackSlotCount());
369 return !is_aborted();
370 }
371
372
ToRegister(int index) const373 Register LCodeGen::ToRegister(int index) const {
374 return Register::FromAllocationIndex(index);
375 }
376
377
ToDoubleRegister(int index) const378 XMMRegister LCodeGen::ToDoubleRegister(int index) const {
379 return XMMRegister::FromAllocationIndex(index);
380 }
381
382
ToRegister(LOperand * op) const383 Register LCodeGen::ToRegister(LOperand* op) const {
384 ASSERT(op->IsRegister());
385 return ToRegister(op->index());
386 }
387
388
ToDoubleRegister(LOperand * op) const389 XMMRegister LCodeGen::ToDoubleRegister(LOperand* op) const {
390 ASSERT(op->IsDoubleRegister());
391 return ToDoubleRegister(op->index());
392 }
393
394
IsInteger32Constant(LConstantOperand * op) const395 bool LCodeGen::IsInteger32Constant(LConstantOperand* op) const {
396 return op->IsConstantOperand() &&
397 chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
398 }
399
400
IsSmiConstant(LConstantOperand * op) const401 bool LCodeGen::IsSmiConstant(LConstantOperand* op) const {
402 return op->IsConstantOperand() &&
403 chunk_->LookupLiteralRepresentation(op).IsSmi();
404 }
405
406
IsTaggedConstant(LConstantOperand * op) const407 bool LCodeGen::IsTaggedConstant(LConstantOperand* op) const {
408 return op->IsConstantOperand() &&
409 chunk_->LookupLiteralRepresentation(op).IsTagged();
410 }
411
412
ToInteger32(LConstantOperand * op) const413 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
414 HConstant* constant = chunk_->LookupConstant(op);
415 return constant->Integer32Value();
416 }
417
418
ToSmi(LConstantOperand * op) const419 Smi* LCodeGen::ToSmi(LConstantOperand* op) const {
420 HConstant* constant = chunk_->LookupConstant(op);
421 return Smi::FromInt(constant->Integer32Value());
422 }
423
424
ToDouble(LConstantOperand * op) const425 double LCodeGen::ToDouble(LConstantOperand* op) const {
426 HConstant* constant = chunk_->LookupConstant(op);
427 ASSERT(constant->HasDoubleValue());
428 return constant->DoubleValue();
429 }
430
431
ToExternalReference(LConstantOperand * op) const432 ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
433 HConstant* constant = chunk_->LookupConstant(op);
434 ASSERT(constant->HasExternalReferenceValue());
435 return constant->ExternalReferenceValue();
436 }
437
438
ToHandle(LConstantOperand * op) const439 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
440 HConstant* constant = chunk_->LookupConstant(op);
441 ASSERT(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
442 return constant->handle(isolate());
443 }
444
445
ArgumentsOffsetWithoutFrame(int index)446 static int ArgumentsOffsetWithoutFrame(int index) {
447 ASSERT(index < 0);
448 return -(index + 1) * kPointerSize + kPCOnStackSize;
449 }
450
451
ToOperand(LOperand * op) const452 Operand LCodeGen::ToOperand(LOperand* op) const {
453 // Does not handle registers. In X64 assembler, plain registers are not
454 // representable as an Operand.
455 ASSERT(op->IsStackSlot() || op->IsDoubleStackSlot());
456 if (NeedsEagerFrame()) {
457 return Operand(rbp, StackSlotOffset(op->index()));
458 } else {
459 // Retrieve parameter without eager stack-frame relative to the
460 // stack-pointer.
461 return Operand(rsp, ArgumentsOffsetWithoutFrame(op->index()));
462 }
463 }
464
465
WriteTranslation(LEnvironment * environment,Translation * translation)466 void LCodeGen::WriteTranslation(LEnvironment* environment,
467 Translation* translation) {
468 if (environment == NULL) return;
469
470 // The translation includes one command per value in the environment.
471 int translation_size = environment->translation_size();
472 // The output frame height does not include the parameters.
473 int height = translation_size - environment->parameter_count();
474
475 WriteTranslation(environment->outer(), translation);
476 bool has_closure_id = !info()->closure().is_null() &&
477 !info()->closure().is_identical_to(environment->closure());
478 int closure_id = has_closure_id
479 ? DefineDeoptimizationLiteral(environment->closure())
480 : Translation::kSelfLiteralId;
481
482 switch (environment->frame_type()) {
483 case JS_FUNCTION:
484 translation->BeginJSFrame(environment->ast_id(), closure_id, height);
485 break;
486 case JS_CONSTRUCT:
487 translation->BeginConstructStubFrame(closure_id, translation_size);
488 break;
489 case JS_GETTER:
490 ASSERT(translation_size == 1);
491 ASSERT(height == 0);
492 translation->BeginGetterStubFrame(closure_id);
493 break;
494 case JS_SETTER:
495 ASSERT(translation_size == 2);
496 ASSERT(height == 0);
497 translation->BeginSetterStubFrame(closure_id);
498 break;
499 case ARGUMENTS_ADAPTOR:
500 translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
501 break;
502 case STUB:
503 translation->BeginCompiledStubFrame();
504 break;
505 }
506
507 int object_index = 0;
508 int dematerialized_index = 0;
509 for (int i = 0; i < translation_size; ++i) {
510 LOperand* value = environment->values()->at(i);
511 AddToTranslation(environment,
512 translation,
513 value,
514 environment->HasTaggedValueAt(i),
515 environment->HasUint32ValueAt(i),
516 &object_index,
517 &dematerialized_index);
518 }
519 }
520
521
AddToTranslation(LEnvironment * environment,Translation * translation,LOperand * op,bool is_tagged,bool is_uint32,int * object_index_pointer,int * dematerialized_index_pointer)522 void LCodeGen::AddToTranslation(LEnvironment* environment,
523 Translation* translation,
524 LOperand* op,
525 bool is_tagged,
526 bool is_uint32,
527 int* object_index_pointer,
528 int* dematerialized_index_pointer) {
529 if (op == LEnvironment::materialization_marker()) {
530 int object_index = (*object_index_pointer)++;
531 if (environment->ObjectIsDuplicateAt(object_index)) {
532 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
533 translation->DuplicateObject(dupe_of);
534 return;
535 }
536 int object_length = environment->ObjectLengthAt(object_index);
537 if (environment->ObjectIsArgumentsAt(object_index)) {
538 translation->BeginArgumentsObject(object_length);
539 } else {
540 translation->BeginCapturedObject(object_length);
541 }
542 int dematerialized_index = *dematerialized_index_pointer;
543 int env_offset = environment->translation_size() + dematerialized_index;
544 *dematerialized_index_pointer += object_length;
545 for (int i = 0; i < object_length; ++i) {
546 LOperand* value = environment->values()->at(env_offset + i);
547 AddToTranslation(environment,
548 translation,
549 value,
550 environment->HasTaggedValueAt(env_offset + i),
551 environment->HasUint32ValueAt(env_offset + i),
552 object_index_pointer,
553 dematerialized_index_pointer);
554 }
555 return;
556 }
557
558 if (op->IsStackSlot()) {
559 if (is_tagged) {
560 translation->StoreStackSlot(op->index());
561 } else if (is_uint32) {
562 translation->StoreUint32StackSlot(op->index());
563 } else {
564 translation->StoreInt32StackSlot(op->index());
565 }
566 } else if (op->IsDoubleStackSlot()) {
567 translation->StoreDoubleStackSlot(op->index());
568 } else if (op->IsArgument()) {
569 ASSERT(is_tagged);
570 int src_index = GetStackSlotCount() + op->index();
571 translation->StoreStackSlot(src_index);
572 } else if (op->IsRegister()) {
573 Register reg = ToRegister(op);
574 if (is_tagged) {
575 translation->StoreRegister(reg);
576 } else if (is_uint32) {
577 translation->StoreUint32Register(reg);
578 } else {
579 translation->StoreInt32Register(reg);
580 }
581 } else if (op->IsDoubleRegister()) {
582 XMMRegister reg = ToDoubleRegister(op);
583 translation->StoreDoubleRegister(reg);
584 } else if (op->IsConstantOperand()) {
585 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
586 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
587 translation->StoreLiteral(src_index);
588 } else {
589 UNREACHABLE();
590 }
591 }
592
593
CallCodeGeneric(Handle<Code> code,RelocInfo::Mode mode,LInstruction * instr,SafepointMode safepoint_mode,int argc)594 void LCodeGen::CallCodeGeneric(Handle<Code> code,
595 RelocInfo::Mode mode,
596 LInstruction* instr,
597 SafepointMode safepoint_mode,
598 int argc) {
599 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size() - masm()->CallSize(code));
600 ASSERT(instr != NULL);
601 __ call(code, mode);
602 RecordSafepointWithLazyDeopt(instr, safepoint_mode, argc);
603
604 // Signal that we don't inline smi code before these stubs in the
605 // optimizing code generator.
606 if (code->kind() == Code::BINARY_OP_IC ||
607 code->kind() == Code::COMPARE_IC) {
608 __ nop();
609 }
610 }
611
612
CallCode(Handle<Code> code,RelocInfo::Mode mode,LInstruction * instr)613 void LCodeGen::CallCode(Handle<Code> code,
614 RelocInfo::Mode mode,
615 LInstruction* instr) {
616 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT, 0);
617 }
618
619
CallRuntime(const Runtime::Function * function,int num_arguments,LInstruction * instr,SaveFPRegsMode save_doubles)620 void LCodeGen::CallRuntime(const Runtime::Function* function,
621 int num_arguments,
622 LInstruction* instr,
623 SaveFPRegsMode save_doubles) {
624 ASSERT(instr != NULL);
625 ASSERT(instr->HasPointerMap());
626
627 __ CallRuntime(function, num_arguments, save_doubles);
628
629 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT, 0);
630 }
631
632
LoadContextFromDeferred(LOperand * context)633 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
634 if (context->IsRegister()) {
635 if (!ToRegister(context).is(rsi)) {
636 __ movq(rsi, ToRegister(context));
637 }
638 } else if (context->IsStackSlot()) {
639 __ movq(rsi, ToOperand(context));
640 } else if (context->IsConstantOperand()) {
641 HConstant* constant =
642 chunk_->LookupConstant(LConstantOperand::cast(context));
643 __ Move(rsi, Handle<Object>::cast(constant->handle(isolate())));
644 } else {
645 UNREACHABLE();
646 }
647 }
648
649
650
CallRuntimeFromDeferred(Runtime::FunctionId id,int argc,LInstruction * instr,LOperand * context)651 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
652 int argc,
653 LInstruction* instr,
654 LOperand* context) {
655 LoadContextFromDeferred(context);
656
657 __ CallRuntimeSaveDoubles(id);
658 RecordSafepointWithRegisters(
659 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
660 }
661
662
RegisterEnvironmentForDeoptimization(LEnvironment * environment,Safepoint::DeoptMode mode)663 void LCodeGen::RegisterEnvironmentForDeoptimization(LEnvironment* environment,
664 Safepoint::DeoptMode mode) {
665 if (!environment->HasBeenRegistered()) {
666 // Physical stack frame layout:
667 // -x ............. -4 0 ..................................... y
668 // [incoming arguments] [spill slots] [pushed outgoing arguments]
669
670 // Layout of the environment:
671 // 0 ..................................................... size-1
672 // [parameters] [locals] [expression stack including arguments]
673
674 // Layout of the translation:
675 // 0 ........................................................ size - 1 + 4
676 // [expression stack including arguments] [locals] [4 words] [parameters]
677 // |>------------ translation_size ------------<|
678
679 int frame_count = 0;
680 int jsframe_count = 0;
681 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
682 ++frame_count;
683 if (e->frame_type() == JS_FUNCTION) {
684 ++jsframe_count;
685 }
686 }
687 Translation translation(&translations_, frame_count, jsframe_count, zone());
688 WriteTranslation(environment, &translation);
689 int deoptimization_index = deoptimizations_.length();
690 int pc_offset = masm()->pc_offset();
691 environment->Register(deoptimization_index,
692 translation.index(),
693 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
694 deoptimizations_.Add(environment, environment->zone());
695 }
696 }
697
698
DeoptimizeIf(Condition cc,LEnvironment * environment,Deoptimizer::BailoutType bailout_type)699 void LCodeGen::DeoptimizeIf(Condition cc,
700 LEnvironment* environment,
701 Deoptimizer::BailoutType bailout_type) {
702 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
703 ASSERT(environment->HasBeenRegistered());
704 int id = environment->deoptimization_index();
705 ASSERT(info()->IsOptimizing() || info()->IsStub());
706 Address entry =
707 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
708 if (entry == NULL) {
709 Abort(kBailoutWasNotPrepared);
710 return;
711 }
712
713 if (DeoptEveryNTimes()) {
714 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
715 Label no_deopt;
716 __ pushfq();
717 __ push(rax);
718 Operand count_operand = masm()->ExternalOperand(count, kScratchRegister);
719 __ movl(rax, count_operand);
720 __ subl(rax, Immediate(1));
721 __ j(not_zero, &no_deopt, Label::kNear);
722 if (FLAG_trap_on_deopt) __ int3();
723 __ movl(rax, Immediate(FLAG_deopt_every_n_times));
724 __ movl(count_operand, rax);
725 __ pop(rax);
726 __ popfq();
727 ASSERT(frame_is_built_);
728 __ call(entry, RelocInfo::RUNTIME_ENTRY);
729 __ bind(&no_deopt);
730 __ movl(count_operand, rax);
731 __ pop(rax);
732 __ popfq();
733 }
734
735 if (info()->ShouldTrapOnDeopt()) {
736 Label done;
737 if (cc != no_condition) {
738 __ j(NegateCondition(cc), &done, Label::kNear);
739 }
740 __ int3();
741 __ bind(&done);
742 }
743
744 ASSERT(info()->IsStub() || frame_is_built_);
745 // Go through jump table if we need to handle condition, build frame, or
746 // restore caller doubles.
747 if (cc == no_condition && frame_is_built_ &&
748 !info()->saves_caller_doubles()) {
749 __ call(entry, RelocInfo::RUNTIME_ENTRY);
750 } else {
751 // We often have several deopts to the same entry, reuse the last
752 // jump entry if this is the case.
753 if (jump_table_.is_empty() ||
754 jump_table_.last().address != entry ||
755 jump_table_.last().needs_frame != !frame_is_built_ ||
756 jump_table_.last().bailout_type != bailout_type) {
757 Deoptimizer::JumpTableEntry table_entry(entry,
758 bailout_type,
759 !frame_is_built_);
760 jump_table_.Add(table_entry, zone());
761 }
762 if (cc == no_condition) {
763 __ jmp(&jump_table_.last().label);
764 } else {
765 __ j(cc, &jump_table_.last().label);
766 }
767 }
768 }
769
770
DeoptimizeIf(Condition cc,LEnvironment * environment)771 void LCodeGen::DeoptimizeIf(Condition cc,
772 LEnvironment* environment) {
773 Deoptimizer::BailoutType bailout_type = info()->IsStub()
774 ? Deoptimizer::LAZY
775 : Deoptimizer::EAGER;
776 DeoptimizeIf(cc, environment, bailout_type);
777 }
778
779
PopulateDeoptimizationData(Handle<Code> code)780 void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
781 int length = deoptimizations_.length();
782 if (length == 0) return;
783 Handle<DeoptimizationInputData> data =
784 factory()->NewDeoptimizationInputData(length, TENURED);
785
786 Handle<ByteArray> translations =
787 translations_.CreateByteArray(isolate()->factory());
788 data->SetTranslationByteArray(*translations);
789 data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
790
791 Handle<FixedArray> literals =
792 factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
793 { AllowDeferredHandleDereference copy_handles;
794 for (int i = 0; i < deoptimization_literals_.length(); i++) {
795 literals->set(i, *deoptimization_literals_[i]);
796 }
797 data->SetLiteralArray(*literals);
798 }
799
800 data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
801 data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
802
803 // Populate the deoptimization entries.
804 for (int i = 0; i < length; i++) {
805 LEnvironment* env = deoptimizations_[i];
806 data->SetAstId(i, env->ast_id());
807 data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
808 data->SetArgumentsStackHeight(i,
809 Smi::FromInt(env->arguments_stack_height()));
810 data->SetPc(i, Smi::FromInt(env->pc_offset()));
811 }
812 code->set_deoptimization_data(*data);
813 }
814
815
DefineDeoptimizationLiteral(Handle<Object> literal)816 int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
817 int result = deoptimization_literals_.length();
818 for (int i = 0; i < deoptimization_literals_.length(); ++i) {
819 if (deoptimization_literals_[i].is_identical_to(literal)) return i;
820 }
821 deoptimization_literals_.Add(literal, zone());
822 return result;
823 }
824
825
PopulateDeoptimizationLiteralsWithInlinedFunctions()826 void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
827 ASSERT(deoptimization_literals_.length() == 0);
828
829 const ZoneList<Handle<JSFunction> >* inlined_closures =
830 chunk()->inlined_closures();
831
832 for (int i = 0, length = inlined_closures->length();
833 i < length;
834 i++) {
835 DefineDeoptimizationLiteral(inlined_closures->at(i));
836 }
837
838 inlined_function_count_ = deoptimization_literals_.length();
839 }
840
841
RecordSafepointWithLazyDeopt(LInstruction * instr,SafepointMode safepoint_mode,int argc)842 void LCodeGen::RecordSafepointWithLazyDeopt(
843 LInstruction* instr, SafepointMode safepoint_mode, int argc) {
844 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
845 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
846 } else {
847 ASSERT(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS);
848 RecordSafepointWithRegisters(
849 instr->pointer_map(), argc, Safepoint::kLazyDeopt);
850 }
851 }
852
853
RecordSafepoint(LPointerMap * pointers,Safepoint::Kind kind,int arguments,Safepoint::DeoptMode deopt_mode)854 void LCodeGen::RecordSafepoint(
855 LPointerMap* pointers,
856 Safepoint::Kind kind,
857 int arguments,
858 Safepoint::DeoptMode deopt_mode) {
859 ASSERT(kind == expected_safepoint_kind_);
860
861 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
862
863 Safepoint safepoint = safepoints_.DefineSafepoint(masm(),
864 kind, arguments, deopt_mode);
865 for (int i = 0; i < operands->length(); i++) {
866 LOperand* pointer = operands->at(i);
867 if (pointer->IsStackSlot()) {
868 safepoint.DefinePointerSlot(pointer->index(), zone());
869 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
870 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
871 }
872 }
873 }
874
875
RecordSafepoint(LPointerMap * pointers,Safepoint::DeoptMode deopt_mode)876 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
877 Safepoint::DeoptMode deopt_mode) {
878 RecordSafepoint(pointers, Safepoint::kSimple, 0, deopt_mode);
879 }
880
881
RecordSafepoint(Safepoint::DeoptMode deopt_mode)882 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode deopt_mode) {
883 LPointerMap empty_pointers(zone());
884 RecordSafepoint(&empty_pointers, deopt_mode);
885 }
886
887
RecordSafepointWithRegisters(LPointerMap * pointers,int arguments,Safepoint::DeoptMode deopt_mode)888 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
889 int arguments,
890 Safepoint::DeoptMode deopt_mode) {
891 RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, deopt_mode);
892 }
893
894
RecordAndWritePosition(int position)895 void LCodeGen::RecordAndWritePosition(int position) {
896 if (position == RelocInfo::kNoPosition) return;
897 masm()->positions_recorder()->RecordPosition(position);
898 masm()->positions_recorder()->WriteRecordedPositions();
899 }
900
901
LabelType(LLabel * label)902 static const char* LabelType(LLabel* label) {
903 if (label->is_loop_header()) return " (loop header)";
904 if (label->is_osr_entry()) return " (OSR entry)";
905 return "";
906 }
907
908
DoLabel(LLabel * label)909 void LCodeGen::DoLabel(LLabel* label) {
910 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
911 current_instruction_,
912 label->hydrogen_value()->id(),
913 label->block_id(),
914 LabelType(label));
915 __ bind(label->label());
916 current_block_ = label->block_id();
917 DoGap(label);
918 }
919
920
DoParallelMove(LParallelMove * move)921 void LCodeGen::DoParallelMove(LParallelMove* move) {
922 resolver_.Resolve(move);
923 }
924
925
DoGap(LGap * gap)926 void LCodeGen::DoGap(LGap* gap) {
927 for (int i = LGap::FIRST_INNER_POSITION;
928 i <= LGap::LAST_INNER_POSITION;
929 i++) {
930 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
931 LParallelMove* move = gap->GetParallelMove(inner_pos);
932 if (move != NULL) DoParallelMove(move);
933 }
934 }
935
936
DoInstructionGap(LInstructionGap * instr)937 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
938 DoGap(instr);
939 }
940
941
DoParameter(LParameter * instr)942 void LCodeGen::DoParameter(LParameter* instr) {
943 // Nothing to do.
944 }
945
946
DoCallStub(LCallStub * instr)947 void LCodeGen::DoCallStub(LCallStub* instr) {
948 ASSERT(ToRegister(instr->context()).is(rsi));
949 ASSERT(ToRegister(instr->result()).is(rax));
950 switch (instr->hydrogen()->major_key()) {
951 case CodeStub::RegExpConstructResult: {
952 RegExpConstructResultStub stub;
953 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
954 break;
955 }
956 case CodeStub::RegExpExec: {
957 RegExpExecStub stub;
958 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
959 break;
960 }
961 case CodeStub::SubString: {
962 SubStringStub stub;
963 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
964 break;
965 }
966 case CodeStub::StringCompare: {
967 StringCompareStub stub;
968 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
969 break;
970 }
971 case CodeStub::TranscendentalCache: {
972 TranscendentalCacheStub stub(instr->transcendental_type(),
973 TranscendentalCacheStub::TAGGED);
974 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
975 break;
976 }
977 default:
978 UNREACHABLE();
979 }
980 }
981
982
DoUnknownOSRValue(LUnknownOSRValue * instr)983 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
984 GenerateOsrPrologue();
985 }
986
987
DoModI(LModI * instr)988 void LCodeGen::DoModI(LModI* instr) {
989 HMod* hmod = instr->hydrogen();
990 HValue* left = hmod->left();
991 HValue* right = hmod->right();
992 if (hmod->HasPowerOf2Divisor()) {
993 // TODO(svenpanne) We should really do the strength reduction on the
994 // Hydrogen level.
995 Register left_reg = ToRegister(instr->left());
996 ASSERT(left_reg.is(ToRegister(instr->result())));
997
998 // Note: The code below even works when right contains kMinInt.
999 int32_t divisor = Abs(right->GetInteger32Constant());
1000
1001 Label left_is_not_negative, done;
1002 if (left->CanBeNegative()) {
1003 __ testl(left_reg, left_reg);
1004 __ j(not_sign, &left_is_not_negative, Label::kNear);
1005 __ negl(left_reg);
1006 __ andl(left_reg, Immediate(divisor - 1));
1007 __ negl(left_reg);
1008 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1009 DeoptimizeIf(zero, instr->environment());
1010 }
1011 __ jmp(&done, Label::kNear);
1012 }
1013
1014 __ bind(&left_is_not_negative);
1015 __ andl(left_reg, Immediate(divisor - 1));
1016 __ bind(&done);
1017 } else {
1018 Register left_reg = ToRegister(instr->left());
1019 ASSERT(left_reg.is(rax));
1020 Register right_reg = ToRegister(instr->right());
1021 ASSERT(!right_reg.is(rax));
1022 ASSERT(!right_reg.is(rdx));
1023 Register result_reg = ToRegister(instr->result());
1024 ASSERT(result_reg.is(rdx));
1025
1026 Label done;
1027 // Check for x % 0, idiv would signal a divide error. We have to
1028 // deopt in this case because we can't return a NaN.
1029 if (right->CanBeZero()) {
1030 __ testl(right_reg, right_reg);
1031 DeoptimizeIf(zero, instr->environment());
1032 }
1033
1034 // Check for kMinInt % -1, idiv would signal a divide error. We
1035 // have to deopt if we care about -0, because we can't return that.
1036 if (left->RangeCanInclude(kMinInt) && right->RangeCanInclude(-1)) {
1037 Label no_overflow_possible;
1038 __ cmpl(left_reg, Immediate(kMinInt));
1039 __ j(not_zero, &no_overflow_possible, Label::kNear);
1040 __ cmpl(right_reg, Immediate(-1));
1041 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1042 DeoptimizeIf(equal, instr->environment());
1043 } else {
1044 __ j(not_equal, &no_overflow_possible, Label::kNear);
1045 __ Set(result_reg, 0);
1046 __ jmp(&done, Label::kNear);
1047 }
1048 __ bind(&no_overflow_possible);
1049 }
1050
1051 // Sign extend dividend in eax into edx:eax, since we are using only the low
1052 // 32 bits of the values.
1053 __ cdq();
1054
1055 // If we care about -0, test if the dividend is <0 and the result is 0.
1056 if (left->CanBeNegative() &&
1057 hmod->CanBeZero() &&
1058 hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1059 Label positive_left;
1060 __ testl(left_reg, left_reg);
1061 __ j(not_sign, &positive_left, Label::kNear);
1062 __ idivl(right_reg);
1063 __ testl(result_reg, result_reg);
1064 DeoptimizeIf(zero, instr->environment());
1065 __ jmp(&done, Label::kNear);
1066 __ bind(&positive_left);
1067 }
1068 __ idivl(right_reg);
1069 __ bind(&done);
1070 }
1071 }
1072
1073
DoMathFloorOfDiv(LMathFloorOfDiv * instr)1074 void LCodeGen::DoMathFloorOfDiv(LMathFloorOfDiv* instr) {
1075 ASSERT(instr->right()->IsConstantOperand());
1076
1077 const Register dividend = ToRegister(instr->left());
1078 int32_t divisor = ToInteger32(LConstantOperand::cast(instr->right()));
1079 const Register result = ToRegister(instr->result());
1080
1081 switch (divisor) {
1082 case 0:
1083 DeoptimizeIf(no_condition, instr->environment());
1084 return;
1085
1086 case 1:
1087 if (!result.is(dividend)) {
1088 __ movl(result, dividend);
1089 }
1090 return;
1091
1092 case -1:
1093 if (!result.is(dividend)) {
1094 __ movl(result, dividend);
1095 }
1096 __ negl(result);
1097 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1098 DeoptimizeIf(zero, instr->environment());
1099 }
1100 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1101 DeoptimizeIf(overflow, instr->environment());
1102 }
1103 return;
1104 }
1105
1106 uint32_t divisor_abs = abs(divisor);
1107 if (IsPowerOf2(divisor_abs)) {
1108 int32_t power = WhichPowerOf2(divisor_abs);
1109 if (divisor < 0) {
1110 __ movsxlq(result, dividend);
1111 __ neg(result);
1112 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1113 DeoptimizeIf(zero, instr->environment());
1114 }
1115 __ sar(result, Immediate(power));
1116 } else {
1117 if (!result.is(dividend)) {
1118 __ movl(result, dividend);
1119 }
1120 __ sarl(result, Immediate(power));
1121 }
1122 } else {
1123 Register reg1 = ToRegister(instr->temp());
1124 Register reg2 = ToRegister(instr->result());
1125
1126 // Find b which: 2^b < divisor_abs < 2^(b+1).
1127 unsigned b = 31 - CompilerIntrinsics::CountLeadingZeros(divisor_abs);
1128 unsigned shift = 32 + b; // Precision +1bit (effectively).
1129 double multiplier_f =
1130 static_cast<double>(static_cast<uint64_t>(1) << shift) / divisor_abs;
1131 int64_t multiplier;
1132 if (multiplier_f - floor(multiplier_f) < 0.5) {
1133 multiplier = static_cast<int64_t>(floor(multiplier_f));
1134 } else {
1135 multiplier = static_cast<int64_t>(floor(multiplier_f)) + 1;
1136 }
1137 // The multiplier is a uint32.
1138 ASSERT(multiplier > 0 &&
1139 multiplier < (static_cast<int64_t>(1) << 32));
1140 // The multiply is int64, so sign-extend to r64.
1141 __ movsxlq(reg1, dividend);
1142 if (divisor < 0 &&
1143 instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1144 __ neg(reg1);
1145 DeoptimizeIf(zero, instr->environment());
1146 }
1147 __ Set(reg2, multiplier);
1148 // Result just fit in r64, because it's int32 * uint32.
1149 __ imul(reg2, reg1);
1150
1151 __ addq(reg2, Immediate(1 << 30));
1152 __ sar(reg2, Immediate(shift));
1153 }
1154 }
1155
1156
DoDivI(LDivI * instr)1157 void LCodeGen::DoDivI(LDivI* instr) {
1158 if (!instr->is_flooring() && instr->hydrogen()->HasPowerOf2Divisor()) {
1159 Register dividend = ToRegister(instr->left());
1160 int32_t divisor =
1161 HConstant::cast(instr->hydrogen()->right())->Integer32Value();
1162 int32_t test_value = 0;
1163 int32_t power = 0;
1164
1165 if (divisor > 0) {
1166 test_value = divisor - 1;
1167 power = WhichPowerOf2(divisor);
1168 } else {
1169 // Check for (0 / -x) that will produce negative zero.
1170 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1171 __ testl(dividend, dividend);
1172 DeoptimizeIf(zero, instr->environment());
1173 }
1174 // Check for (kMinInt / -1).
1175 if (divisor == -1 && instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1176 __ cmpl(dividend, Immediate(kMinInt));
1177 DeoptimizeIf(zero, instr->environment());
1178 }
1179 test_value = - divisor - 1;
1180 power = WhichPowerOf2(-divisor);
1181 }
1182
1183 if (test_value != 0) {
1184 if (instr->hydrogen()->CheckFlag(
1185 HInstruction::kAllUsesTruncatingToInt32)) {
1186 Label done, negative;
1187 __ cmpl(dividend, Immediate(0));
1188 __ j(less, &negative, Label::kNear);
1189 __ sarl(dividend, Immediate(power));
1190 if (divisor < 0) __ negl(dividend);
1191 __ jmp(&done, Label::kNear);
1192
1193 __ bind(&negative);
1194 __ negl(dividend);
1195 __ sarl(dividend, Immediate(power));
1196 if (divisor > 0) __ negl(dividend);
1197 __ bind(&done);
1198 return; // Don't fall through to "__ neg" below.
1199 } else {
1200 // Deoptimize if remainder is not 0.
1201 __ testl(dividend, Immediate(test_value));
1202 DeoptimizeIf(not_zero, instr->environment());
1203 __ sarl(dividend, Immediate(power));
1204 }
1205 }
1206
1207 if (divisor < 0) __ negl(dividend);
1208
1209 return;
1210 }
1211
1212 LOperand* right = instr->right();
1213 ASSERT(ToRegister(instr->result()).is(rax));
1214 ASSERT(ToRegister(instr->left()).is(rax));
1215 ASSERT(!ToRegister(instr->right()).is(rax));
1216 ASSERT(!ToRegister(instr->right()).is(rdx));
1217
1218 Register left_reg = rax;
1219
1220 // Check for x / 0.
1221 Register right_reg = ToRegister(right);
1222 if (instr->hydrogen_value()->CheckFlag(HValue::kCanBeDivByZero)) {
1223 __ testl(right_reg, right_reg);
1224 DeoptimizeIf(zero, instr->environment());
1225 }
1226
1227 // Check for (0 / -x) that will produce negative zero.
1228 if (instr->hydrogen_value()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1229 Label left_not_zero;
1230 __ testl(left_reg, left_reg);
1231 __ j(not_zero, &left_not_zero, Label::kNear);
1232 __ testl(right_reg, right_reg);
1233 DeoptimizeIf(sign, instr->environment());
1234 __ bind(&left_not_zero);
1235 }
1236
1237 // Check for (kMinInt / -1).
1238 if (instr->hydrogen_value()->CheckFlag(HValue::kCanOverflow)) {
1239 Label left_not_min_int;
1240 __ cmpl(left_reg, Immediate(kMinInt));
1241 __ j(not_zero, &left_not_min_int, Label::kNear);
1242 __ cmpl(right_reg, Immediate(-1));
1243 DeoptimizeIf(zero, instr->environment());
1244 __ bind(&left_not_min_int);
1245 }
1246
1247 // Sign extend to rdx.
1248 __ cdq();
1249 __ idivl(right_reg);
1250
1251 if (instr->is_flooring()) {
1252 Label done;
1253 __ testl(rdx, rdx);
1254 __ j(zero, &done, Label::kNear);
1255 __ xorl(rdx, right_reg);
1256 __ sarl(rdx, Immediate(31));
1257 __ addl(rax, rdx);
1258 __ bind(&done);
1259 } else if (!instr->hydrogen()->CheckFlag(
1260 HInstruction::kAllUsesTruncatingToInt32)) {
1261 // Deoptimize if remainder is not 0.
1262 __ testl(rdx, rdx);
1263 DeoptimizeIf(not_zero, instr->environment());
1264 }
1265 }
1266
1267
DoMulI(LMulI * instr)1268 void LCodeGen::DoMulI(LMulI* instr) {
1269 Register left = ToRegister(instr->left());
1270 LOperand* right = instr->right();
1271
1272 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1273 if (instr->hydrogen_value()->representation().IsSmi()) {
1274 __ movq(kScratchRegister, left);
1275 } else {
1276 __ movl(kScratchRegister, left);
1277 }
1278 }
1279
1280 bool can_overflow =
1281 instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
1282 if (right->IsConstantOperand()) {
1283 int32_t right_value = ToInteger32(LConstantOperand::cast(right));
1284 if (right_value == -1) {
1285 __ negl(left);
1286 } else if (right_value == 0) {
1287 __ xorl(left, left);
1288 } else if (right_value == 2) {
1289 __ addl(left, left);
1290 } else if (!can_overflow) {
1291 // If the multiplication is known to not overflow, we
1292 // can use operations that don't set the overflow flag
1293 // correctly.
1294 switch (right_value) {
1295 case 1:
1296 // Do nothing.
1297 break;
1298 case 3:
1299 __ leal(left, Operand(left, left, times_2, 0));
1300 break;
1301 case 4:
1302 __ shll(left, Immediate(2));
1303 break;
1304 case 5:
1305 __ leal(left, Operand(left, left, times_4, 0));
1306 break;
1307 case 8:
1308 __ shll(left, Immediate(3));
1309 break;
1310 case 9:
1311 __ leal(left, Operand(left, left, times_8, 0));
1312 break;
1313 case 16:
1314 __ shll(left, Immediate(4));
1315 break;
1316 default:
1317 __ imull(left, left, Immediate(right_value));
1318 break;
1319 }
1320 } else {
1321 __ imull(left, left, Immediate(right_value));
1322 }
1323 } else if (right->IsStackSlot()) {
1324 if (instr->hydrogen_value()->representation().IsSmi()) {
1325 __ SmiToInteger64(left, left);
1326 __ imul(left, ToOperand(right));
1327 } else {
1328 __ imull(left, ToOperand(right));
1329 }
1330 } else {
1331 if (instr->hydrogen_value()->representation().IsSmi()) {
1332 __ SmiToInteger64(left, left);
1333 __ imul(left, ToRegister(right));
1334 } else {
1335 __ imull(left, ToRegister(right));
1336 }
1337 }
1338
1339 if (can_overflow) {
1340 DeoptimizeIf(overflow, instr->environment());
1341 }
1342
1343 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1344 // Bail out if the result is supposed to be negative zero.
1345 Label done;
1346 if (instr->hydrogen_value()->representation().IsSmi()) {
1347 __ testq(left, left);
1348 } else {
1349 __ testl(left, left);
1350 }
1351 __ j(not_zero, &done, Label::kNear);
1352 if (right->IsConstantOperand()) {
1353 // Constant can't be represented as Smi due to immediate size limit.
1354 ASSERT(!instr->hydrogen_value()->representation().IsSmi());
1355 if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1356 DeoptimizeIf(no_condition, instr->environment());
1357 } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
1358 __ cmpl(kScratchRegister, Immediate(0));
1359 DeoptimizeIf(less, instr->environment());
1360 }
1361 } else if (right->IsStackSlot()) {
1362 if (instr->hydrogen_value()->representation().IsSmi()) {
1363 __ or_(kScratchRegister, ToOperand(right));
1364 } else {
1365 __ orl(kScratchRegister, ToOperand(right));
1366 }
1367 DeoptimizeIf(sign, instr->environment());
1368 } else {
1369 // Test the non-zero operand for negative sign.
1370 if (instr->hydrogen_value()->representation().IsSmi()) {
1371 __ or_(kScratchRegister, ToRegister(right));
1372 } else {
1373 __ orl(kScratchRegister, ToRegister(right));
1374 }
1375 DeoptimizeIf(sign, instr->environment());
1376 }
1377 __ bind(&done);
1378 }
1379 }
1380
1381
DoBitI(LBitI * instr)1382 void LCodeGen::DoBitI(LBitI* instr) {
1383 LOperand* left = instr->left();
1384 LOperand* right = instr->right();
1385 ASSERT(left->Equals(instr->result()));
1386 ASSERT(left->IsRegister());
1387
1388 if (right->IsConstantOperand()) {
1389 int32_t right_operand = ToInteger32(LConstantOperand::cast(right));
1390 switch (instr->op()) {
1391 case Token::BIT_AND:
1392 __ andl(ToRegister(left), Immediate(right_operand));
1393 break;
1394 case Token::BIT_OR:
1395 __ orl(ToRegister(left), Immediate(right_operand));
1396 break;
1397 case Token::BIT_XOR:
1398 if (right_operand == int32_t(~0)) {
1399 __ notl(ToRegister(left));
1400 } else {
1401 __ xorl(ToRegister(left), Immediate(right_operand));
1402 }
1403 break;
1404 default:
1405 UNREACHABLE();
1406 break;
1407 }
1408 } else if (right->IsStackSlot()) {
1409 switch (instr->op()) {
1410 case Token::BIT_AND:
1411 __ and_(ToRegister(left), ToOperand(right));
1412 break;
1413 case Token::BIT_OR:
1414 __ or_(ToRegister(left), ToOperand(right));
1415 break;
1416 case Token::BIT_XOR:
1417 __ xor_(ToRegister(left), ToOperand(right));
1418 break;
1419 default:
1420 UNREACHABLE();
1421 break;
1422 }
1423 } else {
1424 ASSERT(right->IsRegister());
1425 switch (instr->op()) {
1426 case Token::BIT_AND:
1427 __ and_(ToRegister(left), ToRegister(right));
1428 break;
1429 case Token::BIT_OR:
1430 __ or_(ToRegister(left), ToRegister(right));
1431 break;
1432 case Token::BIT_XOR:
1433 __ xor_(ToRegister(left), ToRegister(right));
1434 break;
1435 default:
1436 UNREACHABLE();
1437 break;
1438 }
1439 }
1440 }
1441
1442
DoShiftI(LShiftI * instr)1443 void LCodeGen::DoShiftI(LShiftI* instr) {
1444 LOperand* left = instr->left();
1445 LOperand* right = instr->right();
1446 ASSERT(left->Equals(instr->result()));
1447 ASSERT(left->IsRegister());
1448 if (right->IsRegister()) {
1449 ASSERT(ToRegister(right).is(rcx));
1450
1451 switch (instr->op()) {
1452 case Token::ROR:
1453 __ rorl_cl(ToRegister(left));
1454 break;
1455 case Token::SAR:
1456 __ sarl_cl(ToRegister(left));
1457 break;
1458 case Token::SHR:
1459 __ shrl_cl(ToRegister(left));
1460 if (instr->can_deopt()) {
1461 __ testl(ToRegister(left), ToRegister(left));
1462 DeoptimizeIf(negative, instr->environment());
1463 }
1464 break;
1465 case Token::SHL:
1466 __ shll_cl(ToRegister(left));
1467 break;
1468 default:
1469 UNREACHABLE();
1470 break;
1471 }
1472 } else {
1473 int32_t value = ToInteger32(LConstantOperand::cast(right));
1474 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1475 switch (instr->op()) {
1476 case Token::ROR:
1477 if (shift_count != 0) {
1478 __ rorl(ToRegister(left), Immediate(shift_count));
1479 }
1480 break;
1481 case Token::SAR:
1482 if (shift_count != 0) {
1483 __ sarl(ToRegister(left), Immediate(shift_count));
1484 }
1485 break;
1486 case Token::SHR:
1487 if (shift_count == 0 && instr->can_deopt()) {
1488 __ testl(ToRegister(left), ToRegister(left));
1489 DeoptimizeIf(negative, instr->environment());
1490 } else {
1491 __ shrl(ToRegister(left), Immediate(shift_count));
1492 }
1493 break;
1494 case Token::SHL:
1495 if (shift_count != 0) {
1496 if (instr->hydrogen_value()->representation().IsSmi()) {
1497 __ shl(ToRegister(left), Immediate(shift_count));
1498 } else {
1499 __ shll(ToRegister(left), Immediate(shift_count));
1500 }
1501 }
1502 break;
1503 default:
1504 UNREACHABLE();
1505 break;
1506 }
1507 }
1508 }
1509
1510
DoSubI(LSubI * instr)1511 void LCodeGen::DoSubI(LSubI* instr) {
1512 LOperand* left = instr->left();
1513 LOperand* right = instr->right();
1514 ASSERT(left->Equals(instr->result()));
1515
1516 if (right->IsConstantOperand()) {
1517 __ subl(ToRegister(left),
1518 Immediate(ToInteger32(LConstantOperand::cast(right))));
1519 } else if (right->IsRegister()) {
1520 if (instr->hydrogen_value()->representation().IsSmi()) {
1521 __ subq(ToRegister(left), ToRegister(right));
1522 } else {
1523 __ subl(ToRegister(left), ToRegister(right));
1524 }
1525 } else {
1526 if (instr->hydrogen_value()->representation().IsSmi()) {
1527 __ subq(ToRegister(left), ToOperand(right));
1528 } else {
1529 __ subl(ToRegister(left), ToOperand(right));
1530 }
1531 }
1532
1533 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1534 DeoptimizeIf(overflow, instr->environment());
1535 }
1536 }
1537
1538
DoConstantI(LConstantI * instr)1539 void LCodeGen::DoConstantI(LConstantI* instr) {
1540 __ Set(ToRegister(instr->result()), instr->value());
1541 }
1542
1543
DoConstantS(LConstantS * instr)1544 void LCodeGen::DoConstantS(LConstantS* instr) {
1545 __ Move(ToRegister(instr->result()), instr->value());
1546 }
1547
1548
DoConstantD(LConstantD * instr)1549 void LCodeGen::DoConstantD(LConstantD* instr) {
1550 ASSERT(instr->result()->IsDoubleRegister());
1551 XMMRegister res = ToDoubleRegister(instr->result());
1552 double v = instr->value();
1553 uint64_t int_val = BitCast<uint64_t, double>(v);
1554 // Use xor to produce +0.0 in a fast and compact way, but avoid to
1555 // do so if the constant is -0.0.
1556 if (int_val == 0) {
1557 __ xorps(res, res);
1558 } else {
1559 Register tmp = ToRegister(instr->temp());
1560 __ Set(tmp, int_val);
1561 __ movq(res, tmp);
1562 }
1563 }
1564
1565
DoConstantE(LConstantE * instr)1566 void LCodeGen::DoConstantE(LConstantE* instr) {
1567 __ LoadAddress(ToRegister(instr->result()), instr->value());
1568 }
1569
1570
DoConstantT(LConstantT * instr)1571 void LCodeGen::DoConstantT(LConstantT* instr) {
1572 Handle<Object> value = instr->value(isolate());
1573 __ Move(ToRegister(instr->result()), value);
1574 }
1575
1576
DoMapEnumLength(LMapEnumLength * instr)1577 void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
1578 Register result = ToRegister(instr->result());
1579 Register map = ToRegister(instr->value());
1580 __ EnumLength(result, map);
1581 }
1582
1583
DoElementsKind(LElementsKind * instr)1584 void LCodeGen::DoElementsKind(LElementsKind* instr) {
1585 Register result = ToRegister(instr->result());
1586 Register input = ToRegister(instr->value());
1587
1588 // Load map into |result|.
1589 __ movq(result, FieldOperand(input, HeapObject::kMapOffset));
1590 // Load the map's "bit field 2" into |result|. We only need the first byte.
1591 __ movzxbq(result, FieldOperand(result, Map::kBitField2Offset));
1592 // Retrieve elements_kind from bit field 2.
1593 __ and_(result, Immediate(Map::kElementsKindMask));
1594 __ shr(result, Immediate(Map::kElementsKindShift));
1595 }
1596
1597
DoValueOf(LValueOf * instr)1598 void LCodeGen::DoValueOf(LValueOf* instr) {
1599 Register input = ToRegister(instr->value());
1600 Register result = ToRegister(instr->result());
1601 ASSERT(input.is(result));
1602 Label done;
1603
1604 if (!instr->hydrogen()->value()->IsHeapObject()) {
1605 // If the object is a smi return the object.
1606 __ JumpIfSmi(input, &done, Label::kNear);
1607 }
1608
1609 // If the object is not a value type, return the object.
1610 __ CmpObjectType(input, JS_VALUE_TYPE, kScratchRegister);
1611 __ j(not_equal, &done, Label::kNear);
1612 __ movq(result, FieldOperand(input, JSValue::kValueOffset));
1613
1614 __ bind(&done);
1615 }
1616
1617
DoDateField(LDateField * instr)1618 void LCodeGen::DoDateField(LDateField* instr) {
1619 Register object = ToRegister(instr->date());
1620 Register result = ToRegister(instr->result());
1621 Smi* index = instr->index();
1622 Label runtime, done, not_date_object;
1623 ASSERT(object.is(result));
1624 ASSERT(object.is(rax));
1625
1626 Condition cc = masm()->CheckSmi(object);
1627 DeoptimizeIf(cc, instr->environment());
1628 __ CmpObjectType(object, JS_DATE_TYPE, kScratchRegister);
1629 DeoptimizeIf(not_equal, instr->environment());
1630
1631 if (index->value() == 0) {
1632 __ movq(result, FieldOperand(object, JSDate::kValueOffset));
1633 } else {
1634 if (index->value() < JSDate::kFirstUncachedField) {
1635 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
1636 Operand stamp_operand = __ ExternalOperand(stamp);
1637 __ movq(kScratchRegister, stamp_operand);
1638 __ cmpq(kScratchRegister, FieldOperand(object,
1639 JSDate::kCacheStampOffset));
1640 __ j(not_equal, &runtime, Label::kNear);
1641 __ movq(result, FieldOperand(object, JSDate::kValueOffset +
1642 kPointerSize * index->value()));
1643 __ jmp(&done, Label::kNear);
1644 }
1645 __ bind(&runtime);
1646 __ PrepareCallCFunction(2);
1647 __ movq(arg_reg_1, object);
1648 __ movq(arg_reg_2, index, RelocInfo::NONE64);
1649 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
1650 __ bind(&done);
1651 }
1652 }
1653
1654
BuildSeqStringOperand(Register string,LOperand * index,String::Encoding encoding)1655 Operand LCodeGen::BuildSeqStringOperand(Register string,
1656 LOperand* index,
1657 String::Encoding encoding) {
1658 if (index->IsConstantOperand()) {
1659 int offset = ToInteger32(LConstantOperand::cast(index));
1660 if (encoding == String::TWO_BYTE_ENCODING) {
1661 offset *= kUC16Size;
1662 }
1663 STATIC_ASSERT(kCharSize == 1);
1664 return FieldOperand(string, SeqString::kHeaderSize + offset);
1665 }
1666 return FieldOperand(
1667 string, ToRegister(index),
1668 encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
1669 SeqString::kHeaderSize);
1670 }
1671
1672
DoSeqStringGetChar(LSeqStringGetChar * instr)1673 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
1674 String::Encoding encoding = instr->hydrogen()->encoding();
1675 Register result = ToRegister(instr->result());
1676 Register string = ToRegister(instr->string());
1677
1678 if (FLAG_debug_code) {
1679 __ push(string);
1680 __ movq(string, FieldOperand(string, HeapObject::kMapOffset));
1681 __ movzxbq(string, FieldOperand(string, Map::kInstanceTypeOffset));
1682
1683 __ andb(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
1684 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1685 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1686 __ cmpq(string, Immediate(encoding == String::ONE_BYTE_ENCODING
1687 ? one_byte_seq_type : two_byte_seq_type));
1688 __ Check(equal, kUnexpectedStringType);
1689 __ pop(string);
1690 }
1691
1692 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1693 if (encoding == String::ONE_BYTE_ENCODING) {
1694 __ movzxbl(result, operand);
1695 } else {
1696 __ movzxwl(result, operand);
1697 }
1698 }
1699
1700
DoSeqStringSetChar(LSeqStringSetChar * instr)1701 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
1702 String::Encoding encoding = instr->hydrogen()->encoding();
1703 Register string = ToRegister(instr->string());
1704
1705 if (FLAG_debug_code) {
1706 Register value = ToRegister(instr->value());
1707 Register index = ToRegister(instr->index());
1708 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1709 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1710 int encoding_mask =
1711 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
1712 ? one_byte_seq_type : two_byte_seq_type;
1713 __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
1714 }
1715
1716 Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1717 if (instr->value()->IsConstantOperand()) {
1718 int value = ToInteger32(LConstantOperand::cast(instr->value()));
1719 ASSERT_LE(0, value);
1720 if (encoding == String::ONE_BYTE_ENCODING) {
1721 ASSERT_LE(value, String::kMaxOneByteCharCode);
1722 __ movb(operand, Immediate(value));
1723 } else {
1724 ASSERT_LE(value, String::kMaxUtf16CodeUnit);
1725 __ movw(operand, Immediate(value));
1726 }
1727 } else {
1728 Register value = ToRegister(instr->value());
1729 if (encoding == String::ONE_BYTE_ENCODING) {
1730 __ movb(operand, value);
1731 } else {
1732 __ movw(operand, value);
1733 }
1734 }
1735 }
1736
1737
DoThrow(LThrow * instr)1738 void LCodeGen::DoThrow(LThrow* instr) {
1739 __ push(ToRegister(instr->value()));
1740 ASSERT(ToRegister(instr->context()).is(rsi));
1741 CallRuntime(Runtime::kThrow, 1, instr);
1742
1743 if (FLAG_debug_code) {
1744 Comment("Unreachable code.");
1745 __ int3();
1746 }
1747 }
1748
1749
DoAddI(LAddI * instr)1750 void LCodeGen::DoAddI(LAddI* instr) {
1751 LOperand* left = instr->left();
1752 LOperand* right = instr->right();
1753
1754 Representation target_rep = instr->hydrogen()->representation();
1755 bool is_q = target_rep.IsSmi() || target_rep.IsExternal();
1756
1757 if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
1758 if (right->IsConstantOperand()) {
1759 int32_t offset = ToInteger32(LConstantOperand::cast(right));
1760 if (is_q) {
1761 __ lea(ToRegister(instr->result()),
1762 MemOperand(ToRegister(left), offset));
1763 } else {
1764 __ leal(ToRegister(instr->result()),
1765 MemOperand(ToRegister(left), offset));
1766 }
1767 } else {
1768 Operand address(ToRegister(left), ToRegister(right), times_1, 0);
1769 if (is_q) {
1770 __ lea(ToRegister(instr->result()), address);
1771 } else {
1772 __ leal(ToRegister(instr->result()), address);
1773 }
1774 }
1775 } else {
1776 if (right->IsConstantOperand()) {
1777 if (is_q) {
1778 __ addq(ToRegister(left),
1779 Immediate(ToInteger32(LConstantOperand::cast(right))));
1780 } else {
1781 __ addl(ToRegister(left),
1782 Immediate(ToInteger32(LConstantOperand::cast(right))));
1783 }
1784 } else if (right->IsRegister()) {
1785 if (is_q) {
1786 __ addq(ToRegister(left), ToRegister(right));
1787 } else {
1788 __ addl(ToRegister(left), ToRegister(right));
1789 }
1790 } else {
1791 if (is_q) {
1792 __ addq(ToRegister(left), ToOperand(right));
1793 } else {
1794 __ addl(ToRegister(left), ToOperand(right));
1795 }
1796 }
1797 if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1798 DeoptimizeIf(overflow, instr->environment());
1799 }
1800 }
1801 }
1802
1803
DoMathMinMax(LMathMinMax * instr)1804 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
1805 LOperand* left = instr->left();
1806 LOperand* right = instr->right();
1807 ASSERT(left->Equals(instr->result()));
1808 HMathMinMax::Operation operation = instr->hydrogen()->operation();
1809 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
1810 Label return_left;
1811 Condition condition = (operation == HMathMinMax::kMathMin)
1812 ? less_equal
1813 : greater_equal;
1814 Register left_reg = ToRegister(left);
1815 if (right->IsConstantOperand()) {
1816 Immediate right_imm =
1817 Immediate(ToInteger32(LConstantOperand::cast(right)));
1818 ASSERT(!instr->hydrogen_value()->representation().IsSmi());
1819 __ cmpl(left_reg, right_imm);
1820 __ j(condition, &return_left, Label::kNear);
1821 __ movq(left_reg, right_imm);
1822 } else if (right->IsRegister()) {
1823 Register right_reg = ToRegister(right);
1824 if (instr->hydrogen_value()->representation().IsSmi()) {
1825 __ cmpq(left_reg, right_reg);
1826 } else {
1827 __ cmpl(left_reg, right_reg);
1828 }
1829 __ j(condition, &return_left, Label::kNear);
1830 __ movq(left_reg, right_reg);
1831 } else {
1832 Operand right_op = ToOperand(right);
1833 if (instr->hydrogen_value()->representation().IsSmi()) {
1834 __ cmpq(left_reg, right_op);
1835 } else {
1836 __ cmpl(left_reg, right_op);
1837 }
1838 __ j(condition, &return_left, Label::kNear);
1839 __ movq(left_reg, right_op);
1840 }
1841 __ bind(&return_left);
1842 } else {
1843 ASSERT(instr->hydrogen()->representation().IsDouble());
1844 Label check_nan_left, check_zero, return_left, return_right;
1845 Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
1846 XMMRegister left_reg = ToDoubleRegister(left);
1847 XMMRegister right_reg = ToDoubleRegister(right);
1848 __ ucomisd(left_reg, right_reg);
1849 __ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
1850 __ j(equal, &check_zero, Label::kNear); // left == right.
1851 __ j(condition, &return_left, Label::kNear);
1852 __ jmp(&return_right, Label::kNear);
1853
1854 __ bind(&check_zero);
1855 XMMRegister xmm_scratch = double_scratch0();
1856 __ xorps(xmm_scratch, xmm_scratch);
1857 __ ucomisd(left_reg, xmm_scratch);
1858 __ j(not_equal, &return_left, Label::kNear); // left == right != 0.
1859 // At this point, both left and right are either 0 or -0.
1860 if (operation == HMathMinMax::kMathMin) {
1861 __ orps(left_reg, right_reg);
1862 } else {
1863 // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
1864 __ addsd(left_reg, right_reg);
1865 }
1866 __ jmp(&return_left, Label::kNear);
1867
1868 __ bind(&check_nan_left);
1869 __ ucomisd(left_reg, left_reg); // NaN check.
1870 __ j(parity_even, &return_left, Label::kNear);
1871 __ bind(&return_right);
1872 __ movaps(left_reg, right_reg);
1873
1874 __ bind(&return_left);
1875 }
1876 }
1877
1878
DoArithmeticD(LArithmeticD * instr)1879 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
1880 XMMRegister left = ToDoubleRegister(instr->left());
1881 XMMRegister right = ToDoubleRegister(instr->right());
1882 XMMRegister result = ToDoubleRegister(instr->result());
1883 // All operations except MOD are computed in-place.
1884 ASSERT(instr->op() == Token::MOD || left.is(result));
1885 switch (instr->op()) {
1886 case Token::ADD:
1887 __ addsd(left, right);
1888 break;
1889 case Token::SUB:
1890 __ subsd(left, right);
1891 break;
1892 case Token::MUL:
1893 __ mulsd(left, right);
1894 break;
1895 case Token::DIV:
1896 __ divsd(left, right);
1897 // Don't delete this mov. It may improve performance on some CPUs,
1898 // when there is a mulsd depending on the result
1899 __ movaps(left, left);
1900 break;
1901 case Token::MOD: {
1902 XMMRegister xmm_scratch = double_scratch0();
1903 __ PrepareCallCFunction(2);
1904 __ movaps(xmm_scratch, left);
1905 ASSERT(right.is(xmm1));
1906 __ CallCFunction(
1907 ExternalReference::double_fp_operation(Token::MOD, isolate()), 2);
1908 __ movaps(result, xmm_scratch);
1909 break;
1910 }
1911 default:
1912 UNREACHABLE();
1913 break;
1914 }
1915 }
1916
1917
DoArithmeticT(LArithmeticT * instr)1918 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
1919 ASSERT(ToRegister(instr->context()).is(rsi));
1920 ASSERT(ToRegister(instr->left()).is(rdx));
1921 ASSERT(ToRegister(instr->right()).is(rax));
1922 ASSERT(ToRegister(instr->result()).is(rax));
1923
1924 BinaryOpICStub stub(instr->op(), NO_OVERWRITE);
1925 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
1926 __ nop(); // Signals no inlined code.
1927 }
1928
1929
1930 template<class InstrType>
EmitBranch(InstrType instr,Condition cc)1931 void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
1932 int left_block = instr->TrueDestination(chunk_);
1933 int right_block = instr->FalseDestination(chunk_);
1934
1935 int next_block = GetNextEmittedBlock();
1936
1937 if (right_block == left_block || cc == no_condition) {
1938 EmitGoto(left_block);
1939 } else if (left_block == next_block) {
1940 __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
1941 } else if (right_block == next_block) {
1942 __ j(cc, chunk_->GetAssemblyLabel(left_block));
1943 } else {
1944 __ j(cc, chunk_->GetAssemblyLabel(left_block));
1945 if (cc != always) {
1946 __ jmp(chunk_->GetAssemblyLabel(right_block));
1947 }
1948 }
1949 }
1950
1951
1952 template<class InstrType>
EmitFalseBranch(InstrType instr,Condition cc)1953 void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
1954 int false_block = instr->FalseDestination(chunk_);
1955 __ j(cc, chunk_->GetAssemblyLabel(false_block));
1956 }
1957
1958
DoDebugBreak(LDebugBreak * instr)1959 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
1960 __ int3();
1961 }
1962
1963
DoBranch(LBranch * instr)1964 void LCodeGen::DoBranch(LBranch* instr) {
1965 Representation r = instr->hydrogen()->value()->representation();
1966 if (r.IsInteger32()) {
1967 ASSERT(!info()->IsStub());
1968 Register reg = ToRegister(instr->value());
1969 __ testl(reg, reg);
1970 EmitBranch(instr, not_zero);
1971 } else if (r.IsSmi()) {
1972 ASSERT(!info()->IsStub());
1973 Register reg = ToRegister(instr->value());
1974 __ testq(reg, reg);
1975 EmitBranch(instr, not_zero);
1976 } else if (r.IsDouble()) {
1977 ASSERT(!info()->IsStub());
1978 XMMRegister reg = ToDoubleRegister(instr->value());
1979 XMMRegister xmm_scratch = double_scratch0();
1980 __ xorps(xmm_scratch, xmm_scratch);
1981 __ ucomisd(reg, xmm_scratch);
1982 EmitBranch(instr, not_equal);
1983 } else {
1984 ASSERT(r.IsTagged());
1985 Register reg = ToRegister(instr->value());
1986 HType type = instr->hydrogen()->value()->type();
1987 if (type.IsBoolean()) {
1988 ASSERT(!info()->IsStub());
1989 __ CompareRoot(reg, Heap::kTrueValueRootIndex);
1990 EmitBranch(instr, equal);
1991 } else if (type.IsSmi()) {
1992 ASSERT(!info()->IsStub());
1993 __ SmiCompare(reg, Smi::FromInt(0));
1994 EmitBranch(instr, not_equal);
1995 } else if (type.IsJSArray()) {
1996 ASSERT(!info()->IsStub());
1997 EmitBranch(instr, no_condition);
1998 } else if (type.IsHeapNumber()) {
1999 ASSERT(!info()->IsStub());
2000 XMMRegister xmm_scratch = double_scratch0();
2001 __ xorps(xmm_scratch, xmm_scratch);
2002 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2003 EmitBranch(instr, not_equal);
2004 } else if (type.IsString()) {
2005 ASSERT(!info()->IsStub());
2006 __ cmpq(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2007 EmitBranch(instr, not_equal);
2008 } else {
2009 ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
2010 // Avoid deopts in the case where we've never executed this path before.
2011 if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
2012
2013 if (expected.Contains(ToBooleanStub::UNDEFINED)) {
2014 // undefined -> false.
2015 __ CompareRoot(reg, Heap::kUndefinedValueRootIndex);
2016 __ j(equal, instr->FalseLabel(chunk_));
2017 }
2018 if (expected.Contains(ToBooleanStub::BOOLEAN)) {
2019 // true -> true.
2020 __ CompareRoot(reg, Heap::kTrueValueRootIndex);
2021 __ j(equal, instr->TrueLabel(chunk_));
2022 // false -> false.
2023 __ CompareRoot(reg, Heap::kFalseValueRootIndex);
2024 __ j(equal, instr->FalseLabel(chunk_));
2025 }
2026 if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
2027 // 'null' -> false.
2028 __ CompareRoot(reg, Heap::kNullValueRootIndex);
2029 __ j(equal, instr->FalseLabel(chunk_));
2030 }
2031
2032 if (expected.Contains(ToBooleanStub::SMI)) {
2033 // Smis: 0 -> false, all other -> true.
2034 __ Cmp(reg, Smi::FromInt(0));
2035 __ j(equal, instr->FalseLabel(chunk_));
2036 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
2037 } else if (expected.NeedsMap()) {
2038 // If we need a map later and have a Smi -> deopt.
2039 __ testb(reg, Immediate(kSmiTagMask));
2040 DeoptimizeIf(zero, instr->environment());
2041 }
2042
2043 const Register map = kScratchRegister;
2044 if (expected.NeedsMap()) {
2045 __ movq(map, FieldOperand(reg, HeapObject::kMapOffset));
2046
2047 if (expected.CanBeUndetectable()) {
2048 // Undetectable -> false.
2049 __ testb(FieldOperand(map, Map::kBitFieldOffset),
2050 Immediate(1 << Map::kIsUndetectable));
2051 __ j(not_zero, instr->FalseLabel(chunk_));
2052 }
2053 }
2054
2055 if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
2056 // spec object -> true.
2057 __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
2058 __ j(above_equal, instr->TrueLabel(chunk_));
2059 }
2060
2061 if (expected.Contains(ToBooleanStub::STRING)) {
2062 // String value -> false iff empty.
2063 Label not_string;
2064 __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
2065 __ j(above_equal, ¬_string, Label::kNear);
2066 __ cmpq(FieldOperand(reg, String::kLengthOffset), Immediate(0));
2067 __ j(not_zero, instr->TrueLabel(chunk_));
2068 __ jmp(instr->FalseLabel(chunk_));
2069 __ bind(¬_string);
2070 }
2071
2072 if (expected.Contains(ToBooleanStub::SYMBOL)) {
2073 // Symbol value -> true.
2074 __ CmpInstanceType(map, SYMBOL_TYPE);
2075 __ j(equal, instr->TrueLabel(chunk_));
2076 }
2077
2078 if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
2079 // heap number -> false iff +0, -0, or NaN.
2080 Label not_heap_number;
2081 __ CompareRoot(map, Heap::kHeapNumberMapRootIndex);
2082 __ j(not_equal, ¬_heap_number, Label::kNear);
2083 XMMRegister xmm_scratch = double_scratch0();
2084 __ xorps(xmm_scratch, xmm_scratch);
2085 __ ucomisd(xmm_scratch, FieldOperand(reg, HeapNumber::kValueOffset));
2086 __ j(zero, instr->FalseLabel(chunk_));
2087 __ jmp(instr->TrueLabel(chunk_));
2088 __ bind(¬_heap_number);
2089 }
2090
2091 if (!expected.IsGeneric()) {
2092 // We've seen something for the first time -> deopt.
2093 // This can only happen if we are not generic already.
2094 DeoptimizeIf(no_condition, instr->environment());
2095 }
2096 }
2097 }
2098 }
2099
2100
EmitGoto(int block)2101 void LCodeGen::EmitGoto(int block) {
2102 if (!IsNextEmittedBlock(block)) {
2103 __ jmp(chunk_->GetAssemblyLabel(chunk_->LookupDestination(block)));
2104 }
2105 }
2106
2107
DoGoto(LGoto * instr)2108 void LCodeGen::DoGoto(LGoto* instr) {
2109 EmitGoto(instr->block_id());
2110 }
2111
2112
TokenToCondition(Token::Value op,bool is_unsigned)2113 inline Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2114 Condition cond = no_condition;
2115 switch (op) {
2116 case Token::EQ:
2117 case Token::EQ_STRICT:
2118 cond = equal;
2119 break;
2120 case Token::NE:
2121 case Token::NE_STRICT:
2122 cond = not_equal;
2123 break;
2124 case Token::LT:
2125 cond = is_unsigned ? below : less;
2126 break;
2127 case Token::GT:
2128 cond = is_unsigned ? above : greater;
2129 break;
2130 case Token::LTE:
2131 cond = is_unsigned ? below_equal : less_equal;
2132 break;
2133 case Token::GTE:
2134 cond = is_unsigned ? above_equal : greater_equal;
2135 break;
2136 case Token::IN:
2137 case Token::INSTANCEOF:
2138 default:
2139 UNREACHABLE();
2140 }
2141 return cond;
2142 }
2143
2144
DoCompareNumericAndBranch(LCompareNumericAndBranch * instr)2145 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2146 LOperand* left = instr->left();
2147 LOperand* right = instr->right();
2148 Condition cc = TokenToCondition(instr->op(), instr->is_double());
2149
2150 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2151 // We can statically evaluate the comparison.
2152 double left_val = ToDouble(LConstantOperand::cast(left));
2153 double right_val = ToDouble(LConstantOperand::cast(right));
2154 int next_block = EvalComparison(instr->op(), left_val, right_val) ?
2155 instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
2156 EmitGoto(next_block);
2157 } else {
2158 if (instr->is_double()) {
2159 // Don't base result on EFLAGS when a NaN is involved. Instead
2160 // jump to the false block.
2161 __ ucomisd(ToDoubleRegister(left), ToDoubleRegister(right));
2162 __ j(parity_even, instr->FalseLabel(chunk_));
2163 } else {
2164 int32_t value;
2165 if (right->IsConstantOperand()) {
2166 value = ToInteger32(LConstantOperand::cast(right));
2167 if (instr->hydrogen_value()->representation().IsSmi()) {
2168 __ Cmp(ToRegister(left), Smi::FromInt(value));
2169 } else {
2170 __ cmpl(ToRegister(left), Immediate(value));
2171 }
2172 } else if (left->IsConstantOperand()) {
2173 value = ToInteger32(LConstantOperand::cast(left));
2174 if (instr->hydrogen_value()->representation().IsSmi()) {
2175 if (right->IsRegister()) {
2176 __ Cmp(ToRegister(right), Smi::FromInt(value));
2177 } else {
2178 __ Cmp(ToOperand(right), Smi::FromInt(value));
2179 }
2180 } else if (right->IsRegister()) {
2181 __ cmpl(ToRegister(right), Immediate(value));
2182 } else {
2183 __ cmpl(ToOperand(right), Immediate(value));
2184 }
2185 // We transposed the operands. Reverse the condition.
2186 cc = ReverseCondition(cc);
2187 } else if (instr->hydrogen_value()->representation().IsSmi()) {
2188 if (right->IsRegister()) {
2189 __ cmpq(ToRegister(left), ToRegister(right));
2190 } else {
2191 __ cmpq(ToRegister(left), ToOperand(right));
2192 }
2193 } else {
2194 if (right->IsRegister()) {
2195 __ cmpl(ToRegister(left), ToRegister(right));
2196 } else {
2197 __ cmpl(ToRegister(left), ToOperand(right));
2198 }
2199 }
2200 }
2201 EmitBranch(instr, cc);
2202 }
2203 }
2204
2205
DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch * instr)2206 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2207 Register left = ToRegister(instr->left());
2208
2209 if (instr->right()->IsConstantOperand()) {
2210 Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
2211 __ Cmp(left, right);
2212 } else {
2213 Register right = ToRegister(instr->right());
2214 __ cmpq(left, right);
2215 }
2216 EmitBranch(instr, equal);
2217 }
2218
2219
DoCmpHoleAndBranch(LCmpHoleAndBranch * instr)2220 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2221 if (instr->hydrogen()->representation().IsTagged()) {
2222 Register input_reg = ToRegister(instr->object());
2223 __ Cmp(input_reg, factory()->the_hole_value());
2224 EmitBranch(instr, equal);
2225 return;
2226 }
2227
2228 XMMRegister input_reg = ToDoubleRegister(instr->object());
2229 __ ucomisd(input_reg, input_reg);
2230 EmitFalseBranch(instr, parity_odd);
2231
2232 __ subq(rsp, Immediate(kDoubleSize));
2233 __ movsd(MemOperand(rsp, 0), input_reg);
2234 __ addq(rsp, Immediate(kDoubleSize));
2235
2236 int offset = sizeof(kHoleNanUpper32);
2237 __ cmpl(MemOperand(rsp, -offset), Immediate(kHoleNanUpper32));
2238 EmitBranch(instr, equal);
2239 }
2240
2241
DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch * instr)2242 void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
2243 Representation rep = instr->hydrogen()->value()->representation();
2244 ASSERT(!rep.IsInteger32());
2245
2246 if (rep.IsDouble()) {
2247 XMMRegister value = ToDoubleRegister(instr->value());
2248 XMMRegister xmm_scratch = double_scratch0();
2249 __ xorps(xmm_scratch, xmm_scratch);
2250 __ ucomisd(xmm_scratch, value);
2251 EmitFalseBranch(instr, not_equal);
2252 __ movmskpd(kScratchRegister, value);
2253 __ testl(kScratchRegister, Immediate(1));
2254 EmitBranch(instr, not_zero);
2255 } else {
2256 Register value = ToRegister(instr->value());
2257 Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
2258 __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
2259 __ cmpl(FieldOperand(value, HeapNumber::kExponentOffset),
2260 Immediate(0x80000000));
2261 EmitFalseBranch(instr, not_equal);
2262 __ cmpl(FieldOperand(value, HeapNumber::kMantissaOffset),
2263 Immediate(0x00000000));
2264 EmitBranch(instr, equal);
2265 }
2266 }
2267
2268
EmitIsObject(Register input,Label * is_not_object,Label * is_object)2269 Condition LCodeGen::EmitIsObject(Register input,
2270 Label* is_not_object,
2271 Label* is_object) {
2272 ASSERT(!input.is(kScratchRegister));
2273
2274 __ JumpIfSmi(input, is_not_object);
2275
2276 __ CompareRoot(input, Heap::kNullValueRootIndex);
2277 __ j(equal, is_object);
2278
2279 __ movq(kScratchRegister, FieldOperand(input, HeapObject::kMapOffset));
2280 // Undetectable objects behave like undefined.
2281 __ testb(FieldOperand(kScratchRegister, Map::kBitFieldOffset),
2282 Immediate(1 << Map::kIsUndetectable));
2283 __ j(not_zero, is_not_object);
2284
2285 __ movzxbl(kScratchRegister,
2286 FieldOperand(kScratchRegister, Map::kInstanceTypeOffset));
2287 __ cmpb(kScratchRegister, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2288 __ j(below, is_not_object);
2289 __ cmpb(kScratchRegister, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE));
2290 return below_equal;
2291 }
2292
2293
DoIsObjectAndBranch(LIsObjectAndBranch * instr)2294 void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2295 Register reg = ToRegister(instr->value());
2296
2297 Condition true_cond = EmitIsObject(
2298 reg, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));
2299
2300 EmitBranch(instr, true_cond);
2301 }
2302
2303
EmitIsString(Register input,Register temp1,Label * is_not_string,SmiCheck check_needed=INLINE_SMI_CHECK)2304 Condition LCodeGen::EmitIsString(Register input,
2305 Register temp1,
2306 Label* is_not_string,
2307 SmiCheck check_needed = INLINE_SMI_CHECK) {
2308 if (check_needed == INLINE_SMI_CHECK) {
2309 __ JumpIfSmi(input, is_not_string);
2310 }
2311
2312 Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
2313
2314 return cond;
2315 }
2316
2317
DoIsStringAndBranch(LIsStringAndBranch * instr)2318 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2319 Register reg = ToRegister(instr->value());
2320 Register temp = ToRegister(instr->temp());
2321
2322 SmiCheck check_needed =
2323 instr->hydrogen()->value()->IsHeapObject()
2324 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2325
2326 Condition true_cond = EmitIsString(
2327 reg, temp, instr->FalseLabel(chunk_), check_needed);
2328
2329 EmitBranch(instr, true_cond);
2330 }
2331
2332
DoIsSmiAndBranch(LIsSmiAndBranch * instr)2333 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2334 Condition is_smi;
2335 if (instr->value()->IsRegister()) {
2336 Register input = ToRegister(instr->value());
2337 is_smi = masm()->CheckSmi(input);
2338 } else {
2339 Operand input = ToOperand(instr->value());
2340 is_smi = masm()->CheckSmi(input);
2341 }
2342 EmitBranch(instr, is_smi);
2343 }
2344
2345
DoIsUndetectableAndBranch(LIsUndetectableAndBranch * instr)2346 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2347 Register input = ToRegister(instr->value());
2348 Register temp = ToRegister(instr->temp());
2349
2350 if (!instr->hydrogen()->value()->IsHeapObject()) {
2351 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2352 }
2353 __ movq(temp, FieldOperand(input, HeapObject::kMapOffset));
2354 __ testb(FieldOperand(temp, Map::kBitFieldOffset),
2355 Immediate(1 << Map::kIsUndetectable));
2356 EmitBranch(instr, not_zero);
2357 }
2358
2359
DoStringCompareAndBranch(LStringCompareAndBranch * instr)2360 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2361 ASSERT(ToRegister(instr->context()).is(rsi));
2362 Token::Value op = instr->op();
2363
2364 Handle<Code> ic = CompareIC::GetUninitialized(isolate(), op);
2365 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2366
2367 Condition condition = TokenToCondition(op, false);
2368 __ testq(rax, rax);
2369
2370 EmitBranch(instr, condition);
2371 }
2372
2373
TestType(HHasInstanceTypeAndBranch * instr)2374 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2375 InstanceType from = instr->from();
2376 InstanceType to = instr->to();
2377 if (from == FIRST_TYPE) return to;
2378 ASSERT(from == to || to == LAST_TYPE);
2379 return from;
2380 }
2381
2382
BranchCondition(HHasInstanceTypeAndBranch * instr)2383 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2384 InstanceType from = instr->from();
2385 InstanceType to = instr->to();
2386 if (from == to) return equal;
2387 if (to == LAST_TYPE) return above_equal;
2388 if (from == FIRST_TYPE) return below_equal;
2389 UNREACHABLE();
2390 return equal;
2391 }
2392
2393
DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch * instr)2394 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2395 Register input = ToRegister(instr->value());
2396
2397 if (!instr->hydrogen()->value()->IsHeapObject()) {
2398 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2399 }
2400
2401 __ CmpObjectType(input, TestType(instr->hydrogen()), kScratchRegister);
2402 EmitBranch(instr, BranchCondition(instr->hydrogen()));
2403 }
2404
2405
DoGetCachedArrayIndex(LGetCachedArrayIndex * instr)2406 void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2407 Register input = ToRegister(instr->value());
2408 Register result = ToRegister(instr->result());
2409
2410 __ AssertString(input);
2411
2412 __ movl(result, FieldOperand(input, String::kHashFieldOffset));
2413 ASSERT(String::kHashShift >= kSmiTagSize);
2414 __ IndexFromHash(result, result);
2415 }
2416
2417
DoHasCachedArrayIndexAndBranch(LHasCachedArrayIndexAndBranch * instr)2418 void LCodeGen::DoHasCachedArrayIndexAndBranch(
2419 LHasCachedArrayIndexAndBranch* instr) {
2420 Register input = ToRegister(instr->value());
2421
2422 __ testl(FieldOperand(input, String::kHashFieldOffset),
2423 Immediate(String::kContainsCachedArrayIndexMask));
2424 EmitBranch(instr, equal);
2425 }
2426
2427
2428 // Branches to a label or falls through with the answer in the z flag.
2429 // Trashes the temp register.
EmitClassOfTest(Label * is_true,Label * is_false,Handle<String> class_name,Register input,Register temp,Register temp2)2430 void LCodeGen::EmitClassOfTest(Label* is_true,
2431 Label* is_false,
2432 Handle<String> class_name,
2433 Register input,
2434 Register temp,
2435 Register temp2) {
2436 ASSERT(!input.is(temp));
2437 ASSERT(!input.is(temp2));
2438 ASSERT(!temp.is(temp2));
2439
2440 __ JumpIfSmi(input, is_false);
2441
2442 if (class_name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("Function"))) {
2443 // Assuming the following assertions, we can use the same compares to test
2444 // for both being a function type and being in the object type range.
2445 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
2446 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2447 FIRST_SPEC_OBJECT_TYPE + 1);
2448 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
2449 LAST_SPEC_OBJECT_TYPE - 1);
2450 STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
2451 __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
2452 __ j(below, is_false);
2453 __ j(equal, is_true);
2454 __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
2455 __ j(equal, is_true);
2456 } else {
2457 // Faster code path to avoid two compares: subtract lower bound from the
2458 // actual type and do a signed compare with the width of the type range.
2459 __ movq(temp, FieldOperand(input, HeapObject::kMapOffset));
2460 __ movzxbl(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
2461 __ subq(temp2, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2462 __ cmpq(temp2, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
2463 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2464 __ j(above, is_false);
2465 }
2466
2467 // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2468 // Check if the constructor in the map is a function.
2469 __ movq(temp, FieldOperand(temp, Map::kConstructorOffset));
2470
2471 // Objects with a non-function constructor have class 'Object'.
2472 __ CmpObjectType(temp, JS_FUNCTION_TYPE, kScratchRegister);
2473 if (class_name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("Object"))) {
2474 __ j(not_equal, is_true);
2475 } else {
2476 __ j(not_equal, is_false);
2477 }
2478
2479 // temp now contains the constructor function. Grab the
2480 // instance class name from there.
2481 __ movq(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2482 __ movq(temp, FieldOperand(temp,
2483 SharedFunctionInfo::kInstanceClassNameOffset));
2484 // The class name we are testing against is internalized since it's a literal.
2485 // The name in the constructor is internalized because of the way the context
2486 // is booted. This routine isn't expected to work for random API-created
2487 // classes and it doesn't have to because you can't access it with natives
2488 // syntax. Since both sides are internalized it is sufficient to use an
2489 // identity comparison.
2490 ASSERT(class_name->IsInternalizedString());
2491 __ Cmp(temp, class_name);
2492 // End with the answer in the z flag.
2493 }
2494
2495
DoClassOfTestAndBranch(LClassOfTestAndBranch * instr)2496 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2497 Register input = ToRegister(instr->value());
2498 Register temp = ToRegister(instr->temp());
2499 Register temp2 = ToRegister(instr->temp2());
2500 Handle<String> class_name = instr->hydrogen()->class_name();
2501
2502 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2503 class_name, input, temp, temp2);
2504
2505 EmitBranch(instr, equal);
2506 }
2507
2508
DoCmpMapAndBranch(LCmpMapAndBranch * instr)2509 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2510 Register reg = ToRegister(instr->value());
2511
2512 __ Cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
2513 EmitBranch(instr, equal);
2514 }
2515
2516
DoInstanceOf(LInstanceOf * instr)2517 void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2518 ASSERT(ToRegister(instr->context()).is(rsi));
2519 InstanceofStub stub(InstanceofStub::kNoFlags);
2520 __ push(ToRegister(instr->left()));
2521 __ push(ToRegister(instr->right()));
2522 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
2523 Label true_value, done;
2524 __ testq(rax, rax);
2525 __ j(zero, &true_value, Label::kNear);
2526 __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex);
2527 __ jmp(&done, Label::kNear);
2528 __ bind(&true_value);
2529 __ LoadRoot(ToRegister(instr->result()), Heap::kTrueValueRootIndex);
2530 __ bind(&done);
2531 }
2532
2533
DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal * instr)2534 void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2535 class DeferredInstanceOfKnownGlobal V8_FINAL : public LDeferredCode {
2536 public:
2537 DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
2538 LInstanceOfKnownGlobal* instr)
2539 : LDeferredCode(codegen), instr_(instr) { }
2540 virtual void Generate() V8_OVERRIDE {
2541 codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2542 }
2543 virtual LInstruction* instr() V8_OVERRIDE { return instr_; }
2544 Label* map_check() { return &map_check_; }
2545 private:
2546 LInstanceOfKnownGlobal* instr_;
2547 Label map_check_;
2548 };
2549
2550 ASSERT(ToRegister(instr->context()).is(rsi));
2551 DeferredInstanceOfKnownGlobal* deferred;
2552 deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr);
2553
2554 Label done, false_result;
2555 Register object = ToRegister(instr->value());
2556
2557 // A Smi is not an instance of anything.
2558 __ JumpIfSmi(object, &false_result, Label::kNear);
2559
2560 // This is the inlined call site instanceof cache. The two occurences of the
2561 // hole value will be patched to the last map/result pair generated by the
2562 // instanceof stub.
2563 Label cache_miss;
2564 // Use a temp register to avoid memory operands with variable lengths.
2565 Register map = ToRegister(instr->temp());
2566 __ movq(map, FieldOperand(object, HeapObject::kMapOffset));
2567 __ bind(deferred->map_check()); // Label for calculating code patching.
2568 Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
2569 __ movq(kScratchRegister, cache_cell, RelocInfo::CELL);
2570 __ cmpq(map, Operand(kScratchRegister, 0));
2571 __ j(not_equal, &cache_miss, Label::kNear);
2572 // Patched to load either true or false.
2573 __ LoadRoot(ToRegister(instr->result()), Heap::kTheHoleValueRootIndex);
2574 #ifdef DEBUG
2575 // Check that the code size between patch label and patch sites is invariant.
2576 Label end_of_patched_code;
2577 __ bind(&end_of_patched_code);
2578 ASSERT(true);
2579 #endif
2580 __ jmp(&done, Label::kNear);
2581
2582 // The inlined call site cache did not match. Check for null and string
2583 // before calling the deferred code.
2584 __ bind(&cache_miss); // Null is not an instance of anything.
2585 __ CompareRoot(object, Heap::kNullValueRootIndex);
2586 __ j(equal, &false_result, Label::kNear);
2587
2588 // String values are not instances of anything.
2589 __ JumpIfNotString(object, kScratchRegister, deferred->entry());
2590
2591 __ bind(&false_result);
2592 __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex);
2593
2594 __ bind(deferred->exit());
2595 __ bind(&done);
2596 }
2597
2598
DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal * instr,Label * map_check)2599 void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
2600 Label* map_check) {
2601 {
2602 PushSafepointRegistersScope scope(this);
2603 InstanceofStub::Flags flags = static_cast<InstanceofStub::Flags>(
2604 InstanceofStub::kNoFlags | InstanceofStub::kCallSiteInlineCheck);
2605 InstanceofStub stub(flags);
2606
2607 __ push(ToRegister(instr->value()));
2608 __ Push(instr->function());
2609
2610 static const int kAdditionalDelta = 10;
2611 int delta =
2612 masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
2613 ASSERT(delta >= 0);
2614 __ push_imm32(delta);
2615
2616 // We are pushing three values on the stack but recording a
2617 // safepoint with two arguments because stub is going to
2618 // remove the third argument from the stack before jumping
2619 // to instanceof builtin on the slow path.
2620 CallCodeGeneric(stub.GetCode(isolate()),
2621 RelocInfo::CODE_TARGET,
2622 instr,
2623 RECORD_SAFEPOINT_WITH_REGISTERS,
2624 2);
2625 ASSERT(delta == masm_->SizeOfCodeGeneratedSince(map_check));
2626 LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
2627 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
2628 // Move result to a register that survives the end of the
2629 // PushSafepointRegisterScope.
2630 __ movq(kScratchRegister, rax);
2631 }
2632 __ testq(kScratchRegister, kScratchRegister);
2633 Label load_false;
2634 Label done;
2635 __ j(not_zero, &load_false, Label::kNear);
2636 __ LoadRoot(rax, Heap::kTrueValueRootIndex);
2637 __ jmp(&done, Label::kNear);
2638 __ bind(&load_false);
2639 __ LoadRoot(rax, Heap::kFalseValueRootIndex);
2640 __ bind(&done);
2641 }
2642
2643
DoCmpT(LCmpT * instr)2644 void LCodeGen::DoCmpT(LCmpT* instr) {
2645 ASSERT(ToRegister(instr->context()).is(rsi));
2646 Token::Value op = instr->op();
2647
2648 Handle<Code> ic = CompareIC::GetUninitialized(isolate(), op);
2649 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2650
2651 Condition condition = TokenToCondition(op, false);
2652 Label true_value, done;
2653 __ testq(rax, rax);
2654 __ j(condition, &true_value, Label::kNear);
2655 __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex);
2656 __ jmp(&done, Label::kNear);
2657 __ bind(&true_value);
2658 __ LoadRoot(ToRegister(instr->result()), Heap::kTrueValueRootIndex);
2659 __ bind(&done);
2660 }
2661
2662
DoReturn(LReturn * instr)2663 void LCodeGen::DoReturn(LReturn* instr) {
2664 if (FLAG_trace && info()->IsOptimizing()) {
2665 // Preserve the return value on the stack and rely on the runtime call
2666 // to return the value in the same register. We're leaving the code
2667 // managed by the register allocator and tearing down the frame, it's
2668 // safe to write to the context register.
2669 __ push(rax);
2670 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
2671 __ CallRuntime(Runtime::kTraceExit, 1);
2672 }
2673 if (info()->saves_caller_doubles()) {
2674 RestoreCallerDoubles();
2675 }
2676 int no_frame_start = -1;
2677 if (NeedsEagerFrame()) {
2678 __ movq(rsp, rbp);
2679 __ pop(rbp);
2680 no_frame_start = masm_->pc_offset();
2681 }
2682 if (instr->has_constant_parameter_count()) {
2683 __ Ret((ToInteger32(instr->constant_parameter_count()) + 1) * kPointerSize,
2684 rcx);
2685 } else {
2686 Register reg = ToRegister(instr->parameter_count());
2687 // The argument count parameter is a smi
2688 __ SmiToInteger32(reg, reg);
2689 Register return_addr_reg = reg.is(rcx) ? rbx : rcx;
2690 __ PopReturnAddressTo(return_addr_reg);
2691 __ shl(reg, Immediate(kPointerSizeLog2));
2692 __ addq(rsp, reg);
2693 __ jmp(return_addr_reg);
2694 }
2695 if (no_frame_start != -1) {
2696 info_->AddNoFrameRange(no_frame_start, masm_->pc_offset());
2697 }
2698 }
2699
2700
DoLoadGlobalCell(LLoadGlobalCell * instr)2701 void LCodeGen::DoLoadGlobalCell(LLoadGlobalCell* instr) {
2702 Register result = ToRegister(instr->result());
2703 __ LoadGlobalCell(result, instr->hydrogen()->cell().handle());
2704 if (instr->hydrogen()->RequiresHoleCheck()) {
2705 __ CompareRoot(result, Heap::kTheHoleValueRootIndex);
2706 DeoptimizeIf(equal, instr->environment());
2707 }
2708 }
2709
2710
DoLoadGlobalGeneric(LLoadGlobalGeneric * instr)2711 void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
2712 ASSERT(ToRegister(instr->context()).is(rsi));
2713 ASSERT(ToRegister(instr->global_object()).is(rax));
2714 ASSERT(ToRegister(instr->result()).is(rax));
2715
2716 __ Move(rcx, instr->name());
2717 RelocInfo::Mode mode = instr->for_typeof() ? RelocInfo::CODE_TARGET :
2718 RelocInfo::CODE_TARGET_CONTEXT;
2719 Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize();
2720 CallCode(ic, mode, instr);
2721 }
2722
2723
DoStoreGlobalCell(LStoreGlobalCell * instr)2724 void LCodeGen::DoStoreGlobalCell(LStoreGlobalCell* instr) {
2725 Register value = ToRegister(instr->value());
2726 Handle<Cell> cell_handle = instr->hydrogen()->cell().handle();
2727
2728 // If the cell we are storing to contains the hole it could have
2729 // been deleted from the property dictionary. In that case, we need
2730 // to update the property details in the property dictionary to mark
2731 // it as no longer deleted. We deoptimize in that case.
2732 if (instr->hydrogen()->RequiresHoleCheck()) {
2733 // We have a temp because CompareRoot might clobber kScratchRegister.
2734 Register cell = ToRegister(instr->temp());
2735 ASSERT(!value.is(cell));
2736 __ movq(cell, cell_handle, RelocInfo::CELL);
2737 __ CompareRoot(Operand(cell, 0), Heap::kTheHoleValueRootIndex);
2738 DeoptimizeIf(equal, instr->environment());
2739 // Store the value.
2740 __ movq(Operand(cell, 0), value);
2741 } else {
2742 // Store the value.
2743 __ movq(kScratchRegister, cell_handle, RelocInfo::CELL);
2744 __ movq(Operand(kScratchRegister, 0), value);
2745 }
2746 // Cells are always rescanned, so no write barrier here.
2747 }
2748
2749
DoStoreGlobalGeneric(LStoreGlobalGeneric * instr)2750 void LCodeGen::DoStoreGlobalGeneric(LStoreGlobalGeneric* instr) {
2751 ASSERT(ToRegister(instr->context()).is(rsi));
2752 ASSERT(ToRegister(instr->global_object()).is(rdx));
2753 ASSERT(ToRegister(instr->value()).is(rax));
2754
2755 __ Move(rcx, instr->name());
2756 Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode)
2757 ? isolate()->builtins()->StoreIC_Initialize_Strict()
2758 : isolate()->builtins()->StoreIC_Initialize();
2759 CallCode(ic, RelocInfo::CODE_TARGET_CONTEXT, instr);
2760 }
2761
2762
DoLoadContextSlot(LLoadContextSlot * instr)2763 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
2764 Register context = ToRegister(instr->context());
2765 Register result = ToRegister(instr->result());
2766 __ movq(result, ContextOperand(context, instr->slot_index()));
2767 if (instr->hydrogen()->RequiresHoleCheck()) {
2768 __ CompareRoot(result, Heap::kTheHoleValueRootIndex);
2769 if (instr->hydrogen()->DeoptimizesOnHole()) {
2770 DeoptimizeIf(equal, instr->environment());
2771 } else {
2772 Label is_not_hole;
2773 __ j(not_equal, &is_not_hole, Label::kNear);
2774 __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
2775 __ bind(&is_not_hole);
2776 }
2777 }
2778 }
2779
2780
DoStoreContextSlot(LStoreContextSlot * instr)2781 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
2782 Register context = ToRegister(instr->context());
2783 Register value = ToRegister(instr->value());
2784
2785 Operand target = ContextOperand(context, instr->slot_index());
2786
2787 Label skip_assignment;
2788 if (instr->hydrogen()->RequiresHoleCheck()) {
2789 __ CompareRoot(target, Heap::kTheHoleValueRootIndex);
2790 if (instr->hydrogen()->DeoptimizesOnHole()) {
2791 DeoptimizeIf(equal, instr->environment());
2792 } else {
2793 __ j(not_equal, &skip_assignment);
2794 }
2795 }
2796 __ movq(target, value);
2797
2798 if (instr->hydrogen()->NeedsWriteBarrier()) {
2799 SmiCheck check_needed =
2800 instr->hydrogen()->value()->IsHeapObject()
2801 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2802 int offset = Context::SlotOffset(instr->slot_index());
2803 Register scratch = ToRegister(instr->temp());
2804 __ RecordWriteContextSlot(context,
2805 offset,
2806 value,
2807 scratch,
2808 kSaveFPRegs,
2809 EMIT_REMEMBERED_SET,
2810 check_needed);
2811 }
2812
2813 __ bind(&skip_assignment);
2814 }
2815
2816
DoLoadNamedField(LLoadNamedField * instr)2817 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
2818 HObjectAccess access = instr->hydrogen()->access();
2819 int offset = access.offset();
2820
2821 if (access.IsExternalMemory()) {
2822 Register result = ToRegister(instr->result());
2823 if (instr->object()->IsConstantOperand()) {
2824 ASSERT(result.is(rax));
2825 __ load_rax(ToExternalReference(LConstantOperand::cast(instr->object())));
2826 } else {
2827 Register object = ToRegister(instr->object());
2828 __ Load(result, MemOperand(object, offset), access.representation());
2829 }
2830 return;
2831 }
2832
2833 Register object = ToRegister(instr->object());
2834 if (FLAG_track_double_fields &&
2835 instr->hydrogen()->representation().IsDouble()) {
2836 XMMRegister result = ToDoubleRegister(instr->result());
2837 __ movsd(result, FieldOperand(object, offset));
2838 return;
2839 }
2840
2841 Register result = ToRegister(instr->result());
2842 if (!access.IsInobject()) {
2843 __ movq(result, FieldOperand(object, JSObject::kPropertiesOffset));
2844 object = result;
2845 }
2846 __ Load(result, FieldOperand(object, offset), access.representation());
2847 }
2848
2849
DoLoadNamedGeneric(LLoadNamedGeneric * instr)2850 void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
2851 ASSERT(ToRegister(instr->context()).is(rsi));
2852 ASSERT(ToRegister(instr->object()).is(rax));
2853 ASSERT(ToRegister(instr->result()).is(rax));
2854
2855 __ Move(rcx, instr->name());
2856 Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize();
2857 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2858 }
2859
2860
DoLoadFunctionPrototype(LLoadFunctionPrototype * instr)2861 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
2862 Register function = ToRegister(instr->function());
2863 Register result = ToRegister(instr->result());
2864
2865 // Check that the function really is a function.
2866 __ CmpObjectType(function, JS_FUNCTION_TYPE, result);
2867 DeoptimizeIf(not_equal, instr->environment());
2868
2869 // Check whether the function has an instance prototype.
2870 Label non_instance;
2871 __ testb(FieldOperand(result, Map::kBitFieldOffset),
2872 Immediate(1 << Map::kHasNonInstancePrototype));
2873 __ j(not_zero, &non_instance, Label::kNear);
2874
2875 // Get the prototype or initial map from the function.
2876 __ movq(result,
2877 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
2878
2879 // Check that the function has a prototype or an initial map.
2880 __ CompareRoot(result, Heap::kTheHoleValueRootIndex);
2881 DeoptimizeIf(equal, instr->environment());
2882
2883 // If the function does not have an initial map, we're done.
2884 Label done;
2885 __ CmpObjectType(result, MAP_TYPE, kScratchRegister);
2886 __ j(not_equal, &done, Label::kNear);
2887
2888 // Get the prototype from the initial map.
2889 __ movq(result, FieldOperand(result, Map::kPrototypeOffset));
2890 __ jmp(&done, Label::kNear);
2891
2892 // Non-instance prototype: Fetch prototype from constructor field
2893 // in the function's map.
2894 __ bind(&non_instance);
2895 __ movq(result, FieldOperand(result, Map::kConstructorOffset));
2896
2897 // All done.
2898 __ bind(&done);
2899 }
2900
2901
DoLoadRoot(LLoadRoot * instr)2902 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
2903 Register result = ToRegister(instr->result());
2904 __ LoadRoot(result, instr->index());
2905 }
2906
2907
DoLoadExternalArrayPointer(LLoadExternalArrayPointer * instr)2908 void LCodeGen::DoLoadExternalArrayPointer(
2909 LLoadExternalArrayPointer* instr) {
2910 Register result = ToRegister(instr->result());
2911 Register input = ToRegister(instr->object());
2912 __ movq(result, FieldOperand(input,
2913 ExternalPixelArray::kExternalPointerOffset));
2914 }
2915
2916
DoAccessArgumentsAt(LAccessArgumentsAt * instr)2917 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
2918 Register arguments = ToRegister(instr->arguments());
2919 Register result = ToRegister(instr->result());
2920
2921 if (instr->length()->IsConstantOperand() &&
2922 instr->index()->IsConstantOperand()) {
2923 int32_t const_index = ToInteger32(LConstantOperand::cast(instr->index()));
2924 int32_t const_length = ToInteger32(LConstantOperand::cast(instr->length()));
2925 StackArgumentsAccessor args(arguments, const_length,
2926 ARGUMENTS_DONT_CONTAIN_RECEIVER);
2927 __ movq(result, args.GetArgumentOperand(const_index));
2928 } else {
2929 Register length = ToRegister(instr->length());
2930 // There are two words between the frame pointer and the last argument.
2931 // Subtracting from length accounts for one of them add one more.
2932 if (instr->index()->IsRegister()) {
2933 __ subl(length, ToRegister(instr->index()));
2934 } else {
2935 __ subl(length, ToOperand(instr->index()));
2936 }
2937 StackArgumentsAccessor args(arguments, length,
2938 ARGUMENTS_DONT_CONTAIN_RECEIVER);
2939 __ movq(result, args.GetArgumentOperand(0));
2940 }
2941 }
2942
2943
DoLoadKeyedExternalArray(LLoadKeyed * instr)2944 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
2945 ElementsKind elements_kind = instr->elements_kind();
2946 LOperand* key = instr->key();
2947 if (!key->IsConstantOperand()) {
2948 Register key_reg = ToRegister(key);
2949 // Even though the HLoad/StoreKeyed (in this case) instructions force
2950 // the input representation for the key to be an integer, the input
2951 // gets replaced during bound check elimination with the index argument
2952 // to the bounds check, which can be tagged, so that case must be
2953 // handled here, too.
2954 if (instr->hydrogen()->IsDehoisted()) {
2955 // Sign extend key because it could be a 32 bit negative value
2956 // and the dehoisted address computation happens in 64 bits
2957 __ movsxlq(key_reg, key_reg);
2958 }
2959 }
2960 Operand operand(BuildFastArrayOperand(
2961 instr->elements(),
2962 key,
2963 elements_kind,
2964 0,
2965 instr->additional_index()));
2966
2967 if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) {
2968 XMMRegister result(ToDoubleRegister(instr->result()));
2969 __ movss(result, operand);
2970 __ cvtss2sd(result, result);
2971 } else if (elements_kind == EXTERNAL_DOUBLE_ELEMENTS) {
2972 __ movsd(ToDoubleRegister(instr->result()), operand);
2973 } else {
2974 Register result(ToRegister(instr->result()));
2975 switch (elements_kind) {
2976 case EXTERNAL_BYTE_ELEMENTS:
2977 __ movsxbq(result, operand);
2978 break;
2979 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2980 case EXTERNAL_PIXEL_ELEMENTS:
2981 __ movzxbq(result, operand);
2982 break;
2983 case EXTERNAL_SHORT_ELEMENTS:
2984 __ movsxwq(result, operand);
2985 break;
2986 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2987 __ movzxwq(result, operand);
2988 break;
2989 case EXTERNAL_INT_ELEMENTS:
2990 __ movsxlq(result, operand);
2991 break;
2992 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2993 __ movl(result, operand);
2994 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
2995 __ testl(result, result);
2996 DeoptimizeIf(negative, instr->environment());
2997 }
2998 break;
2999 case EXTERNAL_FLOAT_ELEMENTS:
3000 case EXTERNAL_DOUBLE_ELEMENTS:
3001 case FAST_ELEMENTS:
3002 case FAST_SMI_ELEMENTS:
3003 case FAST_DOUBLE_ELEMENTS:
3004 case FAST_HOLEY_ELEMENTS:
3005 case FAST_HOLEY_SMI_ELEMENTS:
3006 case FAST_HOLEY_DOUBLE_ELEMENTS:
3007 case DICTIONARY_ELEMENTS:
3008 case NON_STRICT_ARGUMENTS_ELEMENTS:
3009 UNREACHABLE();
3010 break;
3011 }
3012 }
3013 }
3014
3015
DoLoadKeyedFixedDoubleArray(LLoadKeyed * instr)3016 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
3017 XMMRegister result(ToDoubleRegister(instr->result()));
3018 LOperand* key = instr->key();
3019 if (!key->IsConstantOperand()) {
3020 Register key_reg = ToRegister(key);
3021 // Even though the HLoad/StoreKeyed instructions force the input
3022 // representation for the key to be an integer, the input gets replaced
3023 // during bound check elimination with the index argument to the bounds
3024 // check, which can be tagged, so that case must be handled here, too.
3025 if (instr->hydrogen()->IsDehoisted()) {
3026 // Sign extend key because it could be a 32 bit negative value
3027 // and the dehoisted address computation happens in 64 bits
3028 __ movsxlq(key_reg, key_reg);
3029 }
3030 }
3031
3032 if (instr->hydrogen()->RequiresHoleCheck()) {
3033 int offset = FixedDoubleArray::kHeaderSize - kHeapObjectTag +
3034 sizeof(kHoleNanLower32);
3035 Operand hole_check_operand = BuildFastArrayOperand(
3036 instr->elements(),
3037 key,
3038 FAST_DOUBLE_ELEMENTS,
3039 offset,
3040 instr->additional_index());
3041 __ cmpl(hole_check_operand, Immediate(kHoleNanUpper32));
3042 DeoptimizeIf(equal, instr->environment());
3043 }
3044
3045 Operand double_load_operand = BuildFastArrayOperand(
3046 instr->elements(),
3047 key,
3048 FAST_DOUBLE_ELEMENTS,
3049 FixedDoubleArray::kHeaderSize - kHeapObjectTag,
3050 instr->additional_index());
3051 __ movsd(result, double_load_operand);
3052 }
3053
3054
DoLoadKeyedFixedArray(LLoadKeyed * instr)3055 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
3056 Register result = ToRegister(instr->result());
3057 LOperand* key = instr->key();
3058 if (!key->IsConstantOperand()) {
3059 Register key_reg = ToRegister(key);
3060 // Even though the HLoad/StoreKeyedFastElement instructions force
3061 // the input representation for the key to be an integer, the input
3062 // gets replaced during bound check elimination with the index
3063 // argument to the bounds check, which can be tagged, so that
3064 // case must be handled here, too.
3065 if (instr->hydrogen()->IsDehoisted()) {
3066 // Sign extend key because it could be a 32 bit negative value
3067 // and the dehoisted address computation happens in 64 bits
3068 __ movsxlq(key_reg, key_reg);
3069 }
3070 }
3071
3072 // Load the result.
3073 __ movq(result,
3074 BuildFastArrayOperand(instr->elements(),
3075 key,
3076 FAST_ELEMENTS,
3077 FixedArray::kHeaderSize - kHeapObjectTag,
3078 instr->additional_index()));
3079
3080 // Check for the hole value.
3081 if (instr->hydrogen()->RequiresHoleCheck()) {
3082 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
3083 Condition smi = __ CheckSmi(result);
3084 DeoptimizeIf(NegateCondition(smi), instr->environment());
3085 } else {
3086 __ CompareRoot(result, Heap::kTheHoleValueRootIndex);
3087 DeoptimizeIf(equal, instr->environment());
3088 }
3089 }
3090 }
3091
3092
DoLoadKeyed(LLoadKeyed * instr)3093 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
3094 if (instr->is_external()) {
3095 DoLoadKeyedExternalArray(instr);
3096 } else if (instr->hydrogen()->representation().IsDouble()) {
3097 DoLoadKeyedFixedDoubleArray(instr);
3098 } else {
3099 DoLoadKeyedFixedArray(instr);
3100 }
3101 }
3102
3103
BuildFastArrayOperand(LOperand * elements_pointer,LOperand * key,ElementsKind elements_kind,uint32_t offset,uint32_t additional_index)3104 Operand LCodeGen::BuildFastArrayOperand(
3105 LOperand* elements_pointer,
3106 LOperand* key,
3107 ElementsKind elements_kind,
3108 uint32_t offset,
3109 uint32_t additional_index) {
3110 Register elements_pointer_reg = ToRegister(elements_pointer);
3111 int shift_size = ElementsKindToShiftSize(elements_kind);
3112 if (key->IsConstantOperand()) {
3113 int32_t constant_value = ToInteger32(LConstantOperand::cast(key));
3114 if (constant_value & 0xF0000000) {
3115 Abort(kArrayIndexConstantValueTooBig);
3116 }
3117 return Operand(elements_pointer_reg,
3118 ((constant_value + additional_index) << shift_size)
3119 + offset);
3120 } else {
3121 ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3122 return Operand(elements_pointer_reg,
3123 ToRegister(key),
3124 scale_factor,
3125 offset + (additional_index << shift_size));
3126 }
3127 }
3128
3129
DoLoadKeyedGeneric(LLoadKeyedGeneric * instr)3130 void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3131 ASSERT(ToRegister(instr->context()).is(rsi));
3132 ASSERT(ToRegister(instr->object()).is(rdx));
3133 ASSERT(ToRegister(instr->key()).is(rax));
3134
3135 Handle<Code> ic = isolate()->builtins()->KeyedLoadIC_Initialize();
3136 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3137 }
3138
3139
DoArgumentsElements(LArgumentsElements * instr)3140 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
3141 Register result = ToRegister(instr->result());
3142
3143 if (instr->hydrogen()->from_inlined()) {
3144 __ lea(result, Operand(rsp, -kFPOnStackSize + -kPCOnStackSize));
3145 } else {
3146 // Check for arguments adapter frame.
3147 Label done, adapted;
3148 __ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
3149 __ Cmp(Operand(result, StandardFrameConstants::kContextOffset),
3150 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
3151 __ j(equal, &adapted, Label::kNear);
3152
3153 // No arguments adaptor frame.
3154 __ movq(result, rbp);
3155 __ jmp(&done, Label::kNear);
3156
3157 // Arguments adaptor frame present.
3158 __ bind(&adapted);
3159 __ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
3160
3161 // Result is the frame pointer for the frame if not adapted and for the real
3162 // frame below the adaptor frame if adapted.
3163 __ bind(&done);
3164 }
3165 }
3166
3167
DoArgumentsLength(LArgumentsLength * instr)3168 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
3169 Register result = ToRegister(instr->result());
3170
3171 Label done;
3172
3173 // If no arguments adaptor frame the number of arguments is fixed.
3174 if (instr->elements()->IsRegister()) {
3175 __ cmpq(rbp, ToRegister(instr->elements()));
3176 } else {
3177 __ cmpq(rbp, ToOperand(instr->elements()));
3178 }
3179 __ movl(result, Immediate(scope()->num_parameters()));
3180 __ j(equal, &done, Label::kNear);
3181
3182 // Arguments adaptor frame present. Get argument length from there.
3183 __ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
3184 __ SmiToInteger32(result,
3185 Operand(result,
3186 ArgumentsAdaptorFrameConstants::kLengthOffset));
3187
3188 // Argument length is in result register.
3189 __ bind(&done);
3190 }
3191
3192
DoWrapReceiver(LWrapReceiver * instr)3193 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3194 Register receiver = ToRegister(instr->receiver());
3195 Register function = ToRegister(instr->function());
3196
3197 // If the receiver is null or undefined, we have to pass the global
3198 // object as a receiver to normal functions. Values have to be
3199 // passed unchanged to builtins and strict-mode functions.
3200 Label global_object, receiver_ok;
3201 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3202
3203 // Do not transform the receiver to object for strict mode
3204 // functions.
3205 __ movq(kScratchRegister,
3206 FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
3207 __ testb(FieldOperand(kScratchRegister,
3208 SharedFunctionInfo::kStrictModeByteOffset),
3209 Immediate(1 << SharedFunctionInfo::kStrictModeBitWithinByte));
3210 __ j(not_equal, &receiver_ok, dist);
3211
3212 // Do not transform the receiver to object for builtins.
3213 __ testb(FieldOperand(kScratchRegister,
3214 SharedFunctionInfo::kNativeByteOffset),
3215 Immediate(1 << SharedFunctionInfo::kNativeBitWithinByte));
3216 __ j(not_equal, &receiver_ok, dist);
3217
3218 // Normal function. Replace undefined or null with global receiver.
3219 __ CompareRoot(receiver, Heap::kNullValueRootIndex);
3220 __ j(equal, &global_object, Label::kNear);
3221 __ CompareRoot(receiver, Heap::kUndefinedValueRootIndex);
3222 __ j(equal, &global_object, Label::kNear);
3223
3224 // The receiver should be a JS object.
3225 Condition is_smi = __ CheckSmi(receiver);
3226 DeoptimizeIf(is_smi, instr->environment());
3227 __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, kScratchRegister);
3228 DeoptimizeIf(below, instr->environment());
3229 __ jmp(&receiver_ok, Label::kNear);
3230
3231 __ bind(&global_object);
3232 // TODO(kmillikin): We have a hydrogen value for the global object. See
3233 // if it's better to use it than to explicitly fetch it from the context
3234 // here.
3235 __ movq(receiver, Operand(rbp, StandardFrameConstants::kContextOffset));
3236 __ movq(receiver, ContextOperand(receiver, Context::GLOBAL_OBJECT_INDEX));
3237 __ movq(receiver,
3238 FieldOperand(receiver, JSGlobalObject::kGlobalReceiverOffset));
3239 __ bind(&receiver_ok);
3240 }
3241
3242
DoApplyArguments(LApplyArguments * instr)3243 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
3244 Register receiver = ToRegister(instr->receiver());
3245 Register function = ToRegister(instr->function());
3246 Register length = ToRegister(instr->length());
3247 Register elements = ToRegister(instr->elements());
3248 ASSERT(receiver.is(rax)); // Used for parameter count.
3249 ASSERT(function.is(rdi)); // Required by InvokeFunction.
3250 ASSERT(ToRegister(instr->result()).is(rax));
3251
3252 // Copy the arguments to this function possibly from the
3253 // adaptor frame below it.
3254 const uint32_t kArgumentsLimit = 1 * KB;
3255 __ cmpq(length, Immediate(kArgumentsLimit));
3256 DeoptimizeIf(above, instr->environment());
3257
3258 __ push(receiver);
3259 __ movq(receiver, length);
3260
3261 // Loop through the arguments pushing them onto the execution
3262 // stack.
3263 Label invoke, loop;
3264 // length is a small non-negative integer, due to the test above.
3265 __ testl(length, length);
3266 __ j(zero, &invoke, Label::kNear);
3267 __ bind(&loop);
3268 StackArgumentsAccessor args(elements, length,
3269 ARGUMENTS_DONT_CONTAIN_RECEIVER);
3270 __ push(args.GetArgumentOperand(0));
3271 __ decl(length);
3272 __ j(not_zero, &loop);
3273
3274 // Invoke the function.
3275 __ bind(&invoke);
3276 ASSERT(instr->HasPointerMap());
3277 LPointerMap* pointers = instr->pointer_map();
3278 SafepointGenerator safepoint_generator(
3279 this, pointers, Safepoint::kLazyDeopt);
3280 ParameterCount actual(rax);
3281 __ InvokeFunction(function, actual, CALL_FUNCTION,
3282 safepoint_generator, CALL_AS_METHOD);
3283 }
3284
3285
DoPushArgument(LPushArgument * instr)3286 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3287 LOperand* argument = instr->value();
3288 EmitPushTaggedOperand(argument);
3289 }
3290
3291
DoDrop(LDrop * instr)3292 void LCodeGen::DoDrop(LDrop* instr) {
3293 __ Drop(instr->count());
3294 }
3295
3296
DoThisFunction(LThisFunction * instr)3297 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3298 Register result = ToRegister(instr->result());
3299 __ movq(result, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
3300 }
3301
3302
DoContext(LContext * instr)3303 void LCodeGen::DoContext(LContext* instr) {
3304 Register result = ToRegister(instr->result());
3305 if (info()->IsOptimizing()) {
3306 __ movq(result, Operand(rbp, StandardFrameConstants::kContextOffset));
3307 } else {
3308 // If there is no frame, the context must be in rsi.
3309 ASSERT(result.is(rsi));
3310 }
3311 }
3312
3313
DoOuterContext(LOuterContext * instr)3314 void LCodeGen::DoOuterContext(LOuterContext* instr) {
3315 Register context = ToRegister(instr->context());
3316 Register result = ToRegister(instr->result());
3317 __ movq(result,
3318 Operand(context, Context::SlotOffset(Context::PREVIOUS_INDEX)));
3319 }
3320
3321
DoDeclareGlobals(LDeclareGlobals * instr)3322 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3323 ASSERT(ToRegister(instr->context()).is(rsi));
3324 __ push(rsi); // The context is the first argument.
3325 __ Push(instr->hydrogen()->pairs());
3326 __ Push(Smi::FromInt(instr->hydrogen()->flags()));
3327 CallRuntime(Runtime::kDeclareGlobals, 3, instr);
3328 }
3329
3330
DoGlobalObject(LGlobalObject * instr)3331 void LCodeGen::DoGlobalObject(LGlobalObject* instr) {
3332 Register context = ToRegister(instr->context());
3333 Register result = ToRegister(instr->result());
3334 __ movq(result,
3335 Operand(context, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
3336 }
3337
3338
DoGlobalReceiver(LGlobalReceiver * instr)3339 void LCodeGen::DoGlobalReceiver(LGlobalReceiver* instr) {
3340 Register global = ToRegister(instr->global());
3341 Register result = ToRegister(instr->result());
3342 __ movq(result, FieldOperand(global, GlobalObject::kGlobalReceiverOffset));
3343 }
3344
3345
CallKnownFunction(Handle<JSFunction> function,int formal_parameter_count,int arity,LInstruction * instr,CallKind call_kind,RDIState rdi_state)3346 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3347 int formal_parameter_count,
3348 int arity,
3349 LInstruction* instr,
3350 CallKind call_kind,
3351 RDIState rdi_state) {
3352 bool dont_adapt_arguments =
3353 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3354 bool can_invoke_directly =
3355 dont_adapt_arguments || formal_parameter_count == arity;
3356
3357 LPointerMap* pointers = instr->pointer_map();
3358
3359 if (can_invoke_directly) {
3360 if (rdi_state == RDI_UNINITIALIZED) {
3361 __ Move(rdi, function);
3362 }
3363
3364 // Change context.
3365 __ movq(rsi, FieldOperand(rdi, JSFunction::kContextOffset));
3366
3367 // Set rax to arguments count if adaption is not needed. Assumes that rax
3368 // is available to write to at this point.
3369 if (dont_adapt_arguments) {
3370 __ Set(rax, arity);
3371 }
3372
3373 // Invoke function.
3374 __ SetCallKind(rcx, call_kind);
3375 if (function.is_identical_to(info()->closure())) {
3376 __ CallSelf();
3377 } else {
3378 __ call(FieldOperand(rdi, JSFunction::kCodeEntryOffset));
3379 }
3380
3381 // Set up deoptimization.
3382 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT, 0);
3383 } else {
3384 // We need to adapt arguments.
3385 SafepointGenerator generator(
3386 this, pointers, Safepoint::kLazyDeopt);
3387 ParameterCount count(arity);
3388 ParameterCount expected(formal_parameter_count);
3389 __ InvokeFunction(
3390 function, expected, count, CALL_FUNCTION, generator, call_kind);
3391 }
3392 }
3393
3394
DoCallConstantFunction(LCallConstantFunction * instr)3395 void LCodeGen::DoCallConstantFunction(LCallConstantFunction* instr) {
3396 ASSERT(ToRegister(instr->result()).is(rax));
3397 CallKnownFunction(instr->hydrogen()->function(),
3398 instr->hydrogen()->formal_parameter_count(),
3399 instr->arity(),
3400 instr,
3401 CALL_AS_METHOD,
3402 RDI_UNINITIALIZED);
3403 }
3404
3405
DoDeferredMathAbsTaggedHeapNumber(LMathAbs * instr)3406 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3407 Register input_reg = ToRegister(instr->value());
3408 __ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset),
3409 Heap::kHeapNumberMapRootIndex);
3410 DeoptimizeIf(not_equal, instr->environment());
3411
3412 Label slow, allocated, done;
3413 Register tmp = input_reg.is(rax) ? rcx : rax;
3414 Register tmp2 = tmp.is(rcx) ? rdx : input_reg.is(rcx) ? rdx : rcx;
3415
3416 // Preserve the value of all registers.
3417 PushSafepointRegistersScope scope(this);
3418
3419 __ movl(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
3420 // Check the sign of the argument. If the argument is positive, just
3421 // return it. We do not need to patch the stack since |input| and
3422 // |result| are the same register and |input| will be restored
3423 // unchanged by popping safepoint registers.
3424 __ testl(tmp, Immediate(HeapNumber::kSignMask));
3425 __ j(zero, &done);
3426
3427 __ AllocateHeapNumber(tmp, tmp2, &slow);
3428 __ jmp(&allocated, Label::kNear);
3429
3430 // Slow case: Call the runtime system to do the number allocation.
3431 __ bind(&slow);
3432 CallRuntimeFromDeferred(
3433 Runtime::kAllocateHeapNumber, 0, instr, instr->context());
3434 // Set the pointer to the new heap number in tmp.
3435 if (!tmp.is(rax)) __ movq(tmp, rax);
3436 // Restore input_reg after call to runtime.
3437 __ LoadFromSafepointRegisterSlot(input_reg, input_reg);
3438
3439 __ bind(&allocated);
3440 __ MoveDouble(tmp2, FieldOperand(input_reg, HeapNumber::kValueOffset));
3441 __ shl(tmp2, Immediate(1));
3442 __ shr(tmp2, Immediate(1));
3443 __ MoveDouble(FieldOperand(tmp, HeapNumber::kValueOffset), tmp2);
3444 __ StoreToSafepointRegisterSlot(input_reg, tmp);
3445
3446 __ bind(&done);
3447 }
3448
3449
EmitIntegerMathAbs(LMathAbs * instr)3450 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3451 Register input_reg = ToRegister(instr->value());
3452 __ testl(input_reg, input_reg);
3453 Label is_positive;
3454 __ j(not_sign, &is_positive, Label::kNear);
3455 __ negl(input_reg); // Sets flags.
3456 DeoptimizeIf(negative, instr->environment());
3457 __ bind(&is_positive);
3458 }
3459
3460
EmitSmiMathAbs(LMathAbs * instr)3461 void LCodeGen::EmitSmiMathAbs(LMathAbs* instr) {
3462 Register input_reg = ToRegister(instr->value());
3463 __ testq(input_reg, input_reg);
3464 Label is_positive;
3465 __ j(not_sign, &is_positive, Label::kNear);
3466 __ neg(input_reg); // Sets flags.
3467 DeoptimizeIf(negative, instr->environment());
3468 __ bind(&is_positive);
3469 }
3470
3471
DoMathAbs(LMathAbs * instr)3472 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3473 // Class for deferred case.
3474 class DeferredMathAbsTaggedHeapNumber V8_FINAL : public LDeferredCode {
3475 public:
3476 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen, LMathAbs* instr)
3477 : LDeferredCode(codegen), instr_(instr) { }
3478 virtual void Generate() V8_OVERRIDE {
3479 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3480 }
3481 virtual LInstruction* instr() V8_OVERRIDE { return instr_; }
3482 private:
3483 LMathAbs* instr_;
3484 };
3485
3486 ASSERT(instr->value()->Equals(instr->result()));
3487 Representation r = instr->hydrogen()->value()->representation();
3488
3489 if (r.IsDouble()) {
3490 XMMRegister scratch = double_scratch0();
3491 XMMRegister input_reg = ToDoubleRegister(instr->value());
3492 __ xorps(scratch, scratch);
3493 __ subsd(scratch, input_reg);
3494 __ andps(input_reg, scratch);
3495 } else if (r.IsInteger32()) {
3496 EmitIntegerMathAbs(instr);
3497 } else if (r.IsSmi()) {
3498 EmitSmiMathAbs(instr);
3499 } else { // Tagged case.
3500 DeferredMathAbsTaggedHeapNumber* deferred =
3501 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
3502 Register input_reg = ToRegister(instr->value());
3503 // Smi check.
3504 __ JumpIfNotSmi(input_reg, deferred->entry());
3505 EmitSmiMathAbs(instr);
3506 __ bind(deferred->exit());
3507 }
3508 }
3509
3510
DoMathFloor(LMathFloor * instr)3511 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3512 XMMRegister xmm_scratch = double_scratch0();
3513 Register output_reg = ToRegister(instr->result());
3514 XMMRegister input_reg = ToDoubleRegister(instr->value());
3515
3516 if (CpuFeatures::IsSupported(SSE4_1)) {
3517 CpuFeatureScope scope(masm(), SSE4_1);
3518 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3519 // Deoptimize if minus zero.
3520 __ movq(output_reg, input_reg);
3521 __ subq(output_reg, Immediate(1));
3522 DeoptimizeIf(overflow, instr->environment());
3523 }
3524 __ roundsd(xmm_scratch, input_reg, Assembler::kRoundDown);
3525 __ cvttsd2si(output_reg, xmm_scratch);
3526 __ cmpl(output_reg, Immediate(0x80000000));
3527 DeoptimizeIf(equal, instr->environment());
3528 } else {
3529 Label negative_sign, done;
3530 // Deoptimize on unordered.
3531 __ xorps(xmm_scratch, xmm_scratch); // Zero the register.
3532 __ ucomisd(input_reg, xmm_scratch);
3533 DeoptimizeIf(parity_even, instr->environment());
3534 __ j(below, &negative_sign, Label::kNear);
3535
3536 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3537 // Check for negative zero.
3538 Label positive_sign;
3539 __ j(above, &positive_sign, Label::kNear);
3540 __ movmskpd(output_reg, input_reg);
3541 __ testq(output_reg, Immediate(1));
3542 DeoptimizeIf(not_zero, instr->environment());
3543 __ Set(output_reg, 0);
3544 __ jmp(&done, Label::kNear);
3545 __ bind(&positive_sign);
3546 }
3547
3548 // Use truncating instruction (OK because input is positive).
3549 __ cvttsd2si(output_reg, input_reg);
3550 // Overflow is signalled with minint.
3551 __ cmpl(output_reg, Immediate(0x80000000));
3552 DeoptimizeIf(equal, instr->environment());
3553 __ jmp(&done, Label::kNear);
3554
3555 // Non-zero negative reaches here.
3556 __ bind(&negative_sign);
3557 // Truncate, then compare and compensate.
3558 __ cvttsd2si(output_reg, input_reg);
3559 __ Cvtlsi2sd(xmm_scratch, output_reg);
3560 __ ucomisd(input_reg, xmm_scratch);
3561 __ j(equal, &done, Label::kNear);
3562 __ subl(output_reg, Immediate(1));
3563 DeoptimizeIf(overflow, instr->environment());
3564
3565 __ bind(&done);
3566 }
3567 }
3568
3569
DoMathRound(LMathRound * instr)3570 void LCodeGen::DoMathRound(LMathRound* instr) {
3571 const XMMRegister xmm_scratch = double_scratch0();
3572 Register output_reg = ToRegister(instr->result());
3573 XMMRegister input_reg = ToDoubleRegister(instr->value());
3574 static int64_t one_half = V8_INT64_C(0x3FE0000000000000); // 0.5
3575 static int64_t minus_one_half = V8_INT64_C(0xBFE0000000000000); // -0.5
3576
3577 Label done, round_to_zero, below_one_half, do_not_compensate, restore;
3578 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
3579 __ movq(kScratchRegister, one_half);
3580 __ movq(xmm_scratch, kScratchRegister);
3581 __ ucomisd(xmm_scratch, input_reg);
3582 __ j(above, &below_one_half, Label::kNear);
3583
3584 // CVTTSD2SI rounds towards zero, since 0.5 <= x, we use floor(0.5 + x).
3585 __ addsd(xmm_scratch, input_reg);
3586 __ cvttsd2si(output_reg, xmm_scratch);
3587 // Overflow is signalled with minint.
3588 __ cmpl(output_reg, Immediate(0x80000000));
3589 __ RecordComment("D2I conversion overflow");
3590 DeoptimizeIf(equal, instr->environment());
3591 __ jmp(&done, dist);
3592
3593 __ bind(&below_one_half);
3594 __ movq(kScratchRegister, minus_one_half);
3595 __ movq(xmm_scratch, kScratchRegister);
3596 __ ucomisd(xmm_scratch, input_reg);
3597 __ j(below_equal, &round_to_zero, Label::kNear);
3598
3599 // CVTTSD2SI rounds towards zero, we use ceil(x - (-0.5)) and then
3600 // compare and compensate.
3601 __ movq(kScratchRegister, input_reg); // Back up input_reg.
3602 __ subsd(input_reg, xmm_scratch);
3603 __ cvttsd2si(output_reg, input_reg);
3604 // Catch minint due to overflow, and to prevent overflow when compensating.
3605 __ cmpl(output_reg, Immediate(0x80000000));
3606 __ RecordComment("D2I conversion overflow");
3607 DeoptimizeIf(equal, instr->environment());
3608
3609 __ Cvtlsi2sd(xmm_scratch, output_reg);
3610 __ ucomisd(input_reg, xmm_scratch);
3611 __ j(equal, &restore, Label::kNear);
3612 __ subl(output_reg, Immediate(1));
3613 // No overflow because we already ruled out minint.
3614 __ bind(&restore);
3615 __ movq(input_reg, kScratchRegister); // Restore input_reg.
3616 __ jmp(&done, dist);
3617
3618 __ bind(&round_to_zero);
3619 // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
3620 // we can ignore the difference between a result of -0 and +0.
3621 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3622 __ movq(output_reg, input_reg);
3623 __ testq(output_reg, output_reg);
3624 __ RecordComment("Minus zero");
3625 DeoptimizeIf(negative, instr->environment());
3626 }
3627 __ Set(output_reg, 0);
3628 __ bind(&done);
3629 }
3630
3631
DoMathSqrt(LMathSqrt * instr)3632 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3633 XMMRegister input_reg = ToDoubleRegister(instr->value());
3634 ASSERT(ToDoubleRegister(instr->result()).is(input_reg));
3635 __ sqrtsd(input_reg, input_reg);
3636 }
3637
3638
DoMathPowHalf(LMathPowHalf * instr)3639 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3640 XMMRegister xmm_scratch = double_scratch0();
3641 XMMRegister input_reg = ToDoubleRegister(instr->value());
3642 ASSERT(ToDoubleRegister(instr->result()).is(input_reg));
3643
3644 // Note that according to ECMA-262 15.8.2.13:
3645 // Math.pow(-Infinity, 0.5) == Infinity
3646 // Math.sqrt(-Infinity) == NaN
3647 Label done, sqrt;
3648 // Check base for -Infinity. According to IEEE-754, double-precision
3649 // -Infinity has the highest 12 bits set and the lowest 52 bits cleared.
3650 __ movq(kScratchRegister, V8_INT64_C(0xFFF0000000000000));
3651 __ movq(xmm_scratch, kScratchRegister);
3652 __ ucomisd(xmm_scratch, input_reg);
3653 // Comparing -Infinity with NaN results in "unordered", which sets the
3654 // zero flag as if both were equal. However, it also sets the carry flag.
3655 __ j(not_equal, &sqrt, Label::kNear);
3656 __ j(carry, &sqrt, Label::kNear);
3657 // If input is -Infinity, return Infinity.
3658 __ xorps(input_reg, input_reg);
3659 __ subsd(input_reg, xmm_scratch);
3660 __ jmp(&done, Label::kNear);
3661
3662 // Square root.
3663 __ bind(&sqrt);
3664 __ xorps(xmm_scratch, xmm_scratch);
3665 __ addsd(input_reg, xmm_scratch); // Convert -0 to +0.
3666 __ sqrtsd(input_reg, input_reg);
3667 __ bind(&done);
3668 }
3669
3670
DoPower(LPower * instr)3671 void LCodeGen::DoPower(LPower* instr) {
3672 Representation exponent_type = instr->hydrogen()->right()->representation();
3673 // Having marked this as a call, we can use any registers.
3674 // Just make sure that the input/output registers are the expected ones.
3675
3676 Register exponent = rdx;
3677 ASSERT(!instr->right()->IsRegister() ||
3678 ToRegister(instr->right()).is(exponent));
3679 ASSERT(!instr->right()->IsDoubleRegister() ||
3680 ToDoubleRegister(instr->right()).is(xmm1));
3681 ASSERT(ToDoubleRegister(instr->left()).is(xmm2));
3682 ASSERT(ToDoubleRegister(instr->result()).is(xmm3));
3683
3684 if (exponent_type.IsSmi()) {
3685 MathPowStub stub(MathPowStub::TAGGED);
3686 __ CallStub(&stub);
3687 } else if (exponent_type.IsTagged()) {
3688 Label no_deopt;
3689 __ JumpIfSmi(exponent, &no_deopt, Label::kNear);
3690 __ CmpObjectType(exponent, HEAP_NUMBER_TYPE, rcx);
3691 DeoptimizeIf(not_equal, instr->environment());
3692 __ bind(&no_deopt);
3693 MathPowStub stub(MathPowStub::TAGGED);
3694 __ CallStub(&stub);
3695 } else if (exponent_type.IsInteger32()) {
3696 MathPowStub stub(MathPowStub::INTEGER);
3697 __ CallStub(&stub);
3698 } else {
3699 ASSERT(exponent_type.IsDouble());
3700 MathPowStub stub(MathPowStub::DOUBLE);
3701 __ CallStub(&stub);
3702 }
3703 }
3704
3705
DoMathExp(LMathExp * instr)3706 void LCodeGen::DoMathExp(LMathExp* instr) {
3707 XMMRegister input = ToDoubleRegister(instr->value());
3708 XMMRegister result = ToDoubleRegister(instr->result());
3709 XMMRegister temp0 = double_scratch0();
3710 Register temp1 = ToRegister(instr->temp1());
3711 Register temp2 = ToRegister(instr->temp2());
3712
3713 MathExpGenerator::EmitMathExp(masm(), input, result, temp0, temp1, temp2);
3714 }
3715
3716
DoMathLog(LMathLog * instr)3717 void LCodeGen::DoMathLog(LMathLog* instr) {
3718 ASSERT(instr->value()->Equals(instr->result()));
3719 XMMRegister input_reg = ToDoubleRegister(instr->value());
3720 XMMRegister xmm_scratch = double_scratch0();
3721 Label positive, done, zero;
3722 __ xorps(xmm_scratch, xmm_scratch);
3723 __ ucomisd(input_reg, xmm_scratch);
3724 __ j(above, &positive, Label::kNear);
3725 __ j(equal, &zero, Label::kNear);
3726 ExternalReference nan =
3727 ExternalReference::address_of_canonical_non_hole_nan();
3728 Operand nan_operand = masm()->ExternalOperand(nan);
3729 __ movsd(input_reg, nan_operand);
3730 __ jmp(&done, Label::kNear);
3731 __ bind(&zero);
3732 ExternalReference ninf =
3733 ExternalReference::address_of_negative_infinity();
3734 Operand ninf_operand = masm()->ExternalOperand(ninf);
3735 __ movsd(input_reg, ninf_operand);
3736 __ jmp(&done, Label::kNear);
3737 __ bind(&positive);
3738 __ fldln2();
3739 __ subq(rsp, Immediate(kDoubleSize));
3740 __ movsd(Operand(rsp, 0), input_reg);
3741 __ fld_d(Operand(rsp, 0));
3742 __ fyl2x();
3743 __ fstp_d(Operand(rsp, 0));
3744 __ movsd(input_reg, Operand(rsp, 0));
3745 __ addq(rsp, Immediate(kDoubleSize));
3746 __ bind(&done);
3747 }
3748
3749
DoMathTan(LMathTan * instr)3750 void LCodeGen::DoMathTan(LMathTan* instr) {
3751 ASSERT(ToDoubleRegister(instr->result()).is(xmm1));
3752 // Set the context register to a GC-safe fake value. Clobbering it is
3753 // OK because this instruction is marked as a call.
3754 __ Set(rsi, 0);
3755 TranscendentalCacheStub stub(TranscendentalCache::TAN,
3756 TranscendentalCacheStub::UNTAGGED);
3757 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
3758 }
3759
3760
DoMathCos(LMathCos * instr)3761 void LCodeGen::DoMathCos(LMathCos* instr) {
3762 ASSERT(ToDoubleRegister(instr->result()).is(xmm1));
3763 // Set the context register to a GC-safe fake value. Clobbering it is
3764 // OK because this instruction is marked as a call.
3765 __ Set(rsi, 0);
3766 TranscendentalCacheStub stub(TranscendentalCache::COS,
3767 TranscendentalCacheStub::UNTAGGED);
3768 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
3769 }
3770
3771
DoMathSin(LMathSin * instr)3772 void LCodeGen::DoMathSin(LMathSin* instr) {
3773 ASSERT(ToDoubleRegister(instr->result()).is(xmm1));
3774 // Set the context register to a GC-safe fake value. Clobbering it is
3775 // OK because this instruction is marked as a call.
3776 __ Set(rsi, 0);
3777 TranscendentalCacheStub stub(TranscendentalCache::SIN,
3778 TranscendentalCacheStub::UNTAGGED);
3779 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
3780 }
3781
3782
DoInvokeFunction(LInvokeFunction * instr)3783 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
3784 ASSERT(ToRegister(instr->context()).is(rsi));
3785 ASSERT(ToRegister(instr->function()).is(rdi));
3786 ASSERT(instr->HasPointerMap());
3787
3788 Handle<JSFunction> known_function = instr->hydrogen()->known_function();
3789 if (known_function.is_null()) {
3790 LPointerMap* pointers = instr->pointer_map();
3791 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3792 ParameterCount count(instr->arity());
3793 __ InvokeFunction(rdi, count, CALL_FUNCTION, generator, CALL_AS_METHOD);
3794 } else {
3795 CallKnownFunction(known_function,
3796 instr->hydrogen()->formal_parameter_count(),
3797 instr->arity(),
3798 instr,
3799 CALL_AS_METHOD,
3800 RDI_CONTAINS_TARGET);
3801 }
3802 }
3803
3804
DoCallKeyed(LCallKeyed * instr)3805 void LCodeGen::DoCallKeyed(LCallKeyed* instr) {
3806 ASSERT(ToRegister(instr->context()).is(rsi));
3807 ASSERT(ToRegister(instr->key()).is(rcx));
3808 ASSERT(ToRegister(instr->result()).is(rax));
3809
3810 int arity = instr->arity();
3811 Handle<Code> ic =
3812 isolate()->stub_cache()->ComputeKeyedCallInitialize(arity);
3813 CallCode(ic, RelocInfo::CODE_TARGET, instr);
3814 }
3815
3816
DoCallNamed(LCallNamed * instr)3817 void LCodeGen::DoCallNamed(LCallNamed* instr) {
3818 ASSERT(ToRegister(instr->context()).is(rsi));
3819 ASSERT(ToRegister(instr->result()).is(rax));
3820
3821 int arity = instr->arity();
3822 RelocInfo::Mode mode = RelocInfo::CODE_TARGET;
3823 Handle<Code> ic =
3824 isolate()->stub_cache()->ComputeCallInitialize(arity, mode);
3825 __ Move(rcx, instr->name());
3826 CallCode(ic, mode, instr);
3827 }
3828
3829
DoCallFunction(LCallFunction * instr)3830 void LCodeGen::DoCallFunction(LCallFunction* instr) {
3831 ASSERT(ToRegister(instr->context()).is(rsi));
3832 ASSERT(ToRegister(instr->function()).is(rdi));
3833 ASSERT(ToRegister(instr->result()).is(rax));
3834
3835 int arity = instr->arity();
3836 CallFunctionStub stub(arity, NO_CALL_FUNCTION_FLAGS);
3837 if (instr->hydrogen()->IsTailCall()) {
3838 if (NeedsEagerFrame()) __ leave();
3839 __ jmp(stub.GetCode(isolate()), RelocInfo::CODE_TARGET);
3840 } else {
3841 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
3842 }
3843 }
3844
3845
DoCallGlobal(LCallGlobal * instr)3846 void LCodeGen::DoCallGlobal(LCallGlobal* instr) {
3847 ASSERT(ToRegister(instr->context()).is(rsi));
3848 ASSERT(ToRegister(instr->result()).is(rax));
3849 int arity = instr->arity();
3850 RelocInfo::Mode mode = RelocInfo::CODE_TARGET_CONTEXT;
3851 Handle<Code> ic =
3852 isolate()->stub_cache()->ComputeCallInitialize(arity, mode);
3853 __ Move(rcx, instr->name());
3854 CallCode(ic, mode, instr);
3855 }
3856
3857
DoCallKnownGlobal(LCallKnownGlobal * instr)3858 void LCodeGen::DoCallKnownGlobal(LCallKnownGlobal* instr) {
3859 ASSERT(ToRegister(instr->result()).is(rax));
3860 CallKnownFunction(instr->hydrogen()->target(),
3861 instr->hydrogen()->formal_parameter_count(),
3862 instr->arity(),
3863 instr,
3864 CALL_AS_FUNCTION,
3865 RDI_UNINITIALIZED);
3866 }
3867
3868
DoCallNew(LCallNew * instr)3869 void LCodeGen::DoCallNew(LCallNew* instr) {
3870 ASSERT(ToRegister(instr->context()).is(rsi));
3871 ASSERT(ToRegister(instr->constructor()).is(rdi));
3872 ASSERT(ToRegister(instr->result()).is(rax));
3873
3874 __ Set(rax, instr->arity());
3875 // No cell in ebx for construct type feedback in optimized code
3876 Handle<Object> undefined_value(isolate()->factory()->undefined_value());
3877 __ Move(rbx, undefined_value);
3878 CallConstructStub stub(NO_CALL_FUNCTION_FLAGS);
3879 CallCode(stub.GetCode(isolate()), RelocInfo::CONSTRUCT_CALL, instr);
3880 }
3881
3882
DoCallNewArray(LCallNewArray * instr)3883 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
3884 ASSERT(ToRegister(instr->context()).is(rsi));
3885 ASSERT(ToRegister(instr->constructor()).is(rdi));
3886 ASSERT(ToRegister(instr->result()).is(rax));
3887
3888 __ Set(rax, instr->arity());
3889 __ Move(rbx, instr->hydrogen()->property_cell());
3890 ElementsKind kind = instr->hydrogen()->elements_kind();
3891 AllocationSiteOverrideMode override_mode =
3892 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
3893 ? DISABLE_ALLOCATION_SITES
3894 : DONT_OVERRIDE;
3895 ContextCheckMode context_mode = CONTEXT_CHECK_NOT_REQUIRED;
3896
3897 if (instr->arity() == 0) {
3898 ArrayNoArgumentConstructorStub stub(kind, context_mode, override_mode);
3899 CallCode(stub.GetCode(isolate()), RelocInfo::CONSTRUCT_CALL, instr);
3900 } else if (instr->arity() == 1) {
3901 Label done;
3902 if (IsFastPackedElementsKind(kind)) {
3903 Label packed_case;
3904 // We might need a change here
3905 // look at the first argument
3906 __ movq(rcx, Operand(rsp, 0));
3907 __ testq(rcx, rcx);
3908 __ j(zero, &packed_case, Label::kNear);
3909
3910 ElementsKind holey_kind = GetHoleyElementsKind(kind);
3911 ArraySingleArgumentConstructorStub stub(holey_kind, context_mode,
3912 override_mode);
3913 CallCode(stub.GetCode(isolate()), RelocInfo::CONSTRUCT_CALL, instr);
3914 __ jmp(&done, Label::kNear);
3915 __ bind(&packed_case);
3916 }
3917
3918 ArraySingleArgumentConstructorStub stub(kind, context_mode, override_mode);
3919 CallCode(stub.GetCode(isolate()), RelocInfo::CONSTRUCT_CALL, instr);
3920 __ bind(&done);
3921 } else {
3922 ArrayNArgumentsConstructorStub stub(kind, context_mode, override_mode);
3923 CallCode(stub.GetCode(isolate()), RelocInfo::CONSTRUCT_CALL, instr);
3924 }
3925 }
3926
3927
DoCallRuntime(LCallRuntime * instr)3928 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
3929 ASSERT(ToRegister(instr->context()).is(rsi));
3930 CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
3931 }
3932
3933
DoStoreCodeEntry(LStoreCodeEntry * instr)3934 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
3935 Register function = ToRegister(instr->function());
3936 Register code_object = ToRegister(instr->code_object());
3937 __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
3938 __ movq(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
3939 }
3940
3941
DoInnerAllocatedObject(LInnerAllocatedObject * instr)3942 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
3943 Register result = ToRegister(instr->result());
3944 Register base = ToRegister(instr->base_object());
3945 if (instr->offset()->IsConstantOperand()) {
3946 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
3947 __ lea(result, Operand(base, ToInteger32(offset)));
3948 } else {
3949 Register offset = ToRegister(instr->offset());
3950 __ lea(result, Operand(base, offset, times_1, 0));
3951 }
3952 }
3953
3954
DoStoreNamedField(LStoreNamedField * instr)3955 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
3956 Representation representation = instr->representation();
3957
3958 HObjectAccess access = instr->hydrogen()->access();
3959 int offset = access.offset();
3960
3961 if (access.IsExternalMemory()) {
3962 ASSERT(!instr->hydrogen()->NeedsWriteBarrier());
3963 Register value = ToRegister(instr->value());
3964 if (instr->object()->IsConstantOperand()) {
3965 ASSERT(value.is(rax));
3966 ASSERT(!access.representation().IsSpecialization());
3967 LConstantOperand* object = LConstantOperand::cast(instr->object());
3968 __ store_rax(ToExternalReference(object));
3969 } else {
3970 Register object = ToRegister(instr->object());
3971 __ Store(MemOperand(object, offset), value, representation);
3972 }
3973 return;
3974 }
3975
3976 Register object = ToRegister(instr->object());
3977 Handle<Map> transition = instr->transition();
3978
3979 if (FLAG_track_fields && representation.IsSmi()) {
3980 if (instr->value()->IsConstantOperand()) {
3981 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
3982 if (!IsSmiConstant(operand_value)) {
3983 DeoptimizeIf(no_condition, instr->environment());
3984 }
3985 }
3986 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
3987 if (instr->value()->IsConstantOperand()) {
3988 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
3989 if (IsInteger32Constant(operand_value)) {
3990 DeoptimizeIf(no_condition, instr->environment());
3991 }
3992 } else {
3993 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
3994 Register value = ToRegister(instr->value());
3995 Condition cc = masm()->CheckSmi(value);
3996 DeoptimizeIf(cc, instr->environment());
3997 }
3998 }
3999 } else if (FLAG_track_double_fields && representation.IsDouble()) {
4000 ASSERT(transition.is_null());
4001 ASSERT(access.IsInobject());
4002 ASSERT(!instr->hydrogen()->NeedsWriteBarrier());
4003 XMMRegister value = ToDoubleRegister(instr->value());
4004 __ movsd(FieldOperand(object, offset), value);
4005 return;
4006 }
4007
4008 if (!transition.is_null()) {
4009 if (!instr->hydrogen()->NeedsWriteBarrierForMap()) {
4010 __ Move(FieldOperand(object, HeapObject::kMapOffset), transition);
4011 } else {
4012 Register temp = ToRegister(instr->temp());
4013 __ Move(kScratchRegister, transition);
4014 __ movq(FieldOperand(object, HeapObject::kMapOffset), kScratchRegister);
4015 // Update the write barrier for the map field.
4016 __ RecordWriteField(object,
4017 HeapObject::kMapOffset,
4018 kScratchRegister,
4019 temp,
4020 kSaveFPRegs,
4021 OMIT_REMEMBERED_SET,
4022 OMIT_SMI_CHECK);
4023 }
4024 }
4025
4026 // Do the store.
4027 SmiCheck check_needed =
4028 instr->hydrogen()->value()->IsHeapObject()
4029 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4030
4031 Register write_register = object;
4032 if (!access.IsInobject()) {
4033 write_register = ToRegister(instr->temp());
4034 __ movq(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
4035 }
4036
4037 if (instr->value()->IsConstantOperand()) {
4038 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4039 if (operand_value->IsRegister()) {
4040 Register value = ToRegister(operand_value);
4041 __ Store(FieldOperand(write_register, offset), value, representation);
4042 } else if (representation.IsInteger32()) {
4043 int32_t value = ToInteger32(operand_value);
4044 ASSERT(!instr->hydrogen()->NeedsWriteBarrier());
4045 __ movl(FieldOperand(write_register, offset), Immediate(value));
4046 } else {
4047 Handle<Object> handle_value = ToHandle(operand_value);
4048 ASSERT(!instr->hydrogen()->NeedsWriteBarrier());
4049 __ Move(FieldOperand(write_register, offset), handle_value);
4050 }
4051 } else {
4052 Register value = ToRegister(instr->value());
4053 __ Store(FieldOperand(write_register, offset), value, representation);
4054 }
4055
4056 if (instr->hydrogen()->NeedsWriteBarrier()) {
4057 Register value = ToRegister(instr->value());
4058 Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
4059 // Update the write barrier for the object for in-object properties.
4060 __ RecordWriteField(write_register,
4061 offset,
4062 value,
4063 temp,
4064 kSaveFPRegs,
4065 EMIT_REMEMBERED_SET,
4066 check_needed);
4067 }
4068 }
4069
4070
DoStoreNamedGeneric(LStoreNamedGeneric * instr)4071 void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4072 ASSERT(ToRegister(instr->context()).is(rsi));
4073 ASSERT(ToRegister(instr->object()).is(rdx));
4074 ASSERT(ToRegister(instr->value()).is(rax));
4075
4076 __ Move(rcx, instr->hydrogen()->name());
4077 Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode)
4078 ? isolate()->builtins()->StoreIC_Initialize_Strict()
4079 : isolate()->builtins()->StoreIC_Initialize();
4080 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4081 }
4082
4083
ApplyCheckIf(Condition cc,LBoundsCheck * check)4084 void LCodeGen::ApplyCheckIf(Condition cc, LBoundsCheck* check) {
4085 if (FLAG_debug_code && check->hydrogen()->skip_check()) {
4086 Label done;
4087 __ j(NegateCondition(cc), &done, Label::kNear);
4088 __ int3();
4089 __ bind(&done);
4090 } else {
4091 DeoptimizeIf(cc, check->environment());
4092 }
4093 }
4094
4095
DoBoundsCheck(LBoundsCheck * instr)4096 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4097 if (instr->hydrogen()->skip_check()) return;
4098
4099 if (instr->length()->IsRegister()) {
4100 Register reg = ToRegister(instr->length());
4101 if (!instr->hydrogen()->length()->representation().IsSmi()) {
4102 __ AssertZeroExtended(reg);
4103 }
4104 if (instr->index()->IsConstantOperand()) {
4105 int32_t constant_index =
4106 ToInteger32(LConstantOperand::cast(instr->index()));
4107 if (instr->hydrogen()->length()->representation().IsSmi()) {
4108 __ Cmp(reg, Smi::FromInt(constant_index));
4109 } else {
4110 __ cmpq(reg, Immediate(constant_index));
4111 }
4112 } else {
4113 Register reg2 = ToRegister(instr->index());
4114 if (!instr->hydrogen()->index()->representation().IsSmi()) {
4115 __ AssertZeroExtended(reg2);
4116 }
4117 __ cmpq(reg, reg2);
4118 }
4119 } else {
4120 Operand length = ToOperand(instr->length());
4121 if (instr->index()->IsConstantOperand()) {
4122 int32_t constant_index =
4123 ToInteger32(LConstantOperand::cast(instr->index()));
4124 if (instr->hydrogen()->length()->representation().IsSmi()) {
4125 __ Cmp(length, Smi::FromInt(constant_index));
4126 } else {
4127 __ cmpq(length, Immediate(constant_index));
4128 }
4129 } else {
4130 __ cmpq(length, ToRegister(instr->index()));
4131 }
4132 }
4133 Condition condition =
4134 instr->hydrogen()->allow_equality() ? below : below_equal;
4135 ApplyCheckIf(condition, instr);
4136 }
4137
4138
DoStoreKeyedExternalArray(LStoreKeyed * instr)4139 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
4140 ElementsKind elements_kind = instr->elements_kind();
4141 LOperand* key = instr->key();
4142 if (!key->IsConstantOperand()) {
4143 Register key_reg = ToRegister(key);
4144 // Even though the HLoad/StoreKeyedFastElement instructions force
4145 // the input representation for the key to be an integer, the input
4146 // gets replaced during bound check elimination with the index
4147 // argument to the bounds check, which can be tagged, so that case
4148 // must be handled here, too.
4149 if (instr->hydrogen()->IsDehoisted()) {
4150 // Sign extend key because it could be a 32 bit negative value
4151 // and the dehoisted address computation happens in 64 bits
4152 __ movsxlq(key_reg, key_reg);
4153 }
4154 }
4155 Operand operand(BuildFastArrayOperand(
4156 instr->elements(),
4157 key,
4158 elements_kind,
4159 0,
4160 instr->additional_index()));
4161
4162 if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) {
4163 XMMRegister value(ToDoubleRegister(instr->value()));
4164 __ cvtsd2ss(value, value);
4165 __ movss(operand, value);
4166 } else if (elements_kind == EXTERNAL_DOUBLE_ELEMENTS) {
4167 __ movsd(operand, ToDoubleRegister(instr->value()));
4168 } else {
4169 Register value(ToRegister(instr->value()));
4170 switch (elements_kind) {
4171 case EXTERNAL_PIXEL_ELEMENTS:
4172 case EXTERNAL_BYTE_ELEMENTS:
4173 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
4174 __ movb(operand, value);
4175 break;
4176 case EXTERNAL_SHORT_ELEMENTS:
4177 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
4178 __ movw(operand, value);
4179 break;
4180 case EXTERNAL_INT_ELEMENTS:
4181 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
4182 __ movl(operand, value);
4183 break;
4184 case EXTERNAL_FLOAT_ELEMENTS:
4185 case EXTERNAL_DOUBLE_ELEMENTS:
4186 case FAST_ELEMENTS:
4187 case FAST_SMI_ELEMENTS:
4188 case FAST_DOUBLE_ELEMENTS:
4189 case FAST_HOLEY_ELEMENTS:
4190 case FAST_HOLEY_SMI_ELEMENTS:
4191 case FAST_HOLEY_DOUBLE_ELEMENTS:
4192 case DICTIONARY_ELEMENTS:
4193 case NON_STRICT_ARGUMENTS_ELEMENTS:
4194 UNREACHABLE();
4195 break;
4196 }
4197 }
4198 }
4199
4200
DoStoreKeyedFixedDoubleArray(LStoreKeyed * instr)4201 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4202 XMMRegister value = ToDoubleRegister(instr->value());
4203 LOperand* key = instr->key();
4204 if (!key->IsConstantOperand()) {
4205 Register key_reg = ToRegister(key);
4206 // Even though the HLoad/StoreKeyedFastElement instructions force
4207 // the input representation for the key to be an integer, the
4208 // input gets replaced during bound check elimination with the index
4209 // argument to the bounds check, which can be tagged, so that case
4210 // must be handled here, too.
4211 if (instr->hydrogen()->IsDehoisted()) {
4212 // Sign extend key because it could be a 32 bit negative value
4213 // and the dehoisted address computation happens in 64 bits
4214 __ movsxlq(key_reg, key_reg);
4215 }
4216 }
4217
4218 if (instr->NeedsCanonicalization()) {
4219 Label have_value;
4220
4221 __ ucomisd(value, value);
4222 __ j(parity_odd, &have_value, Label::kNear); // NaN.
4223
4224 __ Set(kScratchRegister, BitCast<uint64_t>(
4225 FixedDoubleArray::canonical_not_the_hole_nan_as_double()));
4226 __ movq(value, kScratchRegister);
4227
4228 __ bind(&have_value);
4229 }
4230
4231 Operand double_store_operand = BuildFastArrayOperand(
4232 instr->elements(),
4233 key,
4234 FAST_DOUBLE_ELEMENTS,
4235 FixedDoubleArray::kHeaderSize - kHeapObjectTag,
4236 instr->additional_index());
4237
4238 __ movsd(double_store_operand, value);
4239 }
4240
4241
DoStoreKeyedFixedArray(LStoreKeyed * instr)4242 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
4243 Register elements = ToRegister(instr->elements());
4244 LOperand* key = instr->key();
4245 if (!key->IsConstantOperand()) {
4246 Register key_reg = ToRegister(key);
4247 // Even though the HLoad/StoreKeyedFastElement instructions force
4248 // the input representation for the key to be an integer, the
4249 // input gets replaced during bound check elimination with the index
4250 // argument to the bounds check, which can be tagged, so that case
4251 // must be handled here, too.
4252 if (instr->hydrogen()->IsDehoisted()) {
4253 // Sign extend key because it could be a 32 bit negative value
4254 // and the dehoisted address computation happens in 64 bits
4255 __ movsxlq(key_reg, key_reg);
4256 }
4257 }
4258
4259 Operand operand =
4260 BuildFastArrayOperand(instr->elements(),
4261 key,
4262 FAST_ELEMENTS,
4263 FixedArray::kHeaderSize - kHeapObjectTag,
4264 instr->additional_index());
4265 if (instr->value()->IsRegister()) {
4266 __ movq(operand, ToRegister(instr->value()));
4267 } else {
4268 LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
4269 if (IsInteger32Constant(operand_value)) {
4270 Smi* smi_value = Smi::FromInt(ToInteger32(operand_value));
4271 __ Move(operand, smi_value);
4272 } else {
4273 Handle<Object> handle_value = ToHandle(operand_value);
4274 __ Move(operand, handle_value);
4275 }
4276 }
4277
4278 if (instr->hydrogen()->NeedsWriteBarrier()) {
4279 ASSERT(instr->value()->IsRegister());
4280 Register value = ToRegister(instr->value());
4281 ASSERT(!instr->key()->IsConstantOperand());
4282 SmiCheck check_needed =
4283 instr->hydrogen()->value()->IsHeapObject()
4284 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
4285 // Compute address of modified element and store it into key register.
4286 Register key_reg(ToRegister(key));
4287 __ lea(key_reg, operand);
4288 __ RecordWrite(elements,
4289 key_reg,
4290 value,
4291 kSaveFPRegs,
4292 EMIT_REMEMBERED_SET,
4293 check_needed);
4294 }
4295 }
4296
4297
DoStoreKeyed(LStoreKeyed * instr)4298 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
4299 if (instr->is_external()) {
4300 DoStoreKeyedExternalArray(instr);
4301 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
4302 DoStoreKeyedFixedDoubleArray(instr);
4303 } else {
4304 DoStoreKeyedFixedArray(instr);
4305 }
4306 }
4307
4308
DoStoreKeyedGeneric(LStoreKeyedGeneric * instr)4309 void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4310 ASSERT(ToRegister(instr->context()).is(rsi));
4311 ASSERT(ToRegister(instr->object()).is(rdx));
4312 ASSERT(ToRegister(instr->key()).is(rcx));
4313 ASSERT(ToRegister(instr->value()).is(rax));
4314
4315 Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode)
4316 ? isolate()->builtins()->KeyedStoreIC_Initialize_Strict()
4317 : isolate()->builtins()->KeyedStoreIC_Initialize();
4318 CallCode(ic, RelocInfo::CODE_TARGET, instr);
4319 }
4320
4321
DoTransitionElementsKind(LTransitionElementsKind * instr)4322 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4323 Register object_reg = ToRegister(instr->object());
4324
4325 Handle<Map> from_map = instr->original_map();
4326 Handle<Map> to_map = instr->transitioned_map();
4327 ElementsKind from_kind = instr->from_kind();
4328 ElementsKind to_kind = instr->to_kind();
4329
4330 Label not_applicable;
4331 __ Cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
4332 __ j(not_equal, ¬_applicable);
4333 if (IsSimpleMapChangeTransition(from_kind, to_kind)) {
4334 Register new_map_reg = ToRegister(instr->new_map_temp());
4335 __ movq(new_map_reg, to_map, RelocInfo::EMBEDDED_OBJECT);
4336 __ movq(FieldOperand(object_reg, HeapObject::kMapOffset), new_map_reg);
4337 // Write barrier.
4338 ASSERT_NE(instr->temp(), NULL);
4339 __ RecordWriteField(object_reg, HeapObject::kMapOffset, new_map_reg,
4340 ToRegister(instr->temp()), kDontSaveFPRegs);
4341 } else {
4342 ASSERT(ToRegister(instr->context()).is(rsi));
4343 PushSafepointRegistersScope scope(this);
4344 if (!object_reg.is(rax)) {
4345 __ movq(rax, object_reg);
4346 }
4347 __ Move(rbx, to_map);
4348 TransitionElementsKindStub stub(from_kind, to_kind);
4349 __ CallStub(&stub);
4350 RecordSafepointWithRegisters(
4351 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4352 }
4353 __ bind(¬_applicable);
4354 }
4355
4356
DoTrapAllocationMemento(LTrapAllocationMemento * instr)4357 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4358 Register object = ToRegister(instr->object());
4359 Register temp = ToRegister(instr->temp());
4360 Label no_memento_found;
4361 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4362 DeoptimizeIf(equal, instr->environment());
4363 __ bind(&no_memento_found);
4364 }
4365
4366
DoStringAdd(LStringAdd * instr)4367 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4368 ASSERT(ToRegister(instr->context()).is(rsi));
4369 if (FLAG_new_string_add) {
4370 ASSERT(ToRegister(instr->left()).is(rdx));
4371 ASSERT(ToRegister(instr->right()).is(rax));
4372 NewStringAddStub stub(instr->hydrogen()->flags(),
4373 isolate()->heap()->GetPretenureMode());
4374 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
4375 } else {
4376 EmitPushTaggedOperand(instr->left());
4377 EmitPushTaggedOperand(instr->right());
4378 StringAddStub stub(instr->hydrogen()->flags());
4379 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
4380 }
4381 }
4382
4383
DoStringCharCodeAt(LStringCharCodeAt * instr)4384 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4385 class DeferredStringCharCodeAt V8_FINAL : public LDeferredCode {
4386 public:
4387 DeferredStringCharCodeAt(LCodeGen* codegen, LStringCharCodeAt* instr)
4388 : LDeferredCode(codegen), instr_(instr) { }
4389 virtual void Generate() V8_OVERRIDE {
4390 codegen()->DoDeferredStringCharCodeAt(instr_);
4391 }
4392 virtual LInstruction* instr() V8_OVERRIDE { return instr_; }
4393 private:
4394 LStringCharCodeAt* instr_;
4395 };
4396
4397 DeferredStringCharCodeAt* deferred =
4398 new(zone()) DeferredStringCharCodeAt(this, instr);
4399
4400 StringCharLoadGenerator::Generate(masm(),
4401 ToRegister(instr->string()),
4402 ToRegister(instr->index()),
4403 ToRegister(instr->result()),
4404 deferred->entry());
4405 __ bind(deferred->exit());
4406 }
4407
4408
DoDeferredStringCharCodeAt(LStringCharCodeAt * instr)4409 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4410 Register string = ToRegister(instr->string());
4411 Register result = ToRegister(instr->result());
4412
4413 // TODO(3095996): Get rid of this. For now, we need to make the
4414 // result register contain a valid pointer because it is already
4415 // contained in the register pointer map.
4416 __ Set(result, 0);
4417
4418 PushSafepointRegistersScope scope(this);
4419 __ push(string);
4420 // Push the index as a smi. This is safe because of the checks in
4421 // DoStringCharCodeAt above.
4422 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
4423 if (instr->index()->IsConstantOperand()) {
4424 int32_t const_index = ToInteger32(LConstantOperand::cast(instr->index()));
4425 __ Push(Smi::FromInt(const_index));
4426 } else {
4427 Register index = ToRegister(instr->index());
4428 __ Integer32ToSmi(index, index);
4429 __ push(index);
4430 }
4431 CallRuntimeFromDeferred(
4432 Runtime::kStringCharCodeAt, 2, instr, instr->context());
4433 __ AssertSmi(rax);
4434 __ SmiToInteger32(rax, rax);
4435 __ StoreToSafepointRegisterSlot(result, rax);
4436 }
4437
4438
DoStringCharFromCode(LStringCharFromCode * instr)4439 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4440 class DeferredStringCharFromCode V8_FINAL : public LDeferredCode {
4441 public:
4442 DeferredStringCharFromCode(LCodeGen* codegen, LStringCharFromCode* instr)
4443 : LDeferredCode(codegen), instr_(instr) { }
4444 virtual void Generate() V8_OVERRIDE {
4445 codegen()->DoDeferredStringCharFromCode(instr_);
4446 }
4447 virtual LInstruction* instr() V8_OVERRIDE { return instr_; }
4448 private:
4449 LStringCharFromCode* instr_;
4450 };
4451
4452 DeferredStringCharFromCode* deferred =
4453 new(zone()) DeferredStringCharFromCode(this, instr);
4454
4455 ASSERT(instr->hydrogen()->value()->representation().IsInteger32());
4456 Register char_code = ToRegister(instr->char_code());
4457 Register result = ToRegister(instr->result());
4458 ASSERT(!char_code.is(result));
4459
4460 __ cmpl(char_code, Immediate(String::kMaxOneByteCharCode));
4461 __ j(above, deferred->entry());
4462 __ movsxlq(char_code, char_code);
4463 __ LoadRoot(result, Heap::kSingleCharacterStringCacheRootIndex);
4464 __ movq(result, FieldOperand(result,
4465 char_code, times_pointer_size,
4466 FixedArray::kHeaderSize));
4467 __ CompareRoot(result, Heap::kUndefinedValueRootIndex);
4468 __ j(equal, deferred->entry());
4469 __ bind(deferred->exit());
4470 }
4471
4472
DoDeferredStringCharFromCode(LStringCharFromCode * instr)4473 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4474 Register char_code = ToRegister(instr->char_code());
4475 Register result = ToRegister(instr->result());
4476
4477 // TODO(3095996): Get rid of this. For now, we need to make the
4478 // result register contain a valid pointer because it is already
4479 // contained in the register pointer map.
4480 __ Set(result, 0);
4481
4482 PushSafepointRegistersScope scope(this);
4483 __ Integer32ToSmi(char_code, char_code);
4484 __ push(char_code);
4485 CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
4486 __ StoreToSafepointRegisterSlot(result, rax);
4487 }
4488
4489
DoInteger32ToDouble(LInteger32ToDouble * instr)4490 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4491 LOperand* input = instr->value();
4492 ASSERT(input->IsRegister() || input->IsStackSlot());
4493 LOperand* output = instr->result();
4494 ASSERT(output->IsDoubleRegister());
4495 if (input->IsRegister()) {
4496 __ Cvtlsi2sd(ToDoubleRegister(output), ToRegister(input));
4497 } else {
4498 __ Cvtlsi2sd(ToDoubleRegister(output), ToOperand(input));
4499 }
4500 }
4501
4502
DoInteger32ToSmi(LInteger32ToSmi * instr)4503 void LCodeGen::DoInteger32ToSmi(LInteger32ToSmi* instr) {
4504 LOperand* input = instr->value();
4505 ASSERT(input->IsRegister());
4506 LOperand* output = instr->result();
4507 __ Integer32ToSmi(ToRegister(output), ToRegister(input));
4508 if (!instr->hydrogen()->value()->HasRange() ||
4509 !instr->hydrogen()->value()->range()->IsInSmiRange()) {
4510 DeoptimizeIf(overflow, instr->environment());
4511 }
4512 }
4513
4514
DoUint32ToDouble(LUint32ToDouble * instr)4515 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4516 LOperand* input = instr->value();
4517 LOperand* output = instr->result();
4518 LOperand* temp = instr->temp();
4519
4520 __ LoadUint32(ToDoubleRegister(output),
4521 ToRegister(input),
4522 ToDoubleRegister(temp));
4523 }
4524
4525
DoUint32ToSmi(LUint32ToSmi * instr)4526 void LCodeGen::DoUint32ToSmi(LUint32ToSmi* instr) {
4527 LOperand* input = instr->value();
4528 ASSERT(input->IsRegister());
4529 LOperand* output = instr->result();
4530 if (!instr->hydrogen()->value()->HasRange() ||
4531 !instr->hydrogen()->value()->range()->IsInSmiRange() ||
4532 instr->hydrogen()->value()->range()->upper() == kMaxInt) {
4533 // The Range class can't express upper bounds in the (kMaxInt, kMaxUint32]
4534 // interval, so we treat kMaxInt as a sentinel for this entire interval.
4535 __ testl(ToRegister(input), Immediate(0x80000000));
4536 DeoptimizeIf(not_zero, instr->environment());
4537 }
4538 __ Integer32ToSmi(ToRegister(output), ToRegister(input));
4539 }
4540
4541
DoNumberTagI(LNumberTagI * instr)4542 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4543 LOperand* input = instr->value();
4544 ASSERT(input->IsRegister() && input->Equals(instr->result()));
4545 Register reg = ToRegister(input);
4546
4547 __ Integer32ToSmi(reg, reg);
4548 }
4549
4550
DoNumberTagU(LNumberTagU * instr)4551 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4552 class DeferredNumberTagU V8_FINAL : public LDeferredCode {
4553 public:
4554 DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4555 : LDeferredCode(codegen), instr_(instr) { }
4556 virtual void Generate() V8_OVERRIDE {
4557 codegen()->DoDeferredNumberTagU(instr_);
4558 }
4559 virtual LInstruction* instr() V8_OVERRIDE { return instr_; }
4560 private:
4561 LNumberTagU* instr_;
4562 };
4563
4564 LOperand* input = instr->value();
4565 ASSERT(input->IsRegister() && input->Equals(instr->result()));
4566 Register reg = ToRegister(input);
4567
4568 DeferredNumberTagU* deferred = new(zone()) DeferredNumberTagU(this, instr);
4569 __ cmpl(reg, Immediate(Smi::kMaxValue));
4570 __ j(above, deferred->entry());
4571 __ Integer32ToSmi(reg, reg);
4572 __ bind(deferred->exit());
4573 }
4574
4575
DoDeferredNumberTagU(LNumberTagU * instr)4576 void LCodeGen::DoDeferredNumberTagU(LNumberTagU* instr) {
4577 Label slow;
4578 Register reg = ToRegister(instr->value());
4579 Register tmp = reg.is(rax) ? rcx : rax;
4580 XMMRegister temp_xmm = ToDoubleRegister(instr->temp());
4581
4582 // Preserve the value of all registers.
4583 PushSafepointRegistersScope scope(this);
4584
4585 Label done;
4586 // Load value into temp_xmm which will be preserved across potential call to
4587 // runtime (MacroAssembler::EnterExitFrameEpilogue preserves only allocatable
4588 // XMM registers on x64).
4589 XMMRegister xmm_scratch = double_scratch0();
4590 __ LoadUint32(temp_xmm, reg, xmm_scratch);
4591
4592 if (FLAG_inline_new) {
4593 __ AllocateHeapNumber(reg, tmp, &slow);
4594 __ jmp(&done, Label::kNear);
4595 }
4596
4597 // Slow case: Call the runtime system to do the number allocation.
4598 __ bind(&slow);
4599
4600 // Put a valid pointer value in the stack slot where the result
4601 // register is stored, as this register is in the pointer map, but contains an
4602 // integer value.
4603 __ StoreToSafepointRegisterSlot(reg, Immediate(0));
4604
4605 // NumberTagU uses the context from the frame, rather than
4606 // the environment's HContext or HInlinedContext value.
4607 // They only call Runtime::kAllocateHeapNumber.
4608 // The corresponding HChange instructions are added in a phase that does
4609 // not have easy access to the local context.
4610 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4611 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4612 RecordSafepointWithRegisters(
4613 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4614
4615 if (!reg.is(rax)) __ movq(reg, rax);
4616
4617 // Done. Put the value in temp_xmm into the value of the allocated heap
4618 // number.
4619 __ bind(&done);
4620 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), temp_xmm);
4621 __ StoreToSafepointRegisterSlot(reg, reg);
4622 }
4623
4624
DoNumberTagD(LNumberTagD * instr)4625 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4626 class DeferredNumberTagD V8_FINAL : public LDeferredCode {
4627 public:
4628 DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4629 : LDeferredCode(codegen), instr_(instr) { }
4630 virtual void Generate() V8_OVERRIDE {
4631 codegen()->DoDeferredNumberTagD(instr_);
4632 }
4633 virtual LInstruction* instr() V8_OVERRIDE { return instr_; }
4634 private:
4635 LNumberTagD* instr_;
4636 };
4637
4638 XMMRegister input_reg = ToDoubleRegister(instr->value());
4639 Register reg = ToRegister(instr->result());
4640 Register tmp = ToRegister(instr->temp());
4641
4642 DeferredNumberTagD* deferred = new(zone()) DeferredNumberTagD(this, instr);
4643 if (FLAG_inline_new) {
4644 __ AllocateHeapNumber(reg, tmp, deferred->entry());
4645 } else {
4646 __ jmp(deferred->entry());
4647 }
4648 __ bind(deferred->exit());
4649 __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg);
4650 }
4651
4652
DoDeferredNumberTagD(LNumberTagD * instr)4653 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4654 // TODO(3095996): Get rid of this. For now, we need to make the
4655 // result register contain a valid pointer because it is already
4656 // contained in the register pointer map.
4657 Register reg = ToRegister(instr->result());
4658 __ Move(reg, Smi::FromInt(0));
4659
4660 {
4661 PushSafepointRegistersScope scope(this);
4662 // NumberTagD uses the context from the frame, rather than
4663 // the environment's HContext or HInlinedContext value.
4664 // They only call Runtime::kAllocateHeapNumber.
4665 // The corresponding HChange instructions are added in a phase that does
4666 // not have easy access to the local context.
4667 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
4668 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4669 RecordSafepointWithRegisters(
4670 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4671 __ movq(kScratchRegister, rax);
4672 }
4673 __ movq(reg, kScratchRegister);
4674 }
4675
4676
DoSmiTag(LSmiTag * instr)4677 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4678 ASSERT(instr->value()->Equals(instr->result()));
4679 Register input = ToRegister(instr->value());
4680 ASSERT(!instr->hydrogen_value()->CheckFlag(HValue::kCanOverflow));
4681 __ Integer32ToSmi(input, input);
4682 }
4683
4684
DoSmiUntag(LSmiUntag * instr)4685 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4686 ASSERT(instr->value()->Equals(instr->result()));
4687 Register input = ToRegister(instr->value());
4688 if (instr->needs_check()) {
4689 Condition is_smi = __ CheckSmi(input);
4690 DeoptimizeIf(NegateCondition(is_smi), instr->environment());
4691 } else {
4692 __ AssertSmi(input);
4693 }
4694 __ SmiToInteger32(input, input);
4695 }
4696
4697
EmitNumberUntagD(Register input_reg,XMMRegister result_reg,bool can_convert_undefined_to_nan,bool deoptimize_on_minus_zero,LEnvironment * env,NumberUntagDMode mode)4698 void LCodeGen::EmitNumberUntagD(Register input_reg,
4699 XMMRegister result_reg,
4700 bool can_convert_undefined_to_nan,
4701 bool deoptimize_on_minus_zero,
4702 LEnvironment* env,
4703 NumberUntagDMode mode) {
4704 Label convert, load_smi, done;
4705
4706 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4707 // Smi check.
4708 __ JumpIfSmi(input_reg, &load_smi, Label::kNear);
4709
4710 // Heap number map check.
4711 __ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset),
4712 Heap::kHeapNumberMapRootIndex);
4713
4714 // On x64 it is safe to load at heap number offset before evaluating the map
4715 // check, since all heap objects are at least two words long.
4716 __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset));
4717
4718 if (can_convert_undefined_to_nan) {
4719 __ j(not_equal, &convert, Label::kNear);
4720 } else {
4721 DeoptimizeIf(not_equal, env);
4722 }
4723
4724 if (deoptimize_on_minus_zero) {
4725 XMMRegister xmm_scratch = double_scratch0();
4726 __ xorps(xmm_scratch, xmm_scratch);
4727 __ ucomisd(xmm_scratch, result_reg);
4728 __ j(not_equal, &done, Label::kNear);
4729 __ movmskpd(kScratchRegister, result_reg);
4730 __ testq(kScratchRegister, Immediate(1));
4731 DeoptimizeIf(not_zero, env);
4732 }
4733 __ jmp(&done, Label::kNear);
4734
4735 if (can_convert_undefined_to_nan) {
4736 __ bind(&convert);
4737
4738 // Convert undefined (and hole) to NaN. Compute NaN as 0/0.
4739 __ CompareRoot(input_reg, Heap::kUndefinedValueRootIndex);
4740 DeoptimizeIf(not_equal, env);
4741
4742 __ xorps(result_reg, result_reg);
4743 __ divsd(result_reg, result_reg);
4744 __ jmp(&done, Label::kNear);
4745 }
4746 } else {
4747 ASSERT(mode == NUMBER_CANDIDATE_IS_SMI);
4748 }
4749
4750 // Smi to XMM conversion
4751 __ bind(&load_smi);
4752 __ SmiToInteger32(kScratchRegister, input_reg);
4753 __ Cvtlsi2sd(result_reg, kScratchRegister);
4754 __ bind(&done);
4755 }
4756
4757
DoDeferredTaggedToI(LTaggedToI * instr,Label * done)4758 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
4759 Register input_reg = ToRegister(instr->value());
4760
4761 if (instr->truncating()) {
4762 Label no_heap_number, check_bools, check_false;
4763
4764 // Heap number map check.
4765 __ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset),
4766 Heap::kHeapNumberMapRootIndex);
4767 __ j(not_equal, &no_heap_number, Label::kNear);
4768 __ TruncateHeapNumberToI(input_reg, input_reg);
4769 __ jmp(done);
4770
4771 __ bind(&no_heap_number);
4772 // Check for Oddballs. Undefined/False is converted to zero and True to one
4773 // for truncating conversions.
4774 __ CompareRoot(input_reg, Heap::kUndefinedValueRootIndex);
4775 __ j(not_equal, &check_bools, Label::kNear);
4776 __ Set(input_reg, 0);
4777 __ jmp(done);
4778
4779 __ bind(&check_bools);
4780 __ CompareRoot(input_reg, Heap::kTrueValueRootIndex);
4781 __ j(not_equal, &check_false, Label::kNear);
4782 __ Set(input_reg, 1);
4783 __ jmp(done);
4784
4785 __ bind(&check_false);
4786 __ CompareRoot(input_reg, Heap::kFalseValueRootIndex);
4787 __ RecordComment("Deferred TaggedToI: cannot truncate");
4788 DeoptimizeIf(not_equal, instr->environment());
4789 __ Set(input_reg, 0);
4790 __ jmp(done);
4791 } else {
4792 Label bailout;
4793 XMMRegister xmm_temp = ToDoubleRegister(instr->temp());
4794 __ TaggedToI(input_reg, input_reg, xmm_temp,
4795 instr->hydrogen()->GetMinusZeroMode(), &bailout, Label::kNear);
4796
4797 __ jmp(done);
4798 __ bind(&bailout);
4799 DeoptimizeIf(no_condition, instr->environment());
4800 }
4801 }
4802
4803
DoTaggedToI(LTaggedToI * instr)4804 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
4805 class DeferredTaggedToI V8_FINAL : public LDeferredCode {
4806 public:
4807 DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
4808 : LDeferredCode(codegen), instr_(instr) { }
4809 virtual void Generate() V8_OVERRIDE {
4810 codegen()->DoDeferredTaggedToI(instr_, done());
4811 }
4812 virtual LInstruction* instr() V8_OVERRIDE { return instr_; }
4813 private:
4814 LTaggedToI* instr_;
4815 };
4816
4817 LOperand* input = instr->value();
4818 ASSERT(input->IsRegister());
4819 ASSERT(input->Equals(instr->result()));
4820 Register input_reg = ToRegister(input);
4821
4822 if (instr->hydrogen()->value()->representation().IsSmi()) {
4823 __ SmiToInteger32(input_reg, input_reg);
4824 } else {
4825 DeferredTaggedToI* deferred = new(zone()) DeferredTaggedToI(this, instr);
4826 __ JumpIfNotSmi(input_reg, deferred->entry());
4827 __ SmiToInteger32(input_reg, input_reg);
4828 __ bind(deferred->exit());
4829 }
4830 }
4831
4832
DoNumberUntagD(LNumberUntagD * instr)4833 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4834 LOperand* input = instr->value();
4835 ASSERT(input->IsRegister());
4836 LOperand* result = instr->result();
4837 ASSERT(result->IsDoubleRegister());
4838
4839 Register input_reg = ToRegister(input);
4840 XMMRegister result_reg = ToDoubleRegister(result);
4841
4842 HValue* value = instr->hydrogen()->value();
4843 NumberUntagDMode mode = value->representation().IsSmi()
4844 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4845
4846 EmitNumberUntagD(input_reg, result_reg,
4847 instr->hydrogen()->can_convert_undefined_to_nan(),
4848 instr->hydrogen()->deoptimize_on_minus_zero(),
4849 instr->environment(),
4850 mode);
4851 }
4852
4853
DoDoubleToI(LDoubleToI * instr)4854 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
4855 LOperand* input = instr->value();
4856 ASSERT(input->IsDoubleRegister());
4857 LOperand* result = instr->result();
4858 ASSERT(result->IsRegister());
4859
4860 XMMRegister input_reg = ToDoubleRegister(input);
4861 Register result_reg = ToRegister(result);
4862
4863 if (instr->truncating()) {
4864 __ TruncateDoubleToI(result_reg, input_reg);
4865 } else {
4866 Label bailout, done;
4867 XMMRegister xmm_scratch = double_scratch0();
4868 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4869 instr->hydrogen()->GetMinusZeroMode(), &bailout, Label::kNear);
4870
4871 __ jmp(&done, Label::kNear);
4872 __ bind(&bailout);
4873 DeoptimizeIf(no_condition, instr->environment());
4874 __ bind(&done);
4875 }
4876 }
4877
4878
DoDoubleToSmi(LDoubleToSmi * instr)4879 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
4880 LOperand* input = instr->value();
4881 ASSERT(input->IsDoubleRegister());
4882 LOperand* result = instr->result();
4883 ASSERT(result->IsRegister());
4884
4885 XMMRegister input_reg = ToDoubleRegister(input);
4886 Register result_reg = ToRegister(result);
4887
4888 Label bailout, done;
4889 XMMRegister xmm_scratch = double_scratch0();
4890 __ DoubleToI(result_reg, input_reg, xmm_scratch,
4891 instr->hydrogen()->GetMinusZeroMode(), &bailout, Label::kNear);
4892
4893 __ jmp(&done, Label::kNear);
4894 __ bind(&bailout);
4895 DeoptimizeIf(no_condition, instr->environment());
4896 __ bind(&done);
4897
4898 __ Integer32ToSmi(result_reg, result_reg);
4899 DeoptimizeIf(overflow, instr->environment());
4900 }
4901
4902
DoCheckSmi(LCheckSmi * instr)4903 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
4904 LOperand* input = instr->value();
4905 Condition cc = masm()->CheckSmi(ToRegister(input));
4906 DeoptimizeIf(NegateCondition(cc), instr->environment());
4907 }
4908
4909
DoCheckNonSmi(LCheckNonSmi * instr)4910 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
4911 if (!instr->hydrogen()->value()->IsHeapObject()) {
4912 LOperand* input = instr->value();
4913 Condition cc = masm()->CheckSmi(ToRegister(input));
4914 DeoptimizeIf(cc, instr->environment());
4915 }
4916 }
4917
4918
DoCheckInstanceType(LCheckInstanceType * instr)4919 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
4920 Register input = ToRegister(instr->value());
4921
4922 __ movq(kScratchRegister, FieldOperand(input, HeapObject::kMapOffset));
4923
4924 if (instr->hydrogen()->is_interval_check()) {
4925 InstanceType first;
4926 InstanceType last;
4927 instr->hydrogen()->GetCheckInterval(&first, &last);
4928
4929 __ cmpb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset),
4930 Immediate(static_cast<int8_t>(first)));
4931
4932 // If there is only one type in the interval check for equality.
4933 if (first == last) {
4934 DeoptimizeIf(not_equal, instr->environment());
4935 } else {
4936 DeoptimizeIf(below, instr->environment());
4937 // Omit check for the last type.
4938 if (last != LAST_TYPE) {
4939 __ cmpb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset),
4940 Immediate(static_cast<int8_t>(last)));
4941 DeoptimizeIf(above, instr->environment());
4942 }
4943 }
4944 } else {
4945 uint8_t mask;
4946 uint8_t tag;
4947 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
4948
4949 if (IsPowerOf2(mask)) {
4950 ASSERT(tag == 0 || IsPowerOf2(tag));
4951 __ testb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset),
4952 Immediate(mask));
4953 DeoptimizeIf(tag == 0 ? not_zero : zero, instr->environment());
4954 } else {
4955 __ movzxbl(kScratchRegister,
4956 FieldOperand(kScratchRegister, Map::kInstanceTypeOffset));
4957 __ andb(kScratchRegister, Immediate(mask));
4958 __ cmpb(kScratchRegister, Immediate(tag));
4959 DeoptimizeIf(not_equal, instr->environment());
4960 }
4961 }
4962 }
4963
4964
DoCheckValue(LCheckValue * instr)4965 void LCodeGen::DoCheckValue(LCheckValue* instr) {
4966 Register reg = ToRegister(instr->value());
4967 __ Cmp(reg, instr->hydrogen()->object().handle());
4968 DeoptimizeIf(not_equal, instr->environment());
4969 }
4970
4971
DoDeferredInstanceMigration(LCheckMaps * instr,Register object)4972 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
4973 {
4974 PushSafepointRegistersScope scope(this);
4975 __ push(object);
4976 __ Set(rsi, 0);
4977 __ CallRuntimeSaveDoubles(Runtime::kMigrateInstance);
4978 RecordSafepointWithRegisters(
4979 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
4980
4981 __ testq(rax, Immediate(kSmiTagMask));
4982 }
4983 DeoptimizeIf(zero, instr->environment());
4984 }
4985
4986
DoCheckMaps(LCheckMaps * instr)4987 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
4988 class DeferredCheckMaps V8_FINAL : public LDeferredCode {
4989 public:
4990 DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr, Register object)
4991 : LDeferredCode(codegen), instr_(instr), object_(object) {
4992 SetExit(check_maps());
4993 }
4994 virtual void Generate() V8_OVERRIDE {
4995 codegen()->DoDeferredInstanceMigration(instr_, object_);
4996 }
4997 Label* check_maps() { return &check_maps_; }
4998 virtual LInstruction* instr() V8_OVERRIDE { return instr_; }
4999 private:
5000 LCheckMaps* instr_;
5001 Label check_maps_;
5002 Register object_;
5003 };
5004
5005 if (instr->hydrogen()->CanOmitMapChecks()) return;
5006
5007 LOperand* input = instr->value();
5008 ASSERT(input->IsRegister());
5009 Register reg = ToRegister(input);
5010
5011 DeferredCheckMaps* deferred = NULL;
5012 if (instr->hydrogen()->has_migration_target()) {
5013 deferred = new(zone()) DeferredCheckMaps(this, instr, reg);
5014 __ bind(deferred->check_maps());
5015 }
5016
5017 UniqueSet<Map> map_set = instr->hydrogen()->map_set();
5018 Label success;
5019 for (int i = 0; i < map_set.size() - 1; i++) {
5020 Handle<Map> map = map_set.at(i).handle();
5021 __ CompareMap(reg, map);
5022 __ j(equal, &success, Label::kNear);
5023 }
5024
5025 Handle<Map> map = map_set.at(map_set.size() - 1).handle();
5026 __ CompareMap(reg, map);
5027 if (instr->hydrogen()->has_migration_target()) {
5028 __ j(not_equal, deferred->entry());
5029 } else {
5030 DeoptimizeIf(not_equal, instr->environment());
5031 }
5032
5033 __ bind(&success);
5034 }
5035
5036
DoClampDToUint8(LClampDToUint8 * instr)5037 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5038 XMMRegister value_reg = ToDoubleRegister(instr->unclamped());
5039 XMMRegister xmm_scratch = double_scratch0();
5040 Register result_reg = ToRegister(instr->result());
5041 __ ClampDoubleToUint8(value_reg, xmm_scratch, result_reg);
5042 }
5043
5044
DoClampIToUint8(LClampIToUint8 * instr)5045 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5046 ASSERT(instr->unclamped()->Equals(instr->result()));
5047 Register value_reg = ToRegister(instr->result());
5048 __ ClampUint8(value_reg);
5049 }
5050
5051
DoClampTToUint8(LClampTToUint8 * instr)5052 void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
5053 ASSERT(instr->unclamped()->Equals(instr->result()));
5054 Register input_reg = ToRegister(instr->unclamped());
5055 XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm());
5056 XMMRegister xmm_scratch = double_scratch0();
5057 Label is_smi, done, heap_number;
5058 Label::Distance dist = DeoptEveryNTimes() ? Label::kFar : Label::kNear;
5059 __ JumpIfSmi(input_reg, &is_smi, dist);
5060
5061 // Check for heap number
5062 __ Cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
5063 factory()->heap_number_map());
5064 __ j(equal, &heap_number, Label::kNear);
5065
5066 // Check for undefined. Undefined is converted to zero for clamping
5067 // conversions.
5068 __ Cmp(input_reg, factory()->undefined_value());
5069 DeoptimizeIf(not_equal, instr->environment());
5070 __ movq(input_reg, Immediate(0));
5071 __ jmp(&done, Label::kNear);
5072
5073 // Heap number
5074 __ bind(&heap_number);
5075 __ movsd(xmm_scratch, FieldOperand(input_reg, HeapNumber::kValueOffset));
5076 __ ClampDoubleToUint8(xmm_scratch, temp_xmm_reg, input_reg);
5077 __ jmp(&done, Label::kNear);
5078
5079 // smi
5080 __ bind(&is_smi);
5081 __ SmiToInteger32(input_reg, input_reg);
5082 __ ClampUint8(input_reg);
5083
5084 __ bind(&done);
5085 }
5086
5087
DoAllocate(LAllocate * instr)5088 void LCodeGen::DoAllocate(LAllocate* instr) {
5089 class DeferredAllocate V8_FINAL : public LDeferredCode {
5090 public:
5091 DeferredAllocate(LCodeGen* codegen, LAllocate* instr)
5092 : LDeferredCode(codegen), instr_(instr) { }
5093 virtual void Generate() V8_OVERRIDE {
5094 codegen()->DoDeferredAllocate(instr_);
5095 }
5096 virtual LInstruction* instr() V8_OVERRIDE { return instr_; }
5097 private:
5098 LAllocate* instr_;
5099 };
5100
5101 DeferredAllocate* deferred =
5102 new(zone()) DeferredAllocate(this, instr);
5103
5104 Register result = ToRegister(instr->result());
5105 Register temp = ToRegister(instr->temp());
5106
5107 // Allocate memory for the object.
5108 AllocationFlags flags = TAG_OBJECT;
5109 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5110 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5111 }
5112 if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5113 ASSERT(!instr->hydrogen()->IsOldDataSpaceAllocation());
5114 ASSERT(!instr->hydrogen()->IsNewSpaceAllocation());
5115 flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_POINTER_SPACE);
5116 } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5117 ASSERT(!instr->hydrogen()->IsNewSpaceAllocation());
5118 flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_DATA_SPACE);
5119 }
5120
5121 if (instr->size()->IsConstantOperand()) {
5122 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5123 if (size <= Page::kMaxRegularHeapObjectSize) {
5124 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5125 } else {
5126 __ jmp(deferred->entry());
5127 }
5128 } else {
5129 Register size = ToRegister(instr->size());
5130 __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5131 }
5132
5133 __ bind(deferred->exit());
5134
5135 if (instr->hydrogen()->MustPrefillWithFiller()) {
5136 if (instr->size()->IsConstantOperand()) {
5137 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5138 __ movl(temp, Immediate((size / kPointerSize) - 1));
5139 } else {
5140 temp = ToRegister(instr->size());
5141 __ sar(temp, Immediate(kPointerSizeLog2));
5142 __ decl(temp);
5143 }
5144 Label loop;
5145 __ bind(&loop);
5146 __ Move(FieldOperand(result, temp, times_pointer_size, 0),
5147 isolate()->factory()->one_pointer_filler_map());
5148 __ decl(temp);
5149 __ j(not_zero, &loop);
5150 }
5151 }
5152
5153
DoDeferredAllocate(LAllocate * instr)5154 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
5155 Register result = ToRegister(instr->result());
5156
5157 // TODO(3095996): Get rid of this. For now, we need to make the
5158 // result register contain a valid pointer because it is already
5159 // contained in the register pointer map.
5160 __ Move(result, Smi::FromInt(0));
5161
5162 PushSafepointRegistersScope scope(this);
5163 if (instr->size()->IsRegister()) {
5164 Register size = ToRegister(instr->size());
5165 ASSERT(!size.is(result));
5166 __ Integer32ToSmi(size, size);
5167 __ push(size);
5168 } else {
5169 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5170 __ Push(Smi::FromInt(size));
5171 }
5172
5173 int flags = 0;
5174 if (instr->hydrogen()->IsOldPointerSpaceAllocation()) {
5175 ASSERT(!instr->hydrogen()->IsOldDataSpaceAllocation());
5176 ASSERT(!instr->hydrogen()->IsNewSpaceAllocation());
5177 flags = AllocateTargetSpace::update(flags, OLD_POINTER_SPACE);
5178 } else if (instr->hydrogen()->IsOldDataSpaceAllocation()) {
5179 ASSERT(!instr->hydrogen()->IsNewSpaceAllocation());
5180 flags = AllocateTargetSpace::update(flags, OLD_DATA_SPACE);
5181 } else {
5182 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
5183 }
5184 __ Push(Smi::FromInt(flags));
5185
5186 CallRuntimeFromDeferred(
5187 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
5188 __ StoreToSafepointRegisterSlot(result, rax);
5189 }
5190
5191
DoToFastProperties(LToFastProperties * instr)5192 void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5193 ASSERT(ToRegister(instr->value()).is(rax));
5194 __ push(rax);
5195 CallRuntime(Runtime::kToFastProperties, 1, instr);
5196 }
5197
5198
DoRegExpLiteral(LRegExpLiteral * instr)5199 void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5200 ASSERT(ToRegister(instr->context()).is(rsi));
5201 Label materialized;
5202 // Registers will be used as follows:
5203 // rcx = literals array.
5204 // rbx = regexp literal.
5205 // rax = regexp literal clone.
5206 int literal_offset =
5207 FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
5208 __ Move(rcx, instr->hydrogen()->literals());
5209 __ movq(rbx, FieldOperand(rcx, literal_offset));
5210 __ CompareRoot(rbx, Heap::kUndefinedValueRootIndex);
5211 __ j(not_equal, &materialized, Label::kNear);
5212
5213 // Create regexp literal using runtime function
5214 // Result will be in rax.
5215 __ push(rcx);
5216 __ Push(Smi::FromInt(instr->hydrogen()->literal_index()));
5217 __ Push(instr->hydrogen()->pattern());
5218 __ Push(instr->hydrogen()->flags());
5219 CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
5220 __ movq(rbx, rax);
5221
5222 __ bind(&materialized);
5223 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
5224 Label allocated, runtime_allocate;
5225 __ Allocate(size, rax, rcx, rdx, &runtime_allocate, TAG_OBJECT);
5226 __ jmp(&allocated, Label::kNear);
5227
5228 __ bind(&runtime_allocate);
5229 __ push(rbx);
5230 __ Push(Smi::FromInt(size));
5231 CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
5232 __ pop(rbx);
5233
5234 __ bind(&allocated);
5235 // Copy the content into the newly allocated memory.
5236 // (Unroll copy loop once for better throughput).
5237 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
5238 __ movq(rdx, FieldOperand(rbx, i));
5239 __ movq(rcx, FieldOperand(rbx, i + kPointerSize));
5240 __ movq(FieldOperand(rax, i), rdx);
5241 __ movq(FieldOperand(rax, i + kPointerSize), rcx);
5242 }
5243 if ((size % (2 * kPointerSize)) != 0) {
5244 __ movq(rdx, FieldOperand(rbx, size - kPointerSize));
5245 __ movq(FieldOperand(rax, size - kPointerSize), rdx);
5246 }
5247 }
5248
5249
DoFunctionLiteral(LFunctionLiteral * instr)5250 void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5251 ASSERT(ToRegister(instr->context()).is(rsi));
5252 // Use the fast case closure allocation code that allocates in new
5253 // space for nested functions that don't need literals cloning.
5254 bool pretenure = instr->hydrogen()->pretenure();
5255 if (!pretenure && instr->hydrogen()->has_no_literals()) {
5256 FastNewClosureStub stub(instr->hydrogen()->language_mode(),
5257 instr->hydrogen()->is_generator());
5258 __ Move(rbx, instr->hydrogen()->shared_info());
5259 CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
5260 } else {
5261 __ push(rsi);
5262 __ Push(instr->hydrogen()->shared_info());
5263 __ PushRoot(pretenure ? Heap::kTrueValueRootIndex :
5264 Heap::kFalseValueRootIndex);
5265 CallRuntime(Runtime::kNewClosure, 3, instr);
5266 }
5267 }
5268
5269
DoTypeof(LTypeof * instr)5270 void LCodeGen::DoTypeof(LTypeof* instr) {
5271 ASSERT(ToRegister(instr->context()).is(rsi));
5272 LOperand* input = instr->value();
5273 EmitPushTaggedOperand(input);
5274 CallRuntime(Runtime::kTypeof, 1, instr);
5275 }
5276
5277
EmitPushTaggedOperand(LOperand * operand)5278 void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
5279 ASSERT(!operand->IsDoubleRegister());
5280 if (operand->IsConstantOperand()) {
5281 __ Push(ToHandle(LConstantOperand::cast(operand)));
5282 } else if (operand->IsRegister()) {
5283 __ push(ToRegister(operand));
5284 } else {
5285 __ push(ToOperand(operand));
5286 }
5287 }
5288
5289
DoTypeofIsAndBranch(LTypeofIsAndBranch * instr)5290 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5291 Register input = ToRegister(instr->value());
5292 Condition final_branch_condition = EmitTypeofIs(instr, input);
5293 if (final_branch_condition != no_condition) {
5294 EmitBranch(instr, final_branch_condition);
5295 }
5296 }
5297
5298
EmitTypeofIs(LTypeofIsAndBranch * instr,Register input)5299 Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
5300 Label* true_label = instr->TrueLabel(chunk_);
5301 Label* false_label = instr->FalseLabel(chunk_);
5302 Handle<String> type_name = instr->type_literal();
5303 int left_block = instr->TrueDestination(chunk_);
5304 int right_block = instr->FalseDestination(chunk_);
5305 int next_block = GetNextEmittedBlock();
5306
5307 Label::Distance true_distance = left_block == next_block ? Label::kNear
5308 : Label::kFar;
5309 Label::Distance false_distance = right_block == next_block ? Label::kNear
5310 : Label::kFar;
5311 Condition final_branch_condition = no_condition;
5312 if (type_name->Equals(heap()->number_string())) {
5313 __ JumpIfSmi(input, true_label, true_distance);
5314 __ CompareRoot(FieldOperand(input, HeapObject::kMapOffset),
5315 Heap::kHeapNumberMapRootIndex);
5316
5317 final_branch_condition = equal;
5318
5319 } else if (type_name->Equals(heap()->string_string())) {
5320 __ JumpIfSmi(input, false_label, false_distance);
5321 __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
5322 __ j(above_equal, false_label, false_distance);
5323 __ testb(FieldOperand(input, Map::kBitFieldOffset),
5324 Immediate(1 << Map::kIsUndetectable));
5325 final_branch_condition = zero;
5326
5327 } else if (type_name->Equals(heap()->symbol_string())) {
5328 __ JumpIfSmi(input, false_label, false_distance);
5329 __ CmpObjectType(input, SYMBOL_TYPE, input);
5330 final_branch_condition = equal;
5331
5332 } else if (type_name->Equals(heap()->boolean_string())) {
5333 __ CompareRoot(input, Heap::kTrueValueRootIndex);
5334 __ j(equal, true_label, true_distance);
5335 __ CompareRoot(input, Heap::kFalseValueRootIndex);
5336 final_branch_condition = equal;
5337
5338 } else if (FLAG_harmony_typeof && type_name->Equals(heap()->null_string())) {
5339 __ CompareRoot(input, Heap::kNullValueRootIndex);
5340 final_branch_condition = equal;
5341
5342 } else if (type_name->Equals(heap()->undefined_string())) {
5343 __ CompareRoot(input, Heap::kUndefinedValueRootIndex);
5344 __ j(equal, true_label, true_distance);
5345 __ JumpIfSmi(input, false_label, false_distance);
5346 // Check for undetectable objects => true.
5347 __ movq(input, FieldOperand(input, HeapObject::kMapOffset));
5348 __ testb(FieldOperand(input, Map::kBitFieldOffset),
5349 Immediate(1 << Map::kIsUndetectable));
5350 final_branch_condition = not_zero;
5351
5352 } else if (type_name->Equals(heap()->function_string())) {
5353 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5354 __ JumpIfSmi(input, false_label, false_distance);
5355 __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
5356 __ j(equal, true_label, true_distance);
5357 __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
5358 final_branch_condition = equal;
5359
5360 } else if (type_name->Equals(heap()->object_string())) {
5361 __ JumpIfSmi(input, false_label, false_distance);
5362 if (!FLAG_harmony_typeof) {
5363 __ CompareRoot(input, Heap::kNullValueRootIndex);
5364 __ j(equal, true_label, true_distance);
5365 }
5366 __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
5367 __ j(below, false_label, false_distance);
5368 __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
5369 __ j(above, false_label, false_distance);
5370 // Check for undetectable objects => false.
5371 __ testb(FieldOperand(input, Map::kBitFieldOffset),
5372 Immediate(1 << Map::kIsUndetectable));
5373 final_branch_condition = zero;
5374
5375 } else {
5376 __ jmp(false_label, false_distance);
5377 }
5378
5379 return final_branch_condition;
5380 }
5381
5382
DoIsConstructCallAndBranch(LIsConstructCallAndBranch * instr)5383 void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
5384 Register temp = ToRegister(instr->temp());
5385
5386 EmitIsConstructCall(temp);
5387 EmitBranch(instr, equal);
5388 }
5389
5390
EmitIsConstructCall(Register temp)5391 void LCodeGen::EmitIsConstructCall(Register temp) {
5392 // Get the frame pointer for the calling frame.
5393 __ movq(temp, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
5394
5395 // Skip the arguments adaptor frame if it exists.
5396 Label check_frame_marker;
5397 __ Cmp(Operand(temp, StandardFrameConstants::kContextOffset),
5398 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
5399 __ j(not_equal, &check_frame_marker, Label::kNear);
5400 __ movq(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));
5401
5402 // Check the marker in the calling frame.
5403 __ bind(&check_frame_marker);
5404 __ Cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
5405 Smi::FromInt(StackFrame::CONSTRUCT));
5406 }
5407
5408
EnsureSpaceForLazyDeopt(int space_needed)5409 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
5410 if (info()->IsStub()) return;
5411 // Ensure that we have enough space after the previous lazy-bailout
5412 // instruction for patching the code here.
5413 int current_pc = masm()->pc_offset();
5414 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
5415 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
5416 __ Nop(padding_size);
5417 }
5418 }
5419
5420
DoLazyBailout(LLazyBailout * instr)5421 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
5422 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5423 last_lazy_deopt_pc_ = masm()->pc_offset();
5424 ASSERT(instr->HasEnvironment());
5425 LEnvironment* env = instr->environment();
5426 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5427 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5428 }
5429
5430
DoDeoptimize(LDeoptimize * instr)5431 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
5432 Deoptimizer::BailoutType type = instr->hydrogen()->type();
5433 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
5434 // needed return address), even though the implementation of LAZY and EAGER is
5435 // now identical. When LAZY is eventually completely folded into EAGER, remove
5436 // the special case below.
5437 if (info()->IsStub() && type == Deoptimizer::EAGER) {
5438 type = Deoptimizer::LAZY;
5439 }
5440
5441 Comment(";;; deoptimize: %s", instr->hydrogen()->reason());
5442 DeoptimizeIf(no_condition, instr->environment(), type);
5443 }
5444
5445
DoDummy(LDummy * instr)5446 void LCodeGen::DoDummy(LDummy* instr) {
5447 // Nothing to see here, move on!
5448 }
5449
5450
DoDummyUse(LDummyUse * instr)5451 void LCodeGen::DoDummyUse(LDummyUse* instr) {
5452 // Nothing to see here, move on!
5453 }
5454
5455
DoDeferredStackCheck(LStackCheck * instr)5456 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5457 PushSafepointRegistersScope scope(this);
5458 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
5459 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5460 RecordSafepointWithLazyDeopt(instr, RECORD_SAFEPOINT_WITH_REGISTERS, 0);
5461 ASSERT(instr->HasEnvironment());
5462 LEnvironment* env = instr->environment();
5463 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5464 }
5465
5466
DoStackCheck(LStackCheck * instr)5467 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5468 class DeferredStackCheck V8_FINAL : public LDeferredCode {
5469 public:
5470 DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5471 : LDeferredCode(codegen), instr_(instr) { }
5472 virtual void Generate() V8_OVERRIDE {
5473 codegen()->DoDeferredStackCheck(instr_);
5474 }
5475 virtual LInstruction* instr() V8_OVERRIDE { return instr_; }
5476 private:
5477 LStackCheck* instr_;
5478 };
5479
5480 ASSERT(instr->HasEnvironment());
5481 LEnvironment* env = instr->environment();
5482 // There is no LLazyBailout instruction for stack-checks. We have to
5483 // prepare for lazy deoptimization explicitly here.
5484 if (instr->hydrogen()->is_function_entry()) {
5485 // Perform stack overflow check.
5486 Label done;
5487 __ CompareRoot(rsp, Heap::kStackLimitRootIndex);
5488 __ j(above_equal, &done, Label::kNear);
5489
5490 ASSERT(instr->context()->IsRegister());
5491 ASSERT(ToRegister(instr->context()).is(rsi));
5492 CallCode(isolate()->builtins()->StackCheck(),
5493 RelocInfo::CODE_TARGET,
5494 instr);
5495 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5496 last_lazy_deopt_pc_ = masm()->pc_offset();
5497 __ bind(&done);
5498 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5499 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5500 } else {
5501 ASSERT(instr->hydrogen()->is_backwards_branch());
5502 // Perform stack overflow check if this goto needs it before jumping.
5503 DeferredStackCheck* deferred_stack_check =
5504 new(zone()) DeferredStackCheck(this, instr);
5505 __ CompareRoot(rsp, Heap::kStackLimitRootIndex);
5506 __ j(below, deferred_stack_check->entry());
5507 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5508 last_lazy_deopt_pc_ = masm()->pc_offset();
5509 __ bind(instr->done_label());
5510 deferred_stack_check->SetExit(instr->done_label());
5511 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5512 // Don't record a deoptimization index for the safepoint here.
5513 // This will be done explicitly when emitting call and the safepoint in
5514 // the deferred code.
5515 }
5516 }
5517
5518
DoOsrEntry(LOsrEntry * instr)5519 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
5520 // This is a pseudo-instruction that ensures that the environment here is
5521 // properly registered for deoptimization and records the assembler's PC
5522 // offset.
5523 LEnvironment* environment = instr->environment();
5524
5525 // If the environment were already registered, we would have no way of
5526 // backpatching it with the spill slot operands.
5527 ASSERT(!environment->HasBeenRegistered());
5528 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
5529
5530 GenerateOsrPrologue();
5531 }
5532
5533
DoForInPrepareMap(LForInPrepareMap * instr)5534 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
5535 ASSERT(ToRegister(instr->context()).is(rsi));
5536 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
5537 DeoptimizeIf(equal, instr->environment());
5538
5539 Register null_value = rdi;
5540 __ LoadRoot(null_value, Heap::kNullValueRootIndex);
5541 __ cmpq(rax, null_value);
5542 DeoptimizeIf(equal, instr->environment());
5543
5544 Condition cc = masm()->CheckSmi(rax);
5545 DeoptimizeIf(cc, instr->environment());
5546
5547 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
5548 __ CmpObjectType(rax, LAST_JS_PROXY_TYPE, rcx);
5549 DeoptimizeIf(below_equal, instr->environment());
5550
5551 Label use_cache, call_runtime;
5552 __ CheckEnumCache(null_value, &call_runtime);
5553
5554 __ movq(rax, FieldOperand(rax, HeapObject::kMapOffset));
5555 __ jmp(&use_cache, Label::kNear);
5556
5557 // Get the set of properties to enumerate.
5558 __ bind(&call_runtime);
5559 __ push(rax);
5560 CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
5561
5562 __ CompareRoot(FieldOperand(rax, HeapObject::kMapOffset),
5563 Heap::kMetaMapRootIndex);
5564 DeoptimizeIf(not_equal, instr->environment());
5565 __ bind(&use_cache);
5566 }
5567
5568
DoForInCacheArray(LForInCacheArray * instr)5569 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
5570 Register map = ToRegister(instr->map());
5571 Register result = ToRegister(instr->result());
5572 Label load_cache, done;
5573 __ EnumLength(result, map);
5574 __ Cmp(result, Smi::FromInt(0));
5575 __ j(not_equal, &load_cache, Label::kNear);
5576 __ LoadRoot(result, Heap::kEmptyFixedArrayRootIndex);
5577 __ jmp(&done, Label::kNear);
5578 __ bind(&load_cache);
5579 __ LoadInstanceDescriptors(map, result);
5580 __ movq(result,
5581 FieldOperand(result, DescriptorArray::kEnumCacheOffset));
5582 __ movq(result,
5583 FieldOperand(result, FixedArray::SizeFor(instr->idx())));
5584 __ bind(&done);
5585 Condition cc = masm()->CheckSmi(result);
5586 DeoptimizeIf(cc, instr->environment());
5587 }
5588
5589
DoCheckMapValue(LCheckMapValue * instr)5590 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
5591 Register object = ToRegister(instr->value());
5592 __ cmpq(ToRegister(instr->map()),
5593 FieldOperand(object, HeapObject::kMapOffset));
5594 DeoptimizeIf(not_equal, instr->environment());
5595 }
5596
5597
DoLoadFieldByIndex(LLoadFieldByIndex * instr)5598 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
5599 Register object = ToRegister(instr->object());
5600 Register index = ToRegister(instr->index());
5601
5602 Label out_of_object, done;
5603 __ SmiToInteger32(index, index);
5604 __ cmpl(index, Immediate(0));
5605 __ j(less, &out_of_object, Label::kNear);
5606 __ movq(object, FieldOperand(object,
5607 index,
5608 times_pointer_size,
5609 JSObject::kHeaderSize));
5610 __ jmp(&done, Label::kNear);
5611
5612 __ bind(&out_of_object);
5613 __ movq(object, FieldOperand(object, JSObject::kPropertiesOffset));
5614 __ negl(index);
5615 // Index is now equal to out of object property index plus 1.
5616 __ movq(object, FieldOperand(object,
5617 index,
5618 times_pointer_size,
5619 FixedArray::kHeaderSize - kPointerSize));
5620 __ bind(&done);
5621 }
5622
5623
5624 #undef __
5625
5626 } } // namespace v8::internal
5627
5628 #endif // V8_TARGET_ARCH_X64
5629