lithium-codegen-x64.cc 192 KB
Newer Older
1
// Copyright 2013 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

28 29 30 31
#include "v8.h"

#if defined(V8_TARGET_ARCH_X64)

32 33 34 35 36 37 38 39
#include "x64/lithium-codegen-x64.h"
#include "code-stubs.h"
#include "stub-cache.h"

namespace v8 {
namespace internal {


40 41
// When invoking builtins, we need to record the safepoint in the middle of
// the invoke instruction sequence generated by the macro assembler.
lrn@chromium.org's avatar
lrn@chromium.org committed
42
class SafepointGenerator : public CallWrapper {
43 44 45
 public:
  SafepointGenerator(LCodeGen* codegen,
                     LPointerMap* pointers,
46
                     Safepoint::DeoptMode mode)
47 48
      : codegen_(codegen),
        pointers_(pointers),
49
        deopt_mode_(mode) { }
50 51
  virtual ~SafepointGenerator() { }

52 53 54
  virtual void BeforeCall(int call_size) const {
    codegen_->EnsureSpaceForLazyDeopt(Deoptimizer::patch_size() - call_size);
  }
lrn@chromium.org's avatar
lrn@chromium.org committed
55

56
  virtual void AfterCall() const {
57
    codegen_->RecordSafepoint(pointers_, deopt_mode_);
58 59 60 61 62
  }

 private:
  LCodeGen* codegen_;
  LPointerMap* pointers_;
63
  Safepoint::DeoptMode deopt_mode_;
64 65 66
};


67 68
#define __ masm()->

69
bool LCodeGen::GenerateCode() {
70
  HPhase phase("Z_Code generation", chunk());
71 72
  ASSERT(is_unused());
  status_ = GENERATING;
73 74 75

  // Open a frame scope to indicate that there is a frame on the stack.  The
  // MANUAL indicates that the scope shouldn't actually generate code to set up
76
  // the frame (that is done in GeneratePrologue).
77 78
  FrameScope frame_scope(masm_, StackFrame::MANUAL);

79 80 81
  return GeneratePrologue() &&
      GenerateBody() &&
      GenerateDeferredCode() &&
82
      GenerateJumpTable() &&
83 84 85 86 87 88
      GenerateSafepointTable();
}


void LCodeGen::FinishCode(Handle<Code> code) {
  ASSERT(is_done());
89
  code->set_stack_slots(GetStackSlotCount());
90
  code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
91 92 93
  if (FLAG_weak_embedded_maps_in_optimized_code) {
    RegisterDependentCodeForEmbeddedMaps(code);
  }
94
  PopulateDeoptimizationData(code);
95 96 97 98
  for (int i = 0 ; i < prototype_maps_.length(); i++) {
    prototype_maps_.at(i)->AddDependentCode(
        DependentCode::kPrototypeCheckGroup, code);
  }
99 100 101
}


102 103
void LChunkBuilder::Abort(const char* reason) {
  info()->set_bailout_reason(reason);
104 105 106 107 108
  status_ = ABORTED;
}


void LCodeGen::Comment(const char* format, ...) {
109 110 111 112 113 114 115 116 117 118
  if (!FLAG_code_comments) return;
  char buffer[4 * KB];
  StringBuilder builder(buffer, ARRAY_SIZE(buffer));
  va_list arguments;
  va_start(arguments, format);
  builder.AddFormattedList(format, arguments);
  va_end(arguments);

  // Copy the string before recording it in the assembler to avoid
  // issues when the stack allocated buffer goes out of scope.
119
  int length = builder.position();
120
  Vector<char> copy = Vector<char>::New(length + 1);
121
  OS::MemCopy(copy.start(), builder.Finalize(), copy.length());
122
  masm()->RecordComment(copy.start());
123 124 125 126
}


bool LCodeGen::GeneratePrologue() {
127 128
  ASSERT(is_generating());

129 130
  if (info()->IsOptimizing()) {
    ProfileEntryHookStub::MaybeCallEntryHook(masm_);
131

132
#ifdef DEBUG
133
    if (strlen(FLAG_stop_at) > 0 &&
134
        info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
135 136
      __ int3();
    }
137 138
#endif

139 140 141 142 143 144 145 146 147 148 149 150 151 152
    // Strict mode functions need to replace the receiver with undefined
    // when called as functions (without an explicit receiver
    // object). rcx is zero for method calls and non-zero for function
    // calls.
    if (!info_->is_classic_mode() || info_->is_native()) {
      Label ok;
      __ testq(rcx, rcx);
      __ j(zero, &ok, Label::kNear);
      // +1 for return address.
      int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
      __ LoadRoot(kScratchRegister, Heap::kUndefinedValueRootIndex);
      __ movq(Operand(rsp, receiver_offset), kScratchRegister);
      __ bind(&ok);
    }
153 154
  }

155
  info()->set_prologue_offset(masm_->pc_offset());
156 157 158 159 160 161 162 163 164 165 166 167
  if (NeedsEagerFrame()) {
    ASSERT(!frame_is_built_);
    frame_is_built_ = true;
    __ push(rbp);  // Caller's frame pointer.
    __ movq(rbp, rsp);
    __ push(rsi);  // Callee's context.
    if (info()->IsStub()) {
      __ Push(Smi::FromInt(StackFrame::STUB));
    } else {
      __ push(rdi);  // Callee's JS function.
    }
  }
168 169

  // Reserve space for the stack slots needed by the code.
170
  int slots = GetStackSlotCount();
171 172
  if (slots > 0) {
    if (FLAG_debug_code) {
173 174
      __ subq(rsp, Immediate(slots * kPointerSize));
      __ push(rax);
175
      __ Set(rax, slots);
176
      __ movq(kScratchRegister, kSlotsZapValue, RelocInfo::NONE64);
177 178
      Label loop;
      __ bind(&loop);
179 180
      __ movq(MemOperand(rsp, rax, times_pointer_size, 0),
              kScratchRegister);
181 182
      __ decl(rax);
      __ j(not_zero, &loop);
183
      __ pop(rax);
184 185 186 187 188 189 190 191 192 193
    } else {
      __ subq(rsp, Immediate(slots * kPointerSize));
#ifdef _MSC_VER
      // On windows, you may not access the stack more than one page below
      // the most recently mapped page. To make the allocated area randomly
      // accessible, we write to each page in turn (the value is irrelevant).
      const int kPageSize = 4 * KB;
      for (int offset = slots * kPointerSize - kPageSize;
           offset > 0;
           offset -= kPageSize) {
194
        __ movq(Operand(rsp, offset), rax);
195 196 197
      }
#endif
    }
198 199 200 201 202 203 204 205 206 207 208 209 210

    if (info()->saves_caller_doubles()) {
      Comment(";;; Save clobbered callee double registers");
      int count = 0;
      BitVector* doubles = chunk()->allocated_double_registers();
      BitVector::Iterator save_iterator(doubles);
      while (!save_iterator.Done()) {
        __ movsd(MemOperand(rsp, count * kDoubleSize),
                 XMMRegister::FromAllocationIndex(save_iterator.Current()));
        save_iterator.Advance();
        count++;
      }
    }
211 212
  }

213
  // Possibly allocate a local context.
214
  int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
215 216 217 218 219 220 221 222
  if (heap_slots > 0) {
    Comment(";;; Allocate local context");
    // Argument to NewContext is the function, which is still in rdi.
    __ push(rdi);
    if (heap_slots <= FastNewContextStub::kMaximumSlots) {
      FastNewContextStub stub(heap_slots);
      __ CallStub(&stub);
    } else {
223
      __ CallRuntime(Runtime::kNewFunctionContext, 1);
224
    }
225
    RecordSafepoint(Safepoint::kNoLazyDeopt);
226 227 228 229 230 231 232
    // Context is returned in both rax and rsi.  It replaces the context
    // passed to us.  It's saved in the stack and kept live in rsi.
    __ movq(Operand(rbp, StandardFrameConstants::kContextOffset), rsi);

    // Copy any necessary parameters into the context.
    int num_parameters = scope()->num_parameters();
    for (int i = 0; i < num_parameters; i++) {
233 234
      Variable* var = scope()->parameter(i);
      if (var->IsContextSlot()) {
235 236 237 238 239
        int parameter_offset = StandardFrameConstants::kCallerSPOffset +
            (num_parameters - 1 - i) * kPointerSize;
        // Load parameter from stack.
        __ movq(rax, Operand(rbp, parameter_offset));
        // Store it in the context.
240
        int context_offset = Context::SlotOffset(var->index());
241
        __ movq(Operand(rsi, context_offset), rax);
242 243
        // Update the write barrier. This clobbers rax and rbx.
        __ RecordWriteContextSlot(rsi, context_offset, rax, rbx, kSaveFPRegs);
244 245 246 247 248
      }
    }
    Comment(";;; End allocate local context");
  }

249
  // Trace the call.
250
  if (FLAG_trace && info()->IsOptimizing()) {
251 252 253
    __ CallRuntime(Runtime::kTraceEnter, 0);
  }
  return !is_aborted();
254 255 256 257 258 259 260 261 262 263
}


bool LCodeGen::GenerateBody() {
  ASSERT(is_generating());
  bool emit_instructions = true;
  for (current_instruction_ = 0;
       !is_aborted() && current_instruction_ < instructions_->length();
       current_instruction_++) {
    LInstruction* instr = instructions_->at(current_instruction_);
264 265

    // Don't emit code for basic blocks with a replacement.
266
    if (instr->IsLabel()) {
267
      emit_instructions = !LLabel::cast(instr)->HasReplacement();
268
    }
269
    if (!emit_instructions) continue;
270

271 272 273 274 275
    if (FLAG_code_comments && instr->HasInterestingComment(this)) {
      Comment(";;; <@%d,#%d> %s",
              current_instruction_,
              instr->hydrogen_value()->id(),
              instr->Mnemonic());
276
    }
277 278

    instr->CompileToNative(this);
279
  }
280
  EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
281 282 283 284
  return !is_aborted();
}


285
bool LCodeGen::GenerateJumpTable() {
286 287
  Label needs_frame_not_call;
  Label needs_frame_is_call;
288 289 290
  if (jump_table_.length() > 0) {
    Comment(";;; -------------------- Jump table --------------------");
  }
291
  for (int i = 0; i < jump_table_.length(); i++) {
292
    __ bind(&jump_table_[i].label);
293
    Address entry = jump_table_[i].address;
294 295 296
    bool is_lazy_deopt = jump_table_[i].is_lazy_deopt;
    Deoptimizer::BailoutType type =
        is_lazy_deopt ? Deoptimizer::LAZY : Deoptimizer::EAGER;
297
    int id = Deoptimizer::GetDeoptimizationId(isolate(), entry, type);
298 299 300 301 302
    if (id == Deoptimizer::kNotDeoptimizationEntry) {
      Comment(";;; jump table entry %d.", i);
    } else {
      Comment(";;; jump table entry %d: deoptimization bailout %d.", i, id);
    }
303 304
    if (jump_table_[i].needs_frame) {
      __ movq(kScratchRegister, ExternalReference::ForDeoptEntry(entry));
305
      if (is_lazy_deopt) {
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
        if (needs_frame_is_call.is_bound()) {
          __ jmp(&needs_frame_is_call);
        } else {
          __ bind(&needs_frame_is_call);
          __ push(rbp);
          __ movq(rbp, rsp);
          __ push(rsi);
          // This variant of deopt can only be used with stubs. Since we don't
          // have a function pointer to install in the stack frame that we're
          // building, install a special marker there instead.
          ASSERT(info()->IsStub());
          __ Move(rsi, Smi::FromInt(StackFrame::STUB));
          __ push(rsi);
          __ movq(rsi, MemOperand(rsp, kPointerSize));
          __ call(kScratchRegister);
        }
      } else {
        if (needs_frame_not_call.is_bound()) {
          __ jmp(&needs_frame_not_call);
        } else {
          __ bind(&needs_frame_not_call);
          __ push(rbp);
          __ movq(rbp, rsp);
          __ push(rsi);
          // This variant of deopt can only be used with stubs. Since we don't
          // have a function pointer to install in the stack frame that we're
          // building, install a special marker there instead.
          ASSERT(info()->IsStub());
          __ Move(rsi, Smi::FromInt(StackFrame::STUB));
          __ push(rsi);
          __ movq(rsi, MemOperand(rsp, kPointerSize));
          __ jmp(kScratchRegister);
        }
      }
    } else {
341
      if (is_lazy_deopt) {
342
        __ call(entry, RelocInfo::RUNTIME_ENTRY);
343
      } else {
344
        __ jmp(entry, RelocInfo::RUNTIME_ENTRY);
345 346
      }
    }
347 348 349 350 351
  }
  return !is_aborted();
}


352 353
bool LCodeGen::GenerateDeferredCode() {
  ASSERT(is_generating());
354 355 356
  if (deferred_.length() > 0) {
    for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
      LDeferredCode* code = deferred_[i];
357 358 359 360 361
      Comment(";;; <@%d,#%d> "
              "-------------------- Deferred %s --------------------",
              code->instruction_index(),
              code->instr()->hydrogen_value()->id(),
              code->instr()->Mnemonic());
362
      __ bind(code->entry());
363
      if (NeedsDeferredFrame()) {
364
        Comment(";;; Build frame");
365 366 367 368 369 370 371 372
        ASSERT(!frame_is_built_);
        ASSERT(info()->IsStub());
        frame_is_built_ = true;
        // Build the frame in such a way that esi isn't trashed.
        __ push(rbp);  // Caller's frame pointer.
        __ push(Operand(rbp, StandardFrameConstants::kContextOffset));
        __ Push(Smi::FromInt(StackFrame::STUB));
        __ lea(rbp, Operand(rsp, 2 * kPointerSize));
373
        Comment(";;; Deferred code");
374
      }
375
      code->Generate();
376
      if (NeedsDeferredFrame()) {
377
        Comment(";;; Destroy frame");
378 379 380 381 382
        ASSERT(frame_is_built_);
        frame_is_built_ = false;
        __ movq(rsp, rbp);
        __ pop(rbp);
      }
383 384
      __ jmp(code->exit());
    }
385 386 387 388 389 390 391 392 393 394
  }

  // Deferred code is the last part of the instruction sequence. Mark
  // the generated code as done unless we bailed out.
  if (!is_aborted()) status_ = DONE;
  return !is_aborted();
}


bool LCodeGen::GenerateSafepointTable() {
395
  ASSERT(is_done());
396
  safepoints_.Emit(masm(), GetStackSlotCount());
397
  return !is_aborted();
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
}


Register LCodeGen::ToRegister(int index) const {
  return Register::FromAllocationIndex(index);
}


XMMRegister LCodeGen::ToDoubleRegister(int index) const {
  return XMMRegister::FromAllocationIndex(index);
}


Register LCodeGen::ToRegister(LOperand* op) const {
  ASSERT(op->IsRegister());
  return ToRegister(op->index());
}


XMMRegister LCodeGen::ToDoubleRegister(LOperand* op) const {
  ASSERT(op->IsDoubleRegister());
  return ToDoubleRegister(op->index());
}


423 424 425 426 427 428 429 430 431 432 433 434
bool LCodeGen::IsInteger32Constant(LConstantOperand* op) const {
  return op->IsConstantOperand() &&
      chunk_->LookupLiteralRepresentation(op).IsInteger32();
}


bool LCodeGen::IsTaggedConstant(LConstantOperand* op) const {
  return op->IsConstantOperand() &&
      chunk_->LookupLiteralRepresentation(op).IsTagged();
}


435
int LCodeGen::ToInteger32(LConstantOperand* op) const {
436 437
  HConstant* constant = chunk_->LookupConstant(op);
  return constant->Integer32Value();
438 439 440
}


441
double LCodeGen::ToDouble(LConstantOperand* op) const {
442 443 444
  HConstant* constant = chunk_->LookupConstant(op);
  ASSERT(constant->HasDoubleValue());
  return constant->DoubleValue();
445 446 447
}


448
Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
449
  HConstant* constant = chunk_->LookupConstant(op);
450
  ASSERT(chunk_->LookupLiteralRepresentation(op).IsTagged());
451
  return constant->handle();
452 453 454
}


455 456 457 458
Operand LCodeGen::ToOperand(LOperand* op) const {
  // Does not handle registers. In X64 assembler, plain registers are not
  // representable as an Operand.
  ASSERT(op->IsStackSlot() || op->IsDoubleStackSlot());
459
  return Operand(rbp, StackSlotOffset(op->index()));
460 461
}

462

463
void LCodeGen::WriteTranslation(LEnvironment* environment,
464
                                Translation* translation,
465 466
                                int* pushed_arguments_index,
                                int* pushed_arguments_count) {
467 468 469 470 471 472 473
  if (environment == NULL) return;

  // The translation includes one command per value in the environment.
  int translation_size = environment->values()->length();
  // The output frame height does not include the parameters.
  int height = translation_size - environment->parameter_count();

474 475 476 477
  // Function parameters are arguments to the outermost environment. The
  // arguments index points to the first element of a sequence of tagged
  // values on the stack that represent the arguments. This needs to be
  // kept in sync with the LArgumentsElements implementation.
478 479
  *pushed_arguments_index = -environment->parameter_count();
  *pushed_arguments_count = environment->parameter_count();
480 481 482

  WriteTranslation(environment->outer(),
                   translation,
483 484
                   pushed_arguments_index,
                   pushed_arguments_count);
485
  bool has_closure_id = !info()->closure().is_null() &&
486
      !info()->closure().is_identical_to(environment->closure());
487
  int closure_id = has_closure_id
488 489 490
      ? DefineDeoptimizationLiteral(environment->closure())
      : Translation::kSelfLiteralId;

491 492 493 494 495 496 497
  switch (environment->frame_type()) {
    case JS_FUNCTION:
      translation->BeginJSFrame(environment->ast_id(), closure_id, height);
      break;
    case JS_CONSTRUCT:
      translation->BeginConstructStubFrame(closure_id, translation_size);
      break;
498 499 500 501 502
    case JS_GETTER:
      ASSERT(translation_size == 1);
      ASSERT(height == 0);
      translation->BeginGetterStubFrame(closure_id);
      break;
503
    case JS_SETTER:
504 505 506
      ASSERT(translation_size == 2);
      ASSERT(height == 0);
      translation->BeginSetterStubFrame(closure_id);
507
      break;
508 509 510
    case ARGUMENTS_ADAPTOR:
      translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
      break;
511 512 513
    case STUB:
      translation->BeginCompiledStubFrame();
      break;
514
  }
515 516

  // Inlined frames which push their arguments cause the index to be
517 518 519 520 521 522 523 524 525 526 527 528 529 530
  // bumped and another stack area to be used for materialization,
  // otherwise actual argument values are unknown for inlined frames.
  bool arguments_known = true;
  int arguments_index = *pushed_arguments_index;
  int arguments_count = *pushed_arguments_count;
  if (environment->entry() != NULL) {
    arguments_known = environment->entry()->arguments_pushed();
    arguments_index = arguments_index < 0
        ? GetStackSlotCount() : arguments_index + arguments_count;
    arguments_count = environment->entry()->arguments_count() + 1;
    if (environment->entry()->arguments_pushed()) {
      *pushed_arguments_index = arguments_index;
      *pushed_arguments_count = arguments_count;
    }
531 532
  }

533 534 535 536 537 538 539 540 541 542
  for (int i = 0; i < translation_size; ++i) {
    LOperand* value = environment->values()->at(i);
    // spilled_registers_ and spilled_double_registers_ are either
    // both NULL or both set.
    if (environment->spilled_registers() != NULL && value != NULL) {
      if (value->IsRegister() &&
          environment->spilled_registers()[value->index()] != NULL) {
        translation->MarkDuplicate();
        AddToTranslation(translation,
                         environment->spilled_registers()[value->index()],
543
                         environment->HasTaggedValueAt(i),
544
                         environment->HasUint32ValueAt(i),
545 546 547
                         arguments_known,
                         arguments_index,
                         arguments_count);
548 549 550 551 552 553 554
      } else if (
          value->IsDoubleRegister() &&
          environment->spilled_double_registers()[value->index()] != NULL) {
        translation->MarkDuplicate();
        AddToTranslation(
            translation,
            environment->spilled_double_registers()[value->index()],
555
            false,
556
            false,
557 558 559
            arguments_known,
            arguments_index,
            arguments_count);
560 561 562
      }
    }

563 564 565
    AddToTranslation(translation,
                     value,
                     environment->HasTaggedValueAt(i),
566
                     environment->HasUint32ValueAt(i),
567 568 569
                     arguments_known,
                     arguments_index,
                     arguments_count);
570 571 572 573
  }
}


574 575
void LCodeGen::AddToTranslation(Translation* translation,
                                LOperand* op,
576
                                bool is_tagged,
577
                                bool is_uint32,
578
                                bool arguments_known,
579 580
                                int arguments_index,
                                int arguments_count) {
581 582 583 584
  if (op == NULL) {
    // TODO(twuerthinger): Introduce marker operands to indicate that this value
    // is not present and must be reconstructed from the deoptimizer. Currently
    // this is only used for the arguments object.
585 586
    translation->StoreArgumentsObject(
        arguments_known, arguments_index, arguments_count);
587 588 589
  } else if (op->IsStackSlot()) {
    if (is_tagged) {
      translation->StoreStackSlot(op->index());
590 591
    } else if (is_uint32) {
      translation->StoreUint32StackSlot(op->index());
592 593 594 595 596 597 598
    } else {
      translation->StoreInt32StackSlot(op->index());
    }
  } else if (op->IsDoubleStackSlot()) {
    translation->StoreDoubleStackSlot(op->index());
  } else if (op->IsArgument()) {
    ASSERT(is_tagged);
599
    int src_index = GetStackSlotCount() + op->index();
600 601 602 603 604
    translation->StoreStackSlot(src_index);
  } else if (op->IsRegister()) {
    Register reg = ToRegister(op);
    if (is_tagged) {
      translation->StoreRegister(reg);
605 606
    } else if (is_uint32) {
      translation->StoreUint32Register(reg);
607 608 609 610 611 612 613
    } else {
      translation->StoreInt32Register(reg);
    }
  } else if (op->IsDoubleRegister()) {
    XMMRegister reg = ToDoubleRegister(op);
    translation->StoreDoubleRegister(reg);
  } else if (op->IsConstantOperand()) {
614 615
    HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
    int src_index = DefineDeoptimizationLiteral(constant->handle());
616 617 618 619 620 621 622
    translation->StoreLiteral(src_index);
  } else {
    UNREACHABLE();
  }
}


623 624 625 626 627
void LCodeGen::CallCodeGeneric(Handle<Code> code,
                               RelocInfo::Mode mode,
                               LInstruction* instr,
                               SafepointMode safepoint_mode,
                               int argc) {
628
  EnsureSpaceForLazyDeopt(Deoptimizer::patch_size() - masm()->CallSize(code));
629 630 631 632
  ASSERT(instr != NULL);
  LPointerMap* pointers = instr->pointer_map();
  RecordPosition(pointers->position());
  __ call(code, mode);
633
  RecordSafepointWithLazyDeopt(instr, safepoint_mode, argc);
634 635 636

  // Signal that we don't inline smi code before these stubs in the
  // optimizing code generator.
637
  if (code->kind() == Code::BINARY_OP_IC ||
638 639 640
      code->kind() == Code::COMPARE_IC) {
    __ nop();
  }
641 642 643
}


644 645 646 647 648 649 650
void LCodeGen::CallCode(Handle<Code> code,
                        RelocInfo::Mode mode,
                        LInstruction* instr) {
  CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT, 0);
}


651
void LCodeGen::CallRuntime(const Runtime::Function* function,
652 653
                           int num_arguments,
                           LInstruction* instr) {
654 655 656 657 658 659
  ASSERT(instr != NULL);
  ASSERT(instr->HasPointerMap());
  LPointerMap* pointers = instr->pointer_map();
  RecordPosition(pointers->position());

  __ CallRuntime(function, num_arguments);
660
  RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT, 0);
661 662 663 664 665 666 667 668 669
}


void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
                                       int argc,
                                       LInstruction* instr) {
  __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
  __ CallRuntimeSaveDoubles(id);
  RecordSafepointWithRegisters(
670
      instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
671 672 673
}


674 675
void LCodeGen::RegisterEnvironmentForDeoptimization(LEnvironment* environment,
                                                    Safepoint::DeoptMode mode) {
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
  if (!environment->HasBeenRegistered()) {
    // Physical stack frame layout:
    // -x ............. -4  0 ..................................... y
    // [incoming arguments] [spill slots] [pushed outgoing arguments]

    // Layout of the environment:
    // 0 ..................................................... size-1
    // [parameters] [locals] [expression stack including arguments]

    // Layout of the translation:
    // 0 ........................................................ size - 1 + 4
    // [expression stack including arguments] [locals] [4 words] [parameters]
    // |>------------  translation_size ------------<|

    int frame_count = 0;
691
    int jsframe_count = 0;
692 693
    int args_index = 0;
    int args_count = 0;
694 695
    for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
      ++frame_count;
696
      if (e->frame_type() == JS_FUNCTION) {
697 698
        ++jsframe_count;
      }
699
    }
700 701
    Translation translation(&translations_, frame_count, jsframe_count, zone());
    WriteTranslation(environment, &translation, &args_index, &args_count);
702
    int deoptimization_index = deoptimizations_.length();
703 704 705 706
    int pc_offset = masm()->pc_offset();
    environment->Register(deoptimization_index,
                          translation.index(),
                          (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
707
    deoptimizations_.Add(environment, environment->zone());
708
  }
709 710 711 712
}


void LCodeGen::DeoptimizeIf(Condition cc, LEnvironment* environment) {
713
  RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
714 715
  ASSERT(environment->HasBeenRegistered());
  int id = environment->deoptimization_index();
716 717 718 719
  ASSERT(info()->IsOptimizing() || info()->IsStub());
  Deoptimizer::BailoutType bailout_type = info()->IsStub()
      ? Deoptimizer::LAZY
      : Deoptimizer::EAGER;
720 721
  Address entry =
      Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
722 723 724 725 726
  if (entry == NULL) {
    Abort("bailout was not prepared");
    return;
  }

727 728 729 730 731 732 733 734 735 736 737
  ASSERT(FLAG_deopt_every_n_times == 0);  // Not yet implemented on x64.

  if (FLAG_trap_on_deopt) {
    Label done;
    if (cc != no_condition) {
      __ j(NegateCondition(cc), &done, Label::kNear);
    }
    __ int3();
    __ bind(&done);
  }

738
  ASSERT(info()->IsStub() || frame_is_built_);
739 740 741
  bool needs_lazy_deopt = info()->IsStub();
  if (cc == no_condition && frame_is_built_) {
    if (needs_lazy_deopt) {
742
      __ call(entry, RelocInfo::RUNTIME_ENTRY);
743
    } else {
744
      __ jmp(entry, RelocInfo::RUNTIME_ENTRY);
745
    }
746
  } else {
747 748
    // We often have several deopts to the same entry, reuse the last
    // jump entry if this is the case.
749
    if (jump_table_.is_empty() ||
750 751
        jump_table_.last().address != entry ||
        jump_table_.last().needs_frame != !frame_is_built_ ||
752 753
        jump_table_.last().is_lazy_deopt != needs_lazy_deopt) {
      JumpTableEntry table_entry(entry, !frame_is_built_, needs_lazy_deopt);
754
      jump_table_.Add(table_entry, zone());
755
    }
756 757 758 759 760
    if (cc == no_condition) {
      __ jmp(&jump_table_.last().label);
    } else {
      __ j(cc, &jump_table_.last().label);
    }
761
  }
762 763 764
}


765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
void LCodeGen::RegisterDependentCodeForEmbeddedMaps(Handle<Code> code) {
  ZoneList<Handle<Map> > maps(1, zone());
  int mode_mask = RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT);
  for (RelocIterator it(*code, mode_mask); !it.done(); it.next()) {
    RelocInfo::Mode mode = it.rinfo()->rmode();
    if (mode == RelocInfo::EMBEDDED_OBJECT &&
        it.rinfo()->target_object()->IsMap()) {
      Handle<Map> map(Map::cast(it.rinfo()->target_object()));
      if (map->CanTransition()) {
        maps.Add(map, zone());
      }
    }
  }
#ifdef VERIFY_HEAP
  // This disables verification of weak embedded maps after full GC.
  // AddDependentCode can cause a GC, which would observe the state where
  // this code is not yet in the depended code lists of the embedded maps.
  NoWeakEmbeddedMapsVerificationScope disable_verification_of_embedded_maps;
#endif
  for (int i = 0; i < maps.length(); i++) {
785
    maps.at(i)->AddDependentCode(DependentCode::kWeaklyEmbeddedGroup, code);
786 787 788 789
  }
}


790 791 792 793
void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
  int length = deoptimizations_.length();
  if (length == 0) return;
  Handle<DeoptimizationInputData> data =
794
      factory()->NewDeoptimizationInputData(length, TENURED);
795

796 797
  Handle<ByteArray> translations =
      translations_.CreateByteArray(isolate()->factory());
798
  data->SetTranslationByteArray(*translations);
799 800 801
  data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));

  Handle<FixedArray> literals =
