full-codegen-x64.cc 93.5 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#if V8_TARGET_ARCH_X64
6

7
#include "src/assembler-inl.h"
8
#include "src/ast/compile-time-value.h"
9
#include "src/ast/scopes.h"
10
#include "src/builtins/builtins-constructor.h"
11
#include "src/code-factory.h"
12 13
#include "src/code-stubs.h"
#include "src/codegen.h"
14 15
#include "src/compilation-info.h"
#include "src/compiler.h"
16
#include "src/debug/debug.h"
17
#include "src/full-codegen/full-codegen.h"
18
#include "src/heap/heap-inl.h"
19
#include "src/ic/ic.h"
20
#include "src/objects-inl.h"
21 22 23 24

namespace v8 {
namespace internal {

25
#define __ ACCESS_MASM(masm())
26 27 28

class JumpPatchSite BASE_EMBEDDED {
 public:
29
  explicit JumpPatchSite(MacroAssembler* masm) : masm_(masm) {
30 31 32 33 34 35
#ifdef DEBUG
    info_emitted_ = false;
#endif
  }

  ~JumpPatchSite() {
36
    DCHECK(patch_site_.is_bound() == info_emitted_);
37 38
  }

39 40 41
  void EmitJumpIfNotSmi(Register reg,
                        Label* target,
                        Label::Distance near_jump = Label::kFar) {
42
    __ testb(reg, Immediate(kSmiTagMask));
43
    EmitJump(not_carry, target, near_jump);   // Always taken before patched.
44 45
  }

46 47 48
  void EmitJumpIfSmi(Register reg,
                     Label* target,
                     Label::Distance near_jump = Label::kFar) {
49
    __ testb(reg, Immediate(kSmiTagMask));
50
    EmitJump(carry, target, near_jump);  // Never taken before patched.
51 52 53
  }

  void EmitPatchInfo() {
54 55
    if (patch_site_.is_bound()) {
      int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(&patch_site_);
56
      DCHECK(is_uint8(delta_to_patch_site));
57
      __ testl(rax, Immediate(delta_to_patch_site));
58
#ifdef DEBUG
59
      info_emitted_ = true;
60
#endif
61 62 63
    } else {
      __ nop();  // Signals no inlined code.
    }
64 65 66 67
  }

 private:
  // jc will be patched with jz, jnc will become jnz.
68
  void EmitJump(Condition cc, Label* target, Label::Distance near_jump) {
69 70
    DCHECK(!patch_site_.is_bound() && !info_emitted_);
    DCHECK(cc == carry || cc == not_carry);
71
    __ bind(&patch_site_);
72
    __ j(cc, target, near_jump);
73 74
  }

75
  MacroAssembler* masm() { return masm_; }
76 77 78 79 80 81 82 83
  MacroAssembler* masm_;
  Label patch_site_;
#ifdef DEBUG
  bool info_emitted_;
#endif
};


84 85 86 87 88 89
// Generate code for a JS function.  On entry to the function the receiver
// and arguments have been pushed on the stack left to right, with the
// return address on top of them.  The actual argument count matches the
// formal parameter count expected by the function.
//
// The live registers are:
90
//   o rdi: the JS function object being called (i.e. ourselves)
91
//   o rdx: the new target value
92 93 94 95 96 97
//   o rsi: our context
//   o rbp: our caller's frame pointer
//   o rsp: stack pointer (pointing to return address)
//
// The function builds a JS frame.  Please see JavaScriptFrameConstants in
// frames-x64.h for its layout.
98 99
void FullCodeGenerator::Generate() {
  CompilationInfo* info = info_;
100
  DCHECK_EQ(scope(), info->scope());
101
  profiling_counter_ = isolate()->factory()->NewCell(
102
      Handle<Smi>(Smi::FromInt(FLAG_interrupt_budget), isolate()));
103
  SetFunctionPosition(literal());
104
  Comment cmnt(masm_, "[ function compiled by full code generator");
105

106 107
  ProfileEntryHookStub::MaybeCallEntryHook(masm_);

108
  if (FLAG_debug_code && info->ExpectsJSReceiverAsReceiver()) {
109
    StackArgumentsAccessor args(rsp, info->scope()->num_parameters());
110
    __ movp(rcx, args.GetReceiverOperand());
111
    __ AssertNotSmi(rcx);
112
    __ CmpObjectType(rcx, FIRST_JS_RECEIVER_TYPE, rcx);
113
    __ Assert(above_equal, kSloppyFunctionExpectsJSReceiverReceiver);
114 115
  }

116 117 118 119 120
  // 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
  // the frame (that is done below).
  FrameScope frame_scope(masm_, StackFrame::MANUAL);

121
  info->set_prologue_offset(masm_->pc_offset());
122
  __ Prologue(info->GeneratePreagedPrologue());
123

124 125 126
  // Increment invocation count for the function.
  {
    Comment cmnt(masm_, "[ Increment invocation count");
127
    __ movp(rcx, FieldOperand(rdi, JSFunction::kFeedbackVectorOffset));
128
    __ movp(rcx, FieldOperand(rcx, Cell::kValueOffset));
129
    __ SmiAddConstant(
130 131
        FieldOperand(rcx, FeedbackVector::kInvocationCountIndex * kPointerSize +
                              FeedbackVector::kHeaderSize),
132 133 134
        Smi::FromInt(1));
  }

135
  { Comment cmnt(masm_, "[ Allocate locals");
136
    int locals_count = info->scope()->num_stack_slots();
137
    OperandStackDepthIncrement(locals_count);
138 139 140
    if (locals_count == 1) {
      __ PushRoot(Heap::kUndefinedValueRootIndex);
    } else if (locals_count > 1) {
141
      if (locals_count >= 128) {
142 143 144 145 146
        Label ok;
        __ movp(rcx, rsp);
        __ subp(rcx, Immediate(locals_count * kPointerSize));
        __ CompareRoot(rcx, Heap::kRealStackLimitRootIndex);
        __ j(above_equal, &ok, Label::kNear);
147
        __ CallRuntime(Runtime::kThrowStackOverflow);
148
        __ bind(&ok);
149
      }
150
      __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
151 152 153
      const int kMaxPushes = 32;
      if (locals_count >= kMaxPushes) {
        int loop_iterations = locals_count / kMaxPushes;
154
        __ movp(rcx, Immediate(loop_iterations));
155 156 157 158
        Label loop_header;
        __ bind(&loop_header);
        // Do pushes.
        for (int i = 0; i < kMaxPushes; i++) {
159
          __ Push(rax);
160 161
        }
        // Continue loop if not done.
162
        __ decp(rcx);
163 164 165 166 167
        __ j(not_zero, &loop_header, Label::kNear);
      }
      int remaining = locals_count % kMaxPushes;
      // Emit the remaining pushes.
      for (int i  = 0; i < remaining; i++) {
168
        __ Push(rax);
169
      }
170
    }
171
  }
172

173
  bool function_in_register = true;
174

175
  // Possibly allocate a local context.
176
  if (info->scope()->NeedsContext()) {
177
    Comment cmnt(masm_, "[ Allocate context");
178
    bool need_write_barrier = true;
179
    int slots = info->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
180
    // Argument to NewContext is the function, which is still in rdi.
181
    if (info->scope()->is_script_scope()) {
182
      __ Push(rdi);
183
      __ Push(info->scope()->scope_info());
184
      __ CallRuntime(Runtime::kNewScriptContext);
185 186
      PrepareForBailoutForId(BailoutId::ScriptContext(),
                             BailoutState::TOS_REGISTER);
187 188
      // The new target value is not used, clobbering is safe.
      DCHECK_NULL(info->scope()->new_target_var());
189
    } else {
190 191 192
      if (info->scope()->new_target_var() != nullptr) {
        __ Push(rdx);  // Preserve new target.
      }
193 194 195 196
      if (slots <=
          ConstructorBuiltinsAssembler::MaximumFunctionContextSlots()) {
        Callable callable = CodeFactory::FastNewFunctionContext(
            isolate(), info->scope()->scope_type());
197
        __ Set(FastNewFunctionContextDescriptor::SlotsRegister(), slots);
198 199
        __ Call(callable.code(), RelocInfo::CODE_TARGET);
        // Result of the FastNewFunctionContext builtin is always in new space.
200 201 202
        need_write_barrier = false;
      } else {
        __ Push(rdi);
203
        __ Push(Smi::FromInt(info->scope()->scope_type()));
204 205
        __ CallRuntime(Runtime::kNewFunctionContext);
      }
206 207 208
      if (info->scope()->new_target_var() != nullptr) {
        __ Pop(rdx);  // Restore new target.
      }
209 210
    }
    function_in_register = false;
211 212 213 214
    // Context is returned in rax.  It replaces the context passed to us.
    // It's saved in the stack and kept live in rsi.
    __ movp(rsi, rax);
    __ movp(Operand(rbp, StandardFrameConstants::kContextOffset), rax);
215 216

    // Copy any necessary parameters into the context.
217
    int num_parameters = info->scope()->num_parameters();
218 219
    int first_parameter = info->scope()->has_this_declaration() ? -1 : 0;
    for (int i = first_parameter; i < num_parameters; i++) {
220 221
      Variable* var =
          (i == -1) ? info->scope()->receiver() : info->scope()->parameter(i);
222
      if (var->IsContextSlot()) {
223 224 225
        int parameter_offset = StandardFrameConstants::kCallerSPOffset +
            (num_parameters - 1 - i) * kPointerSize;
        // Load parameter from stack.
226
        __ movp(rax, Operand(rbp, parameter_offset));
227
        // Store it in the context.
228
        int context_offset = Context::SlotOffset(var->index());
229
        __ movp(Operand(rsi, context_offset), rax);
230
        // Update the write barrier.  This clobbers rax and rbx.
231 232 233 234 235 236 237 238 239
        if (need_write_barrier) {
          __ RecordWriteContextSlot(
              rsi, context_offset, rax, rbx, kDontSaveFPRegs);
        } else if (FLAG_debug_code) {
          Label done;
          __ JumpIfInNewSpace(rsi, rax, &done, Label::kNear);
          __ Abort(kExpectedNewSpaceObject);
          __ bind(&done);
        }
240 241
      }
    }
242
  }
243

244 245 246
  // Register holding this function and new target are both trashed in case we
  // bailout here. But since that can happen only when new target is not used
  // and we allocate a context, the value of |function_in_register| is correct.
247 248
  PrepareForBailoutForId(BailoutId::FunctionContext(),
                         BailoutState::NO_REGISTERS);
249

250 251 252 253
  // We don't support new.target and rest parameters here.
  DCHECK_NULL(info->scope()->new_target_var());
  DCHECK_NULL(info->scope()->rest_parameter());
  DCHECK_NULL(info->scope()->this_function_var());
254

255
  // Possibly allocate an arguments object.
256 257
  DCHECK_EQ(scope(), info->scope());
  Variable* arguments = info->scope()->arguments();
258 259 260 261
  if (arguments != NULL) {
    // Arguments object must be allocated after the context object, in
    // case the "arguments" or ".arguments" variables are in the context.
    Comment cmnt(masm_, "[ Allocate arguments object");
262 263
    if (!function_in_register) {
      __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
264
    }
265
    if (is_strict(language_mode()) || !has_simple_parameters()) {
266 267 268
      __ call(isolate()->builtins()->FastNewStrictArguments(),
              RelocInfo::CODE_TARGET);
      RestoreContext();
269 270 271
    } else if (literal()->has_duplicate_parameters()) {
      __ Push(rdi);
      __ CallRuntime(Runtime::kNewSloppyArguments_Generic);
272
    } else {
273 274 275
      __ call(isolate()->builtins()->FastNewSloppyArguments(),
              RelocInfo::CODE_TARGET);
      RestoreContext();
276
    }
277

278
    SetVar(arguments, rax, rbx, rdx);
279 280
  }

281
  if (FLAG_trace) {
282
    __ CallRuntime(Runtime::kTraceEnter);
283 284
  }

285 286
  // Visit the declarations and body unless there is an illegal
  // redeclaration.
287 288
  PrepareForBailoutForId(BailoutId::FunctionEntry(),
                         BailoutState::NO_REGISTERS);
289 290
  {
    Comment cmnt(masm_, "[ Declarations");
291
    VisitDeclarations(info->scope()->declarations());
292
  }
293

294 295 296 297 298 299 300
  // Assert that the declarations do not use ICs. Otherwise the debugger
  // won't be able to redirect a PC at an IC to the correct IC in newly
  // recompiled code.
  DCHECK_EQ(0, ic_total_count_);

  {
    Comment cmnt(masm_, "[ Stack check");
301 302
    PrepareForBailoutForId(BailoutId::Declarations(),
                           BailoutState::NO_REGISTERS);
303 304 305 306 307 308
    Label ok;
    __ CompareRoot(rsp, Heap::kStackLimitRootIndex);
    __ j(above_equal, &ok, Label::kNear);
    __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
    __ bind(&ok);
  }
309

310 311 312 313 314
  {
    Comment cmnt(masm_, "[ Body");
    DCHECK(loop_depth() == 0);
    VisitStatements(literal()->body());
    DCHECK(loop_depth() == 0);
315 316
  }

317 318
  // Always emit a 'return undefined' in case control fell off the end of
  // the body.
319 320
  { Comment cmnt(masm_, "[ return <undefined>;");
    __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
321
    EmitReturnSequence();
322
  }
323 324 325
}


kmillikin@chromium.org's avatar
kmillikin@chromium.org committed
326
void FullCodeGenerator::ClearAccumulator() {
327
  __ Set(rax, 0);
kmillikin@chromium.org's avatar
kmillikin@chromium.org committed
328 329 330
}


331
void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
332
  __ Move(rbx, profiling_counter_, RelocInfo::EMBEDDED_OBJECT);
333
  __ SmiAddConstant(FieldOperand(rbx, Cell::kValueOffset),
334 335 336 337 338 339
                    Smi::FromInt(-delta));
}


void FullCodeGenerator::EmitProfilingCounterReset() {
  int reset_value = FLAG_interrupt_budget;
340
  __ Move(rbx, profiling_counter_, RelocInfo::EMBEDDED_OBJECT);
341
  __ Move(kScratchRegister, Smi::FromInt(reset_value));
342
  __ movp(FieldOperand(rbx, Cell::kValueOffset), kScratchRegister);
343 344 345
}


346 347 348
static const byte kJnsOffset = kPointerSize == kInt64Size ? 0x1d : 0x14;


349 350 351
void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
                                                Label* back_edge_target) {
  Comment cmnt(masm_, "[ Back edge bookkeeping");
352
  Label ok;
353

354
  DCHECK(back_edge_target->is_bound());
355 356 357
  int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
  int weight = Min(kMaxBackEdgeWeight,
                   Max(1, distance / kCodeSizeMultiplier));
358
  EmitProfilingCounterDecrement(weight);
359

360 361 362 363 364
  __ j(positive, &ok, Label::kNear);
  {
    PredictableCodeSizeScope predictible_code_size_scope(masm_, kJnsOffset);
    DontEmitDebugCodeScope dont_emit_debug_code_scope(masm_);
    __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
365

366 367 368 369
    // Record a mapping of this PC offset to the OSR id.  This is used to find
    // the AST id from the unoptimized code in order to use it as a key into
    // the deoptimization input data found in the optimized code.
    RecordBackEdge(stmt->OsrEntryId());
370

371 372
    EmitProfilingCounterReset();
  }
373
  __ bind(&ok);
374

375
  PrepareForBailoutForId(stmt->EntryId(), BailoutState::NO_REGISTERS);
376 377 378
  // Record a mapping of the OSR id to this PC.  This is used if the OSR
  // entry becomes the target of a bailout.  We don't expect it to be, but
  // we want it to work if it is.
379
  PrepareForBailoutForId(stmt->OsrEntryId(), BailoutState::NO_REGISTERS);
380 381
}

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
void FullCodeGenerator::EmitProfilingCounterHandlingForReturnSequence(
    bool is_tail_call) {
  // Pretend that the exit is a backwards jump to the entry.
  int weight = 1;
  if (info_->ShouldSelfOptimize()) {
    weight = FLAG_interrupt_budget / FLAG_self_opt_count;
  } else {
    int distance = masm_->pc_offset();
    weight = Min(kMaxBackEdgeWeight, Max(1, distance / kCodeSizeMultiplier));
  }
  EmitProfilingCounterDecrement(weight);
  Label ok;
  __ j(positive, &ok, Label::kNear);
  // Don't need to save result register if we are going to do a tail call.
  if (!is_tail_call) {
    __ Push(rax);
  }
  __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);
  if (!is_tail_call) {
    __ Pop(rax);
  }
  EmitProfilingCounterReset();
  __ bind(&ok);
}
406