802
      factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
803 804 805 806 807 808
  { ALLOW_HANDLE_DEREF(isolate(),
                       "copying a ZoneList of handles into a FixedArray");
    for (int i = 0; i < deoptimization_literals_.length(); i++) {
      literals->set(i, *deoptimization_literals_[i]);
    }
    data->SetLiteralArray(*literals);
809 810
  }

811
  data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
812 813 814 815 816
  data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));

  // Populate the deoptimization entries.
  for (int i = 0; i < length; i++) {
    LEnvironment* env = deoptimizations_[i];
817
    data->SetAstId(i, env->ast_id());
818 819 820
    data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
    data->SetArgumentsStackHeight(i,
                                  Smi::FromInt(env->arguments_stack_height()));
821
    data->SetPc(i, Smi::FromInt(env->pc_offset()));
822 823 824 825 826 827 828 829 830 831
  }
  code->set_deoptimization_data(*data);
}


int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
  int result = deoptimization_literals_.length();
  for (int i = 0; i < deoptimization_literals_.length(); ++i) {
    if (deoptimization_literals_[i].is_identical_to(literal)) return i;
  }
832
  deoptimization_literals_.Add(literal, zone());
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
  return result;
}


void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
  ASSERT(deoptimization_literals_.length() == 0);

  const ZoneList<Handle<JSFunction> >* inlined_closures =
      chunk()->inlined_closures();

  for (int i = 0, length = inlined_closures->length();
       i < length;
       i++) {
    DefineDeoptimizationLiteral(inlined_closures->at(i));
  }

  inlined_function_count_ = deoptimization_literals_.length();
}


853 854 855 856 857 858 859 860 861 862 863 864
void LCodeGen::RecordSafepointWithLazyDeopt(
    LInstruction* instr, SafepointMode safepoint_mode, int argc) {
  if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
    RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
  } else {
    ASSERT(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS);
    RecordSafepointWithRegisters(
        instr->pointer_map(), argc, Safepoint::kLazyDeopt);
  }
}


865 866 867 868
void LCodeGen::RecordSafepoint(
    LPointerMap* pointers,
    Safepoint::Kind kind,
    int arguments,
869
    Safepoint::DeoptMode deopt_mode) {
870 871
  ASSERT(kind == expected_safepoint_kind_);

872
  const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
873

874
  Safepoint safepoint = safepoints_.DefineSafepoint(masm(),
875
      kind, arguments, deopt_mode);
876 877 878
  for (int i = 0; i < operands->length(); i++) {
    LOperand* pointer = operands->at(i);
    if (pointer->IsStackSlot()) {
879
      safepoint.DefinePointerSlot(pointer->index(), zone());
880
    } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
881
      safepoint.DefinePointerRegister(ToRegister(pointer), zone());
882 883
    }
  }
884 885
  if (kind & Safepoint::kWithRegisters) {
    // Register rsi always contains a pointer to the context.
886
    safepoint.DefinePointerRegister(rsi, zone());
887 888 889 890 891
  }
}


void LCodeGen::RecordSafepoint(LPointerMap* pointers,
892 893
                               Safepoint::DeoptMode deopt_mode) {
  RecordSafepoint(pointers, Safepoint::kSimple, 0, deopt_mode);
894 895 896
}


897
void LCodeGen::RecordSafepoint(Safepoint::DeoptMode deopt_mode) {
898
  LPointerMap empty_pointers(RelocInfo::kNoPosition, zone());
899
  RecordSafepoint(&empty_pointers, deopt_mode);
900 901 902
}


903 904
void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
                                            int arguments,
905 906
                                            Safepoint::DeoptMode deopt_mode) {
  RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, deopt_mode);
907 908 909 910
}


void LCodeGen::RecordPosition(int position) {
911
  if (position == RelocInfo::kNoPosition) return;
912 913 914 915
  masm()->positions_recorder()->RecordPosition(position);
}


916 917 918 919 920 921 922
static const char* LabelType(LLabel* label) {
  if (label->is_loop_header()) return " (loop header)";
  if (label->is_osr_entry()) return " (OSR entry)";
  return "";
}


923
void LCodeGen::DoLabel(LLabel* label) {
924 925 926
  Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
          current_instruction_,
          label->hydrogen_value()->id(),
927
          label->block_id(),
928
          LabelType(label));
929 930
  __ bind(label->label());
  current_block_ = label->block_id();
931
  DoGap(label);
932 933 934 935
}


void LCodeGen::DoParallelMove(LParallelMove* move) {
936
  resolver_.Resolve(move);
937 938 939 940 941 942 943 944 945 946 947 948 949 950
}


void LCodeGen::DoGap(LGap* gap) {
  for (int i = LGap::FIRST_INNER_POSITION;
       i <= LGap::LAST_INNER_POSITION;
       i++) {
    LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
    LParallelMove* move = gap->GetParallelMove(inner_pos);
    if (move != NULL) DoParallelMove(move);
  }
}


951 952 953 954 955
void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
  DoGap(instr);
}


956 957 958 959 960 961
void LCodeGen::DoParameter(LParameter* instr) {
  // Nothing to do.
}


void LCodeGen::DoCallStub(LCallStub* instr) {
962 963 964 965
  ASSERT(ToRegister(instr->result()).is(rax));
  switch (instr->hydrogen()->major_key()) {
    case CodeStub::RegExpConstructResult: {
      RegExpConstructResultStub stub;
966
      CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
967 968 969 970
      break;
    }
    case CodeStub::RegExpExec: {
      RegExpExecStub stub;
971
      CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
972 973 974 975
      break;
    }
    case CodeStub::SubString: {
      SubStringStub stub;
976
      CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
977 978 979 980
      break;
    }
    case CodeStub::NumberToString: {
      NumberToStringStub stub;
981
      CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
982 983 984 985
      break;
    }
    case CodeStub::StringAdd: {
      StringAddStub stub(NO_STRING_ADD_FLAGS);
986
      CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
987 988 989 990
      break;
    }
    case CodeStub::StringCompare: {
      StringCompareStub stub;
991
      CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
992 993 994
      break;
    }
    case CodeStub::TranscendentalCache: {
995 996
      TranscendentalCacheStub stub(instr->transcendental_type(),
                                   TranscendentalCacheStub::TAGGED);
997
      CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
998 999 1000 1001 1002
      break;
    }
    default:
      UNREACHABLE();
  }
1003 1004 1005 1006 1007 1008 1009 1010 1011
}


void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
  // Nothing to do.
}


void LCodeGen::DoModI(LModI* instr) {
1012
  if (instr->hydrogen()->HasPowerOf2Divisor()) {
1013
    Register dividend = ToRegister(instr->left());
1014 1015 1016 1017 1018 1019

    int32_t divisor =
        HConstant::cast(instr->hydrogen()->right())->Integer32Value();

    if (divisor < 0) divisor = -divisor;

1020
    Label positive_dividend, done;
1021
    __ testl(dividend, dividend);
1022
    __ j(not_sign, &positive_dividend, Label::kNear);
1023 1024 1025 1026
    __ negl(dividend);
    __ andl(dividend, Immediate(divisor - 1));
    __ negl(dividend);
    if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1027
      __ j(not_zero, &done, Label::kNear);
1028
      DeoptimizeIf(no_condition, instr->environment());
1029 1030
    } else {
      __ jmp(&done, Label::kNear);
1031 1032 1033
    }
    __ bind(&positive_dividend);
    __ andl(dividend, Immediate(divisor - 1));
1034 1035
    __ bind(&done);
  } else {
1036
    Label done, remainder_eq_dividend, slow, do_subtraction, both_positive;
1037 1038
    Register left_reg = ToRegister(instr->left());
    Register right_reg = ToRegister(instr->right());
1039
    Register result_reg = ToRegister(instr->result());
1040

1041 1042
    ASSERT(left_reg.is(rax));
    ASSERT(result_reg.is(rdx));
1043 1044 1045 1046 1047 1048 1049 1050 1051
    ASSERT(!right_reg.is(rax));
    ASSERT(!right_reg.is(rdx));

    // Check for x % 0.
    if (instr->hydrogen()->CheckFlag(HValue::kCanBeDivByZero)) {
      __ testl(right_reg, right_reg);
      DeoptimizeIf(zero, instr->environment());
    }

1052
    __ testl(left_reg, left_reg);
1053 1054
    __ j(zero, &remainder_eq_dividend, Label::kNear);
    __ j(sign, &slow, Label::kNear);
1055 1056

    __ testl(right_reg, right_reg);
1057
    __ j(not_sign, &both_positive, Label::kNear);
1058 1059 1060 1061 1062 1063 1064
    // The sign of the divisor doesn't matter.
    __ neg(right_reg);

    __ bind(&both_positive);
    // If the dividend is smaller than the nonnegative
    // divisor, the dividend is the result.
    __ cmpl(left_reg, right_reg);
1065
    __ j(less, &remainder_eq_dividend, Label::kNear);
1066 1067

    // Check if the divisor is a PowerOfTwo integer.
1068
    Register scratch = ToRegister(instr->temp());
1069 1070 1071
    __ movl(scratch, right_reg);
    __ subl(scratch, Immediate(1));
    __ testl(scratch, right_reg);
1072
    __ j(not_zero, &do_subtraction, Label::kNear);
1073
    __ andl(left_reg, scratch);
1074
    __ jmp(&remainder_eq_dividend, Label::kNear);
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084

    __ bind(&do_subtraction);
    const int kUnfolds = 3;
    // Try a few subtractions of the dividend.
    __ movl(scratch, left_reg);
    for (int i = 0; i < kUnfolds; i++) {
      // Reduce the dividend by the divisor.
      __ subl(left_reg, right_reg);
      // Check if the dividend is less than the divisor.
      __ cmpl(left_reg, right_reg);
1085
      __ j(less, &remainder_eq_dividend, Label::kNear);
1086 1087 1088 1089 1090
    }
    __ movl(left_reg, scratch);

    // Slow case, using idiv instruction.
    __ bind(&slow);
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101

    // Check for (kMinInt % -1).
    if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
      Label left_not_min_int;
      __ cmpl(left_reg, Immediate(kMinInt));
      __ j(not_zero, &left_not_min_int, Label::kNear);
      __ cmpl(right_reg, Immediate(-1));
      DeoptimizeIf(zero, instr->environment());
      __ bind(&left_not_min_int);
    }

1102 1103
    // Sign extend eax to edx.
    // (We are using only the low 32 bits of the values.)
1104 1105 1106 1107
    __ cdq();

    // Check for (0 % -x) that will produce negative zero.
    if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1108 1109
      Label positive_left;
      Label done;
1110
      __ testl(left_reg, left_reg);
1111
      __ j(not_sign, &positive_left, Label::kNear);
1112 1113 1114
      __ idivl(right_reg);

      // Test the remainder for 0, because then the result would be -0.
1115
      __ testl(result_reg, result_reg);
1116
      __ j(not_zero, &done, Label::kNear);
1117 1118 1119 1120 1121 1122 1123 1124

      DeoptimizeIf(no_condition, instr->environment());
      __ bind(&positive_left);
      __ idivl(right_reg);
      __ bind(&done);
    } else {
      __ idivl(right_reg);
    }
1125
    __ jmp(&done, Label::kNear);
1126 1127 1128 1129 1130

    __ bind(&remainder_eq_dividend);
    __ movl(result_reg, left_reg);

    __ bind(&done);
1131 1132 1133 1134 1135
  }
}


void LCodeGen::DoMathFloorOfDiv(LMathFloorOfDiv* instr) {
1136
  ASSERT(instr->right()->IsConstantOperand());
1137

1138 1139
  const Register dividend = ToRegister(instr->left());
  int32_t divisor = ToInteger32(LConstantOperand::cast(instr->right()));
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
  const Register result = ToRegister(instr->result());

  switch (divisor) {
  case 0:
    DeoptimizeIf(no_condition, instr->environment());
    return;

  case 1:
    if (!result.is(dividend)) {
        __ movl(result, dividend);
    }
    return;

  case -1:
    if (!result.is(dividend)) {
      __ movl(result, dividend);
    }
    __ negl(result);
    if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
      DeoptimizeIf(zero, instr->environment());
    }
    if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
      DeoptimizeIf(overflow, instr->environment());
    }
    return;
  }

  uint32_t divisor_abs = abs(divisor);
  if (IsPowerOf2(divisor_abs)) {
    int32_t power = WhichPowerOf2(divisor_abs);
    if (divisor < 0) {
      __ movsxlq(result, dividend);
      __ neg(result);
      if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
        DeoptimizeIf(zero, instr->environment());
      }
      __ sar(result, Immediate(power));
    } else {
      if (!result.is(dividend)) {
        __ movl(result, dividend);
      }
      __ sarl(result, Immediate(power));
    }
  } else {
1184
    Register reg1 = ToRegister(instr->temp());
1185 1186 1187 1188 1189 1190 1191 1192 1193
    Register reg2 = ToRegister(instr->result());

    // Find b which: 2^b < divisor_abs < 2^(b+1).
    unsigned b = 31 - CompilerIntrinsics::CountLeadingZeros(divisor_abs);
    unsigned shift = 32 + b;  // Precision +1bit (effectively).
    double multiplier_f =
        static_cast<double>(static_cast<uint64_t>(1) << shift) / divisor_abs;
    int64_t multiplier;
    if (multiplier_f - floor(multiplier_f) < 0.5) {
1194
        multiplier = static_cast<int64_t>(floor(multiplier_f));
1195
    } else {
1196
        multiplier = static_cast<int64_t>(floor(multiplier_f)) + 1;
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    }
    // The multiplier is a uint32.
    ASSERT(multiplier > 0 &&
           multiplier < (static_cast<int64_t>(1) << 32));
    // The multiply is int64, so sign-extend to r64.
    __ movsxlq(reg1, dividend);
    if (divisor < 0 &&
        instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
      __ neg(reg1);
      DeoptimizeIf(zero, instr->environment());
    }
1208
    __ movq(reg2, multiplier, RelocInfo::NONE64);
1209 1210 1211 1212 1213
    // Result just fit in r64, because it's int32 * uint32.
    __ imul(reg2, reg1);

    __ addq(reg2, Immediate(1 << 30));
    __ sar(reg2, Immediate(shift));
1214
  }
1215 1216 1217 1218
}


void LCodeGen::DoDivI(LDivI* instr) {
1219
  if (!instr->is_flooring() && instr->hydrogen()->HasPowerOf2Divisor()) {
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
    Register dividend = ToRegister(instr->left());
    int32_t divisor =
        HConstant::cast(instr->hydrogen()->right())->Integer32Value();
    int32_t test_value = 0;
    int32_t power = 0;

    if (divisor > 0) {
      test_value = divisor - 1;
      power = WhichPowerOf2(divisor);
    } else {
      // Check for (0 / -x) that will produce negative zero.
      if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
        __ testl(dividend, dividend);
        DeoptimizeIf(zero, instr->environment());
      }
      // Check for (kMinInt / -1).
      if (divisor == -1 && instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
        __ cmpl(dividend, Immediate(kMinInt));
        DeoptimizeIf(zero, instr->environment());
      }
      test_value = - divisor - 1;
      power = WhichPowerOf2(-divisor);
    }

    if (test_value != 0) {
      // Deoptimize if remainder is not 0.
      __ testl(dividend, Immediate(test_value));
      DeoptimizeIf(not_zero, instr->environment());
      __ sarl(dividend, Immediate(power));
    }

    if (divisor < 0) __ negl(dividend);

    return;
  }

1256
  LOperand* right = instr->right();
1257
  ASSERT(ToRegister(instr->result()).is(rax));
1258 1259 1260
  ASSERT(ToRegister(instr->left()).is(rax));
  ASSERT(!ToRegister(instr->right()).is(rax));
  ASSERT(!ToRegister(instr->right()).is(rdx));
1261 1262 1263 1264 1265

  Register left_reg = rax;

  // Check for x / 0.
  Register right_reg = ToRegister(right);
1266
  if (instr->hydrogen_value()->CheckFlag(HValue::kCanBeDivByZero)) {
1267 1268 1269 1270 1271
    __ testl(right_reg, right_reg);
    DeoptimizeIf(zero, instr->environment());
  }

  // Check for (0 / -x) that will produce negative zero.
1272
  if (instr->hydrogen_value()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1273
    Label left_not_zero;
1274
    __ testl(left_reg, left_reg);
1275
    __ j(not_zero, &left_not_zero, Label::kNear);
1276 1277 1278 1279 1280
    __ testl(right_reg, right_reg);
    DeoptimizeIf(sign, instr->environment());
    __ bind(&left_not_zero);
  }

1281
  // Check for (kMinInt / -1).
1282
  if (instr->hydrogen_value()->CheckFlag(HValue::kCanOverflow)) {
1283
    Label left_not_min_int;
1284
    __ cmpl(left_reg, Immediate(kMinInt));
1285
    __ j(not_zero, &left_not_min_int, Label::kNear);
1286 1287 1288 1289 1290 1291 1292 1293 1294
    __ cmpl(right_reg, Immediate(-1));
    DeoptimizeIf(zero, instr->environment());
    __ bind(&left_not_min_int);
  }

  // Sign extend to rdx.
  __ cdq();
  __ idivl(right_reg);

1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
  if (!instr->is_flooring()) {
    // Deoptimize if remainder is not 0.
    __ testl(rdx, rdx);
    DeoptimizeIf(not_zero, instr->environment());
  } else {
    Label done;
    __ testl(rdx, rdx);
    __ j(zero, &done, Label::kNear);
    __ xorl(rdx, right_reg);
    __ sarl(rdx, Immediate(31));
    __ addl(rax, rdx);
    __ bind(&done);
  }
1308
}
1309 1310 1311


void LCodeGen::DoMulI(LMulI* instr) {
1312 1313
  Register left = ToRegister(instr->left());
  LOperand* right = instr->right();
1314 1315 1316 1317 1318

  if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
    __ movl(kScratchRegister, left);
  }

1319 1320
  bool can_overflow =
      instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
1321 1322
  if (right->IsConstantOperand()) {
    int right_value = ToInteger32(LConstantOperand::cast(right));
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
    if (right_value == -1) {
      __ negl(left);
    } else if (right_value == 0) {
      __ xorl(left, left);
    } else if (right_value == 2) {
      __ addl(left, left);
    } else if (!can_overflow) {
      // If the multiplication is known to not overflow, we
      // can use operations that don't set the overflow flag
      // correctly.
      switch (right_value) {
        case 1:
          // Do nothing.
          break;
        case 3:
          __ leal(left, Operand(left, left, times_2, 0));
          break;
        case 4:
          __ shll(left, Immediate(2));
          break;
        case 5:
          __ leal(left, Operand(left, left, times_4, 0));
          break;
        case 8:
          __ shll(left, Immediate(3));
          break;
        case 9:
          __ leal(left, Operand(left, left, times_8, 0));
          break;
        case 16:
          __ shll(left, Immediate(4));
          break;
        default:
          __ imull(left, left, Immediate(right_value));
          break;
      }
    } else {
      __ imull(left, left, Immediate(right_value));
    }
1362 1363 1364 1365 1366 1367
  } else if (right->IsStackSlot()) {
    __ imull(left, ToOperand(right));
  } else {
    __ imull(left, ToRegister(right));
  }

1368
  if (can_overflow) {
1369 1370 1371 1372 1373
    DeoptimizeIf(overflow, instr->environment());
  }

  if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
    // Bail out if the result is supposed to be negative zero.
1374
    Label done;
1375
    __ testl(left, left);
1376
    __ j(not_zero, &done, Label::kNear);
1377
    if (right->IsConstantOperand()) {
1378
      if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1379
        DeoptimizeIf(no_condition, instr->environment());
1380 1381 1382
      } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
        __ cmpl(kScratchRegister, Immediate(0));
        DeoptimizeIf(less, instr->environment());
1383 1384
      }
    } else if (right->IsStackSlot()) {
1385
      __ orl(kScratchRegister, ToOperand(right));
1386 1387 1388
      DeoptimizeIf(sign, instr->environment());
    } else {
      // Test the non-zero operand for negative sign.
1389
      __ orl(kScratchRegister, ToRegister(right));
1390 1391 1392 1393 1394
      DeoptimizeIf(sign, instr->environment());
    }
    __ bind(&done);
  }
}
1395 1396 1397


void LCodeGen::DoBitI(LBitI* instr) {
1398 1399
  LOperand* left = instr->left();
  LOperand* right = instr->right();
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
  ASSERT(left->Equals(instr->result()));
  ASSERT(left->IsRegister());

  if (right->IsConstantOperand()) {
    int right_operand = ToInteger32(LConstantOperand::cast(right));
    switch (instr->op()) {
      case Token::BIT_AND:
        __ andl(ToRegister(left), Immediate(right_operand));
        break;
      case Token::BIT_OR:
        __ orl(ToRegister(left), Immediate(right_operand));
        break;
      case Token::BIT_XOR:
        __ xorl(ToRegister(left), Immediate(right_operand));
        break;
      default:
        UNREACHABLE();
        break;
    }
  } else if (right->IsStackSlot()) {
    switch (instr->op()) {
      case Token::BIT_AND:
        __ andl(ToRegister(left), ToOperand(right));
        break;
      case Token::BIT_OR:
        __ orl(ToRegister(left), ToOperand(right));
        break;
      case Token::BIT_XOR:
        __ xorl(ToRegister(left), ToOperand(right));
        break;
      default:
        UNREACHABLE();
        break;
    }
  } else {
    ASSERT(right->IsRegister());
    switch (instr->op()) {
      case Token::BIT_AND:
        __ andl(ToRegister(left), ToRegister(right));
        break;
      case Token::BIT_OR:
        __ orl(ToRegister(left), ToRegister(right));
        break;
      case Token::BIT_XOR:
        __ xorl(ToRegister(left), ToRegister(right));
        break;
      default:
        UNREACHABLE();
        break;
    }
  }
}
1452 1453 1454


void LCodeGen::DoShiftI(LShiftI* instr) {
1455 1456
  LOperand* left = instr->left();
  LOperand* right = instr->right();
1457 1458 1459 1460 1461 1462
  ASSERT(left->Equals(instr->result()));
  ASSERT(left->IsRegister());
  if (right->IsRegister()) {
    ASSERT(ToRegister(right).is(rcx));

    switch (instr->op()) {
1463 1464 1465
      case Token::ROR:
        __ rorl_cl(ToRegister(left));
        break;
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
      case Token::SAR:
        __ sarl_cl(ToRegister(left));
        break;
      case Token::SHR:
        __ shrl_cl(ToRegister(left));
        if (instr->can_deopt()) {
          __ testl(ToRegister(left), ToRegister(left));
          DeoptimizeIf(negative, instr->environment());
        }
        break;
      case Token::SHL:
        __ shll_cl(ToRegister(left));
        break;
      default:
        UNREACHABLE();
        break;
    }
  } else {
    int value = ToInteger32(LConstantOperand::cast(right));
    uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
    switch (instr->op()) {
1487 1488 1489 1490 1491
      case Token::ROR:
        if (shift_count != 0) {
          __ rorl(ToRegister(left), Immediate(shift_count));
        }
        break;
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
      case Token::SAR:
        if (shift_count != 0) {
          __ sarl(ToRegister(left), Immediate(shift_count));
        }
        break;
      case Token::SHR:
        if (shift_count == 0 && instr->can_deopt()) {
          __ testl(ToRegister(left), ToRegister(left));
          DeoptimizeIf(negative, instr->environment());
        } else {
          __ shrl(ToRegister(left), Immediate(shift_count));
        }
        break;
      case Token::SHL:
        if (shift_count != 0) {
          __ shll(ToRegister(left), Immediate(shift_count));
        }
        break;
      default:
        UNREACHABLE();
        break;
    }
  }
1515 1516 1517 1518
}


void LCodeGen::DoSubI(LSubI* instr) {
1519 1520
  LOperand* left = instr->left();
  LOperand* right = instr->right();
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
  ASSERT(left->Equals(instr->result()));

  if (right->IsConstantOperand()) {
    __ subl(ToRegister(left),
            Immediate(ToInteger32(LConstantOperand::cast(right))));
  } else if (right->IsRegister()) {
    __ subl(ToRegister(left), ToRegister(right));
  } else {
    __ subl(ToRegister(left), ToOperand(right));
  }

  if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
    DeoptimizeIf(overflow, instr->environment());
  }
1535 1536 1537 1538
}


void LCodeGen::DoConstantI(LConstantI* instr) {
1539
  ASSERT(instr->result()->IsRegister());
1540
  __ Set(ToRegister(instr->result()), instr->value());
1541 1542 1543 1544
}


void LCodeGen::DoConstantD(LConstantD* instr) {
1545 1546 1547
  ASSERT(instr->result()->IsDoubleRegister());
  XMMRegister res = ToDoubleRegister(instr->result());
  double v = instr->value();
ager@chromium.org's avatar
ager@chromium.org committed
1548
  uint64_t int_val = BitCast<uint64_t, double>(v);
1549 1550
  // Use xor to produce +0.0 in a fast and compact way, but avoid to
  // do so if the constant is -0.0.
ager@chromium.org's avatar
ager@chromium.org committed
1551
  if (int_val == 0) {
lrn@chromium.org's avatar
lrn@chromium.org committed
1552
    __ xorps(res, res);
1553
  } else {
1554
    Register tmp = ToRegister(instr->temp());
ager@chromium.org's avatar
ager@chromium.org committed
1555 1556
    __ Set(tmp, int_val);
    __ movq(res, tmp);
1557
  }
1558 1559 1560 1561
}


void LCodeGen::DoConstantT(LConstantT* instr) {
1562
  Handle<Object> value = instr->value();
1563
  ALLOW_HANDLE_DEREF(isolate(), "smi check");
1564 1565 1566 1567 1568 1569
  if (value->IsSmi()) {
    __ Move(ToRegister(instr->result()), value);
  } else {
    __ LoadHeapObject(ToRegister(instr->result()),
                      Handle<HeapObject>::cast(value));
  }
1570 1571 1572
}


1573
void LCodeGen::DoFixedArrayBaseLength(LFixedArrayBaseLength* instr) {
1574
  Register result = ToRegister(instr->result());
1575
  Register array = ToRegister(instr->value());
1576
  __ movq(result, FieldOperand(array, FixedArrayBase::kLengthOffset));
1577 1578 1579
}


1580 1581
void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
  Register result = ToRegister(instr->result());
1582
  Register map = ToRegister(instr->value());
1583 1584 1585 1586
  __ EnumLength(result, map);
}


1587 1588
void LCodeGen::DoElementsKind(LElementsKind* instr) {
  Register result = ToRegister(instr->result());
1589
  Register input = ToRegister(instr->value());
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600

  // Load map into |result|.
  __ movq(result, FieldOperand(input, HeapObject::kMapOffset));
  // Load the map's "bit field 2" into |result|. We only need the first byte.
  __ movzxbq(result, FieldOperand(result, Map::kBitField2Offset));
  // Retrieve elements_kind from bit field 2.
  __ and_(result, Immediate(Map::kElementsKindMask));
  __ shr(result, Immediate(Map::kElementsKindShift));
}


1601
void LCodeGen::DoValueOf(LValueOf* instr) {
1602
  Register input = ToRegister(instr->value());
1603 1604
  Register result = ToRegister(instr->result());
  ASSERT(input.is(result));
1605
  Label done;
1606
  // If the object is a smi return the object.
1607
  __ JumpIfSmi(input, &done, Label::kNear);
1608 1609 1610

  // If the object is not a value type, return the object.
  __ CmpObjectType(input, JS_VALUE_TYPE, kScratchRegister);
1611
  __ j(not_equal, &done, Label::kNear);
1612 1613 1614
  __ movq(result, FieldOperand(input, JSValue::kValueOffset));

  __ bind(&done);
1615 1616 1617
}


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 1624
  ASSERT(object.is(result));
  ASSERT(object.is(rax));
1625

1626 1627
  Condition cc = masm()->CheckSmi(object);
  DeoptimizeIf(cc, instr->environment());
1628
  __ CmpObjectType(object, JS_DATE_TYPE, kScratchRegister);
1629
  DeoptimizeIf(not_equal, instr->environment());
1630

1631 1632 1633 1634 1635
  if (index->value() == 0) {
    __ movq(result, FieldOperand(object, JSDate::kValueOffset));
  } else {
    if (index->value() < JSDate::kFirstUncachedField) {
      ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
1636 1637
      Operand stamp_operand = __ ExternalOperand(stamp);
      __ movq(kScratchRegister, stamp_operand);
1638 1639 1640 1641 1642 1643 1644 1645 1646
      __ cmpq(kScratchRegister, FieldOperand(object,
                                             JSDate::kCacheStampOffset));
      __ j(not_equal, &runtime, Label::kNear);
      __ movq(result, FieldOperand(object, JSDate::kValueOffset +
                                           kPointerSize * index->value()));
      __ jmp(&done);
    }
    __ bind(&runtime);
    __ PrepareCallCFunction(2);
1647 1648
    __ movq(arg_reg_1, object);
    __ movq(arg_reg_2, index, RelocInfo::NONE64);
1649 1650 1651
    __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
    __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
    __ bind(&done);
1652 1653 1654 1655
  }
}


1656 1657 1658 1659 1660 1661 1662 1663 1664
void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
  SeqStringSetCharGenerator::Generate(masm(),
                                      instr->encoding(),
                                      ToRegister(instr->string()),
                                      ToRegister(instr->index()),
                                      ToRegister(instr->value()));
}


1665
void LCodeGen::DoBitNotI(LBitNotI* instr) {
1666
  LOperand* input = instr->value();
1667 1668
  ASSERT(input->Equals(instr->result()));
  __ not_(ToRegister(input));
1669 1670 1671 1672
}


void LCodeGen::DoThrow(LThrow* instr) {
1673
  __ push(ToRegister(instr->value()));
1674 1675 1676 1677 1678 1679
  CallRuntime(Runtime::kThrow, 1, instr);

  if (FLAG_debug_code) {
    Comment("Unreachable code.");
    __ int3();
  }
1680 1681 1682 1683
}


void LCodeGen::DoAddI(LAddI* instr) {
1684 1685
  LOperand* left = instr->left();
  LOperand* right = instr->right();
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
  ASSERT(left->Equals(instr->result()));

  if (right->IsConstantOperand()) {
    __ addl(ToRegister(left),
            Immediate(ToInteger32(LConstantOperand::cast(right))));
  } else if (right->IsRegister()) {
    __ addl(ToRegister(left), ToRegister(right));
  } else {
    __ addl(ToRegister(left), ToOperand(right));
  }

  if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
    DeoptimizeIf(overflow, instr->environment());
  }
1700 1701 1702
}


1703
void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
1704 1705
  LOperand* left = instr->left();
  LOperand* right = instr->right();
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
  ASSERT(left->Equals(instr->result()));
  HMathMinMax::Operation operation = instr->hydrogen()->operation();
  if (instr->hydrogen()->representation().IsInteger32()) {
    Label return_left;
    Condition condition = (operation == HMathMinMax::kMathMin)
        ? less_equal
        : greater_equal;
    Register left_reg = ToRegister(left);
    if (right->IsConstantOperand()) {
      Immediate right_imm =
          Immediate(ToInteger32(LConstantOperand::cast(right)));
1717
      __ cmpl(left_reg, right_imm);
1718 1719
      __ j(condition, &return_left, Label::kNear);
      __ movq(left_reg, right_imm);
1720 1721
    } else if (right->IsRegister()) {
      Register right_reg = ToRegister(right);
1722
      __ cmpl(left_reg, right_reg);
1723 1724
      __ j(condition, &return_left, Label::kNear);
      __ movq(left_reg, right_reg);
1725 1726
    } else {
      Operand right_op = ToOperand(right);
1727
      __ cmpl(left_reg, right_op);
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
      __ j(condition, &return_left, Label::kNear);
      __ movq(left_reg, right_op);
    }
    __ bind(&return_left);
  } else {
    ASSERT(instr->hydrogen()->representation().IsDouble());
    Label check_nan_left, check_zero, return_left, return_right;
    Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
    XMMRegister left_reg = ToDoubleRegister(left);
    XMMRegister right_reg = ToDoubleRegister(right);
    __ ucomisd(left_reg, right_reg);
    __ j(parity_even, &check_nan_left, Label::kNear);  // At least one NaN.
    __ j(equal, &check_zero, Label::kNear);  // left == right.
    __ j(condition, &return_left, Label::kNear);
    __ jmp(&return_right, Label::kNear);

    __ bind(&check_zero);
    XMMRegister xmm_scratch = xmm0;
    __ xorps(xmm_scratch, xmm_scratch);
    __ ucomisd(left_reg, xmm_scratch);
    __ j(not_equal, &return_left, Label::kNear);  // left == right != 0.
    // At this point, both left and right are either 0 or -0.
    if (operation == HMathMinMax::kMathMin) {
      __ orpd(left_reg, right_reg);
    } else {
      // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
      __ addsd(left_reg, right_reg);
    }
    __ jmp(&return_left, Label::kNear);

    __ bind(&check_nan_left);
    __ ucomisd(left_reg, left_reg);  // NaN check.
    __ j(parity_even, &return_left, Label::kNear);
    __ bind(&return_right);
    __ movsd(left_reg, right_reg);

    __ bind(&return_left);
  }
}


1769
void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
1770 1771
  XMMRegister left = ToDoubleRegister(instr->left());
  XMMRegister right = ToDoubleRegister(instr->right());
1772
  XMMRegister result = ToDoubleRegister(instr->result());
1773
  // All operations except MOD are computed in-place.
1774
  ASSERT(instr->op() == Token::MOD || left.is(result));
1775 1776
  switch (instr->op()) {
    case Token::ADD:
1777
      __ addsd(left, right);
1778 1779
      break;
    case Token::SUB:
1780
       __ subsd(left, right);
1781 1782
       break;
    case Token::MUL:
1783
      __ mulsd(left, right);
1784 1785
      break;
    case Token::DIV:
1786
      __ divsd(left, right);
1787 1788
      // Don't delete this mov. It may improve performance on some CPUs,
      // when there is a mulsd depending on the result
1789
      __ movaps(left, left);
1790 1791
      break;
    case Token::MOD:
1792
      __ PrepareCallCFunction(2);
lrn@chromium.org's avatar
lrn@chromium.org committed
1793
      __ movaps(xmm0, left);
1794
      ASSERT(right.is(xmm1));
1795 1796
      __ CallCFunction(
          ExternalReference::double_fp_operation(Token::MOD, isolate()), 2);
1797
      __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
lrn@chromium.org's avatar
lrn@chromium.org committed
1798
      __ movaps(result, xmm0);
1799 1800 1801 1802 1803
      break;
    default:
      UNREACHABLE();
      break;
  }
1804 1805 1806 1807
}


void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
1808 1809
  ASSERT(ToRegister(instr->left()).is(rdx));
  ASSERT(ToRegister(instr->right()).is(rax));
1810 1811
  ASSERT(ToRegister(instr->result()).is(rax));

1812
  BinaryOpStub stub(instr->op(), NO_OVERWRITE);
1813
  CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
1814
  __ nop();  // Signals no inlined code.
1815 1816 1817
}


1818
int LCodeGen::GetNextEmittedBlock() const {
1819 1820
  for (int i = current_block_ + 1; i < graph()->blocks()->length(); ++i) {
    if (!chunk_->GetLabel(i)->HasReplacement()) return i;
1821 1822 1823 1824 1825 1826
  }
  return -1;
}


void LCodeGen::EmitBranch(int left_block, int right_block, Condition cc) {
1827
  int next_block = GetNextEmittedBlock();
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
  right_block = chunk_->LookupDestination(right_block);
  left_block = chunk_->LookupDestination(left_block);

  if (right_block == left_block) {
    EmitGoto(left_block);
  } else if (left_block == next_block) {
    __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
  } else if (right_block == next_block) {
    __ j(cc, chunk_->GetAssemblyLabel(left_block));
  } else {
    __ j(cc, chunk_->GetAssemblyLabel(left_block));
    if (cc != always) {
      __ jmp(chunk_->GetAssemblyLabel(right_block));
    }
  }
1843 1844 1845 1846
}


void LCodeGen::DoBranch(LBranch* instr) {
1847 1848 1849
  int true_block = chunk_->LookupDestination(instr->true_block_id());
  int false_block = chunk_->LookupDestination(instr->false_block_id());

1850
  Representation r = instr->hydrogen()->value()->representation();
1851
  if (r.IsInteger32()) {
1852
    Register reg = ToRegister(instr->value());
1853 1854 1855
    __ testl(reg, reg);
    EmitBranch(true_block, false_block, not_zero);
  } else if (r.IsDouble()) {
1856
    XMMRegister reg = ToDoubleRegister(instr->value());
lrn@chromium.org's avatar
lrn@chromium.org committed
1857
    __ xorps(xmm0, xmm0);
1858 1859 1860 1861
    __ ucomisd(reg, xmm0);
    EmitBranch(true_block, false_block, not_equal);
  } else {
    ASSERT(r.IsTagged());
1862
    Register reg = ToRegister(instr->value());
1863
    HType type = instr->hydrogen()->value()->type();
1864
    if (type.IsBoolean()) {
1865
      __ CompareRoot(reg, Heap::kTrueValueRootIndex);
1866 1867 1868 1869 1870 1871 1872 1873
      EmitBranch(true_block, false_block, equal);
    } else if (type.IsSmi()) {
      __ SmiCompare(reg, Smi::FromInt(0));
      EmitBranch(true_block, false_block, not_equal);
    } else {
      Label* true_label = chunk_->GetAssemblyLabel(true_block);
      Label* false_label = chunk_->GetAssemblyLabel(false_block);

1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
      ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
      // Avoid deopts in the case where we've never executed this path before.
      if (expected.IsEmpty()) expected = ToBooleanStub::all_types();

      if (expected.Contains(ToBooleanStub::UNDEFINED)) {
        // undefined -> false.
        __ CompareRoot(reg, Heap::kUndefinedValueRootIndex);
        __ j(equal, false_label);
      }
      if (expected.Contains(ToBooleanStub::BOOLEAN)) {
        // true -> true.
        __ CompareRoot(reg, Heap::kTrueValueRootIndex);
        __ j(equal, true_label);
        // false -> false.
        __ CompareRoot(reg, Heap::kFalseValueRootIndex);
        __ j(equal, false_label);
      }
      if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
        // 'null' -> false.
        __ CompareRoot(reg, Heap::kNullValueRootIndex);
        __ j(equal, false_label);
      }

      if (expected.Contains(ToBooleanStub::SMI)) {
        // Smis: 0 -> false, all other -> true.
        __ Cmp(reg, Smi::FromInt(0));
        __ j(equal, false_label);
        __ JumpIfSmi(reg, true_label);
      } else if (expected.NeedsMap()) {
        // If we need a map later and have a Smi -> deopt.
        __ testb(reg, Immediate(kSmiTagMask));
        DeoptimizeIf(zero, instr->environment());
      }

      const Register map = kScratchRegister;
      if (expected.NeedsMap()) {
        __ movq(map, FieldOperand(reg, HeapObject::kMapOffset));
1911 1912 1913 1914 1915 1916 1917

        if (expected.CanBeUndetectable()) {
          // Undetectable -> false.
          __ testb(FieldOperand(map, Map::kBitFieldOffset),
                   Immediate(1 << Map::kIsUndetectable));
          __ j(not_zero, false_label);
        }
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
      }

      if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
        // spec object -> true.
        __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
        __ j(above_equal, true_label);
      }

      if (expected.Contains(ToBooleanStub::STRING)) {
        // String value -> false iff empty.
        Label not_string;
        __ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
        __ j(above_equal, &not_string, Label::kNear);
        __ cmpq(FieldOperand(reg, String::kLengthOffset), Immediate(0));
        __ j(not_zero, true_label);
        __ jmp(false_label);
        __ bind(&not_string);
      }

      if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
        // heap number -> false iff +0, -0, or NaN.
        Label not_heap_number;
        __ CompareRoot(map, Heap::kHeapNumberMapRootIndex);
        __ j(not_equal, &not_heap_number, Label::kNear);
        __ xorps(xmm0, xmm0);
        __ ucomisd(xmm0, FieldOperand(reg, HeapNumber::kValueOffset));
        __ j(zero, false_label);
        __ jmp(true_label);
        __ bind(&not_heap_number);
      }

1949 1950
      // We've seen something for the first time -> deopt.
      DeoptimizeIf(no_condition, instr->environment());
1951 1952
    }
  }
1953 1954 1955
}


1956
void LCodeGen::EmitGoto(int block) {
1957 1958
  if (!IsNextEmittedBlock(block)) {
    __ jmp(chunk_->GetAssemblyLabel(chunk_->LookupDestination(block)));
1959
  }
1960 1961 1962 1963
}


void LCodeGen::DoGoto(LGoto* instr) {
1964
  EmitGoto(instr->block_id());
1965 1966 1967
}


1968
inline Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
  Condition cond = no_condition;
  switch (op) {
    case Token::EQ:
    case Token::EQ_STRICT:
      cond = equal;
      break;
    case Token::LT:
      cond = is_unsigned ? below : less;
      break;
    case Token::GT:
      cond = is_unsigned ? above : greater;
      break;
    case Token::LTE:
      cond = is_unsigned ? below_equal : less_equal;
      break;
    case Token::GTE:
      cond = is_unsigned ? above_equal : greater_equal;
      break;
    case Token::IN:
    case Token::INSTANCEOF:
    default:
      UNREACHABLE();
  }
  return cond;
}


void LCodeGen::DoCmpIDAndBranch(LCmpIDAndBranch* instr) {
1997 1998
  LOperand* left = instr->left();
  LOperand* right = instr->right();
1999 2000
  int false_block = chunk_->LookupDestination(instr->false_block_id());
  int true_block = chunk_->LookupDestination(instr->true_block_id());
2001
  Condition cc = TokenToCondition(instr->op(), instr->is_double());
2002

2003 2004 2005 2006 2007 2008 2009 2010
  if (left->IsConstantOperand() && right->IsConstantOperand()) {
    // We can statically evaluate the comparison.
    double left_val = ToDouble(LConstantOperand::cast(left));
    double right_val = ToDouble(LConstantOperand::cast(right));
    int next_block =
      EvalComparison(instr->op(), left_val, right_val) ? true_block
                                                       : false_block;
    EmitGoto(next_block);
2011
  } else {
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
    if (instr->is_double()) {
      // Don't base result on EFLAGS when a NaN is involved. Instead
      // jump to the false block.
      __ ucomisd(ToDoubleRegister(left), ToDoubleRegister(right));
      __ j(parity_even, chunk_->GetAssemblyLabel(false_block));
    } else {
      int32_t value;
      if (right->IsConstantOperand()) {
        value = ToInteger32(LConstantOperand::cast(right));
        __ cmpl(ToRegister(left), Immediate(value));
      } else if (left->IsConstantOperand()) {
        value = ToInteger32(LConstantOperand::cast(left));
        if (right->IsRegister()) {
          __ cmpl(ToRegister(right), Immediate(value));
        } else {
          __ cmpl(ToOperand(right), Immediate(value));
        }
        // We transposed the operands. Reverse the condition.
        cc = ReverseCondition(cc);
      } else {
        if (right->IsRegister()) {
          __ cmpl(ToRegister(left), ToRegister(right));
        } else {
          __ cmpl(ToRegister(left), ToOperand(right));
        }
      }
    }
    EmitBranch(true_block, false_block, cc);
2040
  }
2041 2042 2043
}


2044
void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2045
  Register left = ToRegister(instr->left());
2046 2047 2048
  int false_block = chunk_->LookupDestination(instr->false_block_id());
  int true_block = chunk_->LookupDestination(instr->true_block_id());

2049 2050 2051 2052 2053
  if (instr->right()->IsConstantOperand()) {
    __ Cmp(left, ToHandle(LConstantOperand::cast(instr->right())));
  } else {
    __ cmpq(left, ToRegister(instr->right()));
  }
2054 2055 2056 2057
  EmitBranch(true_block, false_block, equal);
}


2058
void LCodeGen::DoCmpConstantEqAndBranch(LCmpConstantEqAndBranch* instr) {
2059
  Register left = ToRegister(instr->left());
2060 2061 2062 2063 2064 2065 2066 2067
  int true_block = chunk_->LookupDestination(instr->true_block_id());
  int false_block = chunk_->LookupDestination(instr->false_block_id());

  __ cmpq(left, Immediate(instr->hydrogen()->right()));
  EmitBranch(true_block, false_block, equal);
}


2068
void LCodeGen::DoIsNilAndBranch(LIsNilAndBranch* instr) {
2069
  Register reg = ToRegister(instr->value());
2070 2071
  int false_block = chunk_->LookupDestination(instr->false_block_id());

2072 2073
  // If the expression is known to be untagged or a smi, then it's definitely
  // not null, and it can't be a an undetectable object.
2074 2075 2076 2077 2078 2079 2080
  if (instr->hydrogen()->representation().IsSpecialization() ||
      instr->hydrogen()->type().IsSmi()) {
    EmitGoto(false_block);
    return;
  }

  int true_block = chunk_->LookupDestination(instr->true_block_id());
2081 2082 2083 2084 2085
  Heap::RootListIndex nil_value = instr->nil() == kNullValue ?
      Heap::kNullValueRootIndex :
      Heap::kUndefinedValueRootIndex;
  __ CompareRoot(reg, nil_value);
  if (instr->kind() == kStrictEquality) {
2086 2087
    EmitBranch(true_block, false_block, equal);
  } else {
2088 2089 2090
    Heap::RootListIndex other_nil_value = instr->nil() == kNullValue ?
        Heap::kUndefinedValueRootIndex :
        Heap::kNullValueRootIndex;
2091 2092 2093
    Label* true_label = chunk_->GetAssemblyLabel(true_block);
    Label* false_label = chunk_->GetAssemblyLabel(false_block);
    __ j(equal, true_label);
2094
    __ CompareRoot(reg, other_nil_value);
2095 2096 2097 2098
    __ j(equal, true_label);
    __ JumpIfSmi(reg, false_label);
    // Check for undetectable objects by looking in the bit field in
    // the map. The object has already been smi checked.
2099
    Register scratch = ToRegister(instr->temp());
2100 2101 2102 2103 2104
    __ movq(scratch, FieldOperand(reg, HeapObject::kMapOffset));
    __ testb(FieldOperand(scratch, Map::kBitFieldOffset),
             Immediate(1 << Map::kIsUndetectable));
    EmitBranch(true_block, false_block, not_zero);
  }
2105 2106 2107 2108 2109 2110
}


Condition LCodeGen::EmitIsObject(Register input,
                                 Label* is_not_object,
                                 Label* is_object) {
2111
  ASSERT(!input.is(kScratchRegister));
2112 2113 2114

  __ JumpIfSmi(input, is_not_object);

2115
  __ CompareRoot(input, Heap::kNullValueRootIndex);
2116 2117
  __ j(equal, is_object);

2118
  __ movq(kScratchRegister, FieldOperand(input, HeapObject::kMapOffset));
2119
  // Undetectable objects behave like undefined.
2120
  __ testb(FieldOperand(kScratchRegister, Map::kBitFieldOffset),
2121 2122 2123
           Immediate(1 << Map::kIsUndetectable));
  __ j(not_zero, is_not_object);

2124 2125
  __ movzxbl(kScratchRegister,
             FieldOperand(kScratchRegister, Map::kInstanceTypeOffset));
2126
  __ cmpb(kScratchRegister, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2127
  __ j(below, is_not_object);
2128
  __ cmpb(kScratchRegister, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE));
2129 2130 2131 2132 2133
  return below_equal;
}


void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
2134
  Register reg = ToRegister(instr->value());
2135 2136 2137 2138 2139 2140

  int true_block = chunk_->LookupDestination(instr->true_block_id());
  int false_block = chunk_->LookupDestination(instr->false_block_id());
  Label* true_label = chunk_->GetAssemblyLabel(true_block);
  Label* false_label = chunk_->GetAssemblyLabel(false_block);

2141
  Condition true_cond = EmitIsObject(reg, false_label, true_label);
2142 2143

  EmitBranch(true_block, false_block, true_cond);
2144 2145 2146
}


2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
Condition LCodeGen::EmitIsString(Register input,
                                 Register temp1,
                                 Label* is_not_string) {
  __ JumpIfSmi(input, is_not_string);
  Condition cond =  masm_->IsObjectStringType(input, temp1, temp1);

  return cond;
}


void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2158 2159
  Register reg = ToRegister(instr->value());
  Register temp = ToRegister(instr->temp());
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170

  int true_block = chunk_->LookupDestination(instr->true_block_id());
  int false_block = chunk_->LookupDestination(instr->false_block_id());
  Label* false_label = chunk_->GetAssemblyLabel(false_block);

  Condition true_cond = EmitIsString(reg, temp, false_label);

  EmitBranch(true_block, false_block, true_cond);
}


2171
void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2172 2173 2174 2175
  int true_block = chunk_->LookupDestination(instr->true_block_id());
  int false_block = chunk_->LookupDestination(instr->false_block_id());

  Condition is_smi;
2176 2177
  if (instr->value()->IsRegister()) {
    Register input = ToRegister(instr->value());
2178 2179
    is_smi = masm()->CheckSmi(input);
  } else {
2180
    Operand input = ToOperand(instr->value());
2181 2182 2183 2184 2185 2186
    is_smi = masm()->CheckSmi(input);
  }
  EmitBranch(true_block, false_block, is_smi);
}


2187
void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2188 2189
  Register input = ToRegister(instr->value());
  Register temp = ToRegister(instr->temp());
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201

  int true_block = chunk_->LookupDestination(instr->true_block_id());
  int false_block = chunk_->LookupDestination(instr->false_block_id());

  __ JumpIfSmi(input, chunk_->GetAssemblyLabel(false_block));
  __ movq(temp, FieldOperand(input, HeapObject::kMapOffset));
  __ testb(FieldOperand(temp, Map::kBitFieldOffset),
           Immediate(1 << Map::kIsUndetectable));
  EmitBranch(true_block, false_block, not_zero);
}


2202 2203 2204 2205 2206
void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
  Token::Value op = instr->op();
  int true_block = chunk_->LookupDestination(instr->true_block_id());
  int false_block = chunk_->LookupDestination(instr->false_block_id());

2207
  Handle<Code> ic = CompareIC::GetUninitialized(isolate(), op);
2208 2209 2210 2211 2212 2213 2214 2215 2216
  CallCode(ic, RelocInfo::CODE_TARGET, instr);

  Condition condition = TokenToCondition(op, false);
  __ testq(rax, rax);

  EmitBranch(true_block, false_block, condition);
}


2217
static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2218 2219 2220 2221 2222 2223 2224 2225
  InstanceType from = instr->from();
  InstanceType to = instr->to();
  if (from == FIRST_TYPE) return to;
  ASSERT(from == to || to == LAST_TYPE);
  return from;
}


2226
static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2227 2228 2229 2230 2231 2232 2233
  InstanceType from = instr->from();
  InstanceType to = instr->to();
  if (from == to) return equal;
  if (to == LAST_TYPE) return above_equal;
  if (from == FIRST_TYPE) return below_equal;
  UNREACHABLE();
  return equal;
2234 2235 2236 2237
}


void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2238
  Register input = ToRegister(instr->value());
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248

  int true_block = chunk_->LookupDestination(instr->true_block_id());
  int false_block = chunk_->LookupDestination(instr->false_block_id());

  Label* false_label = chunk_->GetAssemblyLabel(false_block);

  __ JumpIfSmi(input, false_label);

  __ CmpObjectType(input, TestType(instr->hydrogen()), kScratchRegister);
  EmitBranch(true_block, false_block, BranchCondition(instr->hydrogen()));
2249 2250 2251
}


2252
void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
2253
  Register input = ToRegister(instr->value());
2254 2255
  Register result = ToRegister(instr->result());

2256
  __ AssertString(input);
2257 2258 2259 2260 2261 2262 2263

  __ movl(result, FieldOperand(input, String::kHashFieldOffset));
  ASSERT(String::kHashShift >= kSmiTagSize);
  __ IndexFromHash(result, result);
}


2264 2265
void LCodeGen::DoHasCachedArrayIndexAndBranch(
    LHasCachedArrayIndexAndBranch* instr) {
2266
  Register input = ToRegister(instr->value());
2267 2268 2269 2270 2271 2272

  int true_block = chunk_->LookupDestination(instr->true_block_id());
  int false_block = chunk_->LookupDestination(instr->false_block_id());

  __ testl(FieldOperand(input, String::kHashFieldOffset),
           Immediate(String::kContainsCachedArrayIndexMask));
2273
  EmitBranch(true_block, false_block, equal);
2274 2275 2276
}


2277
// Branches to a label or falls through with the answer in the z flag.
2278
// Trashes the temp register.
2279 2280
void LCodeGen::EmitClassOfTest(Label* is_true,
                               Label* is_false,
2281
                               Handle<String> class_name,
2282
                               Register input,
2283
                               Register temp,
2284 2285 2286 2287 2288
                               Register temp2) {
  ASSERT(!input.is(temp));
  ASSERT(!input.is(temp2));
  ASSERT(!temp.is(temp2));

2289 2290
  __ JumpIfSmi(input, is_false);

2291
  if (class_name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("Function"))) {
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
    // Assuming the following assertions, we can use the same compares to test
    // for both being a function type and being in the object type range.
    STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
    STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
                  FIRST_SPEC_OBJECT_TYPE + 1);
    STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
                  LAST_SPEC_OBJECT_TYPE - 1);
    STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
    __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
    __ j(below, is_false);
    __ j(equal, is_true);
    __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
    __ j(equal, is_true);