407
void FullCodeGenerator::EmitReturnSequence() {
408 409 410 411 412 413
  Comment cmnt(masm_, "[ Return sequence");
  if (return_label_.is_bound()) {
    __ jmp(&return_label_);
  } else {
    __ bind(&return_label_);
    if (FLAG_trace) {
414
      __ Push(rax);
415
      __ CallRuntime(Runtime::kTraceExit);
416
    }
417
    EmitProfilingCounterHandlingForReturnSequence(false);
418

419
    SetReturnPosition(literal());
420
    __ leave();
421

422 423
    int arg_count = info_->scope()->num_parameters() + 1;
    int arguments_bytes = arg_count * kPointerSize;
424
    __ Ret(arguments_bytes, rcx);
425 426 427
  }
}

428 429 430
void FullCodeGenerator::RestoreContext() {
  __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
}
431

432
void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
433
  DCHECK(var->IsStackAllocated() || var->IsContextSlot());
434
  MemOperand operand = codegen()->VarOperand(var, result_register());
435
  codegen()->PushOperand(operand);
436 437 438
}


439
void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
440 441 442
}


443 444 445 446
void FullCodeGenerator::AccumulatorValueContext::Plug(
    Heap::RootListIndex index) const {
  __ LoadRoot(result_register(), index);
}
447

448 449 450

void FullCodeGenerator::StackValueContext::Plug(
    Heap::RootListIndex index) const {
451
  codegen()->OperandStackDepthIncrement(1);
452 453 454 455 456
  __ PushRoot(index);
}


void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
457
  codegen()->PrepareForBailoutBeforeSplit(condition(),
458 459 460
                                          true,
                                          true_label_,
                                          false_label_);
461 462 463
  if (index == Heap::kUndefinedValueRootIndex ||
      index == Heap::kNullValueRootIndex ||
      index == Heap::kFalseValueRootIndex) {
464
    if (false_label_ != fall_through_) __ jmp(false_label_);
465
  } else if (index == Heap::kTrueValueRootIndex) {
466
    if (true_label_ != fall_through_) __ jmp(true_label_);
467 468
  } else {
    __ LoadRoot(result_register(), index);
469
    codegen()->DoTest(this);
470 471 472 473
  }
}


474 475
void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
}
476 477


478 479
void FullCodeGenerator::AccumulatorValueContext::Plug(
    Handle<Object> lit) const {
480 481 482 483 484
  if (lit->IsSmi()) {
    __ SafeMove(result_register(), Smi::cast(*lit));
  } else {
    __ Move(result_register(), lit);
  }
485
}
486

487 488

void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
489
  codegen()->OperandStackDepthIncrement(1);
490 491 492 493 494
  if (lit->IsSmi()) {
    __ SafePush(Smi::cast(*lit));
  } else {
    __ Push(lit);
  }
495 496 497 498
}


void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
499
  codegen()->PrepareForBailoutBeforeSplit(condition(),
500 501 502
                                          true,
                                          true_label_,
                                          false_label_);
503 504
  DCHECK(lit->IsNullOrUndefined(isolate()) || !lit->IsUndetectable());
  if (lit->IsNullOrUndefined(isolate()) || lit->IsFalse(isolate())) {
505
    if (false_label_ != fall_through_) __ jmp(false_label_);
506
  } else if (lit->IsTrue(isolate()) || lit->IsJSObject()) {
507
    if (true_label_ != fall_through_) __ jmp(true_label_);
508 509
  } else if (lit->IsString()) {
    if (String::cast(*lit)->length() == 0) {
510
      if (false_label_ != fall_through_) __ jmp(false_label_);
511
    } else {
512
      if (true_label_ != fall_through_) __ jmp(true_label_);
513 514 515
    }
  } else if (lit->IsSmi()) {
    if (Smi::cast(*lit)->value() == 0) {
516
      if (false_label_ != fall_through_) __ jmp(false_label_);
517
    } else {
518
      if (true_label_ != fall_through_) __ jmp(true_label_);
519 520 521 522
    }
  } else {
    // For simplicity we always test the accumulator register.
    __ Move(result_register(), lit);
523
    codegen()->DoTest(this);
524 525 526 527
  }
}


528 529
void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
                                                       Register reg) const {
530
  DCHECK(count > 0);
531
  if (count > 1) codegen()->DropOperands(count - 1);
532
  __ movp(Operand(rsp, 0), reg);
533 534 535
}


536 537
void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
                                            Label* materialize_false) const {
538
  DCHECK(materialize_true == materialize_false);
539 540
  __ bind(materialize_true);
}
541

542 543 544 545

void FullCodeGenerator::AccumulatorValueContext::Plug(
    Label* materialize_true,
    Label* materialize_false) const {
546
  Label done;
547
  __ bind(materialize_true);
548
  __ Move(result_register(), isolate()->factory()->true_value());
549
  __ jmp(&done, Label::kNear);
550
  __ bind(materialize_false);
551
  __ Move(result_register(), isolate()->factory()->false_value());
552
  __ bind(&done);
553 554 555
}


556 557 558
void FullCodeGenerator::StackValueContext::Plug(
    Label* materialize_true,
    Label* materialize_false) const {
559
  codegen()->OperandStackDepthIncrement(1);
560
  Label done;
561
  __ bind(materialize_true);
562
  __ Push(isolate()->factory()->true_value());
563
  __ jmp(&done, Label::kNear);
564
  __ bind(materialize_false);
565
  __ Push(isolate()->factory()->false_value());
566 567 568 569 570 571
  __ bind(&done);
}


void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
                                          Label* materialize_false) const {
572 573
  DCHECK(materialize_true == true_label_);
  DCHECK(materialize_false == false_label_);
574 575 576 577 578 579 580 581 582 583 584
}


void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
  Heap::RootListIndex value_root_index =
      flag ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex;
  __ LoadRoot(result_register(), value_root_index);
}


void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
585
  codegen()->OperandStackDepthIncrement(1);
586 587 588 589 590 591 592
  Heap::RootListIndex value_root_index =
      flag ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex;
  __ PushRoot(value_root_index);
}


void FullCodeGenerator::TestContext::Plug(bool flag) const {
593
  codegen()->PrepareForBailoutBeforeSplit(condition(),
594 595 596
                                          true,
                                          true_label_,
                                          false_label_);
597 598 599 600
  if (flag) {
    if (true_label_ != fall_through_) __ jmp(true_label_);
  } else {
    if (false_label_ != fall_through_) __ jmp(false_label_);
601 602 603 604
  }
}


605 606
void FullCodeGenerator::DoTest(Expression* condition,
                               Label* if_true,
607 608
                               Label* if_false,
                               Label* fall_through) {
609
  Handle<Code> ic = ToBooleanICStub::GetUninitialized(isolate());
610
  CallIC(ic, condition->test_id());
611 612
  __ CompareRoot(result_register(), Heap::kTrueValueRootIndex);
  Split(equal, if_true, if_false, fall_through);
613
}
614 615


616 617 618 619 620 621 622 623 624 625 626
void FullCodeGenerator::Split(Condition cc,
                              Label* if_true,
                              Label* if_false,
                              Label* fall_through) {
  if (if_false == fall_through) {
    __ j(cc, if_true);
  } else if (if_true == fall_through) {
    __ j(NegateCondition(cc), if_false);
  } else {
    __ j(cc, if_true);
    __ jmp(if_false);
627 628 629 630
  }
}


631
MemOperand FullCodeGenerator::StackOperand(Variable* var) {
632
  DCHECK(var->IsStackAllocated());
633 634 635 636
  // Offset is negative because higher indexes are at lower addresses.
  int offset = -var->index() * kPointerSize;
  // Adjust by a (parameter or local) base offset.
  if (var->IsParameter()) {
637 638
    offset += kFPOnStackSize + kPCOnStackSize +
              (info_->scope()->num_parameters() - 1) * kPointerSize;
639 640
  } else {
    offset += JavaScriptFrameConstants::kLocal0Offset;
641
  }
642
  return Operand(rbp, offset);
643 644 645
}


646
MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
647
  DCHECK(var->IsContextSlot() || var->IsStackAllocated());
648 649 650 651 652 653 654
  if (var->IsContextSlot()) {
    int context_chain_length = scope()->ContextChainLength(var->scope());
    __ LoadContext(scratch, context_chain_length);
    return ContextOperand(scratch, var->index());
  } else {
    return StackOperand(var);
  }
655 656 657
}


658
void FullCodeGenerator::GetVar(Register dest, Variable* var) {
659
  DCHECK(var->IsContextSlot() || var->IsStackAllocated());
660
  MemOperand location = VarOperand(var, dest);
661
  __ movp(dest, location);
662 663 664 665 666 667 668
}


void FullCodeGenerator::SetVar(Variable* var,
                               Register src,
                               Register scratch0,
                               Register scratch1) {
669 670 671 672
  DCHECK(var->IsContextSlot() || var->IsStackAllocated());
  DCHECK(!scratch0.is(src));
  DCHECK(!scratch0.is(scratch1));
  DCHECK(!scratch1.is(src));
673
  MemOperand location = VarOperand(var, scratch0);
674
  __ movp(location, src);
675

676
  // Emit the write barrier code if the location is in the heap.
677 678
  if (var->IsContextSlot()) {
    int offset = Context::SlotOffset(var->index());
679
    __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
680 681 682 683
  }
}


684
void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
685 686 687
                                                     bool should_normalize,
                                                     Label* if_true,
                                                     Label* if_false) {
688 689 690
  // Only prepare for bailouts before splits if we're in a test
  // context. Otherwise, we let the Visit function deal with the
  // preparation to avoid preparing with the same AST id twice.
691
  if (!context()->IsTest()) return;
692

693 694
  Label skip;
  if (should_normalize) __ jmp(&skip, Label::kNear);
695
  PrepareForBailout(expr, BailoutState::TOS_REGISTER);
696 697 698 699 700
  if (should_normalize) {
    __ CompareRoot(rax, Heap::kTrueValueRootIndex);
    Split(equal, if_true, if_false, NULL);
    __ bind(&skip);
  }
701 702 703
}


704
void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
705
  // The variable in the declaration always resides in the current context.
706
  DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
707
  if (FLAG_debug_code) {
708
    // Check that we're not inside a with or catch context.
709
    __ movp(rbx, FieldOperand(rsi, HeapObject::kMapOffset));
710
    __ CompareRoot(rbx, Heap::kWithContextMapRootIndex);
711
    __ Check(not_equal, kDeclarationInWithContext);
712
    __ CompareRoot(rbx, Heap::kCatchContextMapRootIndex);
713
    __ Check(not_equal, kDeclarationInCatchContext);
714 715 716 717 718 719 720
  }
}