2305
  } else {
2306 2307 2308
    // Faster code path to avoid two compares: subtract lower bound from the
    // actual type and do a signed compare with the width of the type range.
    __ movq(temp, FieldOperand(input, HeapObject::kMapOffset));
2309 2310 2311 2312
    __ movzxbl(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
    __ subq(temp2, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
    __ cmpq(temp2, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
                             FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
2313 2314 2315 2316
    __ j(above, is_false);
  }

  // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
2317 2318 2319 2320 2321
  // Check if the constructor in the map is a function.
  __ movq(temp, FieldOperand(temp, Map::kConstructorOffset));

  // Objects with a non-function constructor have class 'Object'.
  __ CmpObjectType(temp, JS_FUNCTION_TYPE, kScratchRegister);
2322
  if (class_name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("Object"))) {
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
    __ j(not_equal, is_true);
  } else {
    __ j(not_equal, is_false);
  }

  // temp now contains the constructor function. Grab the
  // instance class name from there.
  __ movq(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
  __ movq(temp, FieldOperand(temp,
                             SharedFunctionInfo::kInstanceClassNameOffset));
2333 2334 2335
  // The class name we are testing against is internalized since it's a literal.
  // The name in the constructor is internalized because of the way the context
  // is booted.  This routine isn't expected to work for random API-created
2336
  // classes and it doesn't have to because you can't access it with natives
2337 2338 2339
  // syntax.  Since both sides are internalized it is sufficient to use an
  // identity comparison.
  ASSERT(class_name->IsInternalizedString());
2340 2341
  __ Cmp(temp, class_name);
  // End with the answer in the z flag.
2342 2343 2344 2345
}


void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2346 2347 2348
  Register input = ToRegister(instr->value());
  Register temp = ToRegister(instr->temp());
  Register temp2 = ToRegister(instr->temp2());
2349 2350 2351 2352 2353 2354 2355 2356
  Handle<String> class_name = instr->hydrogen()->class_name();

  int true_block = chunk_->LookupDestination(instr->true_block_id());
  int false_block = chunk_->LookupDestination(instr->false_block_id());

  Label* true_label = chunk_->GetAssemblyLabel(true_block);
  Label* false_label = chunk_->GetAssemblyLabel(false_block);

2357
  EmitClassOfTest(true_label, false_label, class_name, input, temp, temp2);
2358 2359

  EmitBranch(true_block, false_block, equal);
2360 2361 2362 2363
}


void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2364
  Register reg = ToRegister(instr->value());
2365 2366 2367 2368 2369
  int true_block = instr->true_block_id();
  int false_block = instr->false_block_id();

  __ Cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
  EmitBranch(true_block, false_block, equal);
2370 2371 2372 2373
}


void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
2374
  InstanceofStub stub(InstanceofStub::kNoFlags);
2375 2376
  __ push(ToRegister(instr->left()));
  __ push(ToRegister(instr->right()));
2377
  CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
2378
  Label true_value, done;
2379
  __ testq(rax, rax);
2380
  __ j(zero, &true_value, Label::kNear);
2381
  __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex);
2382
  __ jmp(&done, Label::kNear);
2383 2384 2385
  __ bind(&true_value);
  __ LoadRoot(ToRegister(instr->result()), Heap::kTrueValueRootIndex);
  __ bind(&done);
2386 2387 2388 2389
}


void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2390 2391 2392 2393 2394 2395
  class DeferredInstanceOfKnownGlobal: public LDeferredCode {
   public:
    DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
                                  LInstanceOfKnownGlobal* instr)
        : LDeferredCode(codegen), instr_(instr) { }
    virtual void Generate() {
2396
      codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
2397
    }
2398
    virtual LInstruction* instr() { return instr_; }
2399
    Label* map_check() { return &map_check_; }
2400 2401
   private:
    LInstanceOfKnownGlobal* instr_;
2402
    Label map_check_;
2403 2404 2405 2406
  };


  DeferredInstanceOfKnownGlobal* deferred;
2407
  deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr);
2408

2409
  Label done, false_result;
2410
  Register object = ToRegister(instr->value());
2411 2412 2413 2414

  // A Smi is not an instance of anything.
  __ JumpIfSmi(object, &false_result);

2415 2416 2417
  // This is the inlined call site instanceof cache. The two occurences of the
  // hole value will be patched to the last map/result pair generated by the
  // instanceof stub.
2418
  Label cache_miss;
2419
  // Use a temp register to avoid memory operands with variable lengths.
2420
  Register map = ToRegister(instr->temp());
2421 2422
  __ movq(map, FieldOperand(object, HeapObject::kMapOffset));
  __ bind(deferred->map_check());  // Label for calculating code patching.
2423 2424 2425 2426
  Handle<JSGlobalPropertyCell> cache_cell =
      factory()->NewJSGlobalPropertyCell(factory()->the_hole_value());
  __ movq(kScratchRegister, cache_cell, RelocInfo::GLOBAL_PROPERTY_CELL);
  __ cmpq(map, Operand(kScratchRegister, 0));
2427
  __ j(not_equal, &cache_miss, Label::kNear);
2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
  // Patched to load either true or false.
  __ LoadRoot(ToRegister(instr->result()), Heap::kTheHoleValueRootIndex);
#ifdef DEBUG
  // Check that the code size between patch label and patch sites is invariant.
  Label end_of_patched_code;
  __ bind(&end_of_patched_code);
  ASSERT(true);
#endif
  __ jmp(&done);

  // The inlined call site cache did not match. Check for null and string
  // before calling the deferred code.
  __ bind(&cache_miss);  // Null is not an instance of anything.
2441
  __ CompareRoot(object, Heap::kNullValueRootIndex);
2442
  __ j(equal, &false_result, Label::kNear);
2443 2444 2445 2446 2447 2448 2449 2450

  // String values are not instances of anything.
  __ JumpIfNotString(object, kScratchRegister, deferred->entry());

  __ bind(&false_result);
  __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex);

  __ bind(deferred->exit());
2451
  __ bind(&done);
2452 2453 2454
}


2455 2456
void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
                                               Label* map_check) {
2457 2458 2459 2460 2461
  {
    PushSafepointRegistersScope scope(this);
    InstanceofStub::Flags flags = static_cast<InstanceofStub::Flags>(
        InstanceofStub::kNoFlags | InstanceofStub::kCallSiteInlineCheck);
    InstanceofStub stub(flags);
2462

2463
    __ push(ToRegister(instr->value()));
2464
    __ PushHeapObject(instr->function());
2465

2466
    static const int kAdditionalDelta = 10;
2467 2468
    int delta =
        masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
2469 2470
    ASSERT(delta >= 0);
    __ push_imm32(delta);
2471 2472 2473 2474 2475

    // We are pushing three values on the stack but recording a
    // safepoint with two arguments because stub is going to
    // remove the third argument from the stack before jumping
    // to instanceof builtin on the slow path.
2476
    CallCodeGeneric(stub.GetCode(isolate()),
2477 2478 2479 2480 2481
                    RelocInfo::CODE_TARGET,
                    instr,
                    RECORD_SAFEPOINT_WITH_REGISTERS,
                    2);
    ASSERT(delta == masm_->SizeOfCodeGeneratedSince(map_check));
2482
    LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
2483
    safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
2484 2485
    // Move result to a register that survives the end of the
    // PushSafepointRegisterScope.
2486 2487
    __ movq(kScratchRegister, rax);
  }
2488 2489 2490 2491 2492 2493 2494 2495 2496
  __ testq(kScratchRegister, kScratchRegister);
  Label load_false;
  Label done;
  __ j(not_zero, &load_false);
  __ LoadRoot(rax, Heap::kTrueValueRootIndex);
  __ jmp(&done);
  __ bind(&load_false);
  __ LoadRoot(rax, Heap::kFalseValueRootIndex);
  __ bind(&done);
2497 2498 2499
}


2500 2501 2502 2503 2504 2505 2506 2507
void LCodeGen::DoInstanceSize(LInstanceSize* instr) {
  Register object = ToRegister(instr->object());
  Register result = ToRegister(instr->result());
  __ movq(result, FieldOperand(object, HeapObject::kMapOffset));
  __ movzxbq(result, FieldOperand(result, Map::kInstanceSizeOffset));
}


2508
void LCodeGen::DoCmpT(LCmpT* instr) {
2509 2510
  Token::Value op = instr->op();

2511
  Handle<Code> ic = CompareIC::GetUninitialized(isolate(), op);
2512 2513 2514
  CallCode(ic, RelocInfo::CODE_TARGET, instr);

  Condition condition = TokenToCondition(op, false);
2515
  Label true_value, done;
2516
  __ testq(rax, rax);
2517
  __ j(condition, &true_value, Label::kNear);
2518
  __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex);
2519
  __ jmp(&done, Label::kNear);
2520 2521 2522
  __ bind(&true_value);
  __ LoadRoot(ToRegister(instr->result()), Heap::kTrueValueRootIndex);
  __ bind(&done);
2523 2524 2525 2526
}


void LCodeGen::DoReturn(LReturn* instr) {
2527
  if (FLAG_trace && info()->IsOptimizing()) {
2528 2529 2530 2531 2532
    // Preserve the return value on the stack and rely on the runtime
    // call to return the value in the same register.
    __ push(rax);
    __ CallRuntime(Runtime::kTraceExit, 1);
  }
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
  if (info()->saves_caller_doubles()) {
    ASSERT(NeedsEagerFrame());
    BitVector* doubles = chunk()->allocated_double_registers();
    BitVector::Iterator save_iterator(doubles);
    int count = 0;
    while (!save_iterator.Done()) {
      __ movsd(XMMRegister::FromAllocationIndex(save_iterator.Current()),
               MemOperand(rsp, count * kDoubleSize));
      save_iterator.Advance();
      count++;
    }
  }
2545 2546 2547 2548
  if (NeedsEagerFrame()) {
    __ movq(rsp, rbp);
    __ pop(rbp);
  }
2549 2550 2551
  if (instr->has_constant_parameter_count()) {
    __ Ret((ToInteger32(instr->constant_parameter_count()) + 1) * kPointerSize,
           rcx);
2552
  } else {
2553 2554 2555 2556 2557 2558
    Register reg = ToRegister(instr->parameter_count());
    Register return_addr_reg = reg.is(rcx) ? rbx : rcx;
    __ pop(return_addr_reg);
    __ shl(reg, Immediate(kPointerSizeLog2));
    __ addq(rsp, reg);
    __ jmp(return_addr_reg);
2559
  }
2560 2561 2562
}


2563
void LCodeGen::DoLoadGlobalCell(LLoadGlobalCell* instr) {
2564
  Register result = ToRegister(instr->result());
2565
  __ LoadGlobalCell(result, instr->hydrogen()->cell());
2566
  if (instr->hydrogen()->RequiresHoleCheck()) {
2567 2568 2569
    __ CompareRoot(result, Heap::kTheHoleValueRootIndex);
    DeoptimizeIf(equal, instr->environment());
  }
2570 2571 2572
}


2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584
void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
  ASSERT(ToRegister(instr->global_object()).is(rax));
  ASSERT(ToRegister(instr->result()).is(rax));

  __ Move(rcx, instr->name());
  RelocInfo::Mode mode = instr->for_typeof() ? RelocInfo::CODE_TARGET :
                                               RelocInfo::CODE_TARGET_CONTEXT;
  Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize();
  CallCode(ic, mode, instr);
}


2585
void LCodeGen::DoStoreGlobalCell(LStoreGlobalCell* instr) {
2586 2587
  Register value = ToRegister(instr->value());
  Handle<JSGlobalPropertyCell> cell_handle = instr->hydrogen()->cell();
2588

2589 2590 2591 2592
  // If the cell we are storing to contains the hole it could have
  // been deleted from the property dictionary. In that case, we need
  // to update the property details in the property dictionary to mark
  // it as no longer deleted. We deoptimize in that case.
2593
  if (instr->hydrogen()->RequiresHoleCheck()) {
2594
    // We have a temp because CompareRoot might clobber kScratchRegister.
2595
    Register cell = ToRegister(instr->temp());
2596 2597 2598
    ASSERT(!value.is(cell));
    __ movq(cell, cell_handle, RelocInfo::GLOBAL_PROPERTY_CELL);
    __ CompareRoot(Operand(cell, 0), Heap::kTheHoleValueRootIndex);
2599
    DeoptimizeIf(equal, instr->environment());
2600 2601 2602 2603 2604 2605
    // Store the value.
    __ movq(Operand(cell, 0), value);
  } else {
    // Store the value.
    __ movq(kScratchRegister, cell_handle, RelocInfo::GLOBAL_PROPERTY_CELL);
    __ movq(Operand(kScratchRegister, 0), value);
2606
  }
2607
  // Cells are always rescanned, so no write barrier here.
2608 2609 2610
}


2611 2612 2613 2614 2615
void LCodeGen::DoStoreGlobalGeneric(LStoreGlobalGeneric* instr) {
  ASSERT(ToRegister(instr->global_object()).is(rdx));
  ASSERT(ToRegister(instr->value()).is(rax));

  __ Move(rcx, instr->name());
2616
  Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode)
mmaly@chromium.org's avatar
mmaly@chromium.org committed
2617 2618
      ? isolate()->builtins()->StoreIC_Initialize_Strict()
      : isolate()->builtins()->StoreIC_Initialize();
2619 2620 2621 2622
  CallCode(ic, RelocInfo::CODE_TARGET_CONTEXT, instr);
}


2623
void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
whesse@chromium.org's avatar
whesse@chromium.org committed
2624
  Register context = ToRegister(instr->context());
2625
  Register result = ToRegister(instr->result());
whesse@chromium.org's avatar
whesse@chromium.org committed
2626
  __ movq(result, ContextOperand(context, instr->slot_index()));
2627 2628
  if (instr->hydrogen()->RequiresHoleCheck()) {
    __ CompareRoot(result, Heap::kTheHoleValueRootIndex);
2629 2630 2631 2632 2633
    if (instr->hydrogen()->DeoptimizesOnHole()) {
      DeoptimizeIf(equal, instr->environment());
    } else {
      Label is_not_hole;
      __ j(not_equal, &is_not_hole, Label::kNear);
2634
      __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
2635 2636
      __ bind(&is_not_hole);
    }
2637
  }
2638 2639 2640 2641
}


void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
whesse@chromium.org's avatar
whesse@chromium.org committed
2642
  Register context = ToRegister(instr->context());
2643
  Register value = ToRegister(instr->value());
2644

2645
  Operand target = ContextOperand(context, instr->slot_index());
2646 2647

  Label skip_assignment;
2648 2649
  if (instr->hydrogen()->RequiresHoleCheck()) {
    __ CompareRoot(target, Heap::kTheHoleValueRootIndex);
2650 2651 2652
    if (instr->hydrogen()->DeoptimizesOnHole()) {
      DeoptimizeIf(equal, instr->environment());
    } else {
2653
      __ j(not_equal, &skip_assignment);
2654
    }
2655 2656
  }
  __ movq(target, value);
2657

2658 2659 2660 2661
  if (instr->hydrogen()->NeedsWriteBarrier()) {
    HType type = instr->hydrogen()->value()->type();
    SmiCheck check_needed =
        type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2662
    int offset = Context::SlotOffset(instr->slot_index());
2663
    Register scratch = ToRegister(instr->temp());
2664 2665 2666 2667 2668 2669 2670
    __ RecordWriteContextSlot(context,
                              offset,
                              value,
                              scratch,
                              kSaveFPRegs,
                              EMIT_REMEMBERED_SET,
                              check_needed);
2671
  }
2672 2673

  __ bind(&skip_assignment);
2674 2675 2676
}


2677
void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
2678
  Register object = ToRegister(instr->object());
2679 2680 2681 2682 2683 2684 2685
  Register result = ToRegister(instr->result());
  if (instr->hydrogen()->is_in_object()) {
    __ movq(result, FieldOperand(object, instr->hydrogen()->offset()));
  } else {
    __ movq(result, FieldOperand(object, JSObject::kPropertiesOffset));
    __ movq(result, FieldOperand(result, instr->hydrogen()->offset()));
  }
2686 2687 2688
}


2689 2690 2691
void LCodeGen::EmitLoadFieldOrConstantFunction(Register result,
                                               Register object,
                                               Handle<Map> type,
2692 2693
                                               Handle<String> name,
                                               LEnvironment* env) {
2694
  LookupResult lookup(isolate());
2695
  type->LookupDescriptor(NULL, *name, &lookup);
2696
  ASSERT(lookup.IsFound() || lookup.IsCacheable());
2697
  if (lookup.IsField()) {
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
    int index = lookup.GetLocalFieldIndexFromMap(*type);
    int offset = index * kPointerSize;
    if (index < 0) {
      // Negative property indices are in-object properties, indexed
      // from the end of the fixed part of the object.
      __ movq(result, FieldOperand(object, offset + type->instance_size()));
    } else {
      // Non-negative property indices are in the properties array.
      __ movq(result, FieldOperand(object, JSObject::kPropertiesOffset));
      __ movq(result, FieldOperand(result, offset + FixedArray::kHeaderSize));
    }
2709
  } else if (lookup.IsConstantFunction()) {
2710
    Handle<JSFunction> function(lookup.GetConstantFunctionFromMap(*type));
2711
    __ LoadHeapObject(result, function);
2712 2713 2714
  } else {
    // Negative lookup.
    // Check prototypes.
2715
    Handle<HeapObject> current(HeapObject::cast((*type)->prototype()));
2716
    Heap* heap = type->GetHeap();
2717 2718
    while (*current != heap->null_value()) {
      __ LoadHeapObject(result, current);
2719
      __ Cmp(FieldOperand(result, HeapObject::kMapOffset),
2720
                          Handle<Map>(current->map()));
2721
      DeoptimizeIf(not_equal, env);
2722 2723
      current =
          Handle<HeapObject>(HeapObject::cast(current->map()->prototype()));
2724 2725
    }
    __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
2726 2727 2728 2729
  }
}


2730 2731
// Check for cases where EmitLoadFieldOrConstantFunction needs to walk the
// prototype chain, which causes unbounded code generation.
2732 2733 2734 2735
static bool CompactEmit(SmallMapList* list,
                        Handle<String> name,
                        int i,
                        Isolate* isolate) {
2736
  Handle<Map> map = list->at(i);
2737 2738
  // If the map has ElementsKind transitions, we will generate map checks
  // for each kind in __ CompareMap(..., ALLOW_ELEMENTS_TRANSITION_MAPS).
2739
  if (map->HasElementsTransition()) return false;
2740
  LookupResult lookup(isolate);
2741
  map->LookupDescriptor(NULL, *name, &lookup);
2742
  return lookup.IsField() || lookup.IsConstantFunction();
2743 2744 2745
}


2746 2747 2748 2749 2750
void LCodeGen::DoLoadNamedFieldPolymorphic(LLoadNamedFieldPolymorphic* instr) {
  Register object = ToRegister(instr->object());
  Register result = ToRegister(instr->result());

  int map_count = instr->hydrogen()->types()->length();
2751
  bool need_generic = instr->hydrogen()->need_generic();
2752

2753 2754 2755 2756 2757 2758
  if (map_count == 0 && !need_generic) {
    DeoptimizeIf(no_condition, instr->environment());
    return;
  }
  Handle<String> name = instr->hydrogen()->name();
  Label done;
2759
  bool all_are_compact = true;
2760
  for (int i = 0; i < map_count; ++i) {
2761 2762
    if (!CompactEmit(instr->hydrogen()->types(), name, i, isolate())) {
      all_are_compact = false;
2763 2764 2765
      break;
    }
  }
2766 2767 2768
  for (int i = 0; i < map_count; ++i) {
    bool last = (i == map_count - 1);
    Handle<Map> map = instr->hydrogen()->types()->at(i);
2769 2770
    Label check_passed;
    __ CompareMap(object, map, &check_passed, ALLOW_ELEMENT_TRANSITION_MAPS);
2771 2772
    if (last && !need_generic) {
      DeoptimizeIf(not_equal, instr->environment());
2773 2774 2775
      __ bind(&check_passed);
      EmitLoadFieldOrConstantFunction(
          result, object, map, name, instr->environment());
2776
    } else {
2777
      Label next;
2778 2779 2780
      bool compact = all_are_compact ? true :
          CompactEmit(instr->hydrogen()->types(), name, i, isolate());
      __ j(not_equal, &next, compact ? Label::kNear : Label::kFar);
2781 2782 2783
      __ bind(&check_passed);
      EmitLoadFieldOrConstantFunction(
          result, object, map, name, instr->environment());
2784
      __ jmp(&done, all_are_compact ? Label::kNear : Label::kFar);
2785 2786 2787
      __ bind(&next);
    }
  }
2788 2789 2790 2791 2792 2793
  if (need_generic) {
    __ Move(rcx, name);
    Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize();
    CallCode(ic, RelocInfo::CODE_TARGET, instr);
  }
  __ bind(&done);
2794 2795 2796
}


2797
void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
2798 2799 2800 2801
  ASSERT(ToRegister(instr->object()).is(rax));
  ASSERT(ToRegister(instr->result()).is(rax));

  __ Move(rcx, instr->name());
2802
  Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize();
2803
  CallCode(ic, RelocInfo::CODE_TARGET, instr);
2804 2805 2806 2807
}


void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
2808 2809 2810 2811 2812 2813 2814 2815
  Register function = ToRegister(instr->function());
  Register result = ToRegister(instr->result());

  // Check that the function really is a function.
  __ CmpObjectType(function, JS_FUNCTION_TYPE, result);
  DeoptimizeIf(not_equal, instr->environment());

  // Check whether the function has an instance prototype.
2816
  Label non_instance;
2817 2818
  __ testb(FieldOperand(result, Map::kBitFieldOffset),
           Immediate(1 << Map::kHasNonInstancePrototype));
2819
  __ j(not_zero, &non_instance, Label::kNear);
2820 2821 2822 2823 2824 2825 2826 2827 2828 2829

  // Get the prototype or initial map from the function.
  __ movq(result,
         FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));

  // Check that the function has a prototype or an initial map.
  __ CompareRoot(result, Heap::kTheHoleValueRootIndex);
  DeoptimizeIf(equal, instr->environment());

  // If the function does not have an initial map, we're done.
2830
  Label done;
2831
  __ CmpObjectType(result, MAP_TYPE, kScratchRegister);
2832
  __ j(not_equal, &done, Label::kNear);
2833 2834 2835

  // Get the prototype from the initial map.
  __ movq(result, FieldOperand(result, Map::kPrototypeOffset));
2836
  __ jmp(&done, Label::kNear);
2837 2838 2839 2840 2841 2842 2843 2844

  // Non-instance prototype: Fetch prototype from constructor field
  // in the function's map.
  __ bind(&non_instance);
  __ movq(result, FieldOperand(result, Map::kConstructorOffset));

  // All done.
  __ bind(&done);
2845 2846 2847 2848
}


void LCodeGen::DoLoadElements(LLoadElements* instr) {
2849
  Register result = ToRegister(instr->result());
2850
  Register input = ToRegister(instr->object());
2851
  __ movq(result, FieldOperand(input, JSObject::kElementsOffset));
2852
  if (FLAG_debug_code) {
2853
    Label done, ok, fail;
2854 2855
    __ CompareRoot(FieldOperand(result, HeapObject::kMapOffset),
                   Heap::kFixedArrayMapRootIndex);
2856
    __ j(equal, &done, Label::kNear);
2857 2858
    __ CompareRoot(FieldOperand(result, HeapObject::kMapOffset),
                   Heap::kFixedCOWArrayMapRootIndex);
2859
    __ j(equal, &done, Label::kNear);
2860 2861 2862
    Register temp((result.is(rax)) ? rbx : rax);
    __ push(temp);
    __ movq(temp, FieldOperand(result, HeapObject::kMapOffset));
2863 2864 2865
    __ movzxbq(temp, FieldOperand(temp, Map::kBitField2Offset));
    __ and_(temp, Immediate(Map::kElementsKindMask));
    __ shr(temp, Immediate(Map::kElementsKindShift));
2866 2867 2868 2869
    __ cmpl(temp, Immediate(GetInitialFastElementsKind()));
    __ j(less, &fail, Label::kNear);
    __ cmpl(temp, Immediate(TERMINAL_FAST_ELEMENTS_KIND));
    __ j(less_equal, &ok, Label::kNear);
2870
    __ cmpl(temp, Immediate(FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND));
2871
    __ j(less, &fail, Label::kNear);
2872
    __ cmpl(temp, Immediate(LAST_EXTERNAL_ARRAY_ELEMENTS_KIND));
2873 2874 2875 2876
    __ j(less_equal, &ok, Label::kNear);
    __ bind(&fail);
    __ Abort("Check for fast or external elements failed");
    __ bind(&ok);
2877
    __ pop(temp);
2878 2879
    __ bind(&done);
  }
2880 2881 2882
}


2883 2884
void LCodeGen::DoLoadExternalArrayPointer(
    LLoadExternalArrayPointer* instr) {
2885
  Register result = ToRegister(instr->result());
2886
  Register input = ToRegister(instr->object());
2887 2888
  __ movq(result, FieldOperand(input,
                               ExternalPixelArray::kExternalPointerOffset));
2889 2890 2891
}


2892
void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
ager@chromium.org's avatar
ager@chromium.org committed
2893 2894
  Register arguments = ToRegister(instr->arguments());
  Register result = ToRegister(instr->result());
2895 2896 2897 2898 2899 2900 2901

  if (instr->length()->IsConstantOperand() &&
      instr->index()->IsConstantOperand()) {
    int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
    int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
    int index = (const_length - const_index) + 1;
    __ movq(result, Operand(arguments, index * kPointerSize));
ager@chromium.org's avatar
ager@chromium.org committed
2902
  } else {
2903 2904 2905 2906 2907 2908 2909 2910 2911 2912
    Register length = ToRegister(instr->length());
    // There are two words between the frame pointer and the last argument.
    // Subtracting from length accounts for one of them add one more.
    if (instr->index()->IsRegister()) {
      __ subl(length, ToRegister(instr->index()));
    } else {
      __ subl(length, ToOperand(instr->index()));
    }
    __ movq(result,
            Operand(arguments, length, times_pointer_size, kPointerSize));
ager@chromium.org's avatar
ager@chromium.org committed
2913
  }
2914 2915 2916
}


2917 2918 2919 2920 2921
void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
  ElementsKind elements_kind = instr->elements_kind();
  LOperand* key = instr->key();
  if (!key->IsConstantOperand()) {
    Register key_reg = ToRegister(key);
2922 2923 2924 2925 2926
    // Even though the HLoad/StoreKeyed (in this case) instructions force
    // the input representation for the key to be an integer, the input
    // gets replaced during bound check elimination with the index argument
    // to the bounds check, which can be tagged, so that case must be
    // handled here, too.
2927
    if (instr->hydrogen()->key()->representation().IsTagged()) {
2928
      __ SmiToInteger64(key_reg, key_reg);
2929
    } else if (instr->hydrogen()->IsDehoisted()) {
2930 2931 2932 2933
      // Sign extend key because it could be a 32 bit negative value
      // and the dehoisted address computation happens in 64 bits
      __ movsxlq(key_reg, key_reg);
    }
2934
  }
2935 2936 2937 2938 2939 2940
  Operand operand(BuildFastArrayOperand(
      instr->elements(),
      key,
      elements_kind,
      0,
      instr->additional_index()));
2941

2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985
  if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) {
    XMMRegister result(ToDoubleRegister(instr->result()));
    __ movss(result, operand);
    __ cvtss2sd(result, result);
  } else if (elements_kind == EXTERNAL_DOUBLE_ELEMENTS) {
    __ movsd(ToDoubleRegister(instr->result()), operand);
  } else {
    Register result(ToRegister(instr->result()));
    switch (elements_kind) {
      case EXTERNAL_BYTE_ELEMENTS:
        __ movsxbq(result, operand);
        break;
      case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
      case EXTERNAL_PIXEL_ELEMENTS:
        __ movzxbq(result, operand);
        break;
      case EXTERNAL_SHORT_ELEMENTS:
        __ movsxwq(result, operand);
        break;
      case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
        __ movzxwq(result, operand);
        break;
      case EXTERNAL_INT_ELEMENTS:
        __ movsxlq(result, operand);
        break;
      case EXTERNAL_UNSIGNED_INT_ELEMENTS:
        __ movl(result, operand);
        if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
          __ testl(result, result);
          DeoptimizeIf(negative, instr->environment());
        }
        break;
      case EXTERNAL_FLOAT_ELEMENTS:
      case EXTERNAL_DOUBLE_ELEMENTS:
      case FAST_ELEMENTS:
      case FAST_SMI_ELEMENTS:
      case FAST_DOUBLE_ELEMENTS:
      case FAST_HOLEY_ELEMENTS:
      case FAST_HOLEY_SMI_ELEMENTS:
      case FAST_HOLEY_DOUBLE_ELEMENTS:
      case DICTIONARY_ELEMENTS:
      case NON_STRICT_ARGUMENTS_ELEMENTS:
        UNREACHABLE();
        break;
2986
    }
2987
  }
2988 2989 2990
}


2991
void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
2992
  XMMRegister result(ToDoubleRegister(instr->result()));
2993
  LOperand* key = instr->key();
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
  if (!key->IsConstantOperand()) {
    Register key_reg = ToRegister(key);
    // Even though the HLoad/StoreKeyed instructions force the input
    // representation for the key to be an integer, the input gets replaced
    // during bound check elimination with the index argument to the bounds
    // check, which can be tagged, so that case must be handled here, too.
    if (instr->hydrogen()->key()->representation().IsTagged()) {
      __ SmiToInteger64(key_reg, key_reg);
    } else if (instr->hydrogen()->IsDehoisted()) {
      // Sign extend key because it could be a 32 bit negative value
      // and the dehoisted address computation happens in 64 bits
      __ movsxlq(key_reg, key_reg);
    }
  }

3009 3010 3011 3012 3013
  if (instr->hydrogen()->RequiresHoleCheck()) {
    int offset = FixedDoubleArray::kHeaderSize - kHeapObjectTag +
        sizeof(kHoleNanLower32);
    Operand hole_check_operand = BuildFastArrayOperand(
        instr->elements(),
3014
        key,
3015 3016 3017 3018 3019 3020
        FAST_DOUBLE_ELEMENTS,
        offset,
        instr->additional_index());
    __ cmpl(hole_check_operand, Immediate(kHoleNanUpper32));
    DeoptimizeIf(equal, instr->environment());
  }
3021 3022

  Operand double_load_operand = BuildFastArrayOperand(
3023
      instr->elements(),
3024
      key,
3025 3026 3027
      FAST_DOUBLE_ELEMENTS,
      FixedDoubleArray::kHeaderSize - kHeapObjectTag,
      instr->additional_index());
3028 3029 3030 3031
  __ movsd(result, double_load_operand);
}


3032 3033 3034
void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
  Register result = ToRegister(instr->result());
  LOperand* key = instr->key();
3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
  if (!key->IsConstantOperand()) {
    Register key_reg = ToRegister(key);
    // Even though the HLoad/StoreKeyedFastElement instructions force
    // the input representation for the key to be an integer, the input
    // gets replaced during bound check elimination with the index
    // argument to the bounds check, which can be tagged, so that
    // case must be handled here, too.
    if (instr->hydrogen()->key()->representation().IsTagged()) {
      __ SmiToInteger64(key_reg, key_reg);
    } else if (instr->hydrogen()->IsDehoisted()) {
      // Sign extend key because it could be a 32 bit negative value
      // and the dehoisted address computation happens in 64 bits
      __ movsxlq(key_reg, key_reg);
    }
  }
3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082

  // Load the result.
  __ movq(result,
          BuildFastArrayOperand(instr->elements(),
                                key,
                                FAST_ELEMENTS,
                                FixedArray::kHeaderSize - kHeapObjectTag,
                                instr->additional_index()));

  // Check for the hole value.
  if (instr->hydrogen()->RequiresHoleCheck()) {
    if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
      Condition smi = __ CheckSmi(result);
      DeoptimizeIf(NegateCondition(smi), instr->environment());
    } else {
      __ CompareRoot(result, Heap::kTheHoleValueRootIndex);
      DeoptimizeIf(equal, instr->environment());
    }
  }
}


void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
  if (instr->is_external()) {
    DoLoadKeyedExternalArray(instr);
  } else if (instr->hydrogen()->representation().IsDouble()) {
    DoLoadKeyedFixedDoubleArray(instr);
  } else {
    DoLoadKeyedFixedArray(instr);
  }
}


3083
Operand LCodeGen::BuildFastArrayOperand(
3084
    LOperand* elements_pointer,
3085
    LOperand* key,
3086
    ElementsKind elements_kind,
3087 3088
    uint32_t offset,
    uint32_t additional_index) {
3089
  Register elements_pointer_reg = ToRegister(elements_pointer);
3090
  int shift_size = ElementsKindToShiftSize(elements_kind);
3091 3092 3093 3094 3095
  if (key->IsConstantOperand()) {
    int constant_value = ToInteger32(LConstantOperand::cast(key));
    if (constant_value & 0xF0000000) {
      Abort("array index constant value too big");
    }
3096
    return Operand(elements_pointer_reg,
3097 3098
                   ((constant_value + additional_index) << shift_size)
                       + offset);
3099 3100
  } else {
    ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
3101 3102 3103 3104
    return Operand(elements_pointer_reg,
                   ToRegister(key),
                   scale_factor,
                   offset + (additional_index << shift_size));
3105 3106 3107 3108
  }
}


3109
void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3110 3111 3112
  ASSERT(ToRegister(instr->object()).is(rdx));
  ASSERT(ToRegister(instr->key()).is(rax));

3113
  Handle<Code> ic = isolate()->builtins()->KeyedLoadIC_Initialize();
3114
  CallCode(ic, RelocInfo::CODE_TARGET, instr);
3115 3116 3117 3118
}


void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
ager@chromium.org's avatar
ager@chromium.org committed
3119 3120
  Register result = ToRegister(instr->result());

3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133
  if (instr->hydrogen()->from_inlined()) {
    __ lea(result, Operand(rsp, -2 * kPointerSize));
  } else {
    // Check for arguments adapter frame.
    Label done, adapted;
    __ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
    __ Cmp(Operand(result, StandardFrameConstants::kContextOffset),
           Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
    __ j(equal, &adapted, Label::kNear);

    // No arguments adaptor frame.
    __ movq(result, rbp);
    __ jmp(&done, Label::kNear);
ager@chromium.org's avatar
ager@chromium.org committed
3134

3135 3136 3137
    // Arguments adaptor frame present.
    __ bind(&adapted);
    __ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
3138

3139 3140 3141 3142
    // Result is the frame pointer for the frame if not adapted and for the real
    // frame below the adaptor frame if adapted.
    __ bind(&done);
  }
3143 3144 3145 3146
}


void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
ager@chromium.org's avatar
ager@chromium.org committed
3147 3148
  Register result = ToRegister(instr->result());

3149
  Label done;
ager@chromium.org's avatar
ager@chromium.org committed
3150 3151

  // If no arguments adaptor frame the number of arguments is fixed.
3152 3153
  if (instr->elements()->IsRegister()) {
    __ cmpq(rbp, ToRegister(instr->elements()));
ager@chromium.org's avatar
ager@chromium.org committed
3154
  } else {
3155
    __ cmpq(rbp, ToOperand(instr->elements()));
ager@chromium.org's avatar
ager@chromium.org committed
3156
  }
3157
  __ movl(result, Immediate(scope()->num_parameters()));
3158
  __ j(equal, &done, Label::kNear);
ager@chromium.org's avatar
ager@chromium.org committed
3159 3160 3161

  // Arguments adaptor frame present. Get argument length from there.
  __ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
3162 3163 3164
  __ SmiToInteger32(result,
                    Operand(result,
                            ArgumentsAdaptorFrameConstants::kLengthOffset));
ager@chromium.org's avatar
ager@chromium.org committed
3165 3166 3167

  // Argument length is in result register.
  __ bind(&done);
3168 3169 3170
}


3171
void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
3172 3173 3174
  Register receiver = ToRegister(instr->receiver());
  Register function = ToRegister(instr->function());

3175 3176 3177
  // If the receiver is null or undefined, we have to pass the global
  // object as a receiver to normal functions. Values have to be
  // passed unchanged to builtins and strict-mode functions.
3178
  Label global_object, receiver_ok;
3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195

  // Do not transform the receiver to object for strict mode
  // functions.
  __ movq(kScratchRegister,
          FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
  __ testb(FieldOperand(kScratchRegister,
                        SharedFunctionInfo::kStrictModeByteOffset),
           Immediate(1 << SharedFunctionInfo::kStrictModeBitWithinByte));
  __ j(not_equal, &receiver_ok, Label::kNear);

  // Do not transform the receiver to object for builtins.
  __ testb(FieldOperand(kScratchRegister,
                        SharedFunctionInfo::kNativeByteOffset),
           Immediate(1 << SharedFunctionInfo::kNativeBitWithinByte));
  __ j(not_equal, &receiver_ok, Label::kNear);

  // Normal function. Replace undefined or null with global receiver.
3196
  __ CompareRoot(receiver, Heap::kNullValueRootIndex);
3197
  __ j(equal, &global_object, Label::kNear);
3198
  __ CompareRoot(receiver, Heap::kUndefinedValueRootIndex);
3199
  __ j(equal, &global_object, Label::kNear);
3200 3201 3202 3203

  // The receiver should be a JS object.
  Condition is_smi = __ CheckSmi(receiver);
  DeoptimizeIf(is_smi, instr->environment());
3204
  __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, kScratchRegister);
3205
  DeoptimizeIf(below, instr->environment());
3206
  __ jmp(&receiver_ok, Label::kNear);
3207 3208 3209 3210 3211

  __ bind(&global_object);
  // TODO(kmillikin): We have a hydrogen value for the global object.  See
  // if it's better to use it than to explicitly fetch it from the context
  // here.
3212
  __ movq(receiver, ContextOperand(rsi, Context::GLOBAL_OBJECT_INDEX));
3213 3214
  __ movq(receiver,
          FieldOperand(receiver, JSGlobalObject::kGlobalReceiverOffset));
3215
  __ bind(&receiver_ok);
3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226
}


void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
  Register receiver = ToRegister(instr->receiver());
  Register function = ToRegister(instr->function());
  Register length = ToRegister(instr->length());
  Register elements = ToRegister(instr->elements());
  ASSERT(receiver.is(rax));  // Used for parameter count.
  ASSERT(function.is(rdi));  // Required by InvokeFunction.
  ASSERT(ToRegister(instr->result()).is(rax));
3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238

  // Copy the arguments to this function possibly from the
  // adaptor frame below it.
  const uint32_t kArgumentsLimit = 1 * KB;
  __ cmpq(length, Immediate(kArgumentsLimit));
  DeoptimizeIf(above, instr->environment());

  __ push(receiver);
  __ movq(receiver, length);

  // Loop through the arguments pushing them onto the execution
  // stack.
3239
  Label invoke, loop;
3240 3241
  // length is a small non-negative integer, due to the test above.
  __ testl(length, length);
3242
  __ j(zero, &invoke, Label::kNear);
3243 3244 3245 3246 3247 3248 3249
  __ bind(&loop);
  __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
  __ decl(length);
  __ j(not_zero, &loop);

  // Invoke the function.
  __ bind(&invoke);
3250
  ASSERT(instr->HasPointerMap());
3251 3252
  LPointerMap* pointers = instr->pointer_map();
  RecordPosition(pointers->position());
3253 3254
  SafepointGenerator safepoint_generator(
      this, pointers, Safepoint::kLazyDeopt);
3255
  ParameterCount actual(rax);
3256 3257
  __ InvokeFunction(function, actual, CALL_FUNCTION,
                    safepoint_generator, CALL_AS_METHOD);
3258
  __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3259 3260 3261 3262
}


void LCodeGen::DoPushArgument(LPushArgument* instr) {
3263
  LOperand* argument = instr->value();
3264
  EmitPushTaggedOperand(argument);
3265 3266 3267
}


3268 3269 3270 3271 3272
void LCodeGen::DoDrop(LDrop* instr) {
  __ Drop(instr->count());
}


3273 3274
void LCodeGen::DoThisFunction(LThisFunction* instr) {
  Register result = ToRegister(instr->result());
3275
  __ movq(result, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
3276 3277 3278
}


3279 3280
void LCodeGen::DoContext(LContext* instr) {
  Register result = ToRegister(instr->result());
3281
  __ movq(result, rsi);
3282 3283 3284
}


3285 3286 3287 3288
void LCodeGen::DoOuterContext(LOuterContext* instr) {
  Register context = ToRegister(instr->context());
  Register result = ToRegister(instr->result());
  __ movq(result,
3289
          Operand(context, Context::SlotOffset(Context::PREVIOUS_INDEX)));
3290 3291 3292
}


3293 3294 3295 3296 3297 3298 3299 3300
void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
  __ push(rsi);  // The context is the first argument.
  __ PushHeapObject(instr->hydrogen()->pairs());
  __ Push(Smi::FromInt(instr->hydrogen()->flags()));
  CallRuntime(Runtime::kDeclareGlobals, 3, instr);
}


3301
void LCodeGen::DoGlobalObject(LGlobalObject* instr) {
3302 3303
  Register result = ToRegister(instr->result());
  __ movq(result, GlobalObjectOperand());
3304 3305 3306 3307
}


void LCodeGen::DoGlobalReceiver(LGlobalReceiver* instr) {
3308
  Register global = ToRegister(instr->global());
3309
  Register result = ToRegister(instr->result());
3310
  __ movq(result, FieldOperand(global, GlobalObject::kGlobalReceiverOffset));
3311 3312 3313 3314
}


void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3315
                                 int formal_parameter_count,
3316
                                 int arity,
3317
                                 LInstruction* instr,
3318 3319
                                 CallKind call_kind,
                                 RDIState rdi_state) {
3320 3321 3322 3323
  bool dont_adapt_arguments =
      formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
  bool can_invoke_directly =
      dont_adapt_arguments || formal_parameter_count == arity;
3324 3325 3326 3327

  LPointerMap* pointers = instr->pointer_map();
  RecordPosition(pointers->position());

3328
  if (can_invoke_directly) {
3329 3330 3331
    if (rdi_state == RDI_UNINITIALIZED) {
      __ LoadHeapObject(rdi, function);
    }
3332

3333 3334
    // Change context.
    __ movq(rsi, FieldOperand(rdi, JSFunction::kContextOffset));
3335 3336 3337

    // Set rax to arguments count if adaption is not needed. Assumes that rax
    // is available to write to at this point.
3338
    if (dont_adapt_arguments) {
3339 3340 3341 3342 3343
      __ Set(rax, arity);
    }

    // Invoke function.
    __ SetCallKind(rcx, call_kind);
3344
    if (function.is_identical_to(info()->closure())) {
3345 3346 3347 3348 3349 3350 3351
      __ CallSelf();
    } else {
      __ call(FieldOperand(rdi, JSFunction::kCodeEntryOffset));
    }

    // Set up deoptimization.
    RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT, 0);
3352
  } else {
3353 3354 3355 3356
    // We need to adapt arguments.
    SafepointGenerator generator(
        this, pointers, Safepoint::kLazyDeopt);
    ParameterCount count(arity);
3357 3358 3359
    ParameterCount expected(formal_parameter_count);
    __ InvokeFunction(
        function, expected, count, CALL_FUNCTION, generator, call_kind);
3360 3361 3362 3363
  }

  // Restore context.
  __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3364 3365 3366 3367
}


void LCodeGen::DoCallConstantFunction(LCallConstantFunction* instr) {
3368
  ASSERT(ToRegister(instr->result()).is(rax));
3369 3370
  CallKnownFunction(instr->hydrogen()->function(),
                    instr->hydrogen()->formal_parameter_count(),
3371 3372
                    instr->arity(),
                    instr,
3373 3374
                    CALL_AS_METHOD,
                    RDI_UNINITIALIZED);
3375 3376 3377
}


3378
void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3379
  Register input_reg = ToRegister(instr->value());
3380 3381 3382 3383 3384 3385 3386 3387 3388
  __ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset),
                 Heap::kHeapNumberMapRootIndex);
  DeoptimizeIf(not_equal, instr->environment());

  Label done;
  Register tmp = input_reg.is(rax) ? rcx : rax;
  Register tmp2 = tmp.is(rcx) ? rdx : input_reg.is(rcx) ? rdx : rcx;

  // Preserve the value of all registers.
3389
  PushSafepointRegistersScope scope(this);
3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409

  Label negative;
  __ movl(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
  // Check the sign of the argument. If the argument is positive, just
  // return it. We do not need to patch the stack since |input| and
  // |result| are the same register and |input| will be restored
  // unchanged by popping safepoint registers.
  __ testl(tmp, Immediate(HeapNumber::kSignMask));
  __ j(not_zero, &negative);
  __ jmp(&done);

  __ bind(&negative);

  Label allocated, slow;
  __ AllocateHeapNumber(tmp, tmp2, &slow);
  __ jmp(&allocated);

  // Slow case: Call the runtime system to do the number allocation.
  __ bind(&slow);

3410
  CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr);
3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429
  // Set the pointer to the new heap number in tmp.
  if (!tmp.is(rax)) {
    __ movq(tmp, rax);
  }

  // Restore input_reg after call to runtime.
  __ LoadFromSafepointRegisterSlot(input_reg, input_reg);

  __ bind(&allocated);
  __ movq(tmp2, FieldOperand(input_reg, HeapNumber::kValueOffset));
  __ shl(tmp2, Immediate(1));
  __ shr(tmp2, Immediate(1));
  __ movq(FieldOperand(tmp, HeapNumber::kValueOffset), tmp2);
  __ StoreToSafepointRegisterSlot(input_reg, tmp);

  __ bind(&done);
}


3430
void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3431
  Register input_reg = ToRegister(instr->value());
3432 3433 3434 3435 3436 3437
  __ testl(input_reg, input_reg);
  Label is_positive;
  __ j(not_sign, &is_positive);
  __ negl(input_reg);  // Sets flags.
  DeoptimizeIf(negative, instr->environment());
  __ bind(&is_positive);
3438 3439 3440
}


3441
void LCodeGen::DoMathAbs(LMathAbs* instr) {
3442 3443 3444
  // Class for deferred case.
  class DeferredMathAbsTaggedHeapNumber: public LDeferredCode {
   public:
3445
    DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen, LMathAbs* instr)
3446 3447 3448 3449
        : LDeferredCode(codegen), instr_(instr) { }
    virtual void Generate() {
      codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
    }
3450
    virtual LInstruction* instr() { return instr_; }
3451
   private:
3452
    LMathAbs* instr_;
3453 3454
  };

3455
  ASSERT(instr->value()->Equals(instr->result()));
3456 3457 3458 3459
  Representation r = instr->hydrogen()->value()->representation();

  if (r.IsDouble()) {
    XMMRegister scratch = xmm0;
3460
    XMMRegister input_reg = ToDoubleRegister(instr->value());
lrn@chromium.org's avatar
lrn@chromium.org committed
3461
    __ xorps(scratch, scratch);
3462 3463 3464 3465 3466 3467
    __ subsd(scratch, input_reg);
    __ andpd(input_reg, scratch);
  } else if (r.IsInteger32()) {
    EmitIntegerMathAbs(instr);
  } else {  // Tagged case.
    DeferredMathAbsTaggedHeapNumber* deferred =
3468
        new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
3469
    Register input_reg = ToRegister(instr->value());
3470 3471
    // Smi check.
    __ JumpIfNotSmi(input_reg, deferred->entry());
3472
    __ SmiToInteger32(input_reg, input_reg);
3473
    EmitIntegerMathAbs(instr);
3474
    __ Integer32ToSmi(input_reg, input_reg);
3475 3476
    __ bind(deferred->exit());
  }
3477 3478 3479
}


3480
void LCodeGen::DoMathFloor(LMathFloor* instr) {
3481 3482
  XMMRegister xmm_scratch = xmm0;
  Register output_reg = ToRegister(instr->result());
3483
  XMMRegister input_reg = ToDoubleRegister(instr->value());
3484

3485
  if (CpuFeatures::IsSupported(SSE4_1)) {
3486
    CpuFeatureScope scope(masm(), SSE4_1);
3487 3488 3489 3490 3491 3492 3493 3494 3495 3496
    if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
      // Deoptimize if minus zero.
      __ movq(output_reg, input_reg);
      __ subq(output_reg, Immediate(1));
      DeoptimizeIf(overflow, instr->environment());
    }
    __ roundsd(xmm_scratch, input_reg, Assembler::kRoundDown);
    __ cvttsd2si(output_reg, xmm_scratch);
    __ cmpl(output_reg, Immediate(0x80000000));
    DeoptimizeIf(equal, instr->environment());
3497
  } else {
3498
    Label negative_sign, done;
3499
    // Deoptimize on unordered.
lrn@chromium.org's avatar
lrn@chromium.org committed
3500
    __ xorps(xmm_scratch, xmm_scratch);  // Zero the register.
3501
    __ ucomisd(input_reg, xmm_scratch);
3502 3503 3504
    DeoptimizeIf(parity_even, instr->environment());
    __ j(below, &negative_sign, Label::kNear);

3505
    if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3506
      // Check for negative zero.
fschneider@chromium.org's avatar
fschneider@chromium.org committed
3507
      Label positive_sign;
3508 3509 3510 3511
      __ j(above, &positive_sign, Label::kNear);
      __ movmskpd(output_reg, input_reg);
      __ testq(output_reg, Immediate(1));
      DeoptimizeIf(not_zero, instr->environment());
fschneider@chromium.org's avatar
fschneider@chromium.org committed
3512
      __ Set(output_reg, 0);
3513 3514
      __ jmp(&done);
      __ bind(&positive_sign);
3515
    }
3516

3517 3518 3519 3520 3521
    // Use truncating instruction (OK because input is positive).
    __ cvttsd2si(output_reg, input_reg);
    // Overflow is signalled with minint.
    __ cmpl(output_reg, Immediate(0x80000000));
    DeoptimizeIf(equal, instr->environment());
3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534
    __ jmp(&done, Label::kNear);

    // Non-zero negative reaches here.
    __ bind(&negative_sign);
    // Truncate, then compare and compensate.
    __ cvttsd2si(output_reg, input_reg);
    __ cvtlsi2sd(xmm_scratch, output_reg);
    __ ucomisd(input_reg, xmm_scratch);
    __ j(equal, &done, Label::kNear);
    __ subl(output_reg, Immediate(1));
    DeoptimizeIf(overflow, instr->environment());

    __ bind(&done);
3535
  }
3536 3537 3538
}


3539
void LCodeGen::DoMathRound(LMathRound* instr) {
3540 3541
  const XMMRegister xmm_scratch = xmm0;
  Register output_reg = ToRegister(instr->result());
3542
  XMMRegister input_reg = ToDoubleRegister(instr->value());
3543 3544
  static int64_t one_half = V8_INT64_C(0x3FE0000000000000);  // 0.5
  static int64_t minus_one_half = V8_INT64_C(0xBFE0000000000000);  // -0.5
3545

3546
  Label done, round_to_zero, below_one_half, do_not_compensate, restore;
3547
  __ movq(kScratchRegister, one_half, RelocInfo::NONE64);
3548
  __ movq(xmm_scratch, kScratchRegister);
3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559
  __ ucomisd(xmm_scratch, input_reg);
  __ j(above, &below_one_half);

  // CVTTSD2SI rounds towards zero, since 0.5 <= x, we use floor(0.5 + x).
  __ addsd(xmm_scratch, input_reg);
  __ cvttsd2si(output_reg, xmm_scratch);
  // Overflow is signalled with minint.
  __ cmpl(output_reg, Immediate(0x80000000));
  __ RecordComment("D2I conversion overflow");
  DeoptimizeIf(equal, instr->environment());
  __ jmp(&done);
3560

3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575
  __ bind(&below_one_half);
  __ movq(kScratchRegister, minus_one_half, RelocInfo::NONE64);
  __ movq(xmm_scratch, kScratchRegister);
  __ ucomisd(xmm_scratch, input_reg);
  __ j(below_equal, &round_to_zero);

  // CVTTSD2SI rounds towards zero, we use ceil(x - (-0.5)) and then
  // compare and compensate.
  __ movq(kScratchRegister, input_reg);  // Back up input_reg.
  __ subsd(input_reg, xmm_scratch);
  __ cvttsd2si(output_reg, input_reg);
  // Catch minint due to overflow, and to prevent overflow when compensating.
  __ cmpl(output_reg, Immediate(0x80000000));
  __ RecordComment("D2I conversion overflow");
  DeoptimizeIf(equal, instr->environment());
3576

3577 3578 3579 3580 3581 3582 3583 3584
  __ cvtlsi2sd(xmm_scratch, output_reg);
  __ ucomisd(input_reg, xmm_scratch);
  __ j(equal, &restore, Label::kNear);
  __ subl(output_reg, Immediate(1));
  // No overflow because we already ruled out minint.
  __ bind(&restore);
  __ movq(input_reg, kScratchRegister);  // Restore input_reg.
  __ jmp(&done);
3585

3586 3587 3588 3589 3590 3591 3592 3593
  __ bind(&round_to_zero);
  // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
  // we can ignore the difference between a result of -0 and +0.
  if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
    __ movq(output_reg, input_reg);
    __ testq(output_reg, output_reg);
    __ RecordComment("Minus zero");
    DeoptimizeIf(negative, instr->environment());
3594
  }
3595 3596
  __ Set(output_reg, 0);
  __ bind(&done);
3597 3598 3599
}


3600
void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3601
  XMMRegister input_reg = ToDoubleRegister(instr->value());
3602 3603
  ASSERT(ToDoubleRegister(instr->result()).is(input_reg));
  __ sqrtsd(input_reg, input_reg);
3604 3605 3606
}


3607
void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3608
  XMMRegister xmm_scratch = xmm0;
3609
  XMMRegister input_reg = ToDoubleRegister(instr->value());
3610
  ASSERT(ToDoubleRegister(instr->result()).is(input_reg));
3611 3612 3613 3614 3615 3616 3617

  // Note that according to ECMA-262 15.8.2.13:
  // Math.pow(-Infinity, 0.5) == Infinity
  // Math.sqrt(-Infinity) == NaN
  Label done, sqrt;
  // Check base for -Infinity.  According to IEEE-754, double-precision
  // -Infinity has the highest 12 bits set and the lowest 52 bits cleared.
3618
  __ movq(kScratchRegister, V8_INT64_C(0xFFF0000000000000), RelocInfo::NONE64);
3619 3620
  __ movq(xmm_scratch, kScratchRegister);
  __ ucomisd(xmm_scratch, input_reg);
3621 3622
  // Comparing -Infinity with NaN results in "unordered", which sets the
  // zero flag as if both were equal.  However, it also sets the carry flag.
3623
  __ j(not_equal, &sqrt, Label::kNear);
3624
  __ j(carry, &sqrt, Label::kNear);
3625 3626 3627 3628 3629 3630 3631
  // If input is -Infinity, return Infinity.
  __ xorps(input_reg, input_reg);
  __ subsd(input_reg, xmm_scratch);
  __ jmp(&done, Label::kNear);

  // Square root.
  __ bind(&sqrt);
lrn@chromium.org's avatar
lrn@chromium.org committed
3632
  __ xorps(xmm_scratch, xmm_scratch);
3633 3634
  __ addsd(input_reg, xmm_scratch);  // Convert -0 to +0.
  __ sqrtsd(input_reg, input_reg);
3635
  __ bind(&done);
3636 3637 3638 3639
}