void FullCodeGenerator::VisitVariableDeclaration(
    VariableDeclaration* declaration) {
  VariableProxy* proxy = declaration->proxy();
721
  Variable* variable = proxy->var();
722
  switch (variable->location()) {
723
    case VariableLocation::UNALLOCATED: {
724
      DCHECK(!variable->binding_needs_init());
725
      globals_->Add(variable->name(), zone());
726
      FeedbackSlot slot = proxy->VariableFeedbackSlot();
727 728
      DCHECK(!slot.IsInvalid());
      globals_->Add(handle(Smi::FromInt(slot.ToInt()), isolate()), zone());
729
      globals_->Add(isolate()->factory()->undefined_value(), zone());
730
      globals_->Add(isolate()->factory()->undefined_value(), zone());
731
      break;
732
    }
733 734
    case VariableLocation::PARAMETER:
    case VariableLocation::LOCAL:
735 736 737 738 739 740 741
      if (variable->binding_needs_init()) {
        Comment cmnt(masm_, "[ VariableDeclaration");
        __ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex);
        __ movp(StackOperand(variable), kScratchRegister);
      }
      break;

742
    case VariableLocation::CONTEXT:
743 744 745 746 747 748 749 750
      if (variable->binding_needs_init()) {
        Comment cmnt(masm_, "[ VariableDeclaration");
        EmitDebugCheckDeclarationContext(variable);
        __ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex);
        __ movp(ContextOperand(rsi, variable->index()), kScratchRegister);
        // No write barrier since the hole value is in old space.
        PrepareForBailoutForId(proxy->id(), BailoutState::NO_REGISTERS);
      }
751
      break;
752

753
    case VariableLocation::LOOKUP:
754 755
    case VariableLocation::MODULE:
      UNREACHABLE();
756 757 758 759
  }
}


760 761 762 763 764
void FullCodeGenerator::VisitFunctionDeclaration(
    FunctionDeclaration* declaration) {
  VariableProxy* proxy = declaration->proxy();
  Variable* variable = proxy->var();
  switch (variable->location()) {
765
    case VariableLocation::UNALLOCATED: {
766
      globals_->Add(variable->name(), zone());
767
      FeedbackSlot slot = proxy->VariableFeedbackSlot();
768 769
      DCHECK(!slot.IsInvalid());
      globals_->Add(handle(Smi::FromInt(slot.ToInt()), isolate()), zone());
770 771 772 773 774 775

      // We need the slot where the literals array lives, too.
      slot = declaration->fun()->LiteralFeedbackSlot();
      DCHECK(!slot.IsInvalid());
      globals_->Add(handle(Smi::FromInt(slot.ToInt()), isolate()), zone());

776 777
      Handle<SharedFunctionInfo> function =
          Compiler::GetSharedFunctionInfo(declaration->fun(), script(), info_);
778 779
      // Check for stack-overflow exception.
      if (function.is_null()) return SetStackOverflow();
780
      globals_->Add(function, zone());
781
      break;
782
    }
783

784 785
    case VariableLocation::PARAMETER:
    case VariableLocation::LOCAL: {
786 787
      Comment cmnt(masm_, "[ FunctionDeclaration");
      VisitForAccumulatorValue(declaration->fun());
788
      __ movp(StackOperand(variable), result_register());
789 790 791
      break;
    }

792
    case VariableLocation::CONTEXT: {
793 794 795
      Comment cmnt(masm_, "[ FunctionDeclaration");
      EmitDebugCheckDeclarationContext(variable);
      VisitForAccumulatorValue(declaration->fun());
796
      __ movp(ContextOperand(rsi, variable->index()), result_register());
797 798 799 800 801 802 803 804 805
      int offset = Context::SlotOffset(variable->index());
      // We know that we have written a function, which is not a smi.
      __ RecordWriteContextSlot(rsi,
                                offset,
                                result_register(),
                                rcx,
                                kDontSaveFPRegs,
                                EMIT_REMEMBERED_SET,
                                OMIT_SMI_CHECK);
806
      PrepareForBailoutForId(proxy->id(), BailoutState::NO_REGISTERS);
807 808 809
      break;
    }

810
    case VariableLocation::LOOKUP:
811 812
    case VariableLocation::MODULE:
      UNREACHABLE();
813 814 815 816
  }
}


817
void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
818 819
  // Call the runtime to declare the globals.
  __ Push(pairs);
820
  __ Push(Smi::FromInt(DeclareGlobalsFlags()));
821
  __ EmitLoadFeedbackVector(rax);
822
  __ Push(rax);
823
  __ CallRuntime(Runtime::kDeclareGlobals);
824 825 826 827
  // Return value is ignored.
}


828
void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
829 830 831
  Comment cmnt(masm_, "[ SwitchStatement");
  Breakable nested_statement(this, stmt);
  SetStatementPosition(stmt);
832

833
  // Keep the switch value on the stack until a case matches.
834
  VisitForStackValue(stmt->tag());
835
  PrepareForBailoutForId(stmt->EntryId(), BailoutState::NO_REGISTERS);
836 837 838 839 840 841 842 843

  ZoneList<CaseClause*>* clauses = stmt->cases();
  CaseClause* default_clause = NULL;  // Can occur anywhere in the list.

  Label next_test;  // Recycled for each test.
  // Compile all the tests with branches to their bodies.
  for (int i = 0; i < clauses->length(); i++) {
    CaseClause* clause = clauses->at(i);
844
    clause->body_target()->Unuse();
845

846 847 848 849 850 851 852 853 854 855 856
    // The default is not a test, but remember it as final fall through.
    if (clause->is_default()) {
      default_clause = clause;
      continue;
    }

    Comment cmnt(masm_, "[ Case comparison");
    __ bind(&next_test);
    next_test.Unuse();

    // Compile the label expression.
857
    VisitForAccumulatorValue(clause->label());
858

859
    // Perform the comparison as if via '==='.
860
    __ movp(rdx, Operand(rsp, 0));  // Switch value.
861
    bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
862
    JumpPatchSite patch_site(masm_);
863
    if (inline_smi_code) {
864
      Label slow_case;
865
      __ movp(rcx, rdx);
866
      __ orp(rcx, rax);
867
      patch_site.EmitJumpIfNotSmi(rcx, &slow_case, Label::kNear);
868

869
      __ cmpp(rdx, rax);
870 871
      __ j(not_equal, &next_test);
      __ Drop(1);  // Switch value is no longer needed.
872
      __ jmp(clause->body_target());
873 874
      __ bind(&slow_case);
    }
875

876
    // Record position before stub call for type feedback.
877
    SetExpressionPosition(clause);
878 879
    Handle<Code> ic =
        CodeFactory::CompareIC(isolate(), Token::EQ_STRICT).code();
880
    CallIC(ic, clause->CompareId());
881
    patch_site.EmitPatchInfo();
882

883 884
    Label skip;
    __ jmp(&skip, Label::kNear);
885
    PrepareForBailout(clause, BailoutState::TOS_REGISTER);
886 887 888 889 890 891
    __ CompareRoot(rax, Heap::kTrueValueRootIndex);
    __ j(not_equal, &next_test);
    __ Drop(1);
    __ jmp(clause->body_target());
    __ bind(&skip);

892
    __ testp(rax, rax);
893 894
    __ j(not_equal, &next_test);
    __ Drop(1);  // Switch value is no longer needed.
895
    __ jmp(clause->body_target());
896 897 898 899 900
  }

  // Discard the test value and jump to the default if present, otherwise to
  // the end of the statement.
  __ bind(&next_test);
901
  DropOperands(1);  // Switch value is no longer needed.
902
  if (default_clause == NULL) {
903
    __ jmp(nested_statement.break_label());
904
  } else {
905
    __ jmp(default_clause->body_target());
906 907 908 909 910 911
  }

  // Compile all the case bodies.
  for (int i = 0; i < clauses->length(); i++) {
    Comment cmnt(masm_, "[ Case body");
    CaseClause* clause = clauses->at(i);
912
    __ bind(clause->body_target());
913
    PrepareForBailoutForId(clause->EntryId(), BailoutState::NO_REGISTERS);
914 915 916
    VisitStatements(clause->statements());
  }

917
  __ bind(nested_statement.break_label());
918
  PrepareForBailoutForId(stmt->ExitId(), BailoutState::NO_REGISTERS);
919 920 921 922
}


void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
923
  Comment cmnt(masm_, "[ ForInStatement");
924 925
  SetStatementPosition(stmt, SKIP_BREAK);

926
  FeedbackSlot slot = stmt->ForInFeedbackSlot();
927

928
  // Get the object to enumerate over.
929
  SetExpressionAsStatementPosition(stmt->enumerable());
930
  VisitForAccumulatorValue(stmt->enumerable());
931 932 933 934 935
  OperandStackDepthIncrement(5);

  Label loop, exit;
  Iteration loop_statement(this, stmt);
  increment_loop_depth();
936

937 938
  // If the object is null or undefined, skip over the loop, otherwise convert
  // it to a JS receiver.  See ECMA-262 version 5, section 12.6.4.
939
  Label convert, done_convert;
940
  __ JumpIfSmi(rax, &convert, Label::kNear);
941
  __ CmpObjectType(rax, FIRST_JS_RECEIVER_TYPE, rcx);
942
  __ j(above_equal, &done_convert, Label::kNear);
943 944 945 946
  __ CompareRoot(rax, Heap::kNullValueRootIndex);
  __ j(equal, &exit);
  __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
  __ j(equal, &exit);
947
  __ bind(&convert);
948
  __ Call(isolate()->builtins()->ToObject(), RelocInfo::CODE_TARGET);
949
  RestoreContext();
950
  __ bind(&done_convert);
951
  PrepareForBailoutForId(stmt->ToObjectId(), BailoutState::TOS_REGISTER);
952
  __ Push(rax);
953

954 955 956 957
  // Check cache validity in generated code. If we cannot guarantee cache
  // validity, call the runtime system to check cache validity or get the
  // property names in a fixed array. Note: Proxies never have an enum cache,
  // so will always take the slow path.
958 959
  Label call_runtime;
  __ CheckEnumCache(&call_runtime);
sgjesse@chromium.org's avatar
sgjesse@chromium.org committed
960 961 962

  // The enum cache is valid.  Load the map of the object being
  // iterated over and use the cache for the iteration.
963
  Label use_cache;
964
  __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));
965
  __ jmp(&use_cache, Label::kNear);
966 967

  // Get the set of properties to enumerate.
sgjesse@chromium.org's avatar
sgjesse@chromium.org committed
968
  __ bind(&call_runtime);
969
  __ Push(rax);  // Duplicate the enumerable object on the stack.
970
  __ CallRuntime(Runtime::kForInEnumerate);
971
  PrepareForBailoutForId(stmt->EnumId(), BailoutState::TOS_REGISTER);
972 973 974 975

  // If we got a map from the runtime call, we can do a fast
  // modification check. Otherwise, we got a fixed array, and we have
  // to do a slow check.
976
  Label fixed_array;
977 978
  __ CompareRoot(FieldOperand(rax, HeapObject::kMapOffset),
                 Heap::kMetaMapRootIndex);
979
  __ j(not_equal, &fixed_array);
980 981

  // We got a map in register rax. Get the enumeration cache from it.
sgjesse@chromium.org's avatar
sgjesse@chromium.org committed
982
  __ bind(&use_cache);
983 984 985 986

  Label no_descriptors;

  __ EnumLength(rdx, rax);
987
  __ Cmp(rdx, Smi::kZero);
988 989
  __ j(equal, &no_descriptors);

990
  __ LoadInstanceDescriptors(rax, rcx);
991 992
  __ movp(rcx, FieldOperand(rcx, DescriptorArray::kEnumCacheOffset));
  __ movp(rcx, FieldOperand(rcx, DescriptorArray::kEnumCacheBridgeCacheOffset));
993

994
  // Set up the four remaining stack slots.
995 996 997
  __ Push(rax);  // Map.
  __ Push(rcx);  // Enumeration cache.
  __ Push(rdx);  // Number of valid entries for the map in the enum cache.
998
  __ Push(Smi::kZero);  // Initial index.
999 1000
  __ jmp(&loop);

1001
  __ bind(&no_descriptors);
1002
  __ addp(rsp, Immediate(kPointerSize));
1003 1004
  __ jmp(&exit);

1005 1006
  // We got a fixed array in register rax. Iterate through that.
  __ bind(&fixed_array);
1007

1008
  __ movp(rcx, Operand(rsp, 0 * kPointerSize));  // Get enumerated object
1009
  __ Push(Smi::FromInt(1));                      // Smi(1) indicates slow check
1010
  __ Push(rax);  // Array
1011
  __ movp(rax, FieldOperand(rax, FixedArray::kLengthOffset));
1012
  __ Push(rax);  // Fixed array length (as smi).
1013
  PrepareForBailoutForId(stmt->PrepareId(), BailoutState::NO_REGISTERS);
1014
  __ Push(Smi::kZero);  // Initial index.
1015 1016 1017

  // Generate code for doing the condition check.
  __ bind(&loop);
1018
  SetExpressionAsStatementPosition(stmt->each());
1019

1020
  __ movp(rax, Operand(rsp, 0 * kPointerSize));  // Get the current index.
1021
  __ cmpp(rax, Operand(rsp, 1 * kPointerSize));  // Compare to the array length.
1022
  __ j(above_equal, loop_statement.break_label());
1023

1024
  // Get the current entry of the array into register rax.
1025
  __ movp(rbx, Operand(rsp, 2 * kPointerSize));
1026
  SmiIndex index = masm()->SmiToIndex(rax, rax, kPointerSizeLog2);
1027 1028
  __ movp(rax,
          FieldOperand(rbx, index.reg, index.scale, FixedArray::kHeaderSize));
1029

1030
  // Get the expected map from the stack or a smi in the
1031
  // permanent slow case into register rdx.
1032
  __ movp(rdx, Operand(rsp, 3 * kPointerSize));
1033 1034

  // Check if the expected map still matches that of the enumerable.
1035
  // If not, we may have to filter the key.
1036
  Label update_each;
1037 1038
  __ movp(rbx, Operand(rsp, 4 * kPointerSize));
  __ cmpp(rdx, FieldOperand(rbx, HeapObject::kMapOffset));
1039
  __ j(equal, &update_each, Label::kNear);
1040

1041 1042
  // We need to filter the key, record slow-path here.
  int const vector_index = SmiFromSlot(slot)->value();
1043
  __ EmitLoadFeedbackVector(rdx);
1044
  __ Move(FieldOperand(rdx, FixedArray::OffsetOfElementAt(vector_index)),
1045
          FeedbackVector::MegamorphicSentinel(isolate()));
1046

1047 1048
  // rax contains the key. The receiver in rbx is the second argument to
  // ForInFilter. ForInFilter returns undefined if the receiver doesn't
1049
  // have the key or returns the name-converted key.
1050
  __ Call(isolate()->builtins()->ForInFilter(), RelocInfo::CODE_TARGET);
1051
  RestoreContext();
1052
  PrepareForBailoutForId(stmt->FilterId(), BailoutState::TOS_REGISTER);
1053 1054
  __ JumpIfRoot(result_register(), Heap::kUndefinedValueRootIndex,
                loop_statement.continue_label());
1055 1056

  // Update the 'each' property or variable from the possibly filtered
1057
  // entry in register rax.
1058 1059
  __ bind(&update_each);
  // Perform the assignment as if via '='.
1060
  { EffectContext context(this);
1061
    EmitAssignment(stmt->each(), stmt->EachFeedbackSlot());
1062
    PrepareForBailoutForId(stmt->AssignmentId(), BailoutState::NO_REGISTERS);
1063
  }
1064

1065
  // Both Crankshaft and Turbofan expect BodyId to be right before stmt->body().
1066
  PrepareForBailoutForId(stmt->BodyId(), BailoutState::NO_REGISTERS);
1067 1068 1069 1070 1071
  // Generate code for the body of the loop.
  Visit(stmt->body());

  // Generate code for going to the next element by incrementing the
  // index (smi) stored on top of the stack.
1072
  __ bind(loop_statement.continue_label());
1073
  PrepareForBailoutForId(stmt->IncrementId(), BailoutState::NO_REGISTERS);
1074 1075
  __ SmiAddConstant(Operand(rsp, 0 * kPointerSize), Smi::FromInt(1));

1076
  EmitBackEdgeBookkeeping(stmt, &loop);
1077
  __ jmp(&loop);
1078

1079
  // Remove the pointers stored on the stack.
1080
  __ bind(loop_statement.break_label());
1081
  DropOperands(5);
1082 1083

  // Exit and decrement the loop depth.
1084
  PrepareForBailoutForId(stmt->ExitId(), BailoutState::NO_REGISTERS);
1085 1086
  __ bind(&exit);
  decrement_loop_depth();
1087 1088
}

1089
void FullCodeGenerator::EmitSetHomeObject(Expression* initializer, int offset,
1090
                                          FeedbackSlot slot) {
1091 1092 1093 1094
  DCHECK(NeedsHomeObject(initializer));
  __ movp(StoreDescriptor::ReceiverRegister(), Operand(rsp, 0));
  __ movp(StoreDescriptor::ValueRegister(),
          Operand(rsp, offset * kPointerSize));
1095
  CallStoreIC(slot, isolate()->factory()->home_object_symbol());
1096 1097
}

1098 1099
void FullCodeGenerator::EmitSetHomeObjectAccumulator(Expression* initializer,
                                                     int offset,
1100
                                                     FeedbackSlot slot) {
1101 1102 1103 1104
  DCHECK(NeedsHomeObject(initializer));
  __ movp(StoreDescriptor::ReceiverRegister(), rax);
  __ movp(StoreDescriptor::ValueRegister(),
          Operand(rsp, offset * kPointerSize));
1105
  CallStoreIC(slot, isolate()->factory()->home_object_symbol());
1106 1107
}

1108
void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy,
1109
                                         TypeofMode typeof_mode) {
1110
  // Record position before possible IC call.
1111
  SetExpressionPosition(proxy);
1112
  PrepareForBailoutForId(proxy->BeforeId(), BailoutState::NO_REGISTERS);
1113 1114
  Variable* var = proxy->var();

1115
  // Two cases: global variable, and all other types of variables.
1116
  switch (var->location()) {
1117
    case VariableLocation::UNALLOCATED: {
1118
      Comment cmnt(masm_, "[ Global variable");
1119
      EmitGlobalVariableLoad(proxy, typeof_mode);
1120 1121 1122
      context()->Plug(rax);
      break;
    }
1123

1124 1125 1126
    case VariableLocation::PARAMETER:
    case VariableLocation::LOCAL:
    case VariableLocation::CONTEXT: {
1127
      DCHECK_EQ(NOT_INSIDE_TYPEOF, typeof_mode);
1128 1129
      Comment cmnt(masm_, var->IsContextSlot() ? "[ Context slot"
                                               : "[ Stack slot");
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
      if (proxy->hole_check_mode() == HoleCheckMode::kRequired) {
        // Throw a reference error when using an uninitialized let/const
        // binding in harmony mode.
        DCHECK(IsLexicalVariableMode(var->mode()));
        Label done;
        GetVar(rax, var);
        __ CompareRoot(rax, Heap::kTheHoleValueRootIndex);
        __ j(not_equal, &done, Label::kNear);
        __ Push(var->name());
        __ CallRuntime(Runtime::kThrowReferenceError);
        __ bind(&done);
        context()->Plug(rax);
        break;
      }
1144
      context()->Plug(var);
1145 1146
      break;
    }
1147

1148
    case VariableLocation::LOOKUP:
1149 1150
    case VariableLocation::MODULE:
      UNREACHABLE();
1151 1152 1153 1154
  }
}


1155 1156
void FullCodeGenerator::EmitAccessor(ObjectLiteralProperty* property) {
  Expression* expression = (property == NULL) ? NULL : property->value();
1157
  if (expression == NULL) {
1158
    OperandStackDepthIncrement(1);
1159 1160 1161
    __ PushRoot(Heap::kNullValueRootIndex);
  } else {
    VisitForStackValue(expression);
1162 1163 1164 1165 1166 1167
    if (NeedsHomeObject(expression)) {
      DCHECK(property->kind() == ObjectLiteral::Property::GETTER ||
             property->kind() == ObjectLiteral::Property::SETTER);
      int offset = property->kind() == ObjectLiteral::Property::GETTER ? 2 : 3;
      EmitSetHomeObject(expression, offset, property->GetSlot());
    }
1168 1169 1170 1171
  }
}


1172
void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1173
  Comment cmnt(masm_, "[ ObjectLiteral");
1174

1175
  Handle<BoilerplateDescription> constant_properties =
1176
      expr->GetOrBuildConstantProperties(isolate());
1177 1178
  int flags = expr->ComputeFlags();
  if (MustCreateObjectLiteralWithRuntime(expr)) {
1179
    __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1180
    __ Push(SmiFromSlot(expr->literal_slot()));
1181 1182
    __ Push(constant_properties);
    __ Push(Smi::FromInt(flags));
1183
    __ CallRuntime(Runtime::kCreateObjectLiteral);
1184
  } else {
1185
    __ movp(rax, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1186
    __ Move(rbx, SmiFromSlot(expr->literal_slot()));
1187 1188
    __ Move(rcx, constant_properties);
    __ Move(rdx, Smi::FromInt(flags));
1189 1190 1191
    Callable callable = CodeFactory::FastCloneShallowObject(
        isolate(), expr->properties_count());
    __ Call(callable.code(), RelocInfo::CODE_TARGET);
1192
    RestoreContext();
1193
  }
1194
  PrepareForBailoutForId(expr->CreateLiteralId(), BailoutState::TOS_REGISTER);
1195

1196 1197
  // If result_saved is true the result is on top of the stack.  If
  // result_saved is false the result is in rax.
1198 1199
  bool result_saved = false;

1200
  AccessorTable accessor_table(zone());
1201 1202 1203
  for (int i = 0; i < expr->properties()->length(); i++) {
    ObjectLiteral::Property* property = expr->properties()->at(i);
    DCHECK(!property->is_computed_name());
1204 1205
    if (property->IsCompileTimeValue()) continue;

arv's avatar
arv committed
1206
    Literal* key = property->key()->AsLiteral();
1207 1208
    Expression* value = property->value();
    if (!result_saved) {
1209
      PushOperand(rax);  // Save result on the stack
1210 1211 1212
      result_saved = true;
    }
    switch (property->kind()) {
1213
      case ObjectLiteral::Property::SPREAD:
1214 1215
      case ObjectLiteral::Property::CONSTANT:
        UNREACHABLE();
1216
      case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1217
        DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
1218
        // Fall through.
1219
      case ObjectLiteral::Property::COMPUTED:
1220 1221
        // It is safe to use [[Put]] here because the boilerplate already
        // contains computed properties with an uninitialized value.
1222 1223
        if (key->IsStringLiteral()) {
          DCHECK(key->IsPropertyName());
1224
          if (property->emit_store()) {
1225
            VisitForAccumulatorValue(value);
1226 1227
            DCHECK(StoreDescriptor::ValueRegister().is(rax));
            __ movp(StoreDescriptor::ReceiverRegister(), Operand(rsp, 0));
1228
            CallStoreIC(property->GetSlot(0), key->value(), true);
1229
            PrepareForBailoutForId(key->id(), BailoutState::NO_REGISTERS);
1230 1231

            if (NeedsHomeObject(value)) {
1232
              EmitSetHomeObjectAccumulator(value, 0, property->GetSlot(1));
1233
            }
1234 1235
          } else {
            VisitForEffect(value);
1236
          }
1237 1238
          break;
        }
1239
        PushOperand(Operand(rsp, 0));  // Duplicate receiver.
1240 1241
        VisitForStackValue(key);
        VisitForStackValue(value);
1242
        if (property->emit_store()) {
1243 1244 1245
          if (NeedsHomeObject(value)) {
            EmitSetHomeObject(value, 2, property->GetSlot());
          }
1246 1247
          PushOperand(Smi::FromInt(SLOPPY));  // Language mode
          CallRuntimeWithOperands(Runtime::kSetProperty);
1248
        } else {
1249
          DropOperands(3);
1250
        }
1251
        break;
1252
      case ObjectLiteral::Property::PROTOTYPE:
1253
        PushOperand(Operand(rsp, 0));  // Duplicate receiver.
1254
        VisitForStackValue(value);
1255
        DCHECK(property->emit_store());
1256
        CallRuntimeWithOperands(Runtime::kInternalSetPrototype);
1257
        PrepareForBailoutForId(expr->GetIdForPropertySet(i),
1258
                               BailoutState::NO_REGISTERS);
1259
        break;
1260
      case ObjectLiteral::Property::GETTER:
1261
        if (property->emit_store()) {
1262
          AccessorTable::Iterator it = accessor_table.lookup(key);
1263
          it->second->bailout_id = expr->GetIdForPropertySet(i);
1264
          it->second->getter = property;
1265
        }
1266 1267
        break;
      case ObjectLiteral::Property::SETTER:
1268
        if (property->emit_store()) {
1269
          AccessorTable::Iterator it = accessor_table.lookup(key);
1270
          it->second->bailout_id = expr->GetIdForPropertySet(i);
1271
          it->second->setter = property;
1272
        }
1273 1274 1275
        break;
    }
  }
1276

1277 1278 1279 1280 1281
  // Emit code to define accessors, using only a single call to the runtime for
  // each pair of corresponding getters and setters.
  for (AccessorTable::Iterator it = accessor_table.begin();
       it != accessor_table.end();
       ++it) {
1282
    PushOperand(Operand(rsp, 0));  // Duplicate receiver.
1283 1284 1285
    VisitForStackValue(it->first);
    EmitAccessor(it->second->getter);
    EmitAccessor(it->second->setter);
1286 1287
    PushOperand(Smi::FromInt(NONE));
    CallRuntimeWithOperands(Runtime::kDefineAccessorPropertyUnchecked);
1288
    PrepareForBailoutForId(it->second->bailout_id, BailoutState::NO_REGISTERS);
1289 1290
  }

1291
  if (result_saved) {
1292
    context()->PlugTOS();
1293
  } else {
1294
    context()->Plug(rax);
1295 1296 1297 1298
  }
}


1299
void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1300
  Comment cmnt(masm_, "[ ArrayLiteral");
1301

1302 1303
  Handle<ConstantElementsPair> constant_elements =
      expr->GetOrBuildConstantElements(isolate());
1304

1305
  if (MustCreateArrayLiteralWithRuntime(expr)) {
1306
    __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1307
    __ Push(SmiFromSlot(expr->literal_slot()));
1308
    __ Push(constant_elements);
1309
    __ Push(Smi::FromInt(expr->ComputeFlags()));
1310
    __ CallRuntime(Runtime::kCreateArrayLiteral);
1311
  } else {
1312
    __ movp(rax, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1313
    __ Move(rbx, SmiFromSlot(expr->literal_slot()));
1314
    __ Move(rcx, constant_elements);
1315
    Callable callable =
1316
        CodeFactory::FastCloneShallowArray(isolate(), TRACK_ALLOCATION_SITE);
1317
    __ Call(callable.code(), RelocInfo::CODE_TARGET);
1318
    RestoreContext();
1319
  }
1320
  PrepareForBailoutForId(expr->CreateLiteralId(), BailoutState::TOS_REGISTER);
1321 1322

  bool result_saved = false;  // Is the result saved to the stack?
1323 1324
  ZoneList<Expression*>* subexprs = expr->values();
  int length = subexprs->length();
1325 1326 1327

  // Emit code to evaluate all the non-constant subexpressions and to store
  // them into the newly cloned array.
1328
  for (int array_index = 0; array_index < length; array_index++) {
arv's avatar
arv committed
1329
    Expression* subexpr = subexprs->at(array_index);
1330
    DCHECK(!subexpr->IsSpread());
arv's avatar
arv committed
1331

1332 1333
    // If the subexpression is a literal or a simple materialized literal it
    // is already set in the cloned array.
1334
    if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1335 1336

    if (!result_saved) {
1337
      PushOperand(rax);  // array literal
1338 1339
      result_saved = true;
    }
1340
    VisitForAccumulatorValue(subexpr);
1341

1342
    __ Move(StoreDescriptor::NameRegister(), Smi::FromInt(array_index));
1343
    __ movp(StoreDescriptor::ReceiverRegister(), Operand(rsp, 0));
1344
    CallKeyedStoreIC(expr->LiteralFeedbackSlot());
1345

1346 1347
    PrepareForBailoutForId(expr->GetIdForElement(array_index),
                           BailoutState::NO_REGISTERS);
arv's avatar
arv committed
1348 1349
  }

1350
  if (result_saved) {
1351
    context()->PlugTOS();
1352
  } else {
1353
    context()->Plug(rax);
1354 1355 1356 1357
  }
}