void LCodeGen::DoPower(LPower* instr) {
3640
  Representation exponent_type = instr->hydrogen()->right()->representation();
3641 3642 3643 3644
  // Having marked this as a call, we can use any registers.
  // Just make sure that the input/output registers are the expected ones.

  Register exponent = rdx;
3645 3646 3647 3648 3649
  ASSERT(!instr->right()->IsRegister() ||
         ToRegister(instr->right()).is(exponent));
  ASSERT(!instr->right()->IsDoubleRegister() ||
         ToDoubleRegister(instr->right()).is(xmm1));
  ASSERT(ToDoubleRegister(instr->left()).is(xmm2));
3650 3651 3652 3653 3654 3655
  ASSERT(ToDoubleRegister(instr->result()).is(xmm3));

  if (exponent_type.IsTagged()) {
    Label no_deopt;
    __ JumpIfSmi(exponent, &no_deopt);
    __ CmpObjectType(exponent, HEAP_NUMBER_TYPE, rcx);
3656
    DeoptimizeIf(not_equal, instr->environment());
3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667
    __ bind(&no_deopt);
    MathPowStub stub(MathPowStub::TAGGED);
    __ CallStub(&stub);
  } else if (exponent_type.IsInteger32()) {
    MathPowStub stub(MathPowStub::INTEGER);
    __ CallStub(&stub);
  } else {
    ASSERT(exponent_type.IsDouble());
    MathPowStub stub(MathPowStub::DOUBLE);
    __ CallStub(&stub);
  }
3668 3669 3670
}


3671
void LCodeGen::DoRandom(LRandom* instr) {
3672 3673 3674 3675 3676 3677 3678 3679 3680 3681
  class DeferredDoRandom: public LDeferredCode {
   public:
    DeferredDoRandom(LCodeGen* codegen, LRandom* instr)
        : LDeferredCode(codegen), instr_(instr) { }
    virtual void Generate() { codegen()->DoDeferredRandom(instr_); }
    virtual LInstruction* instr() { return instr_; }
   private:
    LRandom* instr_;
  };

3682
  DeferredDoRandom* deferred = new(zone()) DeferredDoRandom(this, instr);
3683

3684 3685 3686 3687 3688 3689 3690
  // Having marked this instruction as a call we can use any
  // registers.
  ASSERT(ToDoubleRegister(instr->result()).is(xmm1));

  // Choose the right register for the first argument depending on
  // calling convention.
#ifdef _WIN64
3691
  ASSERT(ToRegister(instr->global_object()).is(rcx));
3692 3693
  Register global_object = rcx;
#else
3694
  ASSERT(ToRegister(instr->global_object()).is(rdi));
3695 3696 3697
  Register global_object = rdi;
#endif

3698 3699 3700
  static const int kSeedSize = sizeof(uint32_t);
  STATIC_ASSERT(kPointerSize == 2 * kSeedSize);

3701
  __ movq(global_object,
3702
          FieldOperand(global_object, GlobalObject::kNativeContextOffset));
3703 3704 3705
  static const int kRandomSeedOffset =
      FixedArray::kHeaderSize + Context::RANDOM_SEED_INDEX * kPointerSize;
  __ movq(rbx, FieldOperand(global_object, kRandomSeedOffset));
3706
  // rbx: FixedArray of the native context's random seeds
3707 3708

  // Load state[0].
3709
  __ movl(rax, FieldOperand(rbx, ByteArray::kHeaderSize));
3710
  // If state[0] == 0, call runtime to initialize seeds.
3711
  __ testl(rax, rax);
3712 3713
  __ j(zero, deferred->entry());
  // Load state[1].
3714
  __ movl(rcx, FieldOperand(rbx, ByteArray::kHeaderSize + kSeedSize));
3715 3716

  // state[0] = 18273 * (state[0] & 0xFFFF) + (state[0] >> 16)
3717
  // Only operate on the lower 32 bit of rax.
3718
  __ movzxwl(rdx, rax);
3719
  __ imull(rdx, rdx, Immediate(18273));
3720 3721
  __ shrl(rax, Immediate(16));
  __ addl(rax, rdx);
3722
  // Save state[0].
3723
  __ movl(FieldOperand(rbx, ByteArray::kHeaderSize), rax);
3724 3725

  // state[1] = 36969 * (state[1] & 0xFFFF) + (state[1] >> 16)
3726
  __ movzxwl(rdx, rcx);
3727
  __ imull(rdx, rdx, Immediate(36969));
3728 3729
  __ shrl(rcx, Immediate(16));
  __ addl(rcx, rdx);
3730
  // Save state[1].
3731
  __ movl(FieldOperand(rbx, ByteArray::kHeaderSize + kSeedSize), rcx);
3732 3733

  // Random bit pattern = (state[0] << 14) + (state[1] & 0x3FFFF)
3734 3735 3736
  __ shll(rax, Immediate(14));
  __ andl(rcx, Immediate(0x3FFFF));
  __ addl(rax, rcx);
3737

3738
  __ bind(deferred->exit());
3739
  // Convert 32 random bits in rax to 0.(32 random bits) in a double
3740 3741
  // by computing:
  // ( 1.(20 0s)(32 random bits) x 2^20 ) - (1.0 x 2^20)).
3742 3743 3744
  __ movq(rcx, V8_INT64_C(0x4130000000000000),
          RelocInfo::NONE64);  // 1.0 x 2^20 as double
  __ movq(xmm2, rcx);
3745
  __ movd(xmm1, rax);
3746 3747 3748 3749 3750
  __ xorps(xmm1, xmm2);
  __ subsd(xmm1, xmm2);
}


3751 3752 3753 3754 3755 3756 3757 3758
void LCodeGen::DoDeferredRandom(LRandom* instr) {
  __ PrepareCallCFunction(1);
  __ CallCFunction(ExternalReference::random_uint32_function(isolate()), 1);
  __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
  // Return value is in rax.
}


3759 3760 3761 3762 3763 3764 3765 3766 3767 3768
void LCodeGen::DoMathExp(LMathExp* instr) {
  XMMRegister input = ToDoubleRegister(instr->value());
  XMMRegister result = ToDoubleRegister(instr->result());
  Register temp1 = ToRegister(instr->temp1());
  Register temp2 = ToRegister(instr->temp2());

  MathExpGenerator::EmitMathExp(masm(), input, result, xmm0, temp1, temp2);
}


3769
void LCodeGen::DoMathLog(LMathLog* instr) {
3770 3771 3772
  ASSERT(ToDoubleRegister(instr->result()).is(xmm1));
  TranscendentalCacheStub stub(TranscendentalCache::LOG,
                               TranscendentalCacheStub::UNTAGGED);
3773
  CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
3774 3775 3776
}


3777
void LCodeGen::DoMathTan(LMathTan* instr) {
3778 3779 3780
  ASSERT(ToDoubleRegister(instr->result()).is(xmm1));
  TranscendentalCacheStub stub(TranscendentalCache::TAN,
                               TranscendentalCacheStub::UNTAGGED);
3781
  CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
3782 3783 3784
}


3785
void LCodeGen::DoMathCos(LMathCos* instr) {
3786
  ASSERT(ToDoubleRegister(instr->result()).is(xmm1));
3787
  TranscendentalCacheStub stub(TranscendentalCache::COS,
3788
                               TranscendentalCacheStub::UNTAGGED);
3789
  CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
3790 3791 3792
}


3793
void LCodeGen::DoMathSin(LMathSin* instr) {
3794
  ASSERT(ToDoubleRegister(instr->result()).is(xmm1));
3795
  TranscendentalCacheStub stub(TranscendentalCache::SIN,
3796
                               TranscendentalCacheStub::UNTAGGED);
3797
  CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
3798 3799 3800
}


3801 3802 3803
void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
  ASSERT(ToRegister(instr->function()).is(rdi));
  ASSERT(instr->HasPointerMap());
3804

3805 3806
  Handle<JSFunction> known_function = instr->hydrogen()->known_function();
  if (known_function.is_null()) {
3807 3808 3809 3810 3811 3812 3813
    LPointerMap* pointers = instr->pointer_map();
    RecordPosition(pointers->position());
    SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
    ParameterCount count(instr->arity());
    __ InvokeFunction(rdi, count, CALL_FUNCTION, generator, CALL_AS_METHOD);
    __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
  } else {
3814 3815
    CallKnownFunction(known_function,
                      instr->hydrogen()->formal_parameter_count(),
3816 3817 3818 3819 3820
                      instr->arity(),
                      instr,
                      CALL_AS_METHOD,
                      RDI_CONTAINS_TARGET);
  }
3821 3822 3823
}


3824
void LCodeGen::DoCallKeyed(LCallKeyed* instr) {
3825 3826 3827 3828
  ASSERT(ToRegister(instr->key()).is(rcx));
  ASSERT(ToRegister(instr->result()).is(rax));

  int arity = instr->arity();
3829 3830
  Handle<Code> ic =
      isolate()->stub_cache()->ComputeKeyedCallInitialize(arity);
3831
  CallCode(ic, RelocInfo::CODE_TARGET, instr);
3832
  __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3833 3834 3835 3836
}


void LCodeGen::DoCallNamed(LCallNamed* instr) {
ricow@chromium.org's avatar
ricow@chromium.org committed
3837
  ASSERT(ToRegister(instr->result()).is(rax));
3838 3839

  int arity = instr->arity();
3840 3841
  RelocInfo::Mode mode = RelocInfo::CODE_TARGET;
  Handle<Code> ic =
3842
      isolate()->stub_cache()->ComputeCallInitialize(arity, mode);
3843
  __ Move(rcx, instr->name());
3844
  CallCode(ic, mode, instr);
3845
  __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3846 3847 3848 3849
}


void LCodeGen::DoCallFunction(LCallFunction* instr) {
3850
  ASSERT(ToRegister(instr->function()).is(rdi));
3851 3852 3853
  ASSERT(ToRegister(instr->result()).is(rax));

  int arity = instr->arity();
3854
  CallFunctionStub stub(arity, NO_CALL_FUNCTION_FLAGS);
3855
  CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
3856
  __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3857 3858 3859 3860
}


void LCodeGen::DoCallGlobal(LCallGlobal* instr) {
3861 3862
  ASSERT(ToRegister(instr->result()).is(rax));
  int arity = instr->arity();
3863 3864
  RelocInfo::Mode mode = RelocInfo::CODE_TARGET_CONTEXT;
  Handle<Code> ic =
3865
      isolate()->stub_cache()->ComputeCallInitialize(arity, mode);
3866
  __ Move(rcx, instr->name());
3867
  CallCode(ic, mode, instr);
3868
  __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
3869 3870 3871 3872
}


void LCodeGen::DoCallKnownGlobal(LCallKnownGlobal* instr) {
3873
  ASSERT(ToRegister(instr->result()).is(rax));
3874 3875
  CallKnownFunction(instr->hydrogen()->target(),
                    instr->hydrogen()->formal_parameter_count(),
3876 3877 3878 3879
                    instr->arity(),
                    instr,
                    CALL_AS_FUNCTION,
                    RDI_UNINITIALIZED);
3880 3881 3882 3883
}


void LCodeGen::DoCallNew(LCallNew* instr) {
3884
  ASSERT(ToRegister(instr->constructor()).is(rdi));
3885 3886 3887
  ASSERT(ToRegister(instr->result()).is(rax));

  __ Set(rax, instr->arity());
3888 3889 3890 3891 3892 3893
  if (FLAG_optimize_constructed_arrays) {
    // No cell in ebx for construct type feedback in optimized code
    Handle<Object> undefined_value(isolate()->factory()->undefined_value());
    __ Move(rbx, undefined_value);
  }
  CallConstructStub stub(NO_CALL_FUNCTION_FLAGS);
3894
  CallCode(stub.GetCode(isolate()), RelocInfo::CONSTRUCT_CALL, instr);
3895 3896 3897
}


3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910
void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
  ASSERT(ToRegister(instr->constructor()).is(rdi));
  ASSERT(ToRegister(instr->result()).is(rax));
  ASSERT(FLAG_optimize_constructed_arrays);

  __ Set(rax, instr->arity());
  __ Move(rbx, instr->hydrogen()->property_cell());
  Handle<Code> array_construct_code =
      isolate()->builtins()->ArrayConstructCode();
  CallCode(array_construct_code, RelocInfo::CONSTRUCT_CALL, instr);
}


3911
void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
3912
  CallRuntime(instr->function(), instr->arity(), instr);
3913 3914 3915
}


3916 3917 3918 3919 3920 3921 3922
void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
  Register result = ToRegister(instr->result());
  Register base = ToRegister(instr->base_object());
  __ lea(result, Operand(base, instr->offset()));
}


3923
void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
3924 3925 3926 3927
  Register object = ToRegister(instr->object());
  int offset = instr->offset();

  if (!instr->transition().is_null()) {
3928 3929 3930 3931
    if (!instr->hydrogen()->NeedsWriteBarrierForMap()) {
      __ Move(FieldOperand(object, HeapObject::kMapOffset),
              instr->transition());
    } else {
3932
      Register temp = ToRegister(instr->temp());
3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943
      __ Move(kScratchRegister, instr->transition());
      __ movq(FieldOperand(object, HeapObject::kMapOffset), kScratchRegister);
      // Update the write barrier for the map field.
      __ RecordWriteField(object,
                          HeapObject::kMapOffset,
                          kScratchRegister,
                          temp,
                          kSaveFPRegs,
                          OMIT_REMEMBERED_SET,
                          OMIT_SMI_CHECK);
    }
3944 3945 3946
  }

  // Do the store.
3947 3948 3949
  HType type = instr->hydrogen()->value()->type();
  SmiCheck check_needed =
      type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
3950 3951 3952 3953 3954 3955 3956 3957 3958 3959

  Register write_register = object;
  if (!instr->is_in_object()) {
    write_register = ToRegister(instr->temp());
    __ movq(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
  }

  if (instr->value()->IsConstantOperand()) {
    LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
    if (IsInteger32Constant(operand_value)) {
3960 3961 3962 3963 3964 3965 3966
      // In lithium register preparation, we made sure that the constant integer
      // operand fits into smi range.
      Smi* smi_value = Smi::FromInt(ToInteger32(operand_value));
      __ Move(FieldOperand(write_register, offset), smi_value);
    } else if (operand_value->IsRegister()) {
      __ movq(FieldOperand(write_register, offset),
              ToRegister(operand_value));
3967
    } else {
3968 3969
      Handle<Object> handle_value = ToHandle(operand_value);
      __ Move(FieldOperand(write_register, offset), handle_value);
3970 3971
    }
  } else {
3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985
    __ movq(FieldOperand(write_register, offset), ToRegister(instr->value()));
  }

  if (instr->hydrogen()->NeedsWriteBarrier()) {
    Register value = ToRegister(instr->value());
    Register temp = instr->is_in_object() ? ToRegister(instr->temp()) : object;
    // Update the write barrier for the object for in-object properties.
    __ RecordWriteField(write_register,
                        offset,
                        value,
                        temp,
                        kSaveFPRegs,
                        EMIT_REMEMBERED_SET,
                        check_needed);
3986
  }
3987 3988 3989 3990
}


void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
3991 3992 3993 3994
  ASSERT(ToRegister(instr->object()).is(rdx));
  ASSERT(ToRegister(instr->value()).is(rax));

  __ Move(rcx, instr->hydrogen()->name());
3995
  Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode)
3996 3997
      ? isolate()->builtins()->StoreIC_Initialize_Strict()
      : isolate()->builtins()->StoreIC_Initialize();
3998
  CallCode(ic, RelocInfo::CODE_TARGET, instr);
3999 4000 4001 4002
}


void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
4003 4004
  if (instr->hydrogen()->skip_check()) return;

4005 4006
  if (instr->length()->IsRegister()) {
    Register reg = ToRegister(instr->length());
4007 4008
    if (!instr->hydrogen()->length()->representation().IsTagged()) {
      __ AssertZeroExtended(reg);
4009 4010
    }
    if (instr->index()->IsConstantOperand()) {
4011 4012 4013 4014 4015 4016 4017
      int constant_index =
          ToInteger32(LConstantOperand::cast(instr->index()));
      if (instr->hydrogen()->length()->representation().IsTagged()) {
        __ Cmp(reg, Smi::FromInt(constant_index));
      } else {
        __ cmpq(reg, Immediate(constant_index));
      }
4018
    } else {
4019
      Register reg2 = ToRegister(instr->index());
4020 4021
      if (!instr->hydrogen()->index()->representation().IsTagged()) {
        __ AssertZeroExtended(reg2);
4022 4023
      }
      __ cmpq(reg, reg2);
4024
    }
4025
  } else {
4026
    Operand length = ToOperand(instr->length());
4027
    if (instr->index()->IsConstantOperand()) {
4028 4029 4030 4031 4032 4033 4034
      int constant_index =
          ToInteger32(LConstantOperand::cast(instr->index()));
      if (instr->hydrogen()->length()->representation().IsTagged()) {
        __ Cmp(length, Smi::FromInt(constant_index));
      } else {
        __ cmpq(length, Immediate(constant_index));
      }
4035
    } else {
4036
      __ cmpq(length, ToRegister(instr->index()));
4037
    }
4038
  }
4039
  DeoptimizeIf(below_equal, instr->environment());
4040 4041 4042
}


4043 4044
void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
  ElementsKind elements_kind = instr->elements_kind();
4045
  LOperand* key = instr->key();
4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060
  if (!key->IsConstantOperand()) {
    Register key_reg = ToRegister(key);
    // Even though the HLoad/StoreKeyedFastElement instructions force
    // the input representation for the key to be an integer, the input
    // gets replaced during bound check elimination with the index
    // argument to the bounds check, which can be tagged, so that case
    // must be handled here, too.
    if (instr->hydrogen()->key()->representation().IsTagged()) {
      __ SmiToInteger64(key_reg, key_reg);
    } else if (instr->hydrogen()->IsDehoisted()) {
      // Sign extend key because it could be a 32 bit negative value
      // and the dehoisted address computation happens in 64 bits
      __ movsxlq(key_reg, key_reg);
    }
  }
4061 4062 4063 4064 4065 4066
  Operand operand(BuildFastArrayOperand(
      instr->elements(),
      key,
      elements_kind,
      0,
      instr->additional_index()));
4067

4068 4069 4070 4071 4072 4073
  if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) {
    XMMRegister value(ToDoubleRegister(instr->value()));
    __ cvtsd2ss(value, value);
    __ movss(operand, value);
  } else if (elements_kind == EXTERNAL_DOUBLE_ELEMENTS) {
    __ movsd(operand, ToDoubleRegister(instr->value()));
4074
  } else {
4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102
    Register value(ToRegister(instr->value()));
    switch (elements_kind) {
      case EXTERNAL_PIXEL_ELEMENTS:
      case EXTERNAL_BYTE_ELEMENTS:
      case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
        __ movb(operand, value);
        break;
      case EXTERNAL_SHORT_ELEMENTS:
      case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
        __ movw(operand, value);
        break;
      case EXTERNAL_INT_ELEMENTS:
      case EXTERNAL_UNSIGNED_INT_ELEMENTS:
        __ movl(operand, value);
        break;
      case EXTERNAL_FLOAT_ELEMENTS:
      case EXTERNAL_DOUBLE_ELEMENTS:
      case FAST_ELEMENTS:
      case FAST_SMI_ELEMENTS:
      case FAST_DOUBLE_ELEMENTS:
      case FAST_HOLEY_ELEMENTS:
      case FAST_HOLEY_SMI_ELEMENTS:
      case FAST_HOLEY_DOUBLE_ELEMENTS:
      case DICTIONARY_ELEMENTS:
      case NON_STRICT_ARGUMENTS_ELEMENTS:
        UNREACHABLE();
        break;
    }
4103
  }
4104 4105 4106
}


4107
void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
4108
  XMMRegister value = ToDoubleRegister(instr->value());
4109
  LOperand* key = instr->key();
4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125
  if (!key->IsConstantOperand()) {
    Register key_reg = ToRegister(key);
    // Even though the HLoad/StoreKeyedFastElement instructions force
    // the input representation for the key to be an integer, the
    // input gets replaced during bound check elimination with the index
    // argument to the bounds check, which can be tagged, so that case
    // must be handled here, too.
    if (instr->hydrogen()->key()->representation().IsTagged()) {
      __ SmiToInteger64(key_reg, key_reg);
    } else if (instr->hydrogen()->IsDehoisted()) {
      // Sign extend key because it could be a 32 bit negative value
      // and the dehoisted address computation happens in 64 bits
      __ movsxlq(key_reg, key_reg);
    }
  }

4126 4127
  if (instr->NeedsCanonicalization()) {
    Label have_value;
4128

4129 4130 4131 4132 4133 4134 4135 4136 4137
    __ ucomisd(value, value);
    __ j(parity_odd, &have_value);  // NaN.

    __ Set(kScratchRegister, BitCast<uint64_t>(
        FixedDoubleArray::canonical_not_the_hole_nan_as_double()));
    __ movq(value, kScratchRegister);

    __ bind(&have_value);
  }
4138 4139

  Operand double_store_operand = BuildFastArrayOperand(
4140
      instr->elements(),
4141
      key,
4142 4143 4144 4145
      FAST_DOUBLE_ELEMENTS,
      FixedDoubleArray::kHeaderSize - kHeapObjectTag,
      instr->additional_index());

4146 4147 4148
  __ movsd(double_store_operand, value);
}

4149 4150 4151 4152

void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
  Register elements = ToRegister(instr->elements());
  LOperand* key = instr->key();
4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167
  if (!key->IsConstantOperand()) {
    Register key_reg = ToRegister(key);
    // Even though the HLoad/StoreKeyedFastElement instructions force
    // the input representation for the key to be an integer, the
    // input gets replaced during bound check elimination with the index
    // argument to the bounds check, which can be tagged, so that case
    // must be handled here, too.
    if (instr->hydrogen()->key()->representation().IsTagged()) {
      __ SmiToInteger64(key_reg, key_reg);
    } else if (instr->hydrogen()->IsDehoisted()) {
      // Sign extend key because it could be a 32 bit negative value
      // and the dehoisted address computation happens in 64 bits
      __ movsxlq(key_reg, key_reg);
    }
  }
4168 4169 4170 4171 4172 4173 4174

  Operand operand =
      BuildFastArrayOperand(instr->elements(),
                            key,
                            FAST_ELEMENTS,
                            FixedArray::kHeaderSize - kHeapObjectTag,
                            instr->additional_index());
4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186
  if (instr->value()->IsRegister()) {
    __ movq(operand, ToRegister(instr->value()));
  } else {
    LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
    if (IsInteger32Constant(operand_value)) {
      Smi* smi_value = Smi::FromInt(ToInteger32(operand_value));
      __ Move(operand, smi_value);
    } else {
      Handle<Object> handle_value = ToHandle(operand_value);
      __ Move(operand, handle_value);
    }
  }
4187 4188

  if (instr->hydrogen()->NeedsWriteBarrier()) {
4189 4190
    ASSERT(instr->value()->IsRegister());
    Register value = ToRegister(instr->value());
4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218
    ASSERT(!instr->key()->IsConstantOperand());
    HType type = instr->hydrogen()->value()->type();
    SmiCheck check_needed =
        type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
    // Compute address of modified element and store it into key register.
    Register key_reg(ToRegister(key));
    __ lea(key_reg, operand);
    __ RecordWrite(elements,
                   key_reg,
                   value,
                   kSaveFPRegs,
                   EMIT_REMEMBERED_SET,
                   check_needed);
  }
}


void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
  if (instr->is_external()) {
    DoStoreKeyedExternalArray(instr);
  } else if (instr->hydrogen()->value()->representation().IsDouble()) {
    DoStoreKeyedFixedDoubleArray(instr);
  } else {
    DoStoreKeyedFixedArray(instr);
  }
}


4219
void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4220 4221 4222 4223
  ASSERT(ToRegister(instr->object()).is(rdx));
  ASSERT(ToRegister(instr->key()).is(rcx));
  ASSERT(ToRegister(instr->value()).is(rax));

4224
  Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode)
4225 4226
      ? isolate()->builtins()->KeyedStoreIC_Initialize_Strict()
      : isolate()->builtins()->KeyedStoreIC_Initialize();
4227
  CallCode(ic, RelocInfo::CODE_TARGET, instr);
4228 4229 4230
}


4231 4232 4233 4234 4235
void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
  Register object_reg = ToRegister(instr->object());

  Handle<Map> from_map = instr->original_map();
  Handle<Map> to_map = instr->transitioned_map();
4236 4237
  ElementsKind from_kind = instr->from_kind();
  ElementsKind to_kind = instr->to_kind();
4238 4239 4240 4241

  Label not_applicable;
  __ Cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
  __ j(not_equal, &not_applicable);
4242
  if (IsSimpleMapChangeTransition(from_kind, to_kind)) {
4243 4244
    Register new_map_reg = ToRegister(instr->new_map_temp());
    __ movq(new_map_reg, to_map, RelocInfo::EMBEDDED_OBJECT);
4245 4246
    __ movq(FieldOperand(object_reg, HeapObject::kMapOffset), new_map_reg);
    // Write barrier.
4247
    ASSERT_NE(instr->temp(), NULL);
4248
    __ RecordWriteField(object_reg, HeapObject::kMapOffset, new_map_reg,
4249
                        ToRegister(instr->temp()), kDontSaveFPRegs);
4250 4251 4252 4253 4254 4255 4256 4257 4258 4259
  } else if (FLAG_compiled_transitions) {
    PushSafepointRegistersScope scope(this);
    if (!object_reg.is(rax)) {
      __ movq(rax, object_reg);
    }
    __ Move(rbx, to_map);
    TransitionElementsKindStub stub(from_kind, to_kind);
    __ CallStub(&stub);
    RecordSafepointWithRegisters(
        instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4260
  } else if (IsFastSmiElementsKind(from_kind) &&
4261
            IsFastDoubleElementsKind(to_kind)) {
4262
    Register fixed_object_reg = ToRegister(instr->temp());
4263
    ASSERT(fixed_object_reg.is(rdx));
4264
    Register new_map_reg = ToRegister(instr->new_map_temp());
4265
    ASSERT(new_map_reg.is(rbx));
4266
    __ movq(new_map_reg, to_map, RelocInfo::EMBEDDED_OBJECT);
4267 4268 4269
    __ movq(fixed_object_reg, object_reg);
    CallCode(isolate()->builtins()->TransitionElementsSmiToDouble(),
             RelocInfo::CODE_TARGET, instr);
4270 4271
  } else if (IsFastDoubleElementsKind(from_kind) &&
             IsFastObjectElementsKind(to_kind)) {
4272
    Register fixed_object_reg = ToRegister(instr->temp());
4273
    ASSERT(fixed_object_reg.is(rdx));
4274
    Register new_map_reg = ToRegister(instr->new_map_temp());
4275
    ASSERT(new_map_reg.is(rbx));
4276
    __ movq(new_map_reg, to_map, RelocInfo::EMBEDDED_OBJECT);
4277 4278 4279 4280 4281 4282 4283 4284 4285 4286
    __ movq(fixed_object_reg, object_reg);
    CallCode(isolate()->builtins()->TransitionElementsDoubleToObject(),
             RelocInfo::CODE_TARGET, instr);
  } else {
    UNREACHABLE();
  }
  __ bind(&not_applicable);
}


4287 4288 4289 4290 4291 4292 4293 4294
void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
  Register object = ToRegister(instr->object());
  Register temp = ToRegister(instr->temp());
  __ TestJSArrayForAllocationSiteInfo(object, temp);
  DeoptimizeIf(equal, instr->environment());
}


4295 4296 4297 4298
void LCodeGen::DoStringAdd(LStringAdd* instr) {
  EmitPushTaggedOperand(instr->left());
  EmitPushTaggedOperand(instr->right());
  StringAddStub stub(NO_STRING_CHECK_IN_STUB);
4299
  CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
4300 4301 4302
}