1358
void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1359
  DCHECK(expr->target()->IsValidReferenceExpressionOrThis());
1360

1361
  Comment cmnt(masm_, "[ Assignment");
1362

1363
  Property* property = expr->target()->AsProperty();
1364
  LhsKind assign_type = Property::GetAssignType(property);
1365 1366 1367 1368 1369 1370 1371 1372

  // Evaluate LHS expression.
  switch (assign_type) {
    case VARIABLE:
      // Nothing to do here.
      break;
    case NAMED_PROPERTY:
      if (expr->is_compound()) {
1373 1374
        // We need the receiver both on the stack and in the register.
        VisitForStackValue(property->obj());
1375
        __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
1376
      } else {
1377
        VisitForStackValue(property->obj());
1378 1379
      }
      break;
1380
    case KEYED_PROPERTY: {
1381
      if (expr->is_compound()) {
1382
        VisitForStackValue(property->obj());
1383
        VisitForStackValue(property->key());
1384 1385
        __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, kPointerSize));
        __ movp(LoadDescriptor::NameRegister(), Operand(rsp, 0));
1386
      } else {
1387 1388
        VisitForStackValue(property->obj());
        VisitForStackValue(property->key());
1389
      }
1390
      break;
1391
    }
1392 1393 1394 1395
    case NAMED_SUPER_PROPERTY:
    case KEYED_SUPER_PROPERTY:
      UNREACHABLE();
      break;
1396 1397
  }

1398 1399
  // For compound assignments we need another deoptimization point after the
  // variable/property load.
1400
  if (expr->is_compound()) {
1401 1402 1403
    { AccumulatorValueContext context(this);
      switch (assign_type) {
        case VARIABLE:
1404
          EmitVariableLoad(expr->target()->AsVariableProxy());
1405
          PrepareForBailout(expr->target(), BailoutState::TOS_REGISTER);
1406 1407 1408
          break;
        case NAMED_PROPERTY:
          EmitNamedPropertyLoad(property);
1409 1410
          PrepareForBailoutForId(property->LoadId(),
                                 BailoutState::TOS_REGISTER);
1411 1412 1413
          break;
        case KEYED_PROPERTY:
          EmitKeyedPropertyLoad(property);
1414 1415
          PrepareForBailoutForId(property->LoadId(),
                                 BailoutState::TOS_REGISTER);
1416
          break;
1417 1418 1419 1420
        case NAMED_SUPER_PROPERTY:
        case KEYED_SUPER_PROPERTY:
          UNREACHABLE();
          break;
1421
      }
1422 1423
    }

1424
    Token::Value op = expr->binary_op();
1425
    PushOperand(rax);  // Left operand goes on the stack.
1426
    VisitForAccumulatorValue(expr->value());
1427

1428
    AccumulatorValueContext context(this);
1429
    if (ShouldInlineSmiCase(op)) {
1430
      EmitInlineSmiBinaryOp(expr->binary_operation(),
1431 1432
                            op,
                            expr->target(),
1433
                            expr->value());
1434
    } else {
1435
      EmitBinaryOp(expr->binary_operation(), op);
1436
    }
1437
    // Deoptimization point in case the binary operation may have side effects.
1438
    PrepareForBailout(expr->binary_operation(), BailoutState::TOS_REGISTER);
1439
  } else {
1440
    VisitForAccumulatorValue(expr->value());
1441 1442
  }

1443
  SetExpressionPosition(expr);
1444 1445 1446

  // Store the value.
  switch (assign_type) {
1447 1448
    case VARIABLE: {
      VariableProxy* proxy = expr->target()->AsVariableProxy();
1449 1450
      EmitVariableAssignment(proxy->var(), expr->op(), expr->AssignmentSlot(),
                             proxy->hole_check_mode());
1451
      PrepareForBailoutForId(expr->AssignmentId(), BailoutState::TOS_REGISTER);
1452
      context()->Plug(rax);
1453
      break;
1454
    }
1455 1456 1457 1458 1459 1460
    case NAMED_PROPERTY:
      EmitNamedPropertyAssignment(expr);
      break;
    case KEYED_PROPERTY:
      EmitKeyedPropertyAssignment(expr);
      break;
1461 1462 1463 1464
    case NAMED_SUPER_PROPERTY:
    case KEYED_SUPER_PROPERTY:
      UNREACHABLE();
      break;
1465 1466 1467 1468
  }
}


1469
void FullCodeGenerator::VisitYield(Yield* expr) {
1470 1471
  // Resumable functions are not supported.
  UNREACHABLE();
1472 1473
}

1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
void FullCodeGenerator::PushOperand(MemOperand operand) {
  OperandStackDepthIncrement(1);
  __ Push(operand);
}

void FullCodeGenerator::EmitOperandStackDepthCheck() {
  if (FLAG_debug_code) {
    int expected_diff = StandardFrameConstants::kFixedFrameSizeFromFp +
                        operand_stack_depth_ * kPointerSize;
    __ movp(rax, rbp);
    __ subp(rax, rsp);
    __ cmpp(rax, Immediate(expected_diff));
    __ Assert(equal, kUnexpectedStackDepth);
  }
}
1489

1490
void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
1491
  Label allocate, done_allocate;
1492

1493 1494
  __ Allocate(JSIteratorResult::kSize, rax, rcx, rdx, &allocate,
              NO_ALLOCATION_FLAGS);
1495
  __ jmp(&done_allocate, Label::kNear);
1496

1497 1498
  __ bind(&allocate);
  __ Push(Smi::FromInt(JSIteratorResult::kSize));
1499
  __ CallRuntime(Runtime::kAllocateInNewSpace);
1500

1501
  __ bind(&done_allocate);
1502
  __ LoadNativeContextSlot(Context::ITERATOR_RESULT_MAP_INDEX, rbx);
1503
  __ movp(FieldOperand(rax, HeapObject::kMapOffset), rbx);
1504 1505 1506 1507 1508 1509 1510
  __ LoadRoot(rbx, Heap::kEmptyFixedArrayRootIndex);
  __ movp(FieldOperand(rax, JSObject::kPropertiesOffset), rbx);
  __ movp(FieldOperand(rax, JSObject::kElementsOffset), rbx);
  __ Pop(FieldOperand(rax, JSIteratorResult::kValueOffset));
  __ LoadRoot(FieldOperand(rax, JSIteratorResult::kDoneOffset),
              done ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex);
  STATIC_ASSERT(JSIteratorResult::kSize == 5 * kPointerSize);
1511
  OperandStackDepthDecrement(1);
1512 1513 1514
}


1515
void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
1516 1517
                                              Token::Value op,
                                              Expression* left,
1518
                                              Expression* right) {
1519 1520 1521
  // Do combined smi check of the operands. Left operand is on the
  // stack (popped into rdx). Right operand is in rax but moved into
  // rcx to make the shifts easier.
1522
  Label done, stub_call, smi_case;
1523
  PopOperand(rdx);
1524
  __ movp(rcx, rax);
1525
  __ orp(rax, rdx);
1526
  JumpPatchSite patch_site(masm_);
1527
  patch_site.EmitJumpIfSmi(rax, &smi_case, Label::kNear);
1528 1529

  __ bind(&stub_call);
1530
  __ movp(rax, rcx);
1531
  Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op).code();
1532
  CallIC(code, expr->BinaryOperationFeedbackId());
1533
  patch_site.EmitPatchInfo();
1534
  __ jmp(&done, Label::kNear);
1535 1536 1537 1538 1539 1540 1541

  __ bind(&smi_case);
  switch (op) {
    case Token::SAR:
      __ SmiShiftArithmeticRight(rax, rdx, rcx);
      break;
    case Token::SHL:
1542
      __ SmiShiftLeft(rax, rdx, rcx, &stub_call);
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
      break;
    case Token::SHR:
      __ SmiShiftLogicalRight(rax, rdx, rcx, &stub_call);
      break;
    case Token::ADD:
      __ SmiAdd(rax, rdx, rcx, &stub_call);
      break;
    case Token::SUB:
      __ SmiSub(rax, rdx, rcx, &stub_call);
      break;
    case Token::MUL:
      __ SmiMul(rax, rdx, rcx, &stub_call);
      break;
    case Token::BIT_OR:
      __ SmiOr(rax, rdx, rcx);
      break;
    case Token::BIT_AND:
      __ SmiAnd(rax, rdx, rcx);
      break;
    case Token::BIT_XOR:
      __ SmiXor(rax, rdx, rcx);
      break;
    default:
      UNREACHABLE();
      break;
  }

  __ bind(&done);
1571
  context()->Plug(rax);
1572 1573 1574
}


1575
void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr, Token::Value op) {
1576
  PopOperand(rdx);
1577
  Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op).code();
1578
  JumpPatchSite patch_site(masm_);    // unbound, signals no inlined smi code.
1579
  CallIC(code, expr->BinaryOperationFeedbackId());
1580
  patch_site.EmitPatchInfo();
1581
  context()->Plug(rax);
1582 1583
}

1584
void FullCodeGenerator::EmitAssignment(Expression* expr, FeedbackSlot slot) {
1585
  DCHECK(expr->IsValidReferenceExpressionOrThis());
1586 1587

  Property* prop = expr->AsProperty();
1588
  LhsKind assign_type = Property::GetAssignType(prop);
1589 1590 1591

  switch (assign_type) {
    case VARIABLE: {
1592
      VariableProxy* proxy = expr->AsVariableProxy();
1593
      EffectContext context(this);
1594 1595
      EmitVariableAssignment(proxy->var(), Token::ASSIGN, slot,
                             proxy->hole_check_mode());
1596 1597 1598
      break;
    }
    case NAMED_PROPERTY: {
1599
      PushOperand(rax);  // Preserve value.
1600
      VisitForAccumulatorValue(prop->obj());
1601
      __ Move(StoreDescriptor::ReceiverRegister(), rax);
1602
      PopOperand(StoreDescriptor::ValueRegister());  // Restore value.
1603
      CallStoreIC(slot, prop->key()->AsLiteral()->value());
1604 1605 1606
      break;
    }
    case KEYED_PROPERTY: {
1607
      PushOperand(rax);  // Preserve value.
1608 1609
      VisitForStackValue(prop->obj());
      VisitForAccumulatorValue(prop->key());
1610
      __ Move(StoreDescriptor::NameRegister(), rax);
1611 1612
      PopOperand(StoreDescriptor::ReceiverRegister());
      PopOperand(StoreDescriptor::ValueRegister());  // Restore value.
1613
      CallKeyedStoreIC(slot);
1614 1615
      break;
    }
1616 1617 1618 1619
    case NAMED_SUPER_PROPERTY:
    case KEYED_SUPER_PROPERTY:
      UNREACHABLE();
      break;
1620
  }
1621
  context()->Plug(rax);
1622 1623 1624
}


1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
    Variable* var, MemOperand location) {
  __ movp(location, rax);
  if (var->IsContextSlot()) {
    __ movp(rdx, rax);
    __ RecordWriteContextSlot(
        rcx, Context::SlotOffset(var->index()), rdx, rbx, kDontSaveFPRegs);
  }
}

1635
void FullCodeGenerator::EmitVariableAssignment(Variable* var, Token::Value op,
1636
                                               FeedbackSlot slot,
1637
                                               HoleCheckMode hole_check_mode) {
1638
  if (var->IsUnallocated()) {
1639
    // Global var, const, or let.
1640
    __ LoadGlobalObject(StoreDescriptor::ReceiverRegister());
1641
    CallStoreIC(slot, var->name());
1642

1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
  } else if (IsLexicalVariableMode(var->mode()) && op != Token::INIT) {
    DCHECK(!var->IsLookupSlot());
    DCHECK(var->IsStackAllocated() || var->IsContextSlot());
    MemOperand location = VarOperand(var, rcx);
    // Perform an initialization check for lexically declared variables.
    if (hole_check_mode == HoleCheckMode::kRequired) {
      Label assign;
      __ movp(rdx, location);
      __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
      __ j(not_equal, &assign, Label::kNear);
      __ Push(var->name());
      __ CallRuntime(Runtime::kThrowReferenceError);
      __ bind(&assign);
    }
    if (var->mode() != CONST) {
      EmitStoreToStackLocalOrContextSlot(var, location);
    } else if (var->throw_on_const_assignment(language_mode())) {
1660
      __ CallRuntime(Runtime::kThrowConstAssignError);
1661
    }
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675

  } else if (var->is_this() && var->mode() == CONST && op == Token::INIT) {
    // Initializing assignment to const {this} needs a write barrier.
    DCHECK(var->IsStackAllocated() || var->IsContextSlot());
    Label uninitialized_this;
    MemOperand location = VarOperand(var, rcx);
    __ movp(rdx, location);
    __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
    __ j(equal, &uninitialized_this);
    __ Push(var->name());
    __ CallRuntime(Runtime::kThrowReferenceError);
    __ bind(&uninitialized_this);
    EmitStoreToStackLocalOrContextSlot(var, location);

1676
  } else {
1677
    DCHECK(var->mode() != CONST || op == Token::INIT);
1678 1679
    DCHECK(var->IsStackAllocated() || var->IsContextSlot());
    DCHECK(!var->IsLookupSlot());
1680 1681
    // Assignment to var or initializing assignment to let/const in harmony
    // mode.
1682
    MemOperand location = VarOperand(var, rcx);
1683 1684 1685 1686 1687 1688
    if (FLAG_debug_code && var->mode() == LET && op == Token::INIT) {
      // Check for an uninitialized let binding.
      __ movp(rdx, location);
      __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
      __ Check(equal, kLetBindingReInitialization);
    }
1689
    EmitStoreToStackLocalOrContextSlot(var, location);
1690
  }
1691 1692 1693
}


1694
void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
1695 1696
  // Assignment to a property, using a named store IC.
  Property* prop = expr->target()->AsProperty();
1697 1698
  DCHECK(prop != NULL);
  DCHECK(prop->key()->IsLiteral());
1699

1700
  PopOperand(StoreDescriptor::ReceiverRegister());
1701
  CallStoreIC(expr->AssignmentSlot(), prop->key()->AsLiteral()->value());
1702

1703
  PrepareForBailoutForId(expr->AssignmentId(), BailoutState::TOS_REGISTER);
1704
  context()->Plug(rax);
1705 1706 1707
}


1708
void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
1709
  // Assignment to a property, using a keyed store IC.
1710 1711
  PopOperand(StoreDescriptor::NameRegister());  // Key.
  PopOperand(StoreDescriptor::ReceiverRegister());
1712
  DCHECK(StoreDescriptor::ValueRegister().is(rax));
1713
  CallKeyedStoreIC(expr->AssignmentSlot());
1714

1715
  PrepareForBailoutForId(expr->AssignmentId(), BailoutState::TOS_REGISTER);
1716
  context()->Plug(rax);
1717 1718
}

verwaest@chromium.org's avatar
verwaest@chromium.org committed
1719
// Code common for calls using the IC.
1720
void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1721 1722
  Expression* callee = expr->expression();

1723
  // Get the target function.
1724
  ConvertReceiverMode convert_mode;
1725
  if (callee->IsVariableProxy()) {
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1726 1727
    { StackValueContext context(this);
      EmitVariableLoad(callee->AsVariableProxy());
1728
      PrepareForBailout(callee, BailoutState::NO_REGISTERS);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1729
    }
1730
    // Push undefined as receiver. This is patched in the Call builtin if it
1731
    // is a sloppy mode method.
1732
    PushOperand(isolate()->factory()->undefined_value());
1733
    convert_mode = ConvertReceiverMode::kNullOrUndefined;
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1734 1735
  } else {
    // Load the function from the receiver.
1736
    DCHECK(callee->IsProperty());
1737
    DCHECK(!callee->AsProperty()->IsSuperAccess());
1738
    __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1739
    EmitNamedPropertyLoad(callee->AsProperty());
1740 1741
    PrepareForBailoutForId(callee->AsProperty()->LoadId(),
                           BailoutState::TOS_REGISTER);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1742
    // Push the target function under the receiver.
1743
    PushOperand(Operand(rsp, 0));
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1744
    __ movp(Operand(rsp, kPointerSize), rax);
1745
    convert_mode = ConvertReceiverMode::kNotNullOrUndefined;
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1746 1747
  }

1748
  EmitCall(expr, convert_mode);
1749 1750 1751
}


verwaest@chromium.org's avatar
verwaest@chromium.org committed
1752
// Common code for calls using the IC.
1753 1754
void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
                                                Expression* key) {
1755 1756 1757
  // Load the key.
  VisitForAccumulatorValue(key);

verwaest@chromium.org's avatar
verwaest@chromium.org committed
1758 1759 1760
  Expression* callee = expr->expression();

  // Load the function from the receiver.
1761
  DCHECK(callee->IsProperty());
1762 1763
  __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
  __ Move(LoadDescriptor::NameRegister(), rax);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1764
  EmitKeyedPropertyLoad(callee->AsProperty());
1765 1766
  PrepareForBailoutForId(callee->AsProperty()->LoadId(),
                         BailoutState::TOS_REGISTER);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1767 1768

  // Push the target function under the receiver.
1769
  PushOperand(Operand(rsp, 0));
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1770 1771
  __ movp(Operand(rsp, kPointerSize), rax);

1772
  EmitCall(expr, ConvertReceiverMode::kNotNullOrUndefined);
1773 1774 1775
}


1776
void FullCodeGenerator::EmitCall(Call* expr, ConvertReceiverMode mode) {
1777
  // Load the arguments.
1778 1779
  ZoneList<Expression*>* args = expr->arguments();
  int arg_count = args->length();
1780 1781
  for (int i = 0; i < arg_count; i++) {
    VisitForStackValue(args->at(i));
1782
  }
1783

1784
  PrepareForBailoutForId(expr->CallId(), BailoutState::NO_REGISTERS);
1785
  SetCallPosition(expr, expr->tail_call_mode());
1786 1787 1788 1789 1790 1791 1792 1793
  if (expr->tail_call_mode() == TailCallMode::kAllow) {
    if (FLAG_trace) {
      __ CallRuntime(Runtime::kTraceTailCall);
    }
    // Update profiling counters before the tail call since we will
    // not return to this function.
    EmitProfilingCounterHandlingForReturnSequence(true);
  }
1794
  Handle<Code> code =
1795 1796
      CodeFactory::CallICTrampoline(isolate(), mode, expr->tail_call_mode())
          .code();
1797
  __ Set(rdx, IntFromSlot(expr->CallFeedbackICSlot()));
1798
  __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
1799
  __ Set(rax, arg_count);
1800
  CallIC(code);
1801
  OperandStackDepthDecrement(arg_count + 1);
1802

1803
  RecordJSReturnSite(expr);
1804
  RestoreContext();
1805
  // Discard the function left on TOS.
1806
  context()->DropAndPlug(1, rax);
1807 1808
}

1809
void FullCodeGenerator::VisitCallNew(CallNew* expr) {
1810 1811 1812 1813 1814
  Comment cmnt(masm_, "[ CallNew");
  // According to ECMA-262, section 11.2.2, page 44, the function
  // expression in new calls must be evaluated before the
  // arguments.

1815 1816 1817
  // Push constructor on the stack.  If it's not a function it's used as
  // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
  // ignored.
1818
  DCHECK(!expr->expression()->IsSuperPropertyReference());
1819
  VisitForStackValue(expr->expression());
1820 1821

  // Push the arguments ("left-to-right") on the stack.
1822
  ZoneList<Expression*>* args = expr->arguments();
1823 1824
  int arg_count = args->length();
  for (int i = 0; i < arg_count; i++) {
1825
    VisitForStackValue(args->at(i));
1826 1827 1828 1829
  }

  // Call the construct call builtin that handles allocation and
  // constructor invocation.
1830
  SetConstructCallPosition(expr);
1831

1832
  // Load function and argument count into rdi and rax.
1833
  __ Set(rax, arg_count);
1834
  __ movp(rdi, Operand(rsp, arg_count * kPointerSize));
1835

1836
  // Record call targets in unoptimized code, but not in the snapshot.
1837
  __ EmitLoadFeedbackVector(rbx);
1838
  __ Move(rdx, SmiFromSlot(expr->CallNewFeedbackSlot()));
1839

1840
  CallConstructStub stub(isolate());
1841
  CallIC(stub.GetCode());
1842
  OperandStackDepthDecrement(arg_count + 1);
1843
  PrepareForBailoutForId(expr->ReturnId(), BailoutState::TOS_REGISTER);
1844
  RestoreContext();
1845
  context()->Plug(rax);
1846 1847
}

1848 1849
void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
1850
  DCHECK(args->length() == 1);
1851

1852
  VisitForAccumulatorValue(args->at(0));
1853 1854 1855 1856

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
1857
  Label* fall_through = NULL;
1858 1859
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);
1860

1861
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
1862 1863 1864
  __ JumpIfSmi(rax, if_true);
  __ jmp(if_false);

1865
  context()->Plug(if_true, if_false);
1866 1867 1868
}


1869
void FullCodeGenerator::EmitIsJSReceiver(CallRuntime* expr) {
1870
  ZoneList<Expression*>* args = expr->arguments();
1871
  DCHECK(args->length() == 1);
1872

1873
  VisitForAccumulatorValue(args->at(0));
1874 1875 1876 1877

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
1878
  Label* fall_through = NULL;
1879 1880
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);
1881 1882

  __ JumpIfSmi(rax, if_false);
1883
  __ CmpObjectType(rax, FIRST_JS_RECEIVER_TYPE, rbx);
1884
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
1885
  Split(above_equal, if_true, if_false, fall_through);
1886

1887
  context()->Plug(if_true, if_false);
1888 1889 1890
}


1891 1892
void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
1893
  DCHECK(args->length() == 1);
1894

1895
  VisitForAccumulatorValue(args->at(0));
1896 1897 1898 1899

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
1900
  Label* fall_through = NULL;
1901 1902
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);
1903 1904 1905

  __ JumpIfSmi(rax, if_false);
  __ CmpObjectType(rax, JS_ARRAY_TYPE, rbx);
1906
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
1907
  Split(equal, if_true, if_false, fall_through);
1908

1909
  context()->Plug(if_true, if_false);
1910 1911 1912
}


1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
void FullCodeGenerator::EmitIsTypedArray(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK(args->length() == 1);

  VisitForAccumulatorValue(args->at(0));

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
                         &if_false, &fall_through);

  __ JumpIfSmi(rax, if_false);
  __ CmpObjectType(rax, JS_TYPED_ARRAY_TYPE, rbx);
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  Split(equal, if_true, if_false, fall_through);

  context()->Plug(if_true, if_false);
}


1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
void FullCodeGenerator::EmitIsJSProxy(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK(args->length() == 1);

  VisitForAccumulatorValue(args->at(0));

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
                         &if_false, &fall_through);

1948

1949
  __ JumpIfSmi(rax, if_false);
1950
  __ CmpObjectType(rax, JS_PROXY_TYPE, rbx);
1951
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
1952
  Split(equal, if_true, if_false, fall_through);
1953 1954 1955 1956

  context()->Plug(if_true, if_false);
}

1957

1958 1959
void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
1960 1961
  DCHECK(args->length() == 1);
  Label done, null, function, non_function_constructor;
1962

1963
  VisitForAccumulatorValue(args->at(0));
1964

1965 1966 1967
  // If the object is not a JSReceiver, we return null.
  __ JumpIfSmi(rax, &null, Label::kNear);
  STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
1968
  __ CmpObjectType(rax, FIRST_JS_RECEIVER_TYPE, rax);
1969
  __ j(below, &null, Label::kNear);
1970

1971 1972 1973 1974
  // Return 'Function' for JSFunction and JSBoundFunction objects.
  __ CmpInstanceType(rax, FIRST_FUNCTION_TYPE);
  STATIC_ASSERT(LAST_FUNCTION_TYPE == LAST_TYPE);
  __ j(above_equal, &function, Label::kNear);
1975 1976

  // Check if the constructor in the map is a JS function.
1977 1978
  __ GetMapConstructor(rax, rax, rbx);
  __ CmpInstanceType(rbx, JS_FUNCTION_TYPE);
1979
  __ j(not_equal, &non_function_constructor, Label::kNear);
1980 1981 1982 1983 1984

  // rax now contains the constructor function. Grab the
  // instance class name from there.
  __ movp(rax, FieldOperand(rax, JSFunction::kSharedFunctionInfoOffset));
  __ movp(rax, FieldOperand(rax, SharedFunctionInfo::kInstanceClassNameOffset));
1985 1986 1987 1988 1989 1990
  __ jmp(&done, Label::kNear);

  // Non-JS objects have class null.
  __ bind(&null);
  __ LoadRoot(rax, Heap::kNullValueRootIndex);
  __ jmp(&done, Label::kNear);
1991 1992 1993

  // Functions have class 'Function'.
  __ bind(&function);
1994 1995
  __ LoadRoot(rax, Heap::kFunction_stringRootIndex);
  __ jmp(&done, Label::kNear);
1996 1997

  // Objects with a non-function constructor have class 'Object'.
1998
  __ bind(&non_function_constructor);
1999
  __ LoadRoot(rax, Heap::kObject_stringRootIndex);
2000 2001 2002 2003

  // All done.
  __ bind(&done);

2004
  context()->Plug(rax);
2005 2006 2007
}


2008 2009
void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
2010
  DCHECK(args->length() == 2);
2011

2012 2013
  VisitForStackValue(args->at(0));
  VisitForAccumulatorValue(args->at(1));
2014 2015 2016 2017 2018

  Register object = rbx;
  Register index = rax;
  Register result = rdx;

2019
  PopOperand(object);
2020 2021 2022 2023

  Label need_conversion;
  Label index_out_of_range;
  Label done;
2024 2025
  StringCharCodeAtGenerator generator(object, index, result, &need_conversion,
                                      &need_conversion, &index_out_of_range);
2026
  generator.GenerateFast(masm_);
2027 2028
  __ jmp(&done);

2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
  __ bind(&index_out_of_range);
  // When the index is out of range, the spec requires us to return
  // NaN.
  __ LoadRoot(result, Heap::kNanValueRootIndex);
  __ jmp(&done);

  __ bind(&need_conversion);
  // Move the undefined value into the result register, which will
  // trigger conversion.
  __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
  __ jmp(&done);

  NopRuntimeCallHelper call_helper;
2042
  generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
2043 2044

  __ bind(&done);
2045
  context()->Plug(result);
2046 2047 2048
}