4303 4304 4305 4306 4307 4308
void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
  class DeferredStringCharCodeAt: public LDeferredCode {
   public:
    DeferredStringCharCodeAt(LCodeGen* codegen, LStringCharCodeAt* instr)
        : LDeferredCode(codegen), instr_(instr) { }
    virtual void Generate() { codegen()->DoDeferredStringCharCodeAt(instr_); }
4309
    virtual LInstruction* instr() { return instr_; }
4310 4311 4312 4313 4314
   private:
    LStringCharCodeAt* instr_;
  };

  DeferredStringCharCodeAt* deferred =
4315
      new(zone()) DeferredStringCharCodeAt(this, instr);
4316

4317 4318 4319 4320 4321
  StringCharLoadGenerator::Generate(masm(),
                                    ToRegister(instr->string()),
                                    ToRegister(instr->index()),
                                    ToRegister(instr->result()),
                                    deferred->entry());
4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334
  __ bind(deferred->exit());
}


void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
  Register string = ToRegister(instr->string());
  Register result = ToRegister(instr->result());

  // TODO(3095996): Get rid of this. For now, we need to make the
  // result register contain a valid pointer because it is already
  // contained in the register pointer map.
  __ Set(result, 0);

4335
  PushSafepointRegistersScope scope(this);
4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347
  __ push(string);
  // Push the index as a smi. This is safe because of the checks in
  // DoStringCharCodeAt above.
  STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
  if (instr->index()->IsConstantOperand()) {
    int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
    __ Push(Smi::FromInt(const_index));
  } else {
    Register index = ToRegister(instr->index());
    __ Integer32ToSmi(index, index);
    __ push(index);
  }
4348
  CallRuntimeFromDeferred(Runtime::kStringCharCodeAt, 2, instr);
4349
  __ AssertSmi(rax);
4350
  __ SmiToInteger32(rax, rax);
4351
  __ StoreToSafepointRegisterSlot(result, rax);
4352 4353 4354
}


4355 4356 4357 4358 4359 4360
void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
  class DeferredStringCharFromCode: public LDeferredCode {
   public:
    DeferredStringCharFromCode(LCodeGen* codegen, LStringCharFromCode* instr)
        : LDeferredCode(codegen), instr_(instr) { }
    virtual void Generate() { codegen()->DoDeferredStringCharFromCode(instr_); }
4361
    virtual LInstruction* instr() { return instr_; }
4362 4363 4364 4365 4366
   private:
    LStringCharFromCode* instr_;
  };

  DeferredStringCharFromCode* deferred =
4367
      new(zone()) DeferredStringCharFromCode(this, instr);
4368 4369 4370 4371 4372 4373

  ASSERT(instr->hydrogen()->value()->representation().IsInteger32());
  Register char_code = ToRegister(instr->char_code());
  Register result = ToRegister(instr->result());
  ASSERT(!char_code.is(result));

4374
  __ cmpl(char_code, Immediate(String::kMaxOneByteCharCode));
4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394
  __ j(above, deferred->entry());
  __ LoadRoot(result, Heap::kSingleCharacterStringCacheRootIndex);
  __ movq(result, FieldOperand(result,
                               char_code, times_pointer_size,
                               FixedArray::kHeaderSize));
  __ CompareRoot(result, Heap::kUndefinedValueRootIndex);
  __ j(equal, deferred->entry());
  __ bind(deferred->exit());
}


void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
  Register char_code = ToRegister(instr->char_code());
  Register result = ToRegister(instr->result());

  // TODO(3095996): Get rid of this. For now, we need to make the
  // result register contain a valid pointer because it is already
  // contained in the register pointer map.
  __ Set(result, 0);

4395
  PushSafepointRegistersScope scope(this);
4396 4397
  __ Integer32ToSmi(char_code, char_code);
  __ push(char_code);
4398
  CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr);
4399 4400 4401 4402
  __ StoreToSafepointRegisterSlot(result, rax);
}


ager@chromium.org's avatar
ager@chromium.org committed
4403 4404 4405 4406 4407 4408 4409
void LCodeGen::DoStringLength(LStringLength* instr) {
  Register string = ToRegister(instr->string());
  Register result = ToRegister(instr->result());
  __ movq(result, FieldOperand(string, String::kLengthOffset));
}


4410
void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4411
  LOperand* input = instr->value();
4412 4413 4414
  ASSERT(input->IsRegister() || input->IsStackSlot());
  LOperand* output = instr->result();
  ASSERT(output->IsDoubleRegister());
4415 4416 4417 4418 4419
  if (input->IsRegister()) {
    __ cvtlsi2sd(ToDoubleRegister(output), ToRegister(input));
  } else {
    __ cvtlsi2sd(ToDoubleRegister(output), ToOperand(input));
  }
4420 4421 4422
}


4423
void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4424
  LOperand* input = instr->value();
4425
  LOperand* output = instr->result();
4426
  LOperand* temp = instr->temp();
4427 4428 4429 4430 4431 4432 4433

  __ LoadUint32(ToDoubleRegister(output),
                ToRegister(input),
                ToDoubleRegister(temp));
}


4434
void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4435
  LOperand* input = instr->value();
4436 4437
  ASSERT(input->IsRegister() && input->Equals(instr->result()));
  Register reg = ToRegister(input);
4438

4439
  __ Integer32ToSmi(reg, reg);
4440 4441 4442
}


4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455
void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
  class DeferredNumberTagU: public LDeferredCode {
   public:
    DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
        : LDeferredCode(codegen), instr_(instr) { }
    virtual void Generate() {
      codegen()->DoDeferredNumberTagU(instr_);
    }
    virtual LInstruction* instr() { return instr_; }
   private:
    LNumberTagU* instr_;
  };

4456
  LOperand* input = instr->value();
4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469
  ASSERT(input->IsRegister() && input->Equals(instr->result()));
  Register reg = ToRegister(input);

  DeferredNumberTagU* deferred = new(zone()) DeferredNumberTagU(this, instr);
  __ cmpl(reg, Immediate(Smi::kMaxValue));
  __ j(above, deferred->entry());
  __ Integer32ToSmi(reg, reg);
  __ bind(deferred->exit());
}


void LCodeGen::DoDeferredNumberTagU(LNumberTagU* instr) {
  Label slow;
4470
  Register reg = ToRegister(instr->value());
4471 4472 4473 4474 4475 4476
  Register tmp = reg.is(rax) ? rcx : rax;

  // Preserve the value of all registers.
  PushSafepointRegistersScope scope(this);

  Label done;
4477 4478 4479 4480
  // Load value into xmm1 which will be preserved across potential call to
  // runtime (MacroAssembler::EnterExitFrameEpilogue preserves only allocatable
  // XMM registers on x64).
  __ LoadUint32(xmm1, reg, xmm0);
4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497

  if (FLAG_inline_new) {
    __ AllocateHeapNumber(reg, tmp, &slow);
    __ jmp(&done, Label::kNear);
  }

  // Slow case: Call the runtime system to do the number allocation.
  __ bind(&slow);

  // Put a valid pointer value in the stack slot where the result
  // register is stored, as this register is in the pointer map, but contains an
  // integer value.
  __ StoreToSafepointRegisterSlot(reg, Immediate(0));

  CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr);
  if (!reg.is(rax)) __ movq(reg, rax);

4498
  // Done. Put the value in xmm1 into the value of the allocated heap
4499 4500
  // number.
  __ bind(&done);
4501
  __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), xmm1);
4502 4503 4504 4505
  __ StoreToSafepointRegisterSlot(reg, reg);
}


4506
void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4507 4508 4509 4510 4511
  class DeferredNumberTagD: public LDeferredCode {
   public:
    DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
        : LDeferredCode(codegen), instr_(instr) { }
    virtual void Generate() { codegen()->DoDeferredNumberTagD(instr_); }
4512
    virtual LInstruction* instr() { return instr_; }
4513 4514 4515 4516
   private:
    LNumberTagD* instr_;
  };

4517
  XMMRegister input_reg = ToDoubleRegister(instr->value());
4518
  Register reg = ToRegister(instr->result());
4519
  Register tmp = ToRegister(instr->temp());
4520

4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550
  bool convert_hole = false;
  HValue* change_input = instr->hydrogen()->value();
  if (change_input->IsLoadKeyed()) {
    HLoadKeyed* load = HLoadKeyed::cast(change_input);
    convert_hole = load->UsesMustHandleHole();
  }

  Label no_special_nan_handling;
  Label done;
  if (convert_hole) {
    XMMRegister input_reg = ToDoubleRegister(instr->value());
    __ ucomisd(input_reg, input_reg);
    __ j(parity_odd, &no_special_nan_handling);
    __ subq(rsp, Immediate(kDoubleSize));
    __ movsd(MemOperand(rsp, 0), input_reg);
    __ cmpl(MemOperand(rsp, sizeof(kHoleNanLower32)),
            Immediate(kHoleNanUpper32));
    Label canonicalize;
    __ j(not_equal, &canonicalize);
    __ addq(rsp, Immediate(kDoubleSize));
    __ Move(reg, factory()->the_hole_value());
    __ jmp(&done);
    __ bind(&canonicalize);
    __ addq(rsp, Immediate(kDoubleSize));
    __ Set(kScratchRegister, BitCast<uint64_t>(
        FixedDoubleArray::canonical_not_the_hole_nan_as_double()));
    __ movq(input_reg, kScratchRegister);
  }

  __ bind(&no_special_nan_handling);
4551
  DeferredNumberTagD* deferred = new(zone()) DeferredNumberTagD(this, instr);
4552 4553 4554 4555 4556 4557 4558
  if (FLAG_inline_new) {
    __ AllocateHeapNumber(reg, tmp, deferred->entry());
  } else {
    __ jmp(deferred->entry());
  }
  __ bind(deferred->exit());
  __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg);
4559 4560

  __ bind(&done);
4561 4562 4563 4564
}


void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4565 4566 4567 4568 4569 4570
  // TODO(3095996): Get rid of this. For now, we need to make the
  // result register contain a valid pointer because it is already
  // contained in the register pointer map.
  Register reg = ToRegister(instr->result());
  __ Move(reg, Smi::FromInt(0));

4571 4572 4573 4574 4575 4576
  {
    PushSafepointRegistersScope scope(this);
    CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr);
    // Ensure that value in rax survives popping registers.
    __ movq(kScratchRegister, rax);
  }
4577
  __ movq(reg, kScratchRegister);
4578 4579 4580 4581
}


void LCodeGen::DoSmiTag(LSmiTag* instr) {
4582 4583
  ASSERT(instr->value()->Equals(instr->result()));
  Register input = ToRegister(instr->value());
4584 4585
  ASSERT(!instr->hydrogen_value()->CheckFlag(HValue::kCanOverflow));
  __ Integer32ToSmi(input, input);
4586 4587 4588 4589
}


void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4590 4591
  ASSERT(instr->value()->Equals(instr->result()));
  Register input = ToRegister(instr->value());
4592 4593 4594
  if (instr->needs_check()) {
    Condition is_smi = __ CheckSmi(input);
    DeoptimizeIf(NegateCondition(is_smi), instr->environment());
4595
  } else {
4596
    __ AssertSmi(input);
4597 4598
  }
  __ SmiToInteger32(input, input);
4599 4600 4601 4602 4603
}


void LCodeGen::EmitNumberUntagD(Register input_reg,
                                XMMRegister result_reg,
4604
                                bool deoptimize_on_undefined,
4605
                                bool deoptimize_on_minus_zero,
4606 4607
                                LEnvironment* env,
                                NumberUntagDMode mode) {
4608
  Label load_smi, done;
4609

4610 4611 4612
  if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
    // Smi check.
    __ JumpIfSmi(input_reg, &load_smi, Label::kNear);
4613

4614 4615 4616 4617 4618 4619 4620 4621
    // Heap number map check.
    __ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset),
                   Heap::kHeapNumberMapRootIndex);
    if (deoptimize_on_undefined) {
      DeoptimizeIf(not_equal, env);
    } else {
      Label heap_number;
      __ j(equal, &heap_number, Label::kNear);
4622

4623 4624
      __ CompareRoot(input_reg, Heap::kUndefinedValueRootIndex);
      DeoptimizeIf(not_equal, env);
4625

4626 4627 4628 4629
      // Convert undefined to NaN. Compute NaN as 0/0.
      __ xorps(result_reg, result_reg);
      __ divsd(result_reg, result_reg);
      __ jmp(&done, Label::kNear);
4630

4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656
      __ bind(&heap_number);
    }
    // Heap number to XMM conversion.
    __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset));
    if (deoptimize_on_minus_zero) {
      XMMRegister xmm_scratch = xmm0;
      __ xorps(xmm_scratch, xmm_scratch);
      __ ucomisd(xmm_scratch, result_reg);
      __ j(not_equal, &done, Label::kNear);
      __ movmskpd(kScratchRegister, result_reg);
      __ testq(kScratchRegister, Immediate(1));
      DeoptimizeIf(not_zero, env);
    }
    __ jmp(&done, Label::kNear);
  } else if (mode == NUMBER_CANDIDATE_IS_SMI_OR_HOLE) {
      __ testq(input_reg, Immediate(kSmiTagMask));
      DeoptimizeIf(not_equal, env);
  } else if (mode == NUMBER_CANDIDATE_IS_SMI_CONVERT_HOLE) {
      __ testq(input_reg, Immediate(kSmiTagMask));
      __ j(zero, &load_smi);
    __ Set(kScratchRegister, BitCast<uint64_t>(
        FixedDoubleArray::hole_nan_as_double()));
    __ movq(result_reg, kScratchRegister);
      __ jmp(&done, Label::kNear);
  } else {
    ASSERT(mode == NUMBER_CANDIDATE_IS_SMI);
4657
  }
4658 4659 4660

  // Smi to XMM conversion
  __ bind(&load_smi);
ager@chromium.org's avatar
ager@chromium.org committed
4661
  __ SmiToInteger32(kScratchRegister, input_reg);
4662 4663
  __ cvtlsi2sd(result_reg, kScratchRegister);
  __ bind(&done);
4664 4665 4666 4667
}


void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr) {
4668
  Label done, heap_number;
4669
  Register input_reg = ToRegister(instr->value());
4670 4671 4672 4673 4674 4675

  // Heap number map check.
  __ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset),
                 Heap::kHeapNumberMapRootIndex);

  if (instr->truncating()) {
4676
    __ j(equal, &heap_number, Label::kNear);
4677 4678 4679 4680
    // Check for undefined. Undefined is converted to zero for truncating
    // conversions.
    __ CompareRoot(input_reg, Heap::kUndefinedValueRootIndex);
    DeoptimizeIf(not_equal, instr->environment());
4681
    __ Set(input_reg, 0);
4682
    __ jmp(&done, Label::kNear);
4683 4684 4685 4686 4687 4688

    __ bind(&heap_number);

    __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
    __ cvttsd2siq(input_reg, xmm0);
    __ Set(kScratchRegister, V8_UINT64_C(0x8000000000000000));
4689
    __ cmpq(input_reg, kScratchRegister);
4690 4691 4692 4693 4694
    DeoptimizeIf(equal, instr->environment());
  } else {
    // Deoptimize if we don't have a heap number.
    DeoptimizeIf(not_equal, instr->environment());

4695
    XMMRegister xmm_temp = ToDoubleRegister(instr->temp());
4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710
    __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
    __ cvttsd2si(input_reg, xmm0);
    __ cvtlsi2sd(xmm_temp, input_reg);
    __ ucomisd(xmm0, xmm_temp);
    DeoptimizeIf(not_equal, instr->environment());
    DeoptimizeIf(parity_even, instr->environment());  // NaN.
    if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
      __ testl(input_reg, input_reg);
      __ j(not_zero, &done);
      __ movmskpd(input_reg, xmm0);
      __ andl(input_reg, Immediate(1));
      DeoptimizeIf(not_zero, instr->environment());
    }
  }
  __ bind(&done);
4711 4712 4713 4714
}


void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
4715 4716 4717 4718 4719 4720 4721 4722 4723 4724
  class DeferredTaggedToI: public LDeferredCode {
   public:
    DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
        : LDeferredCode(codegen), instr_(instr) { }
    virtual void Generate() { codegen()->DoDeferredTaggedToI(instr_); }
    virtual LInstruction* instr() { return instr_; }
   private:
    LTaggedToI* instr_;
  };

4725
  LOperand* input = instr->value();
4726 4727 4728 4729
  ASSERT(input->IsRegister());
  ASSERT(input->Equals(instr->result()));

  Register input_reg = ToRegister(input);
4730
  DeferredTaggedToI* deferred = new(zone()) DeferredTaggedToI(this, instr);
4731 4732 4733
  __ JumpIfNotSmi(input_reg, deferred->entry());
  __ SmiToInteger32(input_reg, input_reg);
  __ bind(deferred->exit());
4734 4735 4736 4737
}


void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4738
  LOperand* input = instr->value();
ager@chromium.org's avatar
ager@chromium.org committed
4739 4740 4741 4742 4743 4744 4745
  ASSERT(input->IsRegister());
  LOperand* result = instr->result();
  ASSERT(result->IsDoubleRegister());

  Register input_reg = ToRegister(input);
  XMMRegister result_reg = ToDoubleRegister(result);

4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762
  NumberUntagDMode mode = NUMBER_CANDIDATE_IS_ANY_TAGGED;
  HValue* value = instr->hydrogen()->value();
  if (value->type().IsSmi()) {
    if (value->IsLoadKeyed()) {
      HLoadKeyed* load = HLoadKeyed::cast(value);
      if (load->UsesMustHandleHole()) {
        if (load->hole_mode() == ALLOW_RETURN_HOLE) {
          mode = NUMBER_CANDIDATE_IS_SMI_CONVERT_HOLE;
        } else {
          mode = NUMBER_CANDIDATE_IS_SMI_OR_HOLE;
        }
      } else {
        mode = NUMBER_CANDIDATE_IS_SMI;
      }
    }
  }

4763 4764
  EmitNumberUntagD(input_reg, result_reg,
                   instr->hydrogen()->deoptimize_on_undefined(),
4765
                   instr->hydrogen()->deoptimize_on_minus_zero(),
4766 4767
                   instr->environment(),
                   mode);
4768 4769 4770 4771
}


void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
4772
  LOperand* input = instr->value();
4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783
  ASSERT(input->IsDoubleRegister());
  LOperand* result = instr->result();
  ASSERT(result->IsRegister());

  XMMRegister input_reg = ToDoubleRegister(input);
  Register result_reg = ToRegister(result);

  if (instr->truncating()) {
    // Performs a truncating conversion of a floating point number as used by
    // the JS bitwise operations.
    __ cvttsd2siq(result_reg, input_reg);
4784 4785 4786
    __ movq(kScratchRegister,
            V8_INT64_C(0x8000000000000000),
            RelocInfo::NONE64);
4787
    __ cmpq(result_reg, kScratchRegister);
4788
    DeoptimizeIf(equal, instr->environment());
4789 4790 4791 4792 4793 4794 4795
  } else {
    __ cvttsd2si(result_reg, input_reg);
    __ cvtlsi2sd(xmm0, result_reg);
    __ ucomisd(xmm0, input_reg);
    DeoptimizeIf(not_equal, instr->environment());
    DeoptimizeIf(parity_even, instr->environment());  // NaN.
    if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4796
      Label done;
4797 4798 4799
      // The integer converted back is equal to the original. We
      // only have to test if we got -0 as an input.
      __ testl(result_reg, result_reg);
4800
      __ j(not_zero, &done, Label::kNear);
4801 4802 4803 4804 4805 4806 4807 4808 4809
      __ movmskpd(result_reg, input_reg);
      // Bit 0 contains the sign of the double in input_reg.
      // If input was positive, we are ok and return 0, otherwise
      // deoptimize.
      __ andl(result_reg, Immediate(1));
      DeoptimizeIf(not_zero, instr->environment());
      __ bind(&done);
    }
  }
4810 4811 4812 4813
}


void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
4814
  LOperand* input = instr->value();
4815
  Condition cc = masm()->CheckSmi(ToRegister(input));
4816 4817 4818 4819 4820
  DeoptimizeIf(NegateCondition(cc), instr->environment());
}


void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
4821
  LOperand* input = instr->value();
4822
  Condition cc = masm()->CheckSmi(ToRegister(input));
4823
  DeoptimizeIf(cc, instr->environment());
4824 4825 4826 4827
}


void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
4828
  Register input = ToRegister(instr->value());
4829 4830 4831

  __ movq(kScratchRegister, FieldOperand(input, HeapObject::kMapOffset));

4832 4833 4834 4835 4836
  if (instr->hydrogen()->is_interval_check()) {
    InstanceType first;
    InstanceType last;
    instr->hydrogen()->GetCheckInterval(&first, &last);

4837 4838
    __ cmpb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset),
            Immediate(static_cast<int8_t>(first)));
4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851

    // If there is only one type in the interval check for equality.
    if (first == last) {
      DeoptimizeIf(not_equal, instr->environment());
    } else {
      DeoptimizeIf(below, instr->environment());
      // Omit check for the last type.
      if (last != LAST_TYPE) {
        __ cmpb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset),
                Immediate(static_cast<int8_t>(last)));
        DeoptimizeIf(above, instr->environment());
      }
    }
4852
  } else {
4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867
    uint8_t mask;
    uint8_t tag;
    instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);

    if (IsPowerOf2(mask)) {
      ASSERT(tag == 0 || IsPowerOf2(tag));
      __ testb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset),
               Immediate(mask));
      DeoptimizeIf(tag == 0 ? not_zero : zero, instr->environment());
    } else {
      __ movzxbl(kScratchRegister,
                 FieldOperand(kScratchRegister, Map::kInstanceTypeOffset));
      __ andb(kScratchRegister, Immediate(mask));
      __ cmpb(kScratchRegister, Immediate(tag));
      DeoptimizeIf(not_equal, instr->environment());
4868 4869
    }
  }
4870 4871 4872 4873
}


void LCodeGen::DoCheckFunction(LCheckFunction* instr) {
4874 4875
  Register reg = ToRegister(instr->value());
  Handle<JSFunction> target = instr->hydrogen()->target();
4876
  ALLOW_HANDLE_DEREF(isolate(), "using raw address");
4877 4878 4879 4880 4881 4882 4883 4884
  if (isolate()->heap()->InNewSpace(*target)) {
    Handle<JSGlobalPropertyCell> cell =
        isolate()->factory()->NewJSGlobalPropertyCell(target);
    __ movq(kScratchRegister, cell, RelocInfo::GLOBAL_PROPERTY_CELL);
    __ cmpq(reg, Operand(kScratchRegister, 0));
  } else {
    __ Cmp(reg, target);
  }
4885
  DeoptimizeIf(not_equal, instr->environment());
4886 4887 4888
}


4889 4890 4891
void LCodeGen::DoCheckMapCommon(Register reg,
                                Handle<Map> map,
                                CompareMapMode mode,
4892
                                LInstruction* instr) {
4893 4894
  Label success;
  __ CompareMap(reg, map, &success, mode);
4895
  DeoptimizeIf(not_equal, instr->environment());
4896 4897 4898 4899
  __ bind(&success);
}


4900
void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
4901
  LOperand* input = instr->value();
4902 4903
  ASSERT(input->IsRegister());
  Register reg = ToRegister(input);
4904 4905 4906 4907 4908

  Label success;
  SmallMapList* map_set = instr->hydrogen()->map_set();
  for (int i = 0; i < map_set->length() - 1; i++) {
    Handle<Map> map = map_set->at(i);
4909
    __ CompareMap(reg, map, &success, REQUIRE_EXACT_MAP);
4910 4911 4912
    __ j(equal, &success);
  }
  Handle<Map> map = map_set->last();
4913
  DoCheckMapCommon(reg, map, REQUIRE_EXACT_MAP, instr);
4914
  __ bind(&success);
4915 4916 4917
}


4918
void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
4919 4920
  XMMRegister value_reg = ToDoubleRegister(instr->unclamped());
  Register result_reg = ToRegister(instr->result());
4921
  __ ClampDoubleToUint8(value_reg, xmm0, result_reg);
4922 4923 4924 4925 4926 4927 4928 4929 4930 4931
}


void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
  ASSERT(instr->unclamped()->Equals(instr->result()));
  Register value_reg = ToRegister(instr->result());
  __ ClampUint8(value_reg);
}


4932
void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
4933 4934
  ASSERT(instr->unclamped()->Equals(instr->result()));
  Register input_reg = ToRegister(instr->unclamped());
4935
  XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm());
4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954
  Label is_smi, done, heap_number;

  __ JumpIfSmi(input_reg, &is_smi);

  // Check for heap number
  __ Cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
         factory()->heap_number_map());
  __ j(equal, &heap_number, Label::kNear);

  // Check for undefined. Undefined is converted to zero for clamping
  // conversions.
  __ Cmp(input_reg, factory()->undefined_value());
  DeoptimizeIf(not_equal, instr->environment());
  __ movq(input_reg, Immediate(0));
  __ jmp(&done, Label::kNear);

  // Heap number
  __ bind(&heap_number);
  __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
4955
  __ ClampDoubleToUint8(xmm0, temp_xmm_reg, input_reg);
4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966
  __ jmp(&done, Label::kNear);

  // smi
  __ bind(&is_smi);
  __ SmiToInteger32(input_reg, input_reg);
  __ ClampUint8(input_reg);

  __ bind(&done);
}


4967
void LCodeGen::DoCheckPrototypeMaps(LCheckPrototypeMaps* instr) {
4968
  Register reg = ToRegister(instr->temp());
4969

4970 4971 4972 4973
  ZoneList<Handle<JSObject> >* prototypes = instr->prototypes();
  ZoneList<Handle<Map> >* maps = instr->maps();

  ASSERT(prototypes->length() == maps->length());
4974

4975 4976 4977 4978 4979 4980 4981 4982 4983
  if (instr->hydrogen()->CanOmitPrototypeChecks()) {
    for (int i = 0; i < maps->length(); i++) {
      prototype_maps_.Add(maps->at(i), info()->zone());
    }
  } else {
    for (int i = 0; i < prototypes->length(); i++) {
      __ LoadHeapObject(reg, prototypes->at(i));
      DoCheckMapCommon(reg, maps->at(i), ALLOW_ELEMENT_TRANSITION_MAPS, instr);
    }
4984
  }
4985 4986 4987
}