2049 2050 2051 2052 2053 2054 2055
void FullCodeGenerator::EmitCall(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK_LE(2, args->length());
  // Push target, receiver and arguments onto the stack.
  for (Expression* const arg : *args) {
    VisitForStackValue(arg);
  }
2056
  PrepareForBailoutForId(expr->CallId(), BailoutState::NO_REGISTERS);
2057 2058 2059 2060 2061 2062
  // Move target to rdi.
  int const argc = args->length() - 2;
  __ movp(rdi, Operand(rsp, (argc + 1) * kPointerSize));
  // Call the target.
  __ Set(rax, argc);
  __ Call(isolate()->builtins()->Call(), RelocInfo::CODE_TARGET);
2063
  OperandStackDepthDecrement(argc + 1);
2064
  RestoreContext();
2065 2066 2067 2068
  // Discard the function left on TOS.
  context()->DropAndPlug(1, rax);
}

2069 2070 2071 2072 2073 2074 2075 2076
void FullCodeGenerator::EmitGetSuperConstructor(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK_EQ(1, args->length());
  VisitForAccumulatorValue(args->at(0));
  __ AssertFunction(rax);
  __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));
  __ movp(rax, FieldOperand(rax, Map::kPrototypeOffset));
  context()->Plug(rax);
2077
}
2078

2079
void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
2080
  DCHECK(expr->arguments()->length() == 0);
2081 2082 2083 2084 2085 2086 2087 2088 2089
  ExternalReference debug_is_active =
      ExternalReference::debug_is_active_address(isolate());
  __ Move(kScratchRegister, debug_is_active);
  __ movzxbp(rax, Operand(kScratchRegister, 0));
  __ Integer32ToSmi(rax, rax);
  context()->Plug(rax);
}


2090 2091 2092 2093 2094 2095 2096 2097
void FullCodeGenerator::EmitCreateIterResultObject(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK_EQ(2, args->length());
  VisitForStackValue(args->at(0));
  VisitForStackValue(args->at(1));

  Label runtime, done;

2098 2099
  __ Allocate(JSIteratorResult::kSize, rax, rcx, rdx, &runtime,
              NO_ALLOCATION_FLAGS);
2100
  __ LoadNativeContextSlot(Context::ITERATOR_RESULT_MAP_INDEX, rbx);
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
  __ movp(FieldOperand(rax, HeapObject::kMapOffset), rbx);
  __ LoadRoot(rbx, Heap::kEmptyFixedArrayRootIndex);
  __ movp(FieldOperand(rax, JSObject::kPropertiesOffset), rbx);
  __ movp(FieldOperand(rax, JSObject::kElementsOffset), rbx);
  __ Pop(FieldOperand(rax, JSIteratorResult::kDoneOffset));
  __ Pop(FieldOperand(rax, JSIteratorResult::kValueOffset));
  STATIC_ASSERT(JSIteratorResult::kSize == 5 * kPointerSize);
  __ jmp(&done, Label::kNear);

  __ bind(&runtime);
2111
  CallRuntimeWithOperands(Runtime::kCreateIterResultObject);
2112 2113 2114 2115 2116 2117

  __ bind(&done);
  context()->Plug(rax);
}


2118
void FullCodeGenerator::EmitLoadJSRuntimeFunction(CallRuntime* expr) {
2119 2120 2121 2122 2123
  // Push function.
  __ LoadNativeContextSlot(expr->context_index(), rax);
  PushOperand(rax);

  // Push undefined as receiver.
2124
  OperandStackDepthIncrement(1);
2125
  __ PushRoot(Heap::kUndefinedValueRootIndex);
2126 2127 2128 2129 2130 2131 2132
}


void FullCodeGenerator::EmitCallJSRuntimeFunction(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  int arg_count = args->length();

2133
  SetCallPosition(expr);
2134
  __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
2135
  __ Set(rax, arg_count);
2136 2137
  __ Call(isolate()->builtins()->Call(ConvertReceiverMode::kNullOrUndefined),
          RelocInfo::CODE_TARGET);
2138
  OperandStackDepthDecrement(arg_count + 1);
2139
  RestoreContext();
2140 2141 2142
}


2143
void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
2144
  switch (expr->op()) {
2145 2146
    case Token::DELETE: {
      Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
2147 2148
      Property* property = expr->expression()->AsProperty();
      VariableProxy* proxy = expr->expression()->AsVariableProxy();
2149

2150 2151 2152
      if (property != NULL) {
        VisitForStackValue(property->obj());
        VisitForStackValue(property->key());
2153 2154 2155
        CallRuntimeWithOperands(is_strict(language_mode())
                                    ? Runtime::kDeleteProperty_Strict
                                    : Runtime::kDeleteProperty_Sloppy);
2156
        context()->Plug(rax);
2157 2158
      } else if (proxy != NULL) {
        Variable* var = proxy->var();
2159 2160
        // Delete of an unqualified identifier is disallowed in strict mode but
        // "delete this" is allowed.
2161
        bool is_this = var->is_this();
2162
        DCHECK(is_sloppy(language_mode()) || is_this);
2163
        if (var->IsUnallocated()) {
2164 2165
          __ movp(rax, NativeContextOperand());
          __ Push(ContextOperand(rax, Context::EXTENSION_INDEX));
2166
          __ Push(var->name());
2167
          __ CallRuntime(Runtime::kDeleteProperty_Sloppy);
2168
          context()->Plug(rax);
2169 2170 2171
        } else {
          DCHECK(!var->IsLookupSlot());
          DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2172 2173 2174
          // Result of deleting non-global variables is false.  'this' is
          // not really a variable, though we implement it as one.  The
          // subexpression does not have side effects.
2175
          context()->Plug(is_this);
2176
        }
2177
      } else {
2178 2179 2180 2181
        // Result of deleting non-property, non-variable reference is true.
        // The subexpression may have side effects.
        VisitForEffect(expr->expression());
        context()->Plug(true);
2182 2183 2184 2185
      }
      break;
    }

2186 2187
    case Token::VOID: {
      Comment cmnt(masm_, "[ UnaryOperation (VOID)");
2188
      VisitForEffect(expr->expression());
2189
      context()->Plug(Heap::kUndefinedValueRootIndex);
2190
      break;
2191
    }
2192

2193
    case Token::NOT: {
2194
      Comment cmnt(masm_, "[ UnaryOperation (NOT)");
2195 2196 2197 2198
      if (context()->IsEffect()) {
        // Unary NOT has no side effects so it's only necessary to visit the
        // subexpression.  Match the optimizing compiler by not branching.
        VisitForEffect(expr->expression());
2199 2200 2201 2202 2203 2204 2205 2206
      } else if (context()->IsTest()) {
        const TestContext* test = TestContext::cast(context());
        // The labels are swapped for the recursive call.
        VisitForControl(expr->expression(),
                        test->false_label(),
                        test->true_label(),
                        test->fall_through());
        context()->Plug(test->true_label(), test->false_label());
2207
      } else {
2208 2209 2210 2211
        // We handle value contexts explicitly rather than simply visiting
        // for control and plugging the control flow into the context,
        // because we need to prepare a pair of extra administrative AST ids
        // for the optimizing compiler.
2212
        DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
2213 2214 2215 2216 2217
        Label materialize_true, materialize_false, done;
        VisitForControl(expr->expression(),
                        &materialize_false,
                        &materialize_true,
                        &materialize_true);
2218
        if (!context()->IsAccumulatorValue()) OperandStackDepthIncrement(1);
2219
        __ bind(&materialize_true);
2220 2221
        PrepareForBailoutForId(expr->MaterializeTrueId(),
                               BailoutState::NO_REGISTERS);
2222 2223 2224 2225 2226 2227 2228
        if (context()->IsAccumulatorValue()) {
          __ LoadRoot(rax, Heap::kTrueValueRootIndex);
        } else {
          __ PushRoot(Heap::kTrueValueRootIndex);
        }
        __ jmp(&done, Label::kNear);
        __ bind(&materialize_false);
2229 2230
        PrepareForBailoutForId(expr->MaterializeFalseId(),
                               BailoutState::NO_REGISTERS);
2231 2232 2233 2234 2235 2236
        if (context()->IsAccumulatorValue()) {
          __ LoadRoot(rax, Heap::kFalseValueRootIndex);
        } else {
          __ PushRoot(Heap::kFalseValueRootIndex);
        }
        __ bind(&done);
2237
      }
2238
      break;
2239 2240 2241 2242
    }

    case Token::TYPEOF: {
      Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
2243 2244
      {
        AccumulatorValueContext context(this);
2245 2246
        VisitForTypeofValue(expr->expression());
      }
2247
      __ movp(rbx, rax);
2248
      __ Call(isolate()->builtins()->Typeof(), RelocInfo::CODE_TARGET);
2249
      context()->Plug(rax);
2250
      break;
2251 2252
    }

2253 2254 2255 2256 2257 2258
    default:
      UNREACHABLE();
  }
}


2259
void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
2260
  DCHECK(expr->expression()->IsValidReferenceExpressionOrThis());
2261

2262 2263 2264
  Comment cmnt(masm_, "[ CountOperation");

  Property* prop = expr->expression()->AsProperty();
2265
  LhsKind assign_type = Property::GetAssignType(prop);
2266 2267 2268

  // Evaluate expression and get value.
  if (assign_type == VARIABLE) {
2269
    DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
2270
    AccumulatorValueContext context(this);
2271
    EmitVariableLoad(expr->expression()->AsVariableProxy());
2272
  } else {
2273
    // Reserve space for result of postfix operation.
2274
    if (expr->is_postfix() && !context()->IsEffect()) {
2275
      PushOperand(Smi::kZero);
2276
    }
2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
    switch (assign_type) {
      case NAMED_PROPERTY: {
        VisitForStackValue(prop->obj());
        __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
        EmitNamedPropertyLoad(prop);
        break;
      }

      case KEYED_PROPERTY: {
        VisitForStackValue(prop->obj());
        VisitForStackValue(prop->key());
        // Leave receiver on stack
        __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, kPointerSize));
        // Copy of key, needed for later store.
        __ movp(LoadDescriptor::NameRegister(), Operand(rsp, 0));
        EmitKeyedPropertyLoad(prop);
        break;
      }

2296 2297
      case NAMED_SUPER_PROPERTY:
      case KEYED_SUPER_PROPERTY:
2298 2299
      case VARIABLE:
        UNREACHABLE();
2300 2301 2302
    }
  }

2303 2304
  // We need a second deoptimization point after loading the value
  // in case evaluating the property load my have a side effect.
2305
  if (assign_type == VARIABLE) {
2306
    PrepareForBailout(expr->expression(), BailoutState::TOS_REGISTER);
2307
  } else {
2308
    PrepareForBailoutForId(prop->LoadId(), BailoutState::TOS_REGISTER);
2309
  }
2310

2311 2312 2313
  // Inline smi case if we are in a loop.
  Label done, stub_call;
  JumpPatchSite patch_site(masm_);
2314
  if (ShouldInlineSmiCase(expr->op())) {
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
    Label slow;
    patch_site.EmitJumpIfNotSmi(rax, &slow, Label::kNear);

    // Save result for postfix expressions.
    if (expr->is_postfix()) {
      if (!context()->IsEffect()) {
        // Save the result on the stack. If we have a named or keyed property
        // we store the result under the receiver that is currently on top
        // of the stack.
        switch (assign_type) {
          case VARIABLE:
2326
            __ Push(rax);
2327 2328
            break;
          case NAMED_PROPERTY:
2329
            __ movp(Operand(rsp, kPointerSize), rax);
2330 2331
            break;
          case KEYED_PROPERTY:
2332
            __ movp(Operand(rsp, 2 * kPointerSize), rax);
2333
            break;
2334
          case NAMED_SUPER_PROPERTY:
2335
          case KEYED_SUPER_PROPERTY:
2336
            UNREACHABLE();
2337
            break;
2338 2339 2340 2341
        }
      }
    }

2342 2343 2344
    SmiOperationConstraints constraints =
        SmiOperationConstraint::kPreserveSourceRegister |
        SmiOperationConstraint::kBailoutOnNoOverflow;
2345
    if (expr->op() == Token::INC) {
2346 2347
      __ SmiAddConstant(rax, rax, Smi::FromInt(1), constraints, &done,
                        Label::kNear);
2348
    } else {
2349 2350
      __ SmiSubConstant(rax, rax, Smi::FromInt(1), constraints, &done,
                        Label::kNear);
2351 2352 2353
    }
    __ jmp(&stub_call, Label::kNear);
    __ bind(&slow);
2354
  }
2355 2356

  // Convert old value into a number.
2357
  __ Call(isolate()->builtins()->ToNumber(), RelocInfo::CODE_TARGET);
2358
  RestoreContext();
2359
  PrepareForBailoutForId(expr->ToNumberId(), BailoutState::TOS_REGISTER);
2360 2361 2362

  // Save result for postfix expressions.
  if (expr->is_postfix()) {
2363 2364 2365 2366 2367 2368
    if (!context()->IsEffect()) {
      // Save the result on the stack. If we have a named or keyed property
      // we store the result under the receiver that is currently on top
      // of the stack.
      switch (assign_type) {
        case VARIABLE:
2369
          PushOperand(rax);
2370 2371
          break;
        case NAMED_PROPERTY:
2372
          __ movp(Operand(rsp, kPointerSize), rax);
2373 2374
          break;
        case KEYED_PROPERTY:
2375
          __ movp(Operand(rsp, 2 * kPointerSize), rax);
2376
          break;
2377
        case NAMED_SUPER_PROPERTY:
2378
        case KEYED_SUPER_PROPERTY:
2379
          UNREACHABLE();
2380
          break;
2381
      }
2382 2383 2384
    }
  }

2385
  SetExpressionPosition(expr);
2386

2387
  // Call stub for +1/-1.
2388
  __ bind(&stub_call);
2389
  __ movp(rdx, rax);
2390
  __ Move(rax, Smi::FromInt(1));
2391 2392
  Handle<Code> code =
      CodeFactory::BinaryOpIC(isolate(), expr->binary_op()).code();
2393
  CallIC(code, expr->CountBinOpFeedbackId());
2394
  patch_site.EmitPatchInfo();
2395
  __ bind(&done);
2396

2397 2398
  // Store the value returned in rax.
  switch (assign_type) {
2399 2400
    case VARIABLE: {
      VariableProxy* proxy = expr->expression()->AsVariableProxy();
2401
      if (expr->is_postfix()) {
2402
        // Perform the assignment as if via '='.
2403
        { EffectContext context(this);
2404 2405
          EmitVariableAssignment(proxy->var(), Token::ASSIGN, expr->CountSlot(),
                                 proxy->hole_check_mode());
2406 2407
          PrepareForBailoutForId(expr->AssignmentId(),
                                 BailoutState::TOS_REGISTER);
2408
          context.Plug(rax);
2409
        }
2410 2411
        // For all contexts except kEffect: We have the result on
        // top of the stack.
2412 2413
        if (!context()->IsEffect()) {
          context()->PlugTOS();
2414 2415
        }
      } else {
2416
        // Perform the assignment as if via '='.
2417 2418
        EmitVariableAssignment(proxy->var(), Token::ASSIGN, expr->CountSlot(),
                               proxy->hole_check_mode());
2419 2420
        PrepareForBailoutForId(expr->AssignmentId(),
                               BailoutState::TOS_REGISTER);
2421
        context()->Plug(rax);
2422 2423
      }
      break;
2424
    }
2425
    case NAMED_PROPERTY: {
2426
      PopOperand(StoreDescriptor::ReceiverRegister());
2427
      CallStoreIC(expr->CountSlot(), prop->key()->AsLiteral()->value());
2428
      PrepareForBailoutForId(expr->AssignmentId(), BailoutState::TOS_REGISTER);
2429
      if (expr->is_postfix()) {
2430 2431
        if (!context()->IsEffect()) {
          context()->PlugTOS();
2432 2433
        }
      } else {
2434
        context()->Plug(rax);
2435 2436 2437 2438
      }
      break;
    }
    case KEYED_PROPERTY: {
2439 2440
      PopOperand(StoreDescriptor::NameRegister());
      PopOperand(StoreDescriptor::ReceiverRegister());
2441
      CallKeyedStoreIC(expr->CountSlot());
2442
      PrepareForBailoutForId(expr->AssignmentId(), BailoutState::TOS_REGISTER);
2443
      if (expr->is_postfix()) {
2444 2445
        if (!context()->IsEffect()) {
          context()->PlugTOS();
2446 2447
        }
      } else {
2448
        context()->Plug(rax);
2449 2450 2451
      }
      break;
    }
2452 2453 2454 2455
    case NAMED_SUPER_PROPERTY:
    case KEYED_SUPER_PROPERTY:
      UNREACHABLE();
      break;
2456 2457 2458
  }
}

2459

2460
void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
2461
                                                 Expression* sub_expr,
2462 2463 2464 2465 2466 2467 2468 2469
                                                 Handle<String> check) {
  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

2470
  { AccumulatorValueContext context(this);
2471
    VisitForTypeofValue(sub_expr);
2472
  }
2473
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2474

2475 2476
  Factory* factory = isolate()->factory();
  if (String::Equals(check, factory->number_string())) {
2477
    __ JumpIfSmi(rax, if_true);
2478
    __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));
2479 2480
    __ CompareRoot(rax, Heap::kHeapNumberMapRootIndex);
    Split(equal, if_true, if_false, fall_through);
2481
  } else if (String::Equals(check, factory->string_string())) {
2482 2483
    __ JumpIfSmi(rax, if_false);
    __ CmpObjectType(rax, FIRST_NONSTRING_TYPE, rdx);
2484
    Split(below, if_true, if_false, fall_through);
2485
  } else if (String::Equals(check, factory->symbol_string())) {
2486 2487 2488
    __ JumpIfSmi(rax, if_false);
    __ CmpObjectType(rax, SYMBOL_TYPE, rdx);
    Split(equal, if_true, if_false, fall_through);
2489
  } else if (String::Equals(check, factory->boolean_string())) {
2490 2491 2492 2493
    __ CompareRoot(rax, Heap::kTrueValueRootIndex);
    __ j(equal, if_true);
    __ CompareRoot(rax, Heap::kFalseValueRootIndex);
    Split(equal, if_true, if_false, fall_through);
2494
  } else if (String::Equals(check, factory->undefined_string())) {
2495 2496
    __ CompareRoot(rax, Heap::kNullValueRootIndex);
    __ j(equal, if_false);
2497
    __ JumpIfSmi(rax, if_false);
2498
    // Check for undetectable objects => true.
2499
    __ movp(rdx, FieldOperand(rax, HeapObject::kMapOffset));
2500 2501 2502
    __ testb(FieldOperand(rdx, Map::kBitFieldOffset),
             Immediate(1 << Map::kIsUndetectable));
    Split(not_zero, if_true, if_false, fall_through);
2503
  } else if (String::Equals(check, factory->function_string())) {
2504
    __ JumpIfSmi(rax, if_false);
2505 2506 2507 2508 2509 2510
    // Check for callable and not undetectable objects => true.
    __ movp(rdx, FieldOperand(rax, HeapObject::kMapOffset));
    __ movzxbl(rdx, FieldOperand(rdx, Map::kBitFieldOffset));
    __ andb(rdx,
            Immediate((1 << Map::kIsCallable) | (1 << Map::kIsUndetectable)));
    __ cmpb(rdx, Immediate(1 << Map::kIsCallable));
2511
    Split(equal, if_true, if_false, fall_through);
2512
  } else if (String::Equals(check, factory->object_string())) {
2513
    __ JumpIfSmi(rax, if_false);
2514 2515
    __ CompareRoot(rax, Heap::kNullValueRootIndex);
    __ j(equal, if_true);
2516 2517
    STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
    __ CmpObjectType(rax, FIRST_JS_RECEIVER_TYPE, rdx);
2518
    __ j(below, if_false);
2519
    // Check for callable or undetectable objects => false.
2520
    __ testb(FieldOperand(rdx, Map::kBitFieldOffset),
2521
             Immediate((1 << Map::kIsCallable) | (1 << Map::kIsUndetectable)));
2522
    Split(zero, if_true, if_false, fall_through);
2523 2524
  } else {
    if (if_false != fall_through) __ jmp(if_false);
2525
  }
2526
  context()->Plug(if_true, if_false);
2527
}
2528 2529


2530
void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
2531
  Comment cmnt(masm_, "[ CompareOperation");
2532

2533 2534 2535 2536
  // First we try a fast inlined version of the compare when one of
  // the operands is a literal.
  if (TryLiteralCompare(expr)) return;

2537 2538
  // Always perform the comparison for its control flow.  Pack the result
  // into the expression's context after the comparison is performed.
2539 2540 2541
  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
2542
  Label* fall_through = NULL;
2543 2544
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);
2545

2546
  Token::Value op = expr->op();
2547
  VisitForStackValue(expr->left());
2548
  switch (op) {
2549
    case Token::IN:
2550
      VisitForStackValue(expr->right());
2551
      SetExpressionPosition(expr);
2552
      EmitHasProperty();
2553
      PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
2554
      __ CompareRoot(rax, Heap::kTrueValueRootIndex);
2555
      Split(equal, if_true, if_false, fall_through);
2556 2557 2558
      break;

    case Token::INSTANCEOF: {
2559
      VisitForAccumulatorValue(expr->right());
2560
      SetExpressionPosition(expr);
2561
      PopOperand(rdx);
2562
      __ Call(isolate()->builtins()->InstanceOf(), RelocInfo::CODE_TARGET);
2563
      RestoreContext();
2564 2565 2566
      PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
      __ CompareRoot(rax, Heap::kTrueValueRootIndex);
      Split(equal, if_true, if_false, fall_through);
2567 2568 2569 2570
      break;
    }

    default: {
2571
      VisitForAccumulatorValue(expr->right());
2572
      SetExpressionPosition(expr);
2573
      Condition cc = CompareIC::ComputeCondition(op);
2574
      PopOperand(rdx);
2575

2576
      bool inline_smi_code = ShouldInlineSmiCase(op);
2577
      JumpPatchSite patch_site(masm_);
2578
      if (inline_smi_code) {
2579
        Label slow_case;
2580
        __ movp(rcx, rdx);
2581
        __ orp(rcx, rax);
2582
        patch_site.EmitJumpIfNotSmi(rcx, &slow_case, Label::kNear);
2583
        __ cmpp(rdx, rax);
2584 2585 2586
        Split(cc, if_true, if_false, NULL);
        __ bind(&slow_case);
      }
2587

2588
      Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
2589
      CallIC(ic, expr->CompareOperationFeedbackId());
2590
      patch_site.EmitPatchInfo();
2591

2592
      PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2593
      __ testp(rax, rax);
2594
      Split(cc, if_true, if_false, fall_through);
2595 2596 2597
    }
  }

2598 2599
  // Convert the result of the comparison into one expected for this
  // expression's context.
2600
  context()->Plug(if_true, if_false);
2601 2602 2603
}


2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614
void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
                                              Expression* sub_expr,
                                              NilValue nil) {
  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  VisitForAccumulatorValue(sub_expr);
2615
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2616
  if (expr->op() == Token::EQ_STRICT) {
2617 2618 2619 2620
    Heap::RootListIndex nil_value = nil == kNullValue ?
        Heap::kNullValueRootIndex :
        Heap::kUndefinedValueRootIndex;
    __ CompareRoot(rax, nil_value);
2621
    Split(equal, if_true, if_false, fall_through);
2622
  } else {
2623 2624 2625 2626 2627
    __ JumpIfSmi(rax, if_false);
    __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));
    __ testb(FieldOperand(rax, Map::kBitFieldOffset),
             Immediate(1 << Map::kIsUndetectable));
    Split(not_zero, if_true, if_false, fall_through);
2628
  }
2629
  context()->Plug(if_true, if_false);
2630 2631 2632
}


2633 2634 2635 2636 2637 2638 2639 2640 2641
Register FullCodeGenerator::result_register() {
  return rax;
}


Register FullCodeGenerator::context_register() {
  return rsi;
}

2642 2643 2644 2645
void FullCodeGenerator::LoadFromFrameField(int frame_offset, Register value) {
  DCHECK(IsAligned(frame_offset, kPointerSize));
  __ movp(value, Operand(rbp, frame_offset));
}
2646

2647
void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
2648
  DCHECK(IsAligned(frame_offset, kPointerSize));
2649
  __ movp(Operand(rbp, frame_offset), value);
2650 2651 2652
}


2653
void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
2654
  __ movp(dst, ContextOperand(rsi, context_index));
2655 2656 2657
}


2658
void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
2659
  DeclarationScope* closure_scope = scope()->GetClosureScope();
2660 2661
  if (closure_scope->is_script_scope() ||
      closure_scope->is_module_scope()) {
2662
    // Contexts nested in the native context have a canonical empty function
2663
    // as their closure, not the anonymous closure containing the global
2664
    // code.
2665
    __ movp(rax, NativeContextOperand());
2666
    PushOperand(ContextOperand(rax, Context::CLOSURE_INDEX));
2667
  } else if (closure_scope->is_eval_scope()) {
2668 2669 2670
    // Contexts created by a call to eval have the same closure as the
    // context calling eval, not the anonymous closure containing the eval
    // code.  Fetch it from the context.
2671
    PushOperand(ContextOperand(rsi, Context::CLOSURE_INDEX));
2672
  } else {
2673
    DCHECK(closure_scope->is_function_scope());
2674
    PushOperand(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
2675 2676 2677 2678
  }
}


2679
#undef __
2680

2681 2682 2683 2684

static const byte kJnsInstruction = 0x79;
static const byte kNopByteOne = 0x66;
static const byte kNopByteTwo = 0x90;
2685 2686 2687
#ifdef DEBUG
static const byte kCallInstruction = 0xe8;
#endif
2688 2689 2690


void BackEdgeTable::PatchAt(Code* unoptimized_code,
2691 2692
                            Address pc,
                            BackEdgeState target_state,
2693
                            Code* replacement_code) {
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717
  Address call_target_address = pc - kIntSize;
  Address jns_instr_address = call_target_address - 3;
  Address jns_offset_address = call_target_address - 2;

  switch (target_state) {
    case INTERRUPT:
      //     sub <profiling_counter>, <delta>  ;; Not changed
      //     jns ok
      //     call <interrupt stub>
      //   ok:
      *jns_instr_address = kJnsInstruction;
      *jns_offset_address = kJnsOffset;
      break;
    case ON_STACK_REPLACEMENT:
      //     sub <profiling_counter>, <delta>  ;; Not changed
      //     nop
      //     nop
      //     call <on-stack replacment>
      //   ok:
      *jns_instr_address = kNopByteOne;
      *jns_offset_address = kNopByteTwo;
      break;
  }

2718 2719
  Assembler::set_target_address_at(unoptimized_code->GetIsolate(),
                                   call_target_address, unoptimized_code,
2720 2721 2722 2723 2724 2725 2726 2727 2728
                                   replacement_code->entry());
  unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
      unoptimized_code, call_target_address, replacement_code);
}


BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
    Isolate* isolate,
    Code* unoptimized_code,
2729 2730 2731
    Address pc) {
  Address call_target_address = pc - kIntSize;
  Address jns_instr_address = call_target_address - 3;
2732
  DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
2733 2734

  if (*jns_instr_address == kJnsInstruction) {
2735 2736
    DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
    DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
2737 2738
              Assembler::target_address_at(call_target_address,
                                           unoptimized_code));
2739 2740
    return INTERRUPT;
  }
2741

2742 2743
  DCHECK_EQ(kNopByteOne, *jns_instr_address);
  DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
2744

2745 2746 2747 2748
  DCHECK_EQ(
      isolate->builtins()->OnStackReplacement()->entry(),
      Assembler::target_address_at(call_target_address, unoptimized_code));
  return ON_STACK_REPLACEMENT;
2749 2750
}

2751 2752
}  // namespace internal
}  // namespace v8
2753 2754

#endif  // V8_TARGET_ARCH_X64