4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998
void LCodeGen::DoAllocateObject(LAllocateObject* instr) {
  class DeferredAllocateObject: public LDeferredCode {
   public:
    DeferredAllocateObject(LCodeGen* codegen, LAllocateObject* instr)
        : LDeferredCode(codegen), instr_(instr) { }
    virtual void Generate() { codegen()->DoDeferredAllocateObject(instr_); }
    virtual LInstruction* instr() { return instr_; }
   private:
    LAllocateObject* instr_;
  };

4999 5000
  DeferredAllocateObject* deferred =
      new(zone()) DeferredAllocateObject(this, instr);
5001

5002
  Register result = ToRegister(instr->result());
5003
  Register scratch = ToRegister(instr->temp());
5004
  Handle<JSFunction> constructor = instr->hydrogen()->constructor();
5005
  Handle<Map> initial_map = instr->hydrogen()->constructor_initial_map();
5006 5007 5008 5009 5010
  int instance_size = initial_map->instance_size();
  ASSERT(initial_map->pre_allocated_property_fields() +
         initial_map->unused_property_fields() -
         initial_map->inobject_properties() == 0);

5011 5012
  __ Allocate(instance_size, result, no_reg, scratch, deferred->entry(),
              TAG_OBJECT);
5013

5014 5015 5016 5017 5018 5019 5020 5021
  __ bind(deferred->exit());
  if (FLAG_debug_code) {
    Label is_in_new_space;
    __ JumpIfInNewSpace(result, scratch, &is_in_new_space);
    __ Abort("Allocated object is not in new-space");
    __ bind(&is_in_new_space);
  }

5022 5023 5024 5025 5026 5027
  // Load the initial map.
  Register map = scratch;
  __ LoadHeapObject(scratch, constructor);
  __ movq(map, FieldOperand(scratch, JSFunction::kPrototypeOrInitialMapOffset));

  if (FLAG_debug_code) {
5028
    __ AssertNotSmi(map);
5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055
    __ cmpb(FieldOperand(map, Map::kInstanceSizeOffset),
            Immediate(instance_size >> kPointerSizeLog2));
    __ Assert(equal, "Unexpected instance size");
    __ cmpb(FieldOperand(map, Map::kPreAllocatedPropertyFieldsOffset),
            Immediate(initial_map->pre_allocated_property_fields()));
    __ Assert(equal, "Unexpected pre-allocated property fields count");
    __ cmpb(FieldOperand(map, Map::kUnusedPropertyFieldsOffset),
            Immediate(initial_map->unused_property_fields()));
    __ Assert(equal, "Unexpected unused property fields count");
    __ cmpb(FieldOperand(map, Map::kInObjectPropertiesOffset),
            Immediate(initial_map->inobject_properties()));
    __ Assert(equal, "Unexpected in-object property fields count");
  }

  // Initialize map and fields of the newly allocated object.
  ASSERT(initial_map->instance_type() == JS_OBJECT_TYPE);
  __ movq(FieldOperand(result, JSObject::kMapOffset), map);
  __ LoadRoot(scratch, Heap::kEmptyFixedArrayRootIndex);
  __ movq(FieldOperand(result, JSObject::kElementsOffset), scratch);
  __ movq(FieldOperand(result, JSObject::kPropertiesOffset), scratch);
  if (initial_map->inobject_properties() != 0) {
    __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex);
    for (int i = 0; i < initial_map->inobject_properties(); i++) {
      int property_offset = JSObject::kHeaderSize + i * kPointerSize;
      __ movq(FieldOperand(result, property_offset), scratch);
    }
  }
5056 5057 5058 5059 5060
}


void LCodeGen::DoDeferredAllocateObject(LAllocateObject* instr) {
  Register result = ToRegister(instr->result());
5061
  Handle<Map> initial_map = instr->hydrogen()->constructor_initial_map();
5062
  int instance_size = initial_map->instance_size();
5063 5064 5065 5066 5067 5068 5069

  // TODO(3095996): Get rid of this. For now, we need to make the
  // result register contain a valid pointer because it is already
  // contained in the register pointer map.
  __ Set(result, 0);

  PushSafepointRegistersScope scope(this);
5070 5071
  __ Push(Smi::FromInt(instance_size));
  CallRuntimeFromDeferred(Runtime::kAllocateInNewSpace, 1, instr);
5072 5073 5074 5075
  __ StoreToSafepointRegisterSlot(result, rax);
}


5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092
void LCodeGen::DoAllocate(LAllocate* instr) {
  class DeferredAllocate: public LDeferredCode {
   public:
    DeferredAllocate(LCodeGen* codegen, LAllocate* instr)
        : LDeferredCode(codegen), instr_(instr) { }
    virtual void Generate() { codegen()->DoDeferredAllocate(instr_); }
    virtual LInstruction* instr() { return instr_; }
   private:
    LAllocate* instr_;
  };

  DeferredAllocate* deferred =
      new(zone()) DeferredAllocate(this, instr);

  Register result = ToRegister(instr->result());
  Register temp = ToRegister(instr->temp());

5093 5094 5095 5096 5097
  // Allocate memory for the object.
  AllocationFlags flags = TAG_OBJECT;
  if (instr->hydrogen()->MustAllocateDoubleAligned()) {
    flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
  }
5098 5099 5100
  if (instr->hydrogen()->CanAllocateInOldPointerSpace()) {
    flags = static_cast<AllocationFlags>(flags | PRETENURE_OLD_POINTER_SPACE);
  }
5101 5102
  if (instr->size()->IsConstantOperand()) {
    int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5103
    __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5104
  } else {
5105
    Register size = ToRegister(instr->size());
5106
    __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124
  }

  __ bind(deferred->exit());
}


void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
  Register size = ToRegister(instr->size());
  Register result = ToRegister(instr->result());

  // TODO(3095996): Get rid of this. For now, we need to make the
  // result register contain a valid pointer because it is already
  // contained in the register pointer map.
  __ Set(result, 0);

  PushSafepointRegistersScope scope(this);
  __ Integer32ToSmi(size, size);
  __ push(size);
5125 5126 5127 5128 5129 5130 5131
  if (instr->hydrogen()->CanAllocateInOldPointerSpace()) {
    CallRuntimeFromDeferred(
        Runtime::kAllocateInOldPointerSpace, 1, instr);
  } else {
    CallRuntimeFromDeferred(
        Runtime::kAllocateInNewSpace, 1, instr);
  }
5132 5133 5134 5135
  __ StoreToSafepointRegisterSlot(result, rax);
}


5136
void LCodeGen::DoArrayLiteral(LArrayLiteral* instr) {
5137
  Handle<FixedArray> literals = instr->hydrogen()->literals();
5138 5139
  ElementsKind boilerplate_elements_kind =
      instr->hydrogen()->boilerplate_elements_kind();
5140 5141
  AllocationSiteMode allocation_site_mode =
      instr->hydrogen()->allocation_site_mode();
5142 5143 5144

  // Deopt if the array literal boilerplate ElementsKind is of a type different
  // than the expected one. The check isn't necessary if the boilerplate has
5145 5146 5147
  // already been converted to TERMINAL_FAST_ELEMENTS_KIND.
  if (CanTransitionToMoreGeneralFastElementsKind(
          boilerplate_elements_kind, true)) {
5148
    __ LoadHeapObject(rax, instr->hydrogen()->boilerplate_object());
5149 5150 5151 5152 5153 5154 5155 5156 5157
    __ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset));
    // Load the map's "bit field 2".
    __ movb(rbx, FieldOperand(rbx, Map::kBitField2Offset));
    // Retrieve elements_kind from bit field 2.
    __ and_(rbx, Immediate(Map::kElementsKindMask));
    __ cmpb(rbx, Immediate(boilerplate_elements_kind <<
                           Map::kElementsKindShift));
    DeoptimizeIf(not_equal, instr->environment());
  }
5158

5159 5160 5161
  // Set up the parameters to the stub/runtime call and pick the right
  // runtime function or stub to call. Boilerplate already exists,
  // constant elements are never accessed, pass an empty fixed array.
5162 5163 5164
  int length = instr->hydrogen()->length();
  if (instr->hydrogen()->IsCopyOnWrite()) {
    ASSERT(instr->hydrogen()->depth() == 1);
5165 5166 5167
    __ LoadHeapObject(rax, literals);
    __ Move(rbx, Smi::FromInt(instr->hydrogen()->literal_index()));
    __ Move(rcx, isolate()->factory()->empty_fixed_array());
5168 5169
    FastCloneShallowArrayStub::Mode mode =
        FastCloneShallowArrayStub::COPY_ON_WRITE_ELEMENTS;
5170
    FastCloneShallowArrayStub stub(mode, DONT_TRACK_ALLOCATION_SITE, length);
5171
    CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
5172
  } else if (instr->hydrogen()->depth() > 1) {
5173 5174 5175
    __ PushHeapObject(literals);
    __ Push(Smi::FromInt(instr->hydrogen()->literal_index()));
    __ Push(isolate()->factory()->empty_fixed_array());
5176 5177
    CallRuntime(Runtime::kCreateArrayLiteral, 3, instr);
  } else if (length > FastCloneShallowArrayStub::kMaximumClonedLength) {
5178 5179 5180
    __ PushHeapObject(literals);
    __ Push(Smi::FromInt(instr->hydrogen()->literal_index()));
    __ Push(isolate()->factory()->empty_fixed_array());
5181 5182
    CallRuntime(Runtime::kCreateArrayLiteralShallow, 3, instr);
  } else {
5183 5184 5185
    __ LoadHeapObject(rax, literals);
    __ Move(rbx, Smi::FromInt(instr->hydrogen()->literal_index()));
    __ Move(rcx, isolate()->factory()->empty_fixed_array());
5186
    FastCloneShallowArrayStub::Mode mode =
5187
        boilerplate_elements_kind == FAST_DOUBLE_ELEMENTS
5188 5189 5190
        ? FastCloneShallowArrayStub::CLONE_DOUBLE_ELEMENTS
        : FastCloneShallowArrayStub::CLONE_ELEMENTS;
    FastCloneShallowArrayStub stub(mode, allocation_site_mode, length);
5191
    CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
5192
  }
5193 5194 5195
}


5196
void LCodeGen::DoObjectLiteral(LObjectLiteral* instr) {
5197
  Handle<FixedArray> literals = instr->hydrogen()->literals();
5198 5199 5200 5201 5202 5203 5204 5205 5206
  Handle<FixedArray> constant_properties =
      instr->hydrogen()->constant_properties();

  int flags = instr->hydrogen()->fast_elements()
      ? ObjectLiteral::kFastElements
      : ObjectLiteral::kNoFlags;
  flags |= instr->hydrogen()->has_function()
      ? ObjectLiteral::kHasFunction
      : ObjectLiteral::kNoFlags;
5207

5208 5209
  // Set up the parameters to the stub/runtime call and pick the right
  // runtime function or stub to call.
5210
  int properties_count = instr->hydrogen()->constant_properties_length() / 2;
5211
  if (instr->hydrogen()->depth() > 1) {
5212 5213 5214 5215
    __ PushHeapObject(literals);
    __ Push(Smi::FromInt(instr->hydrogen()->literal_index()));
    __ Push(constant_properties);
    __ Push(Smi::FromInt(flags));
5216
    CallRuntime(Runtime::kCreateObjectLiteral, 4, instr);
5217 5218
  } else if (flags != ObjectLiteral::kFastElements ||
      properties_count > FastCloneShallowObjectStub::kMaximumClonedProperties) {
5219 5220 5221 5222
    __ PushHeapObject(literals);
    __ Push(Smi::FromInt(instr->hydrogen()->literal_index()));
    __ Push(constant_properties);
    __ Push(Smi::FromInt(flags));
5223
    CallRuntime(Runtime::kCreateObjectLiteralShallow, 4, instr);
5224
  } else {
5225 5226 5227 5228
    __ LoadHeapObject(rax, literals);
    __ Move(rbx, Smi::FromInt(instr->hydrogen()->literal_index()));
    __ Move(rcx, constant_properties);
    __ Move(rdx, Smi::FromInt(flags));
5229
    FastCloneShallowObjectStub stub(properties_count);
5230
    CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
5231
  }
5232 5233 5234
}


5235
void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5236
  ASSERT(ToRegister(instr->value()).is(rax));
5237 5238 5239 5240 5241
  __ push(rax);
  CallRuntime(Runtime::kToFastProperties, 1, instr);
}


5242
void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5243
  Label materialized;
5244 5245 5246 5247
  // Registers will be used as follows:
  // rcx = literals array.
  // rbx = regexp literal.
  // rax = regexp literal clone.
5248 5249 5250
  int literal_offset =
      FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
  __ LoadHeapObject(rcx, instr->hydrogen()->literals());
5251 5252
  __ movq(rbx, FieldOperand(rcx, literal_offset));
  __ CompareRoot(rbx, Heap::kUndefinedValueRootIndex);
5253
  __ j(not_equal, &materialized, Label::kNear);
5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266

  // Create regexp literal using runtime function
  // Result will be in rax.
  __ push(rcx);
  __ Push(Smi::FromInt(instr->hydrogen()->literal_index()));
  __ Push(instr->hydrogen()->pattern());
  __ Push(instr->hydrogen()->flags());
  CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
  __ movq(rbx, rax);

  __ bind(&materialized);
  int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
  Label allocated, runtime_allocate;
5267
  __ Allocate(size, rax, rcx, rdx, &runtime_allocate, TAG_OBJECT);
5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288
  __ jmp(&allocated);

  __ bind(&runtime_allocate);
  __ push(rbx);
  __ Push(Smi::FromInt(size));
  CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
  __ pop(rbx);

  __ bind(&allocated);
  // Copy the content into the newly allocated memory.
  // (Unroll copy loop once for better throughput).
  for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
    __ movq(rdx, FieldOperand(rbx, i));
    __ movq(rcx, FieldOperand(rbx, i + kPointerSize));
    __ movq(FieldOperand(rax, i), rdx);
    __ movq(FieldOperand(rax, i + kPointerSize), rcx);
  }
  if ((size % (2 * kPointerSize)) != 0) {
    __ movq(rdx, FieldOperand(rbx, size - kPointerSize));
    __ movq(FieldOperand(rax, size - kPointerSize), rdx);
  }
5289 5290 5291 5292
}


void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5293 5294 5295
  // Use the fast case closure allocation code that allocates in new
  // space for nested functions that don't need literals cloning.
  bool pretenure = instr->hydrogen()->pretenure();
5296 5297 5298 5299
  if (!pretenure && instr->hydrogen()->has_no_literals()) {
    FastNewClosureStub stub(instr->hydrogen()->language_mode(),
                            instr->hydrogen()->is_generator());
    __ Push(instr->hydrogen()->shared_info());
5300
    CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
5301 5302
  } else {
    __ push(rsi);
5303 5304 5305
    __ Push(instr->hydrogen()->shared_info());
    __ PushRoot(pretenure ? Heap::kTrueValueRootIndex :
                            Heap::kFalseValueRootIndex);
5306 5307
    CallRuntime(Runtime::kNewClosure, 3, instr);
  }
5308 5309 5310 5311
}


void LCodeGen::DoTypeof(LTypeof* instr) {
5312
  LOperand* input = instr->value();
5313
  EmitPushTaggedOperand(input);
5314
  CallRuntime(Runtime::kTypeof, 1, instr);
5315 5316 5317
}


5318 5319 5320
void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
  ASSERT(!operand->IsDoubleRegister());
  if (operand->IsConstantOperand()) {
5321
    Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
5322
    ALLOW_HANDLE_DEREF(isolate(), "smi check");
5323 5324 5325 5326 5327
    if (object->IsSmi()) {
      __ Push(Handle<Smi>::cast(object));
    } else {
      __ PushHeapObject(Handle<HeapObject>::cast(object));
    }
5328 5329
  } else if (operand->IsRegister()) {
    __ push(ToRegister(operand));
5330
  } else {
5331
    __ push(ToOperand(operand));
5332 5333 5334 5335
  }
}


5336
void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5337
  Register input = ToRegister(instr->value());
5338 5339 5340 5341 5342
  int true_block = chunk_->LookupDestination(instr->true_block_id());
  int false_block = chunk_->LookupDestination(instr->false_block_id());
  Label* true_label = chunk_->GetAssemblyLabel(true_block);
  Label* false_label = chunk_->GetAssemblyLabel(false_block);

5343 5344 5345 5346 5347
  Condition final_branch_condition =
      EmitTypeofIs(true_label, false_label, input, instr->type_literal());
  if (final_branch_condition != no_condition) {
    EmitBranch(true_block, false_block, final_branch_condition);
  }
5348 5349 5350 5351 5352 5353 5354
}


Condition LCodeGen::EmitTypeofIs(Label* true_label,
                                 Label* false_label,
                                 Register input,
                                 Handle<String> type_name) {
5355
  Condition final_branch_condition = no_condition;
5356
  if (type_name->Equals(heap()->number_string())) {
5357
    __ JumpIfSmi(input, true_label);
5358 5359 5360
    __ CompareRoot(FieldOperand(input, HeapObject::kMapOffset),
                   Heap::kHeapNumberMapRootIndex);

5361 5362
    final_branch_condition = equal;

5363
  } else if (type_name->Equals(heap()->string_string())) {
5364
    __ JumpIfSmi(input, false_label);
5365 5366
    __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
    __ j(above_equal, false_label);
5367 5368
    __ testb(FieldOperand(input, Map::kBitFieldOffset),
             Immediate(1 << Map::kIsUndetectable));
5369
    final_branch_condition = zero;
5370

5371 5372 5373 5374 5375
  } else if (type_name->Equals(heap()->symbol_string())) {
    __ JumpIfSmi(input, false_label);
    __ CmpObjectType(input, SYMBOL_TYPE, input);
    final_branch_condition = equal;

5376
  } else if (type_name->Equals(heap()->boolean_string())) {
5377 5378 5379 5380 5381
    __ CompareRoot(input, Heap::kTrueValueRootIndex);
    __ j(equal, true_label);
    __ CompareRoot(input, Heap::kFalseValueRootIndex);
    final_branch_condition = equal;

5382
  } else if (FLAG_harmony_typeof && type_name->Equals(heap()->null_string())) {
5383 5384 5385
    __ CompareRoot(input, Heap::kNullValueRootIndex);
    final_branch_condition = equal;

5386
  } else if (type_name->Equals(heap()->undefined_string())) {
5387 5388 5389 5390 5391 5392 5393 5394 5395
    __ CompareRoot(input, Heap::kUndefinedValueRootIndex);
    __ j(equal, true_label);
    __ JumpIfSmi(input, false_label);
    // Check for undetectable objects => true.
    __ movq(input, FieldOperand(input, HeapObject::kMapOffset));
    __ testb(FieldOperand(input, Map::kBitFieldOffset),
             Immediate(1 << Map::kIsUndetectable));
    final_branch_condition = not_zero;

5396
  } else if (type_name->Equals(heap()->function_string())) {
5397
    STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
5398
    __ JumpIfSmi(input, false_label);
5399 5400 5401 5402
    __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
    __ j(equal, true_label);
    __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
    final_branch_condition = equal;
5403

5404
  } else if (type_name->Equals(heap()->object_string())) {
5405
    __ JumpIfSmi(input, false_label);
5406 5407 5408 5409
    if (!FLAG_harmony_typeof) {
      __ CompareRoot(input, Heap::kNullValueRootIndex);
      __ j(equal, true_label);
    }
5410
    __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
5411
    __ j(below, false_label);
5412 5413
    __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
    __ j(above, false_label);
5414 5415 5416
    // Check for undetectable objects => false.
    __ testb(FieldOperand(input, Map::kBitFieldOffset),
             Immediate(1 << Map::kIsUndetectable));
5417
    final_branch_condition = zero;
5418 5419 5420 5421 5422 5423

  } else {
    __ jmp(false_label);
  }

  return final_branch_condition;
5424 5425 5426
}


5427
void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
5428
  Register temp = ToRegister(instr->temp());
5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441
  int true_block = chunk_->LookupDestination(instr->true_block_id());
  int false_block = chunk_->LookupDestination(instr->false_block_id());

  EmitIsConstructCall(temp);
  EmitBranch(true_block, false_block, equal);
}


void LCodeGen::EmitIsConstructCall(Register temp) {
  // Get the frame pointer for the calling frame.
  __ movq(temp, Operand(rbp, StandardFrameConstants::kCallerFPOffset));

  // Skip the arguments adaptor frame if it exists.
5442
  Label check_frame_marker;
5443 5444
  __ Cmp(Operand(temp, StandardFrameConstants::kContextOffset),
         Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
5445
  __ j(not_equal, &check_frame_marker, Label::kNear);
5446 5447 5448 5449
  __ movq(temp, Operand(rax, StandardFrameConstants::kCallerFPOffset));

  // Check the marker in the calling frame.
  __ bind(&check_frame_marker);
5450 5451
  __ Cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
         Smi::FromInt(StackFrame::CONSTRUCT));
5452 5453 5454
}


5455
void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
5456
  if (info()->IsStub()) return;
5457 5458 5459
  // Ensure that we have enough space after the previous lazy-bailout
  // instruction for patching the code here.
  int current_pc = masm()->pc_offset();
5460 5461
  if (current_pc < last_lazy_deopt_pc_ + space_needed) {
    int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
5462
    __ Nop(padding_size);
5463 5464 5465 5466
  }
}


5467
void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
5468 5469
  EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
  last_lazy_deopt_pc_ = masm()->pc_offset();
5470 5471 5472 5473
  ASSERT(instr->HasEnvironment());
  LEnvironment* env = instr->environment();
  RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
  safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5474 5475 5476 5477 5478 5479 5480 5481
}


void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
  DeoptimizeIf(no_condition, instr->environment());
}


5482 5483 5484 5485 5486
void LCodeGen::DoDummyUse(LDummyUse* instr) {
  // Nothing to see here, move on!
}


5487
void LCodeGen::DoDeleteProperty(LDeleteProperty* instr) {
5488 5489
  LOperand* obj = instr->object();
  LOperand* key = instr->key();
5490 5491
  EmitPushTaggedOperand(obj);
  EmitPushTaggedOperand(key);
5492
  ASSERT(instr->HasPointerMap());
5493 5494 5495 5496 5497
  LPointerMap* pointers = instr->pointer_map();
  RecordPosition(pointers->position());
  // Create safepoint generator that will also ensure enough space in the
  // reloc info for patching in deoptimization (since this is invoking a
  // builtin)
5498 5499
  SafepointGenerator safepoint_generator(
      this, pointers, Safepoint::kLazyDeopt);
5500
  __ Push(Smi::FromInt(strict_mode_flag()));
5501
  __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION, safepoint_generator);
5502 5503 5504
}


5505 5506 5507 5508 5509
void LCodeGen::DoIn(LIn* instr) {
  LOperand* obj = instr->object();
  LOperand* key = instr->key();
  EmitPushTaggedOperand(key);
  EmitPushTaggedOperand(obj);
5510
  ASSERT(instr->HasPointerMap());
5511 5512
  LPointerMap* pointers = instr->pointer_map();
  RecordPosition(pointers->position());
5513 5514
  SafepointGenerator safepoint_generator(
      this, pointers, Safepoint::kLazyDeopt);
5515
  __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION, safepoint_generator);
5516 5517 5518
}


5519
void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5520 5521 5522 5523 5524 5525 5526
  PushSafepointRegistersScope scope(this);
  __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
  __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
  RecordSafepointWithLazyDeopt(instr, RECORD_SAFEPOINT_WITH_REGISTERS, 0);
  ASSERT(instr->HasEnvironment());
  LEnvironment* env = instr->environment();
  safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5527 5528 5529
}


5530
void LCodeGen::DoStackCheck(LStackCheck* instr) {
5531 5532 5533 5534 5535
  class DeferredStackCheck: public LDeferredCode {
   public:
    DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
        : LDeferredCode(codegen), instr_(instr) { }
    virtual void Generate() { codegen()->DoDeferredStackCheck(instr_); }
5536
    virtual LInstruction* instr() { return instr_; }
5537 5538 5539
   private:
    LStackCheck* instr_;
  };
5540

5541 5542
  ASSERT(instr->HasEnvironment());
  LEnvironment* env = instr->environment();
5543 5544 5545 5546 5547 5548 5549 5550
  // There is no LLazyBailout instruction for stack-checks. We have to
  // prepare for lazy deoptimization explicitly here.
  if (instr->hydrogen()->is_function_entry()) {
    // Perform stack overflow check.
    Label done;
    __ CompareRoot(rsp, Heap::kStackLimitRootIndex);
    __ j(above_equal, &done, Label::kNear);
    StackCheckStub stub;
5551
    CallCode(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, instr);
5552 5553 5554 5555 5556 5557 5558 5559 5560
    EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
    last_lazy_deopt_pc_ = masm()->pc_offset();
    __ bind(&done);
    RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
    safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
  } else {
    ASSERT(instr->hydrogen()->is_backwards_branch());
    // Perform stack overflow check if this goto needs it before jumping.
    DeferredStackCheck* deferred_stack_check =
5561
        new(zone()) DeferredStackCheck(this, instr);
5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572
    __ CompareRoot(rsp, Heap::kStackLimitRootIndex);
    __ j(below, deferred_stack_check->entry());
    EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
    last_lazy_deopt_pc_ = masm()->pc_offset();
    __ bind(instr->done_label());
    deferred_stack_check->SetExit(instr->done_label());
    RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
    // Don't record a deoptimization index for the safepoint here.
    // This will be done explicitly when emitting call and the safepoint in
    // the deferred code.
  }
5573 5574 5575
}


5576
void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
5577 5578 5579 5580 5581 5582 5583 5584 5585 5586
  // This is a pseudo-instruction that ensures that the environment here is
  // properly registered for deoptimization and records the assembler's PC
  // offset.
  LEnvironment* environment = instr->environment();
  environment->SetSpilledRegisters(instr->SpilledRegisterArray(),
                                   instr->SpilledDoubleRegisterArray());

  // If the environment were already registered, we would have no way of
  // backpatching it with the spill slot operands.
  ASSERT(!environment->HasBeenRegistered());
5587
  RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
5588 5589
  ASSERT(osr_pc_offset_ == -1);
  osr_pc_offset_ = masm()->pc_offset();
5590 5591
}

5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629

void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
  __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
  DeoptimizeIf(equal, instr->environment());

  Register null_value = rdi;
  __ LoadRoot(null_value, Heap::kNullValueRootIndex);
  __ cmpq(rax, null_value);
  DeoptimizeIf(equal, instr->environment());

  Condition cc = masm()->CheckSmi(rax);
  DeoptimizeIf(cc, instr->environment());

  STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
  __ CmpObjectType(rax, LAST_JS_PROXY_TYPE, rcx);
  DeoptimizeIf(below_equal, instr->environment());

  Label use_cache, call_runtime;
  __ CheckEnumCache(null_value, &call_runtime);

  __ movq(rax, FieldOperand(rax, HeapObject::kMapOffset));
  __ jmp(&use_cache, Label::kNear);

  // Get the set of properties to enumerate.
  __ bind(&call_runtime);
  __ push(rax);
  CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);

  __ CompareRoot(FieldOperand(rax, HeapObject::kMapOffset),
                 Heap::kMetaMapRootIndex);
  DeoptimizeIf(not_equal, instr->environment());
  __ bind(&use_cache);
}


void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
  Register map = ToRegister(instr->map());
  Register result = ToRegister(instr->result());
5630 5631 5632 5633 5634 5635 5636
  Label load_cache, done;
  __ EnumLength(result, map);
  __ Cmp(result, Smi::FromInt(0));
  __ j(not_equal, &load_cache);
  __ LoadRoot(result, Heap::kEmptyFixedArrayRootIndex);
  __ jmp(&done);
  __ bind(&load_cache);
5637 5638
  __ LoadInstanceDescriptors(map, result);
  __ movq(result,
5639
          FieldOperand(result, DescriptorArray::kEnumCacheOffset));
5640 5641
  __ movq(result,
          FieldOperand(result, FixedArray::SizeFor(instr->idx())));
5642
  __ bind(&done);
5643
  Condition cc = masm()->CheckSmi(result);
5644
  DeoptimizeIf(cc, instr->environment());
5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681
}


void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
  Register object = ToRegister(instr->value());
  __ cmpq(ToRegister(instr->map()),
          FieldOperand(object, HeapObject::kMapOffset));
  DeoptimizeIf(not_equal, instr->environment());
}


void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
  Register object = ToRegister(instr->object());
  Register index = ToRegister(instr->index());

  Label out_of_object, done;
  __ SmiToInteger32(index, index);
  __ cmpl(index, Immediate(0));
  __ j(less, &out_of_object);
  __ movq(object, FieldOperand(object,
                               index,
                               times_pointer_size,
                               JSObject::kHeaderSize));
  __ jmp(&done, Label::kNear);

  __ bind(&out_of_object);
  __ movq(object, FieldOperand(object, JSObject::kPropertiesOffset));
  __ negl(index);
  // Index is now equal to out of object property index plus 1.
  __ movq(object, FieldOperand(object,
                               index,
                               times_pointer_size,
                               FixedArray::kHeaderSize - kPointerSize));
  __ bind(&done);
}


5682 5683 5684
#undef __

} }  // namespace v8::internal
5685 5686

#endif  // V8_TARGET_ARCH_X64