full-codegen-x64.cc 122 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/full-codegen/full-codegen.h"
8
#include "src/ast/compile-time-value.h"
9
#include "src/ast/scopes.h"
10
#include "src/code-factory.h"
11 12
#include "src/code-stubs.h"
#include "src/codegen.h"
13 14
#include "src/compilation-info.h"
#include "src/compiler.h"
15
#include "src/debug/debug.h"
16
#include "src/ic/ic.h"
17 18 19 20

namespace v8 {
namespace internal {

21
#define __ ACCESS_MASM(masm())
22 23 24

class JumpPatchSite BASE_EMBEDDED {
 public:
25
  explicit JumpPatchSite(MacroAssembler* masm) : masm_(masm) {
26 27 28 29 30 31
#ifdef DEBUG
    info_emitted_ = false;
#endif
  }

  ~JumpPatchSite() {
32
    DCHECK(patch_site_.is_bound() == info_emitted_);
33 34
  }

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

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

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

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

71
  MacroAssembler* masm() { return masm_; }
72 73 74 75 76 77 78 79
  MacroAssembler* masm_;
  Label patch_site_;
#ifdef DEBUG
  bool info_emitted_;
#endif
};


80 81 82 83 84 85
// 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:
86
//   o rdi: the JS function object being called (i.e. ourselves)
87
//   o rdx: the new target value
88 89 90 91 92 93
//   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.
94 95
void FullCodeGenerator::Generate() {
  CompilationInfo* info = info_;
96
  DCHECK_EQ(scope(), info->scope());
97
  profiling_counter_ = isolate()->factory()->NewCell(
98
      Handle<Smi>(Smi::FromInt(FLAG_interrupt_budget), isolate()));
99
  SetFunctionPosition(literal());
100
  Comment cmnt(masm_, "[ function compiled by full code generator");
101

102 103
  ProfileEntryHookStub::MaybeCallEntryHook(masm_);

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

112 113 114 115 116
  // 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);

117
  info->set_prologue_offset(masm_->pc_offset());
118
  __ Prologue(info->GeneratePreagedPrologue());
119

120 121 122 123 124 125 126 127 128 129 130 131
  // Increment invocation count for the function.
  {
    Comment cmnt(masm_, "[ Increment invocation count");
    __ movp(rcx, FieldOperand(rdi, JSFunction::kLiteralsOffset));
    __ movp(rcx, FieldOperand(rcx, LiteralsArray::kFeedbackVectorOffset));
    __ SmiAddConstant(
        FieldOperand(rcx,
                     TypeFeedbackVector::kInvocationCountIndex * kPointerSize +
                         TypeFeedbackVector::kHeaderSize),
        Smi::FromInt(1));
  }

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

172
  bool function_in_register = true;
173

174
  // Possibly allocate a local context.
175
  if (info->scope()->NeedsContext()) {
176
    Comment cmnt(masm_, "[ Allocate context");
177
    bool need_write_barrier = true;
178
    int slots = info->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
179
    // Argument to NewContext is the function, which is still in rdi.
180
    if (info->scope()->is_script_scope()) {
181
      __ Push(rdi);
182
      __ Push(info->scope()->scope_info());
183
      __ CallRuntime(Runtime::kNewScriptContext);
184 185
      PrepareForBailoutForId(BailoutId::ScriptContext(),
                             BailoutState::TOS_REGISTER);
186 187
      // The new target value is not used, clobbering is safe.
      DCHECK_NULL(info->scope()->new_target_var());
188
    } else {
189 190 191
      if (info->scope()->new_target_var() != nullptr) {
        __ Push(rdx);  // Preserve new target.
      }
192 193 194 195 196
      FastNewFunctionContextStub stub(isolate());
      __ Set(FastNewFunctionContextDescriptor::SlotsRegister(), slots);
      __ CallStub(&stub);
      // Result of FastNewFunctionContextStub is always in new space.
      need_write_barrier = false;
197 198 199
      if (info->scope()->new_target_var() != nullptr) {
        __ Pop(rdx);  // Restore new target.
      }
200 201
    }
    function_in_register = false;
202 203 204 205
    // 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);
206 207

    // Copy any necessary parameters into the context.
208
    int num_parameters = info->scope()->num_parameters();
209 210
    int first_parameter = info->scope()->has_this_declaration() ? -1 : 0;
    for (int i = first_parameter; i < num_parameters; i++) {
211 212
      Variable* var =
          (i == -1) ? info->scope()->receiver() : info->scope()->parameter(i);
213
      if (var->IsContextSlot()) {
214 215 216
        int parameter_offset = StandardFrameConstants::kCallerSPOffset +
            (num_parameters - 1 - i) * kPointerSize;
        // Load parameter from stack.
217
        __ movp(rax, Operand(rbp, parameter_offset));
218
        // Store it in the context.
219
        int context_offset = Context::SlotOffset(var->index());
220
        __ movp(Operand(rsi, context_offset), rax);
221
        // Update the write barrier.  This clobbers rax and rbx.
222 223 224 225 226 227 228 229 230
        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);
        }
231 232
      }
    }
233
  }
234

235 236 237
  // 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.
238 239
  PrepareForBailoutForId(BailoutId::FunctionContext(),
                         BailoutState::NO_REGISTERS);
240

241 242
  // Possibly set up a local binding to the this function which is used in
  // derived constructors with super calls.
243
  Variable* this_function_var = info->scope()->this_function_var();
244 245
  if (this_function_var != nullptr) {
    Comment cmnt(masm_, "[ This function");
246 247
    if (!function_in_register) {
      __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
248
      // The write barrier clobbers register again, keep it marked as such.
249
    }
250
    SetVar(this_function_var, rdi, rbx, rcx);
251 252
  }

253
  // Possibly set up a local binding to the new target value.
254
  Variable* new_target_var = info->scope()->new_target_var();
255 256
  if (new_target_var != nullptr) {
    Comment cmnt(masm_, "[ new.target");
257
    SetVar(new_target_var, rdx, rbx, rcx);
258 259
  }

260
  // Possibly allocate RestParameters
261 262
  Variable* rest_param = info->scope()->rest_parameter();
  if (rest_param != nullptr) {
263
    Comment cmnt(masm_, "[ Allocate rest parameter array");
264 265 266 267
    if (!function_in_register) {
      __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
    }
    FastNewRestParameterStub stub(isolate());
268
    __ CallStub(&stub);
269
    function_in_register = false;
270 271 272
    SetVar(rest_param, rax, rbx, rdx);
  }

273
  // Possibly allocate an arguments object.
274 275
  DCHECK_EQ(scope(), info->scope());
  Variable* arguments = info->scope()->arguments();
276 277 278 279
  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");
280 281
    if (!function_in_register) {
      __ movp(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
282
    }
283 284 285
    if (is_strict(language_mode()) || !has_simple_parameters()) {
      FastNewStrictArgumentsStub stub(isolate());
      __ CallStub(&stub);
286 287 288
    } else if (literal()->has_duplicate_parameters()) {
      __ Push(rdi);
      __ CallRuntime(Runtime::kNewSloppyArguments_Generic);
289
    } else {
290
      FastNewSloppyArgumentsStub stub(isolate());
291 292
      __ CallStub(&stub);
    }
293

294
    SetVar(arguments, rax, rbx, rdx);
295 296
  }

297
  if (FLAG_trace) {
298
    __ CallRuntime(Runtime::kTraceEnter);
299 300
  }

301 302
  // Visit the declarations and body unless there is an illegal
  // redeclaration.
303 304
  PrepareForBailoutForId(BailoutId::FunctionEntry(),
                         BailoutState::NO_REGISTERS);
305 306
  {
    Comment cmnt(masm_, "[ Declarations");
307
    VisitDeclarations(info->scope()->declarations());
308
  }
309

310 311 312 313 314 315 316
  // 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");
317 318
    PrepareForBailoutForId(BailoutId::Declarations(),
                           BailoutState::NO_REGISTERS);
319 320 321 322 323 324
    Label ok;
    __ CompareRoot(rsp, Heap::kStackLimitRootIndex);
    __ j(above_equal, &ok, Label::kNear);
    __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
    __ bind(&ok);
  }
325

326 327 328 329 330
  {
    Comment cmnt(masm_, "[ Body");
    DCHECK(loop_depth() == 0);
    VisitStatements(literal()->body());
    DCHECK(loop_depth() == 0);
331 332
  }

333 334
  // Always emit a 'return undefined' in case control fell off the end of
  // the body.
335 336
  { Comment cmnt(masm_, "[ return <undefined>;");
    __ LoadRoot(rax, Heap::kUndefinedValueRootIndex);
337
    EmitReturnSequence();
338
  }
339 340 341
}


kmillikin@chromium.org's avatar
kmillikin@chromium.org committed
342
void FullCodeGenerator::ClearAccumulator() {
343
  __ Set(rax, 0);
kmillikin@chromium.org's avatar
kmillikin@chromium.org committed
344 345 346
}


347
void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
348
  __ Move(rbx, profiling_counter_, RelocInfo::EMBEDDED_OBJECT);
349
  __ SmiAddConstant(FieldOperand(rbx, Cell::kValueOffset),
350 351 352 353 354 355
                    Smi::FromInt(-delta));
}


void FullCodeGenerator::EmitProfilingCounterReset() {
  int reset_value = FLAG_interrupt_budget;
356
  __ Move(rbx, profiling_counter_, RelocInfo::EMBEDDED_OBJECT);
357
  __ Move(kScratchRegister, Smi::FromInt(reset_value));
358
  __ movp(FieldOperand(rbx, Cell::kValueOffset), kScratchRegister);
359 360 361
}


362 363 364
static const byte kJnsOffset = kPointerSize == kInt64Size ? 0x1d : 0x14;


365 366 367
void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
                                                Label* back_edge_target) {
  Comment cmnt(masm_, "[ Back edge bookkeeping");
368
  Label ok;
369

370
  DCHECK(back_edge_target->is_bound());
371 372 373
  int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
  int weight = Min(kMaxBackEdgeWeight,
                   Max(1, distance / kCodeSizeMultiplier));
374
  EmitProfilingCounterDecrement(weight);
375

376 377 378 379 380
  __ 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);
381

382 383 384 385
    // 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());
386

387 388
    EmitProfilingCounterReset();
  }
389
  __ bind(&ok);
390

391
  PrepareForBailoutForId(stmt->EntryId(), BailoutState::NO_REGISTERS);
392 393 394
  // 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.
395
  PrepareForBailoutForId(stmt->OsrEntryId(), BailoutState::NO_REGISTERS);
396 397
}

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
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);
}
422

423
void FullCodeGenerator::EmitReturnSequence() {
424 425 426 427 428 429
  Comment cmnt(masm_, "[ Return sequence");
  if (return_label_.is_bound()) {
    __ jmp(&return_label_);
  } else {
    __ bind(&return_label_);
    if (FLAG_trace) {
430
      __ Push(rax);
431
      __ CallRuntime(Runtime::kTraceExit);
432
    }
433
    EmitProfilingCounterHandlingForReturnSequence(false);
434

435
    SetReturnPosition(literal());
436
    __ leave();
437

438 439
    int arg_count = info_->scope()->num_parameters() + 1;
    int arguments_bytes = arg_count * kPointerSize;
440
    __ Ret(arguments_bytes, rcx);
441 442 443
  }
}

444 445 446
void FullCodeGenerator::RestoreContext() {
  __ movp(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
}
447

448
void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
449
  DCHECK(var->IsStackAllocated() || var->IsContextSlot());
450
  MemOperand operand = codegen()->VarOperand(var, result_register());
451
  codegen()->PushOperand(operand);
452 453 454
}


455
void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
456 457 458
}


459 460 461 462
void FullCodeGenerator::AccumulatorValueContext::Plug(
    Heap::RootListIndex index) const {
  __ LoadRoot(result_register(), index);
}
463

464 465 466

void FullCodeGenerator::StackValueContext::Plug(
    Heap::RootListIndex index) const {
467
  codegen()->OperandStackDepthIncrement(1);
468 469 470 471 472
  __ PushRoot(index);
}


void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
473
  codegen()->PrepareForBailoutBeforeSplit(condition(),
474 475 476
                                          true,
                                          true_label_,
                                          false_label_);
477 478 479
  if (index == Heap::kUndefinedValueRootIndex ||
      index == Heap::kNullValueRootIndex ||
      index == Heap::kFalseValueRootIndex) {
480
    if (false_label_ != fall_through_) __ jmp(false_label_);
481
  } else if (index == Heap::kTrueValueRootIndex) {
482
    if (true_label_ != fall_through_) __ jmp(true_label_);
483 484
  } else {
    __ LoadRoot(result_register(), index);
485
    codegen()->DoTest(this);
486 487 488 489
  }
}


490 491
void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
}
492 493


494 495
void FullCodeGenerator::AccumulatorValueContext::Plug(
    Handle<Object> lit) const {
496 497 498 499 500
  if (lit->IsSmi()) {
    __ SafeMove(result_register(), Smi::cast(*lit));
  } else {
    __ Move(result_register(), lit);
  }
501
}
502

503 504

void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
505
  codegen()->OperandStackDepthIncrement(1);
506 507 508 509 510
  if (lit->IsSmi()) {
    __ SafePush(Smi::cast(*lit));
  } else {
    __ Push(lit);
  }
511 512 513 514
}


void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
515
  codegen()->PrepareForBailoutBeforeSplit(condition(),
516 517 518
                                          true,
                                          true_label_,
                                          false_label_);
519
  DCHECK(lit->IsNull(isolate()) || lit->IsUndefined(isolate()) ||
520
         !lit->IsUndetectable());
521 522
  if (lit->IsUndefined(isolate()) || lit->IsNull(isolate()) ||
      lit->IsFalse(isolate())) {
523
    if (false_label_ != fall_through_) __ jmp(false_label_);
524
  } else if (lit->IsTrue(isolate()) || lit->IsJSObject()) {
525
    if (true_label_ != fall_through_) __ jmp(true_label_);
526 527
  } else if (lit->IsString()) {
    if (String::cast(*lit)->length() == 0) {
528
      if (false_label_ != fall_through_) __ jmp(false_label_);
529
    } else {
530
      if (true_label_ != fall_through_) __ jmp(true_label_);
531 532 533
    }
  } else if (lit->IsSmi()) {
    if (Smi::cast(*lit)->value() == 0) {
534
      if (false_label_ != fall_through_) __ jmp(false_label_);
535
    } else {
536
      if (true_label_ != fall_through_) __ jmp(true_label_);
537 538 539 540
    }
  } else {
    // For simplicity we always test the accumulator register.
    __ Move(result_register(), lit);
541
    codegen()->DoTest(this);
542 543 544 545
  }
}


546 547
void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
                                                       Register reg) const {
548
  DCHECK(count > 0);
549
  if (count > 1) codegen()->DropOperands(count - 1);
550
  __ movp(Operand(rsp, 0), reg);
551 552 553
}


554 555
void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
                                            Label* materialize_false) const {
556
  DCHECK(materialize_true == materialize_false);
557 558
  __ bind(materialize_true);
}
559

560 561 562 563

void FullCodeGenerator::AccumulatorValueContext::Plug(
    Label* materialize_true,
    Label* materialize_false) const {
564
  Label done;
565
  __ bind(materialize_true);
566
  __ Move(result_register(), isolate()->factory()->true_value());
567
  __ jmp(&done, Label::kNear);
568
  __ bind(materialize_false);
569
  __ Move(result_register(), isolate()->factory()->false_value());
570
  __ bind(&done);
571 572 573
}


574 575 576
void FullCodeGenerator::StackValueContext::Plug(
    Label* materialize_true,
    Label* materialize_false) const {
577
  codegen()->OperandStackDepthIncrement(1);
578
  Label done;
579
  __ bind(materialize_true);
580
  __ Push(isolate()->factory()->true_value());
581
  __ jmp(&done, Label::kNear);
582
  __ bind(materialize_false);
583
  __ Push(isolate()->factory()->false_value());
584 585 586 587 588 589
  __ bind(&done);
}


void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
                                          Label* materialize_false) const {
590 591
  DCHECK(materialize_true == true_label_);
  DCHECK(materialize_false == false_label_);
592 593 594 595 596 597 598 599 600 601 602
}


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 {
603
  codegen()->OperandStackDepthIncrement(1);
604 605 606 607 608 609 610
  Heap::RootListIndex value_root_index =
      flag ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex;
  __ PushRoot(value_root_index);
}


void FullCodeGenerator::TestContext::Plug(bool flag) const {
611
  codegen()->PrepareForBailoutBeforeSplit(condition(),
612 613 614
                                          true,
                                          true_label_,
                                          false_label_);
615 616 617 618
  if (flag) {
    if (true_label_ != fall_through_) __ jmp(true_label_);
  } else {
    if (false_label_ != fall_through_) __ jmp(false_label_);
619 620 621 622
  }
}


623 624
void FullCodeGenerator::DoTest(Expression* condition,
                               Label* if_true,
625 626
                               Label* if_false,
                               Label* fall_through) {
627
  Handle<Code> ic = ToBooleanICStub::GetUninitialized(isolate());
628
  CallIC(ic, condition->test_id());
629 630
  __ CompareRoot(result_register(), Heap::kTrueValueRootIndex);
  Split(equal, if_true, if_false, fall_through);
631
}
632 633


634 635 636 637 638 639 640 641 642 643 644
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);
645 646 647 648
  }
}


649
MemOperand FullCodeGenerator::StackOperand(Variable* var) {
650
  DCHECK(var->IsStackAllocated());
651 652 653 654
  // 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()) {
655 656
    offset += kFPOnStackSize + kPCOnStackSize +
              (info_->scope()->num_parameters() - 1) * kPointerSize;
657 658
  } else {
    offset += JavaScriptFrameConstants::kLocal0Offset;
659
  }
660
  return Operand(rbp, offset);
661 662 663
}


664
MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
665
  DCHECK(var->IsContextSlot() || var->IsStackAllocated());
666 667 668 669 670 671 672
  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);
  }
673 674 675
}


676
void FullCodeGenerator::GetVar(Register dest, Variable* var) {
677
  DCHECK(var->IsContextSlot() || var->IsStackAllocated());
678
  MemOperand location = VarOperand(var, dest);
679
  __ movp(dest, location);
680 681 682 683 684 685 686
}


void FullCodeGenerator::SetVar(Variable* var,
                               Register src,
                               Register scratch0,
                               Register scratch1) {
687 688 689 690
  DCHECK(var->IsContextSlot() || var->IsStackAllocated());
  DCHECK(!scratch0.is(src));
  DCHECK(!scratch0.is(scratch1));
  DCHECK(!scratch1.is(src));
691
  MemOperand location = VarOperand(var, scratch0);
692
  __ movp(location, src);
693

694
  // Emit the write barrier code if the location is in the heap.
695 696
  if (var->IsContextSlot()) {
    int offset = Context::SlotOffset(var->index());
697
    __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
698 699 700 701
  }
}


702
void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
703 704 705
                                                     bool should_normalize,
                                                     Label* if_true,
                                                     Label* if_false) {
706 707 708
  // 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.
709
  if (!context()->IsTest()) return;
710

711 712
  Label skip;
  if (should_normalize) __ jmp(&skip, Label::kNear);
713
  PrepareForBailout(expr, BailoutState::TOS_REGISTER);
714 715 716 717 718
  if (should_normalize) {
    __ CompareRoot(rax, Heap::kTrueValueRootIndex);
    Split(equal, if_true, if_false, NULL);
    __ bind(&skip);
  }
719 720 721
}


722
void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
723
  // The variable in the declaration always resides in the current context.
724
  DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
725
  if (FLAG_debug_code) {
726
    // Check that we're not inside a with or catch context.
727
    __ movp(rbx, FieldOperand(rsi, HeapObject::kMapOffset));
728
    __ CompareRoot(rbx, Heap::kWithContextMapRootIndex);
729
    __ Check(not_equal, kDeclarationInWithContext);
730
    __ CompareRoot(rbx, Heap::kCatchContextMapRootIndex);
731
    __ Check(not_equal, kDeclarationInCatchContext);
732 733 734 735 736 737 738
  }
}


void FullCodeGenerator::VisitVariableDeclaration(
    VariableDeclaration* declaration) {
  VariableProxy* proxy = declaration->proxy();
739
  Variable* variable = proxy->var();
740
  switch (variable->location()) {
741
    case VariableLocation::UNALLOCATED: {
742
      DCHECK(!variable->binding_needs_init());
743 744 745
      FeedbackVectorSlot slot = proxy->VariableFeedbackSlot();
      DCHECK(!slot.IsInvalid());
      globals_->Add(handle(Smi::FromInt(slot.ToInt()), isolate()), zone());
746
      globals_->Add(isolate()->factory()->undefined_value(), zone());
747
      break;
748
    }
749 750
    case VariableLocation::PARAMETER:
    case VariableLocation::LOCAL:
751
      if (variable->binding_needs_init()) {
752
        Comment cmnt(masm_, "[ VariableDeclaration");
753
        __ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex);
754
        __ movp(StackOperand(variable), kScratchRegister);
755
      }
756
      break;
757

758
    case VariableLocation::CONTEXT:
759
      if (variable->binding_needs_init()) {
760 761
        Comment cmnt(masm_, "[ VariableDeclaration");
        EmitDebugCheckDeclarationContext(variable);
762
        __ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex);
763
        __ movp(ContextOperand(rsi, variable->index()), kScratchRegister);
764
        // No write barrier since the hole value is in old space.
765
        PrepareForBailoutForId(proxy->id(), BailoutState::NO_REGISTERS);
766 767
      }
      break;
768

769
    case VariableLocation::LOOKUP: {
770
      Comment cmnt(masm_, "[ VariableDeclaration");
771 772
      DCHECK_EQ(VAR, variable->mode());
      DCHECK(!variable->binding_needs_init());
773 774
      __ Push(variable->name());
      __ CallRuntime(Runtime::kDeclareEvalVar);
775
      PrepareForBailoutForId(proxy->id(), BailoutState::NO_REGISTERS);
776
      break;
777
    }
778 779 780

    case VariableLocation::MODULE:
      UNREACHABLE();
781 782 783 784
  }
}


785 786 787 788 789
void FullCodeGenerator::VisitFunctionDeclaration(
    FunctionDeclaration* declaration) {
  VariableProxy* proxy = declaration->proxy();
  Variable* variable = proxy->var();
  switch (variable->location()) {
790
    case VariableLocation::UNALLOCATED: {
791 792 793
      FeedbackVectorSlot slot = proxy->VariableFeedbackSlot();
      DCHECK(!slot.IsInvalid());
      globals_->Add(handle(Smi::FromInt(slot.ToInt()), isolate()), zone());
794
      Handle<SharedFunctionInfo> function =
795
          Compiler::GetSharedFunctionInfo(declaration->fun(), script(), info_);
796 797
      // Check for stack-overflow exception.
      if (function.is_null()) return SetStackOverflow();
798
      globals_->Add(function, zone());
799
      break;
800
    }
801

802 803
    case VariableLocation::PARAMETER:
    case VariableLocation::LOCAL: {
804 805
      Comment cmnt(masm_, "[ FunctionDeclaration");
      VisitForAccumulatorValue(declaration->fun());
806
      __ movp(StackOperand(variable), result_register());
807 808 809
      break;
    }

810
    case VariableLocation::CONTEXT: {
811 812 813
      Comment cmnt(masm_, "[ FunctionDeclaration");
      EmitDebugCheckDeclarationContext(variable);
      VisitForAccumulatorValue(declaration->fun());
814
      __ movp(ContextOperand(rsi, variable->index()), result_register());
815 816 817 818 819 820 821 822 823
      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);
824
      PrepareForBailoutForId(proxy->id(), BailoutState::NO_REGISTERS);
825 826 827
      break;
    }

828
    case VariableLocation::LOOKUP: {
829
      Comment cmnt(masm_, "[ FunctionDeclaration");
830
      PushOperand(variable->name());
831
      VisitForStackValue(declaration->fun());
832
      CallRuntimeWithOperands(Runtime::kDeclareEvalFunction);
833
      PrepareForBailoutForId(proxy->id(), BailoutState::NO_REGISTERS);
834 835
      break;
    }
836 837 838

    case VariableLocation::MODULE:
      UNREACHABLE();
839 840 841 842
  }
}


843
void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
844 845
  // Call the runtime to declare the globals.
  __ Push(pairs);
846
  __ Push(Smi::FromInt(DeclareGlobalsFlags()));
847 848
  __ EmitLoadTypeFeedbackVector(rax);
  __ Push(rax);
849
  __ CallRuntime(Runtime::kDeclareGlobals);
850 851 852 853
  // Return value is ignored.
}


854
void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
855 856 857
  Comment cmnt(masm_, "[ SwitchStatement");
  Breakable nested_statement(this, stmt);
  SetStatementPosition(stmt);
858

859
  // Keep the switch value on the stack until a case matches.
860
  VisitForStackValue(stmt->tag());
861
  PrepareForBailoutForId(stmt->EntryId(), BailoutState::NO_REGISTERS);
862 863 864 865 866 867 868 869

  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);
870
    clause->body_target()->Unuse();
871

872 873 874 875 876 877 878 879 880 881 882
    // 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.
883
    VisitForAccumulatorValue(clause->label());
884

885
    // Perform the comparison as if via '==='.
886
    __ movp(rdx, Operand(rsp, 0));  // Switch value.
887
    bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
888
    JumpPatchSite patch_site(masm_);
889
    if (inline_smi_code) {
890
      Label slow_case;
891
      __ movp(rcx, rdx);
892
      __ orp(rcx, rax);
893
      patch_site.EmitJumpIfNotSmi(rcx, &slow_case, Label::kNear);
894

895
      __ cmpp(rdx, rax);
896 897
      __ j(not_equal, &next_test);
      __ Drop(1);  // Switch value is no longer needed.
898
      __ jmp(clause->body_target());
899 900
      __ bind(&slow_case);
    }
901

902
    // Record position before stub call for type feedback.
903
    SetExpressionPosition(clause);
904 905
    Handle<Code> ic =
        CodeFactory::CompareIC(isolate(), Token::EQ_STRICT).code();
906
    CallIC(ic, clause->CompareId());
907
    patch_site.EmitPatchInfo();
908

909 910
    Label skip;
    __ jmp(&skip, Label::kNear);
911
    PrepareForBailout(clause, BailoutState::TOS_REGISTER);
912 913 914 915 916 917
    __ CompareRoot(rax, Heap::kTrueValueRootIndex);
    __ j(not_equal, &next_test);
    __ Drop(1);
    __ jmp(clause->body_target());
    __ bind(&skip);

918
    __ testp(rax, rax);
919 920
    __ j(not_equal, &next_test);
    __ Drop(1);  // Switch value is no longer needed.
921
    __ jmp(clause->body_target());
922 923 924 925 926
  }

  // Discard the test value and jump to the default if present, otherwise to
  // the end of the statement.
  __ bind(&next_test);
927
  DropOperands(1);  // Switch value is no longer needed.
928
  if (default_clause == NULL) {
929
    __ jmp(nested_statement.break_label());
930
  } else {
931
    __ jmp(default_clause->body_target());
932 933 934 935 936 937
  }

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

943
  __ bind(nested_statement.break_label());
944
  PrepareForBailoutForId(stmt->ExitId(), BailoutState::NO_REGISTERS);
945 946 947 948
}


void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
949
  Comment cmnt(masm_, "[ ForInStatement");
950 951
  SetStatementPosition(stmt, SKIP_BREAK);

952
  FeedbackVectorSlot slot = stmt->ForInFeedbackSlot();
953

954
  // Get the object to enumerate over.
955
  SetExpressionAsStatementPosition(stmt->enumerable());
956
  VisitForAccumulatorValue(stmt->enumerable());
957 958 959 960 961
  OperandStackDepthIncrement(5);

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

963 964
  // 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.
965
  Label convert, done_convert;
966
  __ JumpIfSmi(rax, &convert, Label::kNear);
967
  __ CmpObjectType(rax, FIRST_JS_RECEIVER_TYPE, rcx);
968
  __ j(above_equal, &done_convert, Label::kNear);
969 970 971 972
  __ CompareRoot(rax, Heap::kNullValueRootIndex);
  __ j(equal, &exit);
  __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
  __ j(equal, &exit);
973
  __ bind(&convert);
974 975
  ToObjectStub stub(isolate());
  __ CallStub(&stub);
976
  RestoreContext();
977
  __ bind(&done_convert);
978
  PrepareForBailoutForId(stmt->ToObjectId(), BailoutState::TOS_REGISTER);
979
  __ Push(rax);
980

981 982 983 984
  // 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.
985 986
  Label call_runtime;
  __ CheckEnumCache(&call_runtime);
sgjesse@chromium.org's avatar
sgjesse@chromium.org committed
987 988 989

  // The enum cache is valid.  Load the map of the object being
  // iterated over and use the cache for the iteration.
990
  Label use_cache;
991
  __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));
992
  __ jmp(&use_cache, Label::kNear);
993 994

  // Get the set of properties to enumerate.
sgjesse@chromium.org's avatar
sgjesse@chromium.org committed
995
  __ bind(&call_runtime);
996
  __ Push(rax);  // Duplicate the enumerable object on the stack.
997
  __ CallRuntime(Runtime::kForInEnumerate);
998
  PrepareForBailoutForId(stmt->EnumId(), BailoutState::TOS_REGISTER);
999 1000 1001 1002

  // 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.
1003
  Label fixed_array;
1004 1005
  __ CompareRoot(FieldOperand(rax, HeapObject::kMapOffset),
                 Heap::kMetaMapRootIndex);
1006
  __ j(not_equal, &fixed_array);
1007 1008

  // We got a map in register rax. Get the enumeration cache from it.
sgjesse@chromium.org's avatar
sgjesse@chromium.org committed
1009
  __ bind(&use_cache);
1010 1011 1012 1013 1014 1015 1016

  Label no_descriptors;

  __ EnumLength(rdx, rax);
  __ Cmp(rdx, Smi::FromInt(0));
  __ j(equal, &no_descriptors);

1017
  __ LoadInstanceDescriptors(rax, rcx);
1018 1019
  __ movp(rcx, FieldOperand(rcx, DescriptorArray::kEnumCacheOffset));
  __ movp(rcx, FieldOperand(rcx, DescriptorArray::kEnumCacheBridgeCacheOffset));
1020

1021
  // Set up the four remaining stack slots.
1022 1023 1024
  __ Push(rax);  // Map.
  __ Push(rcx);  // Enumeration cache.
  __ Push(rdx);  // Number of valid entries for the map in the enum cache.
1025 1026 1027
  __ Push(Smi::FromInt(0));  // Initial index.
  __ jmp(&loop);

1028
  __ bind(&no_descriptors);
1029
  __ addp(rsp, Immediate(kPointerSize));
1030 1031
  __ jmp(&exit);

1032 1033
  // We got a fixed array in register rax. Iterate through that.
  __ bind(&fixed_array);
1034

1035
  __ movp(rcx, Operand(rsp, 0 * kPointerSize));  // Get enumerated object
1036
  __ Push(Smi::FromInt(1));                      // Smi(1) indicates slow check
1037
  __ Push(rax);  // Array
1038
  __ movp(rax, FieldOperand(rax, FixedArray::kLengthOffset));
1039
  __ Push(rax);  // Fixed array length (as smi).
1040
  PrepareForBailoutForId(stmt->PrepareId(), BailoutState::NO_REGISTERS);
1041 1042 1043 1044
  __ Push(Smi::FromInt(0));  // Initial index.

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

1047
  __ movp(rax, Operand(rsp, 0 * kPointerSize));  // Get the current index.
1048
  __ cmpp(rax, Operand(rsp, 1 * kPointerSize));  // Compare to the array length.
1049
  __ j(above_equal, loop_statement.break_label());
1050

1051
  // Get the current entry of the array into register rax.
1052
  __ movp(rbx, Operand(rsp, 2 * kPointerSize));
1053
  SmiIndex index = masm()->SmiToIndex(rax, rax, kPointerSizeLog2);
1054 1055
  __ movp(rax,
          FieldOperand(rbx, index.reg, index.scale, FixedArray::kHeaderSize));
1056

1057
  // Get the expected map from the stack or a smi in the
1058
  // permanent slow case into register rdx.
1059
  __ movp(rdx, Operand(rsp, 3 * kPointerSize));
1060 1061

  // Check if the expected map still matches that of the enumerable.
1062
  // If not, we may have to filter the key.
1063
  Label update_each;
1064 1065
  __ movp(rbx, Operand(rsp, 4 * kPointerSize));
  __ cmpp(rdx, FieldOperand(rbx, HeapObject::kMapOffset));
1066
  __ j(equal, &update_each, Label::kNear);
1067

1068 1069
  // We need to filter the key, record slow-path here.
  int const vector_index = SmiFromSlot(slot)->value();
1070 1071 1072 1073
  __ EmitLoadTypeFeedbackVector(rdx);
  __ Move(FieldOperand(rdx, FixedArray::OffsetOfElementAt(vector_index)),
          TypeFeedbackVector::MegamorphicSentinel(isolate()));

1074 1075 1076 1077 1078 1079
  // rax contains the key. The receiver in rbx is the second argument to the
  // ForInFilterStub. ForInFilter returns undefined if the receiver doesn't
  // have the key or returns the name-converted key.
  ForInFilterStub has_stub(isolate());
  __ CallStub(&has_stub);
  RestoreContext();
1080
  PrepareForBailoutForId(stmt->FilterId(), BailoutState::TOS_REGISTER);
1081 1082
  __ JumpIfRoot(result_register(), Heap::kUndefinedValueRootIndex,
                loop_statement.continue_label());
1083 1084

  // Update the 'each' property or variable from the possibly filtered
1085
  // entry in register rax.
1086 1087
  __ bind(&update_each);
  // Perform the assignment as if via '='.
1088
  { EffectContext context(this);
1089
    EmitAssignment(stmt->each(), stmt->EachFeedbackSlot());
1090
    PrepareForBailoutForId(stmt->AssignmentId(), BailoutState::NO_REGISTERS);
1091
  }
1092

1093
  // Both Crankshaft and Turbofan expect BodyId to be right before stmt->body().
1094
  PrepareForBailoutForId(stmt->BodyId(), BailoutState::NO_REGISTERS);
1095 1096 1097 1098 1099
  // 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.
1100
  __ bind(loop_statement.continue_label());
1101
  PrepareForBailoutForId(stmt->IncrementId(), BailoutState::NO_REGISTERS);
1102 1103
  __ SmiAddConstant(Operand(rsp, 0 * kPointerSize), Smi::FromInt(1));

1104
  EmitBackEdgeBookkeeping(stmt, &loop);
1105
  __ jmp(&loop);
1106

1107
  // Remove the pointers stored on the stack.
1108
  __ bind(loop_statement.break_label());
1109
  DropOperands(5);
1110 1111

  // Exit and decrement the loop depth.
1112
  PrepareForBailoutForId(stmt->ExitId(), BailoutState::NO_REGISTERS);
1113 1114
  __ bind(&exit);
  decrement_loop_depth();
1115 1116 1117
}


1118
void FullCodeGenerator::EmitSetHomeObject(Expression* initializer, int offset,
1119
                                          FeedbackVectorSlot slot) {
1120 1121 1122 1123
  DCHECK(NeedsHomeObject(initializer));
  __ movp(StoreDescriptor::ReceiverRegister(), Operand(rsp, 0));
  __ movp(StoreDescriptor::ValueRegister(),
          Operand(rsp, offset * kPointerSize));
1124
  CallStoreIC(slot, isolate()->factory()->home_object_symbol());
1125 1126 1127
}


1128 1129 1130
void FullCodeGenerator::EmitSetHomeObjectAccumulator(Expression* initializer,
                                                     int offset,
                                                     FeedbackVectorSlot slot) {
1131 1132 1133 1134
  DCHECK(NeedsHomeObject(initializer));
  __ movp(StoreDescriptor::ReceiverRegister(), rax);
  __ movp(StoreDescriptor::ValueRegister(),
          Operand(rsp, offset * kPointerSize));
1135
  CallStoreIC(slot, isolate()->factory()->home_object_symbol());
1136 1137 1138
}


1139
void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1140
                                                      TypeofMode typeof_mode,
1141
                                                      Label* slow) {
1142 1143 1144
  Register context = rsi;
  Register temp = rdx;

1145 1146 1147 1148 1149 1150 1151
  int to_check = scope()->ContextChainLengthUntilOutermostSloppyEval();
  for (Scope* s = scope(); to_check > 0; s = s->outer_scope()) {
    if (!s->NeedsContext()) continue;
    if (s->calls_sloppy_eval()) {
      // Check that extension is "the hole".
      __ JumpIfNotRoot(ContextOperand(context, Context::EXTENSION_INDEX),
                       Heap::kTheHoleValueRootIndex, slow);
1152
    }
1153 1154 1155 1156 1157
    // Load next context in chain.
    __ movp(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
    // Walk the rest of the chain without clobbering rsi.
    context = temp;
    to_check--;
1158 1159
  }

1160 1161
  // All extension objects were empty and it is safe to use a normal global
  // load machinery.
1162
  EmitGlobalVariableLoad(proxy, typeof_mode);
1163 1164 1165
}


1166 1167
MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
                                                                Label* slow) {
1168
  DCHECK(var->IsContextSlot());
1169 1170 1171
  Register context = rsi;
  Register temp = rbx;

1172
  for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
1173
    if (s->NeedsContext()) {
1174
      if (s->calls_sloppy_eval()) {
1175 1176 1177
        // Check that extension is "the hole".
        __ JumpIfNotRoot(ContextOperand(context, Context::EXTENSION_INDEX),
                         Heap::kTheHoleValueRootIndex, slow);
1178
      }
1179
      __ movp(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
1180 1181 1182 1183
      // Walk the rest of the chain without clobbering rsi.
      context = temp;
    }
  }
1184 1185 1186
  // Check that last extension is "the hole".
  __ JumpIfNotRoot(ContextOperand(context, Context::EXTENSION_INDEX),
                   Heap::kTheHoleValueRootIndex, slow);
1187 1188 1189 1190

  // This function is used only for loads, not stores, so it's safe to
  // return an rsi-based operand (the write barrier cannot be allowed to
  // destroy the rsi register).
1191
  return ContextOperand(context, var->index());
1192 1193 1194
}


1195
void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1196 1197
                                                  TypeofMode typeof_mode,
                                                  Label* slow, Label* done) {
1198 1199 1200 1201 1202
  // Generate fast-case code for variables that might be shadowed by
  // eval-introduced variables.  Eval is used a lot without
  // introducing variables.  In those cases, we do not want to
  // perform a runtime call for all variables in the scope
  // containing the eval.
1203
  Variable* var = proxy->var();
1204
  if (var->mode() == DYNAMIC_GLOBAL) {
1205
    EmitLoadGlobalCheckExtensions(proxy, typeof_mode, slow);
1206
    __ jmp(done);
1207
  } else if (var->mode() == DYNAMIC_LOCAL) {
1208
    Variable* local = var->local_if_not_shadowed();
1209
    __ movp(rax, ContextSlotOperandCheckExtensions(local, slow));
1210
    if (local->binding_needs_init()) {
1211 1212
      __ CompareRoot(rax, Heap::kTheHoleValueRootIndex);
      __ j(not_equal, done);
1213 1214
      __ Push(var->name());
      __ CallRuntime(Runtime::kThrowReferenceError);
1215 1216
    } else {
      __ jmp(done);
1217 1218 1219 1220
    }
  }
}

1221
void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy,
1222
                                         TypeofMode typeof_mode) {
1223
  // Record position before possible IC call.
1224
  SetExpressionPosition(proxy);
1225
  PrepareForBailoutForId(proxy->BeforeId(), BailoutState::NO_REGISTERS);
1226 1227
  Variable* var = proxy->var();

1228 1229 1230
  // Three cases: global variables, lookup variables, and all other types of
  // variables.
  switch (var->location()) {
1231
    case VariableLocation::UNALLOCATED: {
1232
      Comment cmnt(masm_, "[ Global variable");
1233
      EmitGlobalVariableLoad(proxy, typeof_mode);
1234 1235 1236
      context()->Plug(rax);
      break;
    }
1237

1238 1239 1240
    case VariableLocation::PARAMETER:
    case VariableLocation::LOCAL:
    case VariableLocation::CONTEXT: {
1241
      DCHECK_EQ(NOT_INSIDE_TYPEOF, typeof_mode);
1242 1243
      Comment cmnt(masm_, var->IsContextSlot() ? "[ Context slot"
                                               : "[ Stack slot");
1244
      if (NeedsHoleCheckForLoad(proxy)) {
1245 1246 1247
        // Throw a reference error when using an uninitialized let/const
        // binding in harmony mode.
        DCHECK(IsLexicalVariableMode(var->mode()));
1248 1249 1250 1251
        Label done;
        GetVar(rax, var);
        __ CompareRoot(rax, Heap::kTheHoleValueRootIndex);
        __ j(not_equal, &done, Label::kNear);
1252 1253
        __ Push(var->name());
        __ CallRuntime(Runtime::kThrowReferenceError);
1254 1255 1256
        __ bind(&done);
        context()->Plug(rax);
        break;
1257
      }
1258
      context()->Plug(var);
1259 1260
      break;
    }
1261

1262
    case VariableLocation::LOOKUP: {
1263
      Comment cmnt(masm_, "[ Lookup slot");
1264 1265 1266
      Label done, slow;
      // Generate code for loading from variables potentially shadowed
      // by eval-introduced variables.
1267
      EmitDynamicLookupFastCase(proxy, typeof_mode, &slow, &done);
1268
      __ bind(&slow);
1269
      __ Push(var->name());
1270
      Runtime::FunctionId function_id =
1271
          typeof_mode == NOT_INSIDE_TYPEOF
1272
              ? Runtime::kLoadLookupSlot
1273
              : Runtime::kLoadLookupSlotInsideTypeof;
1274
      __ CallRuntime(function_id);
1275 1276
      __ bind(&done);
      context()->Plug(rax);
1277
      break;
1278
    }
1279 1280 1281

    case VariableLocation::MODULE:
      UNREACHABLE();
1282 1283 1284 1285
  }
}


1286 1287
void FullCodeGenerator::EmitAccessor(ObjectLiteralProperty* property) {
  Expression* expression = (property == NULL) ? NULL : property->value();
1288
  if (expression == NULL) {
1289
    OperandStackDepthIncrement(1);
1290 1291 1292
    __ PushRoot(Heap::kNullValueRootIndex);
  } else {
    VisitForStackValue(expression);
1293 1294 1295 1296 1297 1298
    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());
    }
1299 1300 1301 1302
  }
}


1303
void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
1304
  Comment cmnt(masm_, "[ ObjectLiteral");
1305

1306
  Handle<FixedArray> constant_properties = expr->constant_properties();
1307 1308
  int flags = expr->ComputeFlags();
  if (MustCreateObjectLiteralWithRuntime(expr)) {
1309
    __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1310 1311 1312
    __ Push(Smi::FromInt(expr->literal_index()));
    __ Push(constant_properties);
    __ Push(Smi::FromInt(flags));
1313
    __ CallRuntime(Runtime::kCreateObjectLiteral);
1314
  } else {
1315
    __ movp(rax, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1316 1317 1318
    __ Move(rbx, Smi::FromInt(expr->literal_index()));
    __ Move(rcx, constant_properties);
    __ Move(rdx, Smi::FromInt(flags));
1319
    FastCloneShallowObjectStub stub(isolate(), expr->properties_count());
1320
    __ CallStub(&stub);
1321
    RestoreContext();
1322
  }
1323
  PrepareForBailoutForId(expr->CreateLiteralId(), BailoutState::TOS_REGISTER);
1324

1325 1326
  // If result_saved is true the result is on top of the stack.  If
  // result_saved is false the result is in rax.
1327 1328
  bool result_saved = false;

1329
  AccessorTable accessor_table(zone());
arv's avatar
arv committed
1330 1331 1332 1333
  int property_index = 0;
  for (; property_index < expr->properties()->length(); property_index++) {
    ObjectLiteral::Property* property = expr->properties()->at(property_index);
    if (property->is_computed_name()) break;
1334 1335
    if (property->IsCompileTimeValue()) continue;

arv's avatar
arv committed
1336
    Literal* key = property->key()->AsLiteral();
1337 1338
    Expression* value = property->value();
    if (!result_saved) {
1339
      PushOperand(rax);  // Save result on the stack
1340 1341 1342
      result_saved = true;
    }
    switch (property->kind()) {
1343 1344
      case ObjectLiteral::Property::CONSTANT:
        UNREACHABLE();
1345
      case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1346
        DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
1347
        // Fall through.
1348
      case ObjectLiteral::Property::COMPUTED:
1349 1350
        // It is safe to use [[Put]] here because the boilerplate already
        // contains computed properties with an uninitialized value.
1351 1352
        if (key->IsStringLiteral()) {
          DCHECK(key->IsPropertyName());
1353
          if (property->emit_store()) {
1354
            VisitForAccumulatorValue(value);
1355 1356
            DCHECK(StoreDescriptor::ValueRegister().is(rax));
            __ movp(StoreDescriptor::ReceiverRegister(), Operand(rsp, 0));
1357
            CallStoreIC(property->GetSlot(0), key->value());
1358
            PrepareForBailoutForId(key->id(), BailoutState::NO_REGISTERS);
1359 1360

            if (NeedsHomeObject(value)) {
1361
              EmitSetHomeObjectAccumulator(value, 0, property->GetSlot(1));
1362
            }
1363 1364
          } else {
            VisitForEffect(value);
1365
          }
1366 1367
          break;
        }
1368
        PushOperand(Operand(rsp, 0));  // Duplicate receiver.
1369 1370
        VisitForStackValue(key);
        VisitForStackValue(value);
1371
        if (property->emit_store()) {
1372 1373 1374
          if (NeedsHomeObject(value)) {
            EmitSetHomeObject(value, 2, property->GetSlot());
          }
1375 1376
          PushOperand(Smi::FromInt(SLOPPY));  // Language mode
          CallRuntimeWithOperands(Runtime::kSetProperty);
1377
        } else {
1378
          DropOperands(3);
1379
        }
1380
        break;
1381
      case ObjectLiteral::Property::PROTOTYPE:
1382
        PushOperand(Operand(rsp, 0));  // Duplicate receiver.
1383
        VisitForStackValue(value);
1384
        DCHECK(property->emit_store());
1385
        CallRuntimeWithOperands(Runtime::kInternalSetPrototype);
1386
        PrepareForBailoutForId(expr->GetIdForPropertySet(property_index),
1387
                               BailoutState::NO_REGISTERS);
1388
        break;
1389
      case ObjectLiteral::Property::GETTER:
1390
        if (property->emit_store()) {
1391 1392 1393
          AccessorTable::Iterator it = accessor_table.lookup(key);
          it->second->bailout_id = expr->GetIdForPropertySet(property_index);
          it->second->getter = property;
1394
        }
1395 1396
        break;
      case ObjectLiteral::Property::SETTER:
1397
        if (property->emit_store()) {
1398 1399 1400
          AccessorTable::Iterator it = accessor_table.lookup(key);
          it->second->bailout_id = expr->GetIdForPropertySet(property_index);
          it->second->setter = property;
1401
        }
1402 1403 1404
        break;
    }
  }
1405

1406 1407 1408 1409 1410
  // 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) {
1411
    PushOperand(Operand(rsp, 0));  // Duplicate receiver.
1412 1413 1414
    VisitForStackValue(it->first);
    EmitAccessor(it->second->getter);
    EmitAccessor(it->second->setter);
1415 1416
    PushOperand(Smi::FromInt(NONE));
    CallRuntimeWithOperands(Runtime::kDefineAccessorPropertyUnchecked);
1417
    PrepareForBailoutForId(it->second->bailout_id, BailoutState::NO_REGISTERS);
1418 1419
  }

arv's avatar
arv committed
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
  // Object literals have two parts. The "static" part on the left contains no
  // computed property names, and so we can compute its map ahead of time; see
  // runtime.cc::CreateObjectLiteralBoilerplate. The second "dynamic" part
  // starts with the first computed property name, and continues with all
  // properties to its right.  All the code from above initializes the static
  // component of the object literal, and arranges for the map of the result to
  // reflect the static order in which the keys appear. For the dynamic
  // properties, we compile them into a series of "SetOwnProperty" runtime
  // calls. This will preserve insertion order.
  for (; property_index < expr->properties()->length(); property_index++) {
    ObjectLiteral::Property* property = expr->properties()->at(property_index);

    Expression* value = property->value();
    if (!result_saved) {
1434
      PushOperand(rax);  // Save result on the stack
arv's avatar
arv committed
1435 1436 1437
      result_saved = true;
    }

1438
    PushOperand(Operand(rsp, 0));  // Duplicate receiver.
arv's avatar
arv committed
1439 1440 1441 1442

    if (property->kind() == ObjectLiteral::Property::PROTOTYPE) {
      DCHECK(!property->is_computed_name());
      VisitForStackValue(value);
1443
      DCHECK(property->emit_store());
1444
      CallRuntimeWithOperands(Runtime::kInternalSetPrototype);
1445
      PrepareForBailoutForId(expr->GetIdForPropertySet(property_index),
1446
                             BailoutState::NO_REGISTERS);
arv's avatar
arv committed
1447
    } else {
1448
      EmitPropertyKey(property, expr->GetIdForPropertyName(property_index));
arv's avatar
arv committed
1449
      VisitForStackValue(value);
1450 1451 1452
      if (NeedsHomeObject(value)) {
        EmitSetHomeObject(value, 2, property->GetSlot());
      }
arv's avatar
arv committed
1453 1454 1455 1456 1457 1458

      switch (property->kind()) {
        case ObjectLiteral::Property::CONSTANT:
        case ObjectLiteral::Property::MATERIALIZED_LITERAL:
        case ObjectLiteral::Property::COMPUTED:
          if (property->emit_store()) {
1459 1460 1461
            PushOperand(Smi::FromInt(NONE));
            PushOperand(Smi::FromInt(property->NeedsSetFunctionName()));
            CallRuntimeWithOperands(Runtime::kDefineDataPropertyInLiteral);
1462 1463
            PrepareForBailoutForId(expr->GetIdForPropertySet(property_index),
                                   BailoutState::NO_REGISTERS);
arv's avatar
arv committed
1464
          } else {
1465
            DropOperands(3);
arv's avatar
arv committed
1466 1467 1468 1469 1470 1471 1472 1473
          }
          break;

        case ObjectLiteral::Property::PROTOTYPE:
          UNREACHABLE();
          break;

        case ObjectLiteral::Property::GETTER:
1474 1475
          PushOperand(Smi::FromInt(NONE));
          CallRuntimeWithOperands(Runtime::kDefineGetterPropertyUnchecked);
arv's avatar
arv committed
1476 1477 1478
          break;

        case ObjectLiteral::Property::SETTER:
1479 1480
          PushOperand(Smi::FromInt(NONE));
          CallRuntimeWithOperands(Runtime::kDefineSetterPropertyUnchecked);
arv's avatar
arv committed
1481 1482 1483 1484 1485
          break;
      }
    }
  }

1486
  if (result_saved) {
1487
    context()->PlugTOS();
1488
  } else {
1489
    context()->Plug(rax);
1490 1491 1492 1493
  }
}


1494
void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
1495
  Comment cmnt(masm_, "[ ArrayLiteral");
1496

1497
  Handle<FixedArray> constant_elements = expr->constant_elements();
1498
  bool has_constant_fast_elements =
1499
      IsFastObjectElementsKind(expr->constant_elements_kind());
1500

1501
  AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
1502 1503 1504 1505 1506 1507
  if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
    // If the only customer of allocation sites is transitioning, then
    // we can turn it off if we don't have anywhere else to transition to.
    allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
  }

1508
  if (MustCreateArrayLiteralWithRuntime(expr)) {
1509
    __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1510 1511
    __ Push(Smi::FromInt(expr->literal_index()));
    __ Push(constant_elements);
1512
    __ Push(Smi::FromInt(expr->ComputeFlags()));
1513
    __ CallRuntime(Runtime::kCreateArrayLiteral);
1514
  } else {
1515
    __ movp(rax, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
1516 1517
    __ Move(rbx, Smi::FromInt(expr->literal_index()));
    __ Move(rcx, constant_elements);
1518
    FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
1519
    __ CallStub(&stub);
1520
    RestoreContext();
1521
  }
1522
  PrepareForBailoutForId(expr->CreateLiteralId(), BailoutState::TOS_REGISTER);
1523 1524

  bool result_saved = false;  // Is the result saved to the stack?
1525 1526
  ZoneList<Expression*>* subexprs = expr->values();
  int length = subexprs->length();
1527 1528 1529

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

1534 1535
    // If the subexpression is a literal or a simple materialized literal it
    // is already set in the cloned array.
1536
    if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
1537 1538

    if (!result_saved) {
1539
      PushOperand(rax);  // array literal
1540 1541
      result_saved = true;
    }
1542
    VisitForAccumulatorValue(subexpr);
1543

1544
    __ Move(StoreDescriptor::NameRegister(), Smi::FromInt(array_index));
1545
    __ movp(StoreDescriptor::ReceiverRegister(), Operand(rsp, 0));
1546
    CallKeyedStoreIC(expr->LiteralFeedbackSlot());
1547

1548 1549
    PrepareForBailoutForId(expr->GetIdForElement(array_index),
                           BailoutState::NO_REGISTERS);
arv's avatar
arv committed
1550 1551
  }

1552
  if (result_saved) {
1553
    context()->PlugTOS();
1554
  } else {
1555
    context()->Plug(rax);
1556 1557 1558 1559
  }
}


1560
void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1561
  DCHECK(expr->target()->IsValidReferenceExpressionOrThis());
1562

1563
  Comment cmnt(masm_, "[ Assignment");
1564

1565
  Property* property = expr->target()->AsProperty();
1566
  LhsKind assign_type = Property::GetAssignType(property);
1567 1568 1569 1570 1571 1572 1573 1574

  // Evaluate LHS expression.
  switch (assign_type) {
    case VARIABLE:
      // Nothing to do here.
      break;
    case NAMED_PROPERTY:
      if (expr->is_compound()) {
1575 1576
        // We need the receiver both on the stack and in the register.
        VisitForStackValue(property->obj());
1577
        __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
1578
      } else {
1579
        VisitForStackValue(property->obj());
1580 1581
      }
      break;
1582
    case NAMED_SUPER_PROPERTY:
1583 1584
      VisitForStackValue(
          property->obj()->AsSuperPropertyReference()->this_var());
1585
      VisitForAccumulatorValue(
1586
          property->obj()->AsSuperPropertyReference()->home_object());
1587
      PushOperand(result_register());
1588
      if (expr->is_compound()) {
1589 1590
        PushOperand(MemOperand(rsp, kPointerSize));
        PushOperand(result_register());
1591 1592
      }
      break;
1593
    case KEYED_SUPER_PROPERTY:
1594
      VisitForStackValue(
1595 1596
          property->obj()->AsSuperPropertyReference()->this_var());
      VisitForStackValue(
1597
          property->obj()->AsSuperPropertyReference()->home_object());
1598
      VisitForAccumulatorValue(property->key());
1599
      PushOperand(result_register());
1600
      if (expr->is_compound()) {
1601 1602 1603
        PushOperand(MemOperand(rsp, 2 * kPointerSize));
        PushOperand(MemOperand(rsp, 2 * kPointerSize));
        PushOperand(result_register());
1604 1605
      }
      break;
1606
    case KEYED_PROPERTY: {
1607
      if (expr->is_compound()) {
1608
        VisitForStackValue(property->obj());
1609
        VisitForStackValue(property->key());
1610 1611
        __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, kPointerSize));
        __ movp(LoadDescriptor::NameRegister(), Operand(rsp, 0));
1612
      } else {
1613 1614
        VisitForStackValue(property->obj());
        VisitForStackValue(property->key());
1615
      }
1616
      break;
1617
    }
1618 1619
  }

1620 1621
  // For compound assignments we need another deoptimization point after the
  // variable/property load.
1622
  if (expr->is_compound()) {
1623 1624 1625
    { AccumulatorValueContext context(this);
      switch (assign_type) {
        case VARIABLE:
1626
          EmitVariableLoad(expr->target()->AsVariableProxy());
1627
          PrepareForBailout(expr->target(), BailoutState::TOS_REGISTER);
1628 1629 1630
          break;
        case NAMED_PROPERTY:
          EmitNamedPropertyLoad(property);
1631 1632
          PrepareForBailoutForId(property->LoadId(),
                                 BailoutState::TOS_REGISTER);
1633
          break;
1634 1635
        case NAMED_SUPER_PROPERTY:
          EmitNamedSuperPropertyLoad(property);
1636 1637
          PrepareForBailoutForId(property->LoadId(),
                                 BailoutState::TOS_REGISTER);
1638
          break;
1639 1640
        case KEYED_SUPER_PROPERTY:
          EmitKeyedSuperPropertyLoad(property);
1641 1642
          PrepareForBailoutForId(property->LoadId(),
                                 BailoutState::TOS_REGISTER);
1643
          break;
1644 1645
        case KEYED_PROPERTY:
          EmitKeyedPropertyLoad(property);
1646 1647
          PrepareForBailoutForId(property->LoadId(),
                                 BailoutState::TOS_REGISTER);
1648 1649
          break;
      }
1650 1651
    }

1652
    Token::Value op = expr->binary_op();
1653
    PushOperand(rax);  // Left operand goes on the stack.
1654
    VisitForAccumulatorValue(expr->value());
1655

1656
    AccumulatorValueContext context(this);
1657
    if (ShouldInlineSmiCase(op)) {
1658
      EmitInlineSmiBinaryOp(expr->binary_operation(),
1659 1660
                            op,
                            expr->target(),
1661
                            expr->value());
1662
    } else {
1663
      EmitBinaryOp(expr->binary_operation(), op);
1664
    }
1665
    // Deoptimization point in case the binary operation may have side effects.
1666
    PrepareForBailout(expr->binary_operation(), BailoutState::TOS_REGISTER);
1667
  } else {
1668
    VisitForAccumulatorValue(expr->value());
1669 1670
  }

1671
  SetExpressionPosition(expr);
1672 1673 1674 1675 1676

  // Store the value.
  switch (assign_type) {
    case VARIABLE:
      EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
1677
                             expr->op(), expr->AssignmentSlot());
1678
      PrepareForBailoutForId(expr->AssignmentId(), BailoutState::TOS_REGISTER);
1679
      context()->Plug(rax);
1680 1681 1682 1683
      break;
    case NAMED_PROPERTY:
      EmitNamedPropertyAssignment(expr);
      break;
1684
    case NAMED_SUPER_PROPERTY:
1685 1686
      EmitNamedSuperPropertyStore(property);
      context()->Plug(rax);
1687
      break;
1688 1689 1690 1691
    case KEYED_SUPER_PROPERTY:
      EmitKeyedSuperPropertyStore(property);
      context()->Plug(rax);
      break;
1692 1693 1694 1695 1696 1697 1698
    case KEYED_PROPERTY:
      EmitKeyedPropertyAssignment(expr);
      break;
  }
}


1699 1700
void FullCodeGenerator::VisitYield(Yield* expr) {
  Comment cmnt(masm_, "[ Yield");
1701 1702
  SetExpressionPosition(expr);

1703 1704 1705 1706
  // Evaluate yielded value first; the initial iterator definition depends on
  // this.  It stays on the stack while we update the iterator.
  VisitForStackValue(expr->expression());

1707
  Label suspend, continuation, post_runtime, resume, exception;
1708 1709 1710

  __ jmp(&suspend);
  __ bind(&continuation);
1711
  // When we arrive here, rax holds the generator object.
1712
  __ RecordGeneratorContinuation();
1713
  __ movp(rbx, FieldOperand(rax, JSGeneratorObject::kResumeModeOffset));
1714
  __ movp(rax, FieldOperand(rax, JSGeneratorObject::kInputOrDebugPosOffset));
1715 1716 1717 1718
  STATIC_ASSERT(JSGeneratorObject::kNext < JSGeneratorObject::kReturn);
  STATIC_ASSERT(JSGeneratorObject::kThrow > JSGeneratorObject::kReturn);
  __ SmiCompare(rbx, Smi::FromInt(JSGeneratorObject::kReturn));
  __ j(less, &resume);
1719
  __ Push(result_register());
1720
  __ j(greater, &exception);
1721 1722 1723
  EmitCreateIteratorResult(true);
  EmitUnwindAndReturn();

1724
  __ bind(&exception);
1725 1726
  __ CallRuntime(expr->rethrow_on_exception() ? Runtime::kReThrow
                                              : Runtime::kThrow);
1727

1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
  __ bind(&suspend);
  OperandStackDepthIncrement(1);  // Not popped on this path.
  VisitForAccumulatorValue(expr->generator_object());
  DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
  __ Move(FieldOperand(rax, JSGeneratorObject::kContinuationOffset),
          Smi::FromInt(continuation.pos()));
  __ movp(FieldOperand(rax, JSGeneratorObject::kContextOffset), rsi);
  __ movp(rcx, rsi);
  __ RecordWriteField(rax, JSGeneratorObject::kContextOffset, rcx, rdx,
                      kDontSaveFPRegs);
  __ leap(rbx, Operand(rbp, StandardFrameConstants::kExpressionsOffset));
  __ cmpp(rsp, rbx);
  __ j(equal, &post_runtime);
  __ Push(rax);  // generator object
  __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
1743
  RestoreContext();
1744 1745 1746 1747 1748 1749 1750
  __ bind(&post_runtime);

  PopOperand(result_register());
  EmitReturnSequence();

  __ bind(&resume);
  context()->Plug(result_register());
1751 1752
}

1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
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);
  }
}
1768

1769
void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
1770
  Label allocate, done_allocate;
1771

1772 1773
  __ Allocate(JSIteratorResult::kSize, rax, rcx, rdx, &allocate,
              NO_ALLOCATION_FLAGS);
1774
  __ jmp(&done_allocate, Label::kNear);
1775

1776 1777
  __ bind(&allocate);
  __ Push(Smi::FromInt(JSIteratorResult::kSize));
1778
  __ CallRuntime(Runtime::kAllocateInNewSpace);
1779

1780
  __ bind(&done_allocate);
1781
  __ LoadNativeContextSlot(Context::ITERATOR_RESULT_MAP_INDEX, rbx);
1782
  __ movp(FieldOperand(rax, HeapObject::kMapOffset), rbx);
1783 1784 1785 1786 1787 1788 1789
  __ 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);
1790
  OperandStackDepthDecrement(1);
1791 1792 1793
}


1794
void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
1795 1796
                                              Token::Value op,
                                              Expression* left,
1797
                                              Expression* right) {
1798 1799 1800
  // 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.
1801
  Label done, stub_call, smi_case;
1802
  PopOperand(rdx);
1803
  __ movp(rcx, rax);
1804
  __ orp(rax, rdx);
1805
  JumpPatchSite patch_site(masm_);
1806
  patch_site.EmitJumpIfSmi(rax, &smi_case, Label::kNear);
1807 1808

  __ bind(&stub_call);
1809
  __ movp(rax, rcx);
1810
  Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op).code();
1811
  CallIC(code, expr->BinaryOperationFeedbackId());
1812
  patch_site.EmitPatchInfo();
1813
  __ jmp(&done, Label::kNear);
1814 1815 1816 1817 1818 1819 1820

  __ bind(&smi_case);
  switch (op) {
    case Token::SAR:
      __ SmiShiftArithmeticRight(rax, rdx, rcx);
      break;
    case Token::SHL:
1821
      __ SmiShiftLeft(rax, rdx, rcx, &stub_call);
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
      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);
1850
  context()->Plug(rax);
1851 1852 1853
}


1854
void FullCodeGenerator::EmitClassDefineProperties(ClassLiteral* lit) {
1855
  for (int i = 0; i < lit->properties()->length(); i++) {
1856
    ClassLiteral::Property* property = lit->properties()->at(i);
1857 1858 1859
    Expression* value = property->value();

    if (property->is_static()) {
1860
      PushOperand(Operand(rsp, kPointerSize));  // constructor
1861
    } else {
1862
      PushOperand(Operand(rsp, 0));  // prototype
1863
    }
1864
    EmitPropertyKey(property, lit->GetIdForProperty(i));
1865 1866 1867 1868 1869 1870

    // The static prototype property is read only. We handle the non computed
    // property name case in the parser. Since this is the only case where we
    // need to check for an own read only property we special case this so we do
    // not need to do this for every property.
    if (property->is_static() && property->is_computed_name()) {
1871
      __ CallRuntime(Runtime::kThrowIfStaticPrototype);
1872 1873 1874
      __ Push(rax);
    }

1875
    VisitForStackValue(value);
1876 1877 1878
    if (NeedsHomeObject(value)) {
      EmitSetHomeObject(value, 2, property->GetSlot());
    }
1879 1880

    switch (property->kind()) {
1881
      case ClassLiteral::Property::METHOD:
1882 1883 1884
        PushOperand(Smi::FromInt(DONT_ENUM));
        PushOperand(Smi::FromInt(property->NeedsSetFunctionName()));
        CallRuntimeWithOperands(Runtime::kDefineDataPropertyInLiteral);
1885 1886
        break;

1887
      case ClassLiteral::Property::GETTER:
1888 1889
        PushOperand(Smi::FromInt(DONT_ENUM));
        CallRuntimeWithOperands(Runtime::kDefineGetterPropertyUnchecked);
1890 1891
        break;

1892
      case ClassLiteral::Property::SETTER:
1893 1894
        PushOperand(Smi::FromInt(DONT_ENUM));
        CallRuntimeWithOperands(Runtime::kDefineSetterPropertyUnchecked);
1895 1896
        break;

1897
      case ClassLiteral::Property::FIELD:
1898 1899 1900 1901 1902 1903 1904
      default:
        UNREACHABLE();
    }
  }
}


1905
void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr, Token::Value op) {
1906
  PopOperand(rdx);
1907
  Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), op).code();
1908
  JumpPatchSite patch_site(masm_);    // unbound, signals no inlined smi code.
1909
  CallIC(code, expr->BinaryOperationFeedbackId());
1910
  patch_site.EmitPatchInfo();
1911
  context()->Plug(rax);
1912 1913 1914
}


1915
void FullCodeGenerator::EmitAssignment(Expression* expr,
1916
                                       FeedbackVectorSlot slot) {
1917
  DCHECK(expr->IsValidReferenceExpressionOrThis());
1918 1919

  Property* prop = expr->AsProperty();
1920
  LhsKind assign_type = Property::GetAssignType(prop);
1921 1922 1923 1924

  switch (assign_type) {
    case VARIABLE: {
      Variable* var = expr->AsVariableProxy()->var();
1925
      EffectContext context(this);
1926
      EmitVariableAssignment(var, Token::ASSIGN, slot);
1927 1928 1929
      break;
    }
    case NAMED_PROPERTY: {
1930
      PushOperand(rax);  // Preserve value.
1931
      VisitForAccumulatorValue(prop->obj());
1932
      __ Move(StoreDescriptor::ReceiverRegister(), rax);
1933
      PopOperand(StoreDescriptor::ValueRegister());  // Restore value.
1934
      CallStoreIC(slot, prop->key()->AsLiteral()->value());
1935 1936
      break;
    }
1937
    case NAMED_SUPER_PROPERTY: {
1938
      PushOperand(rax);
1939
      VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
1940
      VisitForAccumulatorValue(
1941
          prop->obj()->AsSuperPropertyReference()->home_object());
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
      // stack: value, this; rax: home_object
      Register scratch = rcx;
      Register scratch2 = rdx;
      __ Move(scratch, result_register());               // home_object
      __ movp(rax, MemOperand(rsp, kPointerSize));       // value
      __ movp(scratch2, MemOperand(rsp, 0));             // this
      __ movp(MemOperand(rsp, kPointerSize), scratch2);  // this
      __ movp(MemOperand(rsp, 0), scratch);              // home_object
      // stack: this, home_object; rax: value
      EmitNamedSuperPropertyStore(prop);
      break;
    }
    case KEYED_SUPER_PROPERTY: {
1955
      PushOperand(rax);
1956 1957
      VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
      VisitForStackValue(
1958
          prop->obj()->AsSuperPropertyReference()->home_object());
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
      VisitForAccumulatorValue(prop->key());
      Register scratch = rcx;
      Register scratch2 = rdx;
      __ movp(scratch2, MemOperand(rsp, 2 * kPointerSize));  // value
      // stack: value, this, home_object; rax: key, rdx: value
      __ movp(scratch, MemOperand(rsp, kPointerSize));  // this
      __ movp(MemOperand(rsp, 2 * kPointerSize), scratch);
      __ movp(scratch, MemOperand(rsp, 0));  // home_object
      __ movp(MemOperand(rsp, kPointerSize), scratch);
      __ movp(MemOperand(rsp, 0), rax);
      __ Move(rax, scratch2);
      // stack: this, home_object, key; rax: value.
      EmitKeyedSuperPropertyStore(prop);
      break;
    }
1974
    case KEYED_PROPERTY: {
1975
      PushOperand(rax);  // Preserve value.
1976 1977
      VisitForStackValue(prop->obj());
      VisitForAccumulatorValue(prop->key());
1978
      __ Move(StoreDescriptor::NameRegister(), rax);
1979 1980
      PopOperand(StoreDescriptor::ReceiverRegister());
      PopOperand(StoreDescriptor::ValueRegister());  // Restore value.
1981
      CallKeyedStoreIC(slot);
1982 1983 1984
      break;
    }
  }
1985
  context()->Plug(rax);
1986 1987 1988
}


1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
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);
  }
}


2000
void FullCodeGenerator::EmitVariableAssignment(Variable* var, Token::Value op,
2001
                                               FeedbackVectorSlot slot) {
2002
  if (var->IsUnallocated()) {
2003
    // Global var, const, or let.
2004
    __ LoadGlobalObject(StoreDescriptor::ReceiverRegister());
2005
    CallStoreIC(slot, var->name());
2006

2007
  } else if (IsLexicalVariableMode(var->mode()) && op != Token::INIT) {
2008 2009 2010
    DCHECK(!var->IsLookupSlot());
    DCHECK(var->IsStackAllocated() || var->IsContextSlot());
    MemOperand location = VarOperand(var, rcx);
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
    // Perform an initialization check for lexically declared variables.
    if (var->binding_needs_init()) {
      Label assign;
      __ movp(rdx, location);
      __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
      __ j(not_equal, &assign, Label::kNear);
      __ Push(var->name());
      __ CallRuntime(Runtime::kThrowReferenceError);
      __ bind(&assign);
    }
2021
    if (var->mode() != CONST) {
2022
      EmitStoreToStackLocalOrContextSlot(var, location);
2023 2024
    } else if (var->throw_on_const_assignment(language_mode())) {
      __ CallRuntime(Runtime::kThrowConstAssignError);
2025
    }
2026

2027
  } else if (var->is_this() && var->mode() == CONST && op == Token::INIT) {
2028 2029 2030 2031 2032 2033 2034 2035
    // 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());
2036
    __ CallRuntime(Runtime::kThrowReferenceError);
2037 2038 2039
    __ bind(&uninitialized_this);
    EmitStoreToStackLocalOrContextSlot(var, location);

2040 2041
  } else {
    DCHECK(var->mode() != CONST || op == Token::INIT);
2042
    if (var->IsLookupSlot()) {
2043 2044
      // Assignment to var.
      __ Push(var->name());
2045 2046 2047 2048
      __ Push(rax);
      __ CallRuntime(is_strict(language_mode())
                         ? Runtime::kStoreLookupSlot_Strict
                         : Runtime::kStoreLookupSlot_Sloppy);
2049
    } else {
2050 2051
      // Assignment to var or initializing assignment to let/const in harmony
      // mode.
2052
      DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2053
      MemOperand location = VarOperand(var, rcx);
2054
      if (FLAG_debug_code && var->mode() == LET && op == Token::INIT) {
2055
        // Check for an uninitialized let binding.
2056
        __ movp(rdx, location);
2057
        __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex);
2058
        __ Check(equal, kLetBindingReInitialization);
2059
      }
2060
      EmitStoreToStackLocalOrContextSlot(var, location);
2061
    }
2062
  }
2063 2064 2065
}


2066
void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
2067 2068
  // Assignment to a property, using a named store IC.
  Property* prop = expr->target()->AsProperty();
2069 2070
  DCHECK(prop != NULL);
  DCHECK(prop->key()->IsLiteral());
2071

2072
  PopOperand(StoreDescriptor::ReceiverRegister());
2073
  CallStoreIC(expr->AssignmentSlot(), prop->key()->AsLiteral()->value());
2074

2075
  PrepareForBailoutForId(expr->AssignmentId(), BailoutState::TOS_REGISTER);
2076
  context()->Plug(rax);
2077 2078 2079
}


2080
void FullCodeGenerator::EmitNamedSuperPropertyStore(Property* prop) {
2081 2082 2083 2084 2085 2086 2087
  // Assignment to named property of super.
  // rax : value
  // stack : receiver ('this'), home_object
  DCHECK(prop != NULL);
  Literal* key = prop->key()->AsLiteral();
  DCHECK(key != NULL);

2088 2089 2090 2091 2092
  PushOperand(key->value());
  PushOperand(rax);
  CallRuntimeWithOperands(is_strict(language_mode())
                              ? Runtime::kStoreToSuper_Strict
                              : Runtime::kStoreToSuper_Sloppy);
2093 2094 2095
}


2096 2097 2098 2099 2100 2101
void FullCodeGenerator::EmitKeyedSuperPropertyStore(Property* prop) {
  // Assignment to named property of super.
  // rax : value
  // stack : receiver ('this'), home_object, key
  DCHECK(prop != NULL);

2102 2103 2104 2105
  PushOperand(rax);
  CallRuntimeWithOperands(is_strict(language_mode())
                              ? Runtime::kStoreKeyedToSuper_Strict
                              : Runtime::kStoreKeyedToSuper_Sloppy);
2106 2107 2108
}


2109
void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
2110
  // Assignment to a property, using a keyed store IC.
2111 2112
  PopOperand(StoreDescriptor::NameRegister());  // Key.
  PopOperand(StoreDescriptor::ReceiverRegister());
2113
  DCHECK(StoreDescriptor::ValueRegister().is(rax));
2114
  CallKeyedStoreIC(expr->AssignmentSlot());
2115

2116
  PrepareForBailoutForId(expr->AssignmentId(), BailoutState::TOS_REGISTER);
2117
  context()->Plug(rax);
2118 2119 2120
}


2121
void FullCodeGenerator::CallIC(Handle<Code> code,
2122
                               TypeFeedbackId ast_id) {
2123
  ic_total_count_++;
2124
  __ call(code, RelocInfo::CODE_TARGET, ast_id);
2125 2126 2127
}


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

2132
  // Get the target function.
2133
  ConvertReceiverMode convert_mode;
2134
  if (callee->IsVariableProxy()) {
verwaest@chromium.org's avatar
verwaest@chromium.org committed
2135 2136
    { StackValueContext context(this);
      EmitVariableLoad(callee->AsVariableProxy());
2137
      PrepareForBailout(callee, BailoutState::NO_REGISTERS);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
2138
    }
2139
    // Push undefined as receiver. This is patched in the Call builtin if it
2140
    // is a sloppy mode method.
2141
    PushOperand(isolate()->factory()->undefined_value());
2142
    convert_mode = ConvertReceiverMode::kNullOrUndefined;
verwaest@chromium.org's avatar
verwaest@chromium.org committed
2143 2144
  } else {
    // Load the function from the receiver.
2145
    DCHECK(callee->IsProperty());
2146
    DCHECK(!callee->AsProperty()->IsSuperAccess());
2147
    __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
verwaest@chromium.org's avatar
verwaest@chromium.org committed
2148
    EmitNamedPropertyLoad(callee->AsProperty());
2149 2150
    PrepareForBailoutForId(callee->AsProperty()->LoadId(),
                           BailoutState::TOS_REGISTER);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
2151
    // Push the target function under the receiver.
2152
    PushOperand(Operand(rsp, 0));
verwaest@chromium.org's avatar
verwaest@chromium.org committed
2153
    __ movp(Operand(rsp, kPointerSize), rax);
2154
    convert_mode = ConvertReceiverMode::kNotNullOrUndefined;
verwaest@chromium.org's avatar
verwaest@chromium.org committed
2155 2156
  }

2157
  EmitCall(expr, convert_mode);
2158 2159 2160
}


2161 2162 2163 2164 2165
void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
  Expression* callee = expr->expression();
  DCHECK(callee->IsProperty());
  Property* prop = callee->AsProperty();
  DCHECK(prop->IsSuperAccess());
2166
  SetExpressionPosition(prop);
2167 2168 2169 2170

  Literal* key = prop->key()->AsLiteral();
  DCHECK(!key->value()->IsSmi());
  // Load the function from the receiver.
2171
  SuperPropertyReference* super_ref = prop->obj()->AsSuperPropertyReference();
2172
  VisitForStackValue(super_ref->home_object());
2173
  VisitForAccumulatorValue(super_ref->this_var());
2174 2175 2176 2177
  PushOperand(rax);
  PushOperand(rax);
  PushOperand(Operand(rsp, kPointerSize * 2));
  PushOperand(key->value());
2178 2179 2180 2181

  // Stack here:
  //  - home_object
  //  - this (receiver)
2182 2183
  //  - this (receiver) <-- LoadFromSuper will pop here and below.
  //  - home_object
2184
  //  - key
2185
  CallRuntimeWithOperands(Runtime::kLoadFromSuper);
2186
  PrepareForBailoutForId(prop->LoadId(), BailoutState::TOS_REGISTER);
2187 2188 2189 2190 2191 2192 2193

  // Replace home_object with target function.
  __ movp(Operand(rsp, kPointerSize), rax);

  // Stack here:
  // - target function
  // - this (receiver)
2194
  EmitCall(expr);
2195 2196 2197
}


verwaest@chromium.org's avatar
verwaest@chromium.org committed
2198
// Common code for calls using the IC.
2199 2200
void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
                                                Expression* key) {
2201 2202 2203
  // Load the key.
  VisitForAccumulatorValue(key);

verwaest@chromium.org's avatar
verwaest@chromium.org committed
2204 2205 2206
  Expression* callee = expr->expression();

  // Load the function from the receiver.
2207
  DCHECK(callee->IsProperty());
2208 2209
  __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
  __ Move(LoadDescriptor::NameRegister(), rax);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
2210
  EmitKeyedPropertyLoad(callee->AsProperty());
2211 2212
  PrepareForBailoutForId(callee->AsProperty()->LoadId(),
                         BailoutState::TOS_REGISTER);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
2213 2214

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

2218
  EmitCall(expr, ConvertReceiverMode::kNotNullOrUndefined);
2219 2220 2221
}


2222 2223 2224 2225 2226 2227
void FullCodeGenerator::EmitKeyedSuperCallWithLoadIC(Call* expr) {
  Expression* callee = expr->expression();
  DCHECK(callee->IsProperty());
  Property* prop = callee->AsProperty();
  DCHECK(prop->IsSuperAccess());

2228
  SetExpressionPosition(prop);
2229
  // Load the function from the receiver.
2230
  SuperPropertyReference* super_ref = prop->obj()->AsSuperPropertyReference();
2231
  VisitForStackValue(super_ref->home_object());
2232
  VisitForAccumulatorValue(super_ref->this_var());
2233 2234 2235
  PushOperand(rax);
  PushOperand(rax);
  PushOperand(Operand(rsp, kPointerSize * 2));
2236 2237 2238 2239 2240 2241 2242 2243
  VisitForStackValue(prop->key());

  // Stack here:
  //  - home_object
  //  - this (receiver)
  //  - this (receiver) <-- LoadKeyedFromSuper will pop here and below.
  //  - home_object
  //  - key
2244
  CallRuntimeWithOperands(Runtime::kLoadKeyedFromSuper);
2245
  PrepareForBailoutForId(prop->LoadId(), BailoutState::TOS_REGISTER);
2246 2247 2248 2249 2250 2251 2252

  // Replace home_object with target function.
  __ movp(Operand(rsp, kPointerSize), rax);

  // Stack here:
  // - target function
  // - this (receiver)
2253
  EmitCall(expr);
2254 2255 2256
}


2257
void FullCodeGenerator::EmitCall(Call* expr, ConvertReceiverMode mode) {
2258
  // Load the arguments.
2259 2260
  ZoneList<Expression*>* args = expr->arguments();
  int arg_count = args->length();
2261 2262
  for (int i = 0; i < arg_count; i++) {
    VisitForStackValue(args->at(i));
2263
  }
2264

2265
  PrepareForBailoutForId(expr->CallId(), BailoutState::NO_REGISTERS);
2266
  SetCallPosition(expr, expr->tail_call_mode());
2267 2268 2269 2270 2271 2272 2273 2274
  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);
  }
ishell's avatar
ishell committed
2275 2276 2277
  Handle<Code> ic =
      CodeFactory::CallIC(isolate(), arg_count, mode, expr->tail_call_mode())
          .code();
2278
  __ Move(rdx, SmiFromSlot(expr->CallFeedbackICSlot()));
2279
  __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
2280 2281 2282
  // Don't assign a type feedback id to the IC, since type feedback is provided
  // by the vector above.
  CallIC(ic);
2283
  OperandStackDepthDecrement(arg_count + 1);
2284

2285
  RecordJSReturnSite(expr);
2286
  RestoreContext();
2287
  // Discard the function left on TOS.
2288
  context()->DropAndPlug(1, rax);
2289 2290
}

2291 2292
void FullCodeGenerator::EmitResolvePossiblyDirectEval(Call* expr) {
  int arg_count = expr->arguments()->length();
2293 2294
  // Push copy of the first argument or undefined if it doesn't exist.
  if (arg_count > 0) {
2295
    __ Push(Operand(rsp, arg_count * kPointerSize));
2296 2297 2298 2299
  } else {
    __ PushRoot(Heap::kUndefinedValueRootIndex);
  }

2300 2301 2302
  // Push the enclosing function.
  __ Push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));

2303
  // Push the language mode.
2304
  __ Push(Smi::FromInt(language_mode()));
2305

2306 2307
  // Push the start position of the scope the calls resides in.
  __ Push(Smi::FromInt(scope()->start_position()));
2308

2309 2310 2311
  // Push the source position of the eval call.
  __ Push(Smi::FromInt(expr->position()));

2312
  // Do the runtime call.
2313
  __ CallRuntime(Runtime::kResolvePossiblyDirectEval);
2314 2315 2316
}


2317 2318 2319 2320 2321
// See http://www.ecma-international.org/ecma-262/6.0/#sec-function-calls.
void FullCodeGenerator::PushCalleeAndWithBaseObject(Call* expr) {
  VariableProxy* callee = expr->expression()->AsVariableProxy();
  if (callee->var()->IsLookupSlot()) {
    Label slow, done;
2322 2323 2324 2325
    SetExpressionPosition(callee);
    // Generate code for loading from variables potentially shadowed by
    // eval-introduced variables.
    EmitDynamicLookupFastCase(callee, NOT_INSIDE_TYPEOF, &slow, &done);
2326 2327 2328 2329
    __ bind(&slow);
    // Call the runtime to find the function to call (returned in rax) and
    // the object holding it (returned in rdx).
    __ Push(callee->name());
2330
    __ CallRuntime(Runtime::kLoadLookupSlotForCall);
2331 2332
    PushOperand(rax);  // Function.
    PushOperand(rdx);  // Receiver.
2333
    PrepareForBailoutForId(expr->LookupId(), BailoutState::NO_REGISTERS);
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351

    // If fast case code has been generated, emit code to push the function
    // and receiver and have the slow path jump around this code.
    if (done.is_linked()) {
      Label call;
      __ jmp(&call, Label::kNear);
      __ bind(&done);
      // Push function.
      __ Push(rax);
      // Pass undefined as the receiver, which is the WithBaseObject of a
      // non-object environment record.  If the callee is sloppy, it will patch
      // it up to be the global receiver.
      __ PushRoot(Heap::kUndefinedValueRootIndex);
      __ bind(&call);
    }
  } else {
    VisitForStackValue(callee);
    // refEnv.WithBaseObject()
2352
    OperandStackDepthIncrement(1);
2353 2354 2355 2356 2357
    __ PushRoot(Heap::kUndefinedValueRootIndex);
  }
}


2358
void FullCodeGenerator::EmitPossiblyEvalCall(Call* expr) {
2359
  // In a call to eval, we first call Runtime_ResolvePossiblyDirectEval
2360 2361 2362 2363 2364
  // to resolve the function we need to call.  Then we call the resolved
  // function using the given arguments.
  ZoneList<Expression*>* args = expr->arguments();
  int arg_count = args->length();
  PushCalleeAndWithBaseObject(expr);
2365

2366 2367 2368 2369
  // Push the arguments.
  for (int i = 0; i < arg_count; i++) {
    VisitForStackValue(args->at(i));
  }
2370

2371 2372 2373
  // Push a copy of the function (found below the arguments) and resolve
  // eval.
  __ Push(Operand(rsp, (arg_count + 1) * kPointerSize));
2374
  EmitResolvePossiblyDirectEval(expr);
2375

2376 2377
  // Touch up the callee.
  __ movp(Operand(rsp, (arg_count + 1) * kPointerSize), rax);
2378

2379
  PrepareForBailoutForId(expr->EvalId(), BailoutState::NO_REGISTERS);
2380

2381
  SetCallPosition(expr);
2382
  __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
2383
  __ Set(rax, arg_count);
2384 2385 2386
  __ Call(isolate()->builtins()->Call(ConvertReceiverMode::kAny,
                                      expr->tail_call_mode()),
          RelocInfo::CODE_TARGET);
2387
  OperandStackDepthDecrement(arg_count + 1);
2388
  RecordJSReturnSite(expr);
2389
  RestoreContext();
2390
  context()->DropAndPlug(1, rax);
2391 2392 2393
}


2394
void FullCodeGenerator::VisitCallNew(CallNew* expr) {
2395 2396 2397 2398 2399
  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.

2400 2401 2402
  // 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.
2403
  DCHECK(!expr->expression()->IsSuperPropertyReference());
2404
  VisitForStackValue(expr->expression());
2405 2406

  // Push the arguments ("left-to-right") on the stack.
2407
  ZoneList<Expression*>* args = expr->arguments();
2408 2409
  int arg_count = args->length();
  for (int i = 0; i < arg_count; i++) {
2410
    VisitForStackValue(args->at(i));
2411 2412 2413 2414
  }

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

2417
  // Load function and argument count into rdi and rax.
2418
  __ Set(rax, arg_count);
2419
  __ movp(rdi, Operand(rsp, arg_count * kPointerSize));
2420

2421
  // Record call targets in unoptimized code, but not in the snapshot.
2422
  __ EmitLoadTypeFeedbackVector(rbx);
2423
  __ Move(rdx, SmiFromSlot(expr->CallNewFeedbackSlot()));
2424

2425 2426
  CallConstructStub stub(isolate());
  __ Call(stub.GetCode(), RelocInfo::CODE_TARGET);
2427
  OperandStackDepthDecrement(arg_count + 1);
2428
  PrepareForBailoutForId(expr->ReturnId(), BailoutState::TOS_REGISTER);
2429
  RestoreContext();
2430
  context()->Plug(rax);
2431 2432 2433
}


2434
void FullCodeGenerator::EmitSuperConstructorCall(Call* expr) {
2435 2436 2437
  SuperCallReference* super_call_ref =
      expr->expression()->AsSuperCallReference();
  DCHECK_NOT_NULL(super_call_ref);
2438

2439 2440 2441 2442 2443 2444
  // Push the super constructor target on the stack (may be null,
  // but the Construct builtin can deal with that properly).
  VisitForAccumulatorValue(super_call_ref->this_function_var());
  __ AssertFunction(result_register());
  __ movp(result_register(),
          FieldOperand(result_register(), HeapObject::kMapOffset));
2445
  PushOperand(FieldOperand(result_register(), Map::kPrototypeOffset));
2446 2447 2448 2449 2450 2451 2452 2453 2454 2455

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

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

2458
  // Load new target into rdx.
2459
  VisitForAccumulatorValue(super_call_ref->new_target_var());
2460
  __ movp(rdx, result_register());
2461 2462

  // Load function and argument count into rdi and rax.
2463 2464 2465
  __ Set(rax, arg_count);
  __ movp(rdi, Operand(rsp, arg_count * kPointerSize));

2466
  __ Call(isolate()->builtins()->Construct(), RelocInfo::CODE_TARGET);
2467
  OperandStackDepthDecrement(arg_count + 1);
2468 2469

  RecordJSReturnSite(expr);
2470
  RestoreContext();
2471 2472 2473 2474
  context()->Plug(rax);
}


2475 2476
void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
2477
  DCHECK(args->length() == 1);
2478

2479
  VisitForAccumulatorValue(args->at(0));
2480 2481 2482 2483

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

2488
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2489 2490 2491
  __ JumpIfSmi(rax, if_true);
  __ jmp(if_false);

2492
  context()->Plug(if_true, if_false);
2493 2494 2495
}


2496
void FullCodeGenerator::EmitIsJSReceiver(CallRuntime* expr) {
2497
  ZoneList<Expression*>* args = expr->arguments();
2498
  DCHECK(args->length() == 1);
2499

2500
  VisitForAccumulatorValue(args->at(0));
2501 2502 2503 2504

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
2505
  Label* fall_through = NULL;
2506 2507
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);
2508 2509

  __ JumpIfSmi(rax, if_false);
2510
  __ CmpObjectType(rax, FIRST_JS_RECEIVER_TYPE, rbx);
2511
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2512
  Split(above_equal, if_true, if_false, fall_through);
2513

2514
  context()->Plug(if_true, if_false);
2515 2516 2517
}


2518 2519
void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
2520
  DCHECK(args->length() == 1);
2521

2522
  VisitForAccumulatorValue(args->at(0));
2523 2524 2525 2526

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
2527
  Label* fall_through = NULL;
2528 2529
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);
2530 2531 2532

  __ JumpIfSmi(rax, if_false);
  __ CmpObjectType(rax, JS_ARRAY_TYPE, rbx);
2533
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2534
  Split(equal, if_true, if_false, fall_through);
2535

2536
  context()->Plug(if_true, if_false);
2537 2538 2539
}


2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
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);
}


2562 2563
void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
2564
  DCHECK(args->length() == 1);
2565

2566
  VisitForAccumulatorValue(args->at(0));
2567 2568 2569 2570

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
2571
  Label* fall_through = NULL;
2572 2573
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);
2574 2575 2576

  __ JumpIfSmi(rax, if_false);
  __ CmpObjectType(rax, JS_REGEXP_TYPE, rbx);
2577
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2578
  Split(equal, if_true, if_false, fall_through);
2579

2580
  context()->Plug(if_true, if_false);
2581 2582 2583
}


2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
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);

2597

2598
  __ JumpIfSmi(rax, if_false);
2599
  __ CmpObjectType(rax, JS_PROXY_TYPE, rbx);
2600
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2601
  Split(equal, if_true, if_false, fall_through);
2602 2603 2604 2605

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

2606

2607 2608
void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
2609 2610
  DCHECK(args->length() == 1);
  Label done, null, function, non_function_constructor;
2611

2612
  VisitForAccumulatorValue(args->at(0));
2613

2614 2615 2616
  // If the object is not a JSReceiver, we return null.
  __ JumpIfSmi(rax, &null, Label::kNear);
  STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
2617
  __ CmpObjectType(rax, FIRST_JS_RECEIVER_TYPE, rax);
2618
  __ j(below, &null, Label::kNear);
2619

2620 2621 2622 2623
  // 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);
2624 2625

  // Check if the constructor in the map is a JS function.
2626 2627
  __ GetMapConstructor(rax, rax, rbx);
  __ CmpInstanceType(rbx, JS_FUNCTION_TYPE);
2628
  __ j(not_equal, &non_function_constructor, Label::kNear);
2629 2630 2631 2632 2633

  // 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));
2634 2635 2636 2637 2638 2639
  __ jmp(&done, Label::kNear);

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

  // Functions have class 'Function'.
  __ bind(&function);
2643 2644
  __ LoadRoot(rax, Heap::kFunction_stringRootIndex);
  __ jmp(&done, Label::kNear);
2645 2646

  // Objects with a non-function constructor have class 'Object'.
2647
  __ bind(&non_function_constructor);
2648
  __ LoadRoot(rax, Heap::kObject_stringRootIndex);
2649 2650 2651 2652

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

2653
  context()->Plug(rax);
2654 2655 2656
}


2657 2658
void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
2659
  DCHECK(args->length() == 1);
2660

2661
  VisitForAccumulatorValue(args->at(0));
2662

2663 2664 2665 2666
  Label done;
  StringCharFromCodeGenerator generator(rax, rbx);
  generator.GenerateFast(masm_);
  __ jmp(&done);
2667

2668 2669
  NopRuntimeCallHelper call_helper;
  generator.GenerateSlow(masm_, call_helper);
2670

2671
  __ bind(&done);
2672
  context()->Plug(rbx);
2673 2674 2675
}


2676 2677
void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
2678
  DCHECK(args->length() == 2);
2679

2680 2681
  VisitForStackValue(args->at(0));
  VisitForAccumulatorValue(args->at(1));
2682 2683 2684 2685 2686

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

2687
  PopOperand(object);
2688 2689 2690 2691

  Label need_conversion;
  Label index_out_of_range;
  Label done;
2692 2693
  StringCharCodeAtGenerator generator(object, index, result, &need_conversion,
                                      &need_conversion, &index_out_of_range);
2694
  generator.GenerateFast(masm_);
2695 2696
  __ jmp(&done);

2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
  __ 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;
2710
  generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
2711 2712

  __ bind(&done);
2713
  context()->Plug(result);
2714 2715 2716
}


2717 2718 2719 2720 2721 2722 2723
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);
  }
2724
  PrepareForBailoutForId(expr->CallId(), BailoutState::NO_REGISTERS);
2725 2726 2727 2728 2729 2730
  // 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);
2731
  OperandStackDepthDecrement(argc + 1);
2732
  RestoreContext();
2733 2734 2735 2736 2737
  // Discard the function left on TOS.
  context()->DropAndPlug(1, rax);
}


2738 2739
void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
2740
  DCHECK(args->length() == 1);
2741

2742
  VisitForAccumulatorValue(args->at(0));
2743 2744 2745 2746 2747

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
2748 2749
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);
2750 2751 2752

  __ testl(FieldOperand(rax, String::kHashFieldOffset),
           Immediate(String::kContainsCachedArrayIndexMask));
2753
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
2754 2755 2756
  __ j(zero, if_true);
  __ jmp(if_false);

2757
  context()->Plug(if_true, if_false);
2758 2759 2760
}


2761 2762
void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
2763
  DCHECK(args->length() == 1);
2764
  VisitForAccumulatorValue(args->at(0));
2765

2766
  __ AssertString(rax);
2767

2768
  __ movl(rax, FieldOperand(rax, String::kHashFieldOffset));
2769
  DCHECK(String::kHashShift >= kSmiTagSize);
2770 2771
  __ IndexFromHash(rax, rax);

2772
  context()->Plug(rax);
2773 2774 2775
}


2776 2777 2778 2779 2780 2781 2782 2783
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);
2784
}
2785

2786
void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
2787
  DCHECK(expr->arguments()->length() == 0);
2788 2789 2790 2791 2792 2793 2794 2795 2796
  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);
}


2797 2798 2799 2800 2801 2802 2803 2804
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;

2805 2806
  __ Allocate(JSIteratorResult::kSize, rax, rcx, rdx, &runtime,
              NO_ALLOCATION_FLAGS);
2807
  __ LoadNativeContextSlot(Context::ITERATOR_RESULT_MAP_INDEX, rbx);
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
  __ 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);
2818
  CallRuntimeWithOperands(Runtime::kCreateIterResultObject);
2819 2820 2821 2822 2823 2824

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


2825
void FullCodeGenerator::EmitLoadJSRuntimeFunction(CallRuntime* expr) {
2826 2827 2828 2829 2830
  // Push function.
  __ LoadNativeContextSlot(expr->context_index(), rax);
  PushOperand(rax);

  // Push undefined as receiver.
2831
  OperandStackDepthIncrement(1);
2832
  __ PushRoot(Heap::kUndefinedValueRootIndex);
2833 2834 2835 2836 2837 2838 2839
}


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

2840
  SetCallPosition(expr);
2841
  __ movp(rdi, Operand(rsp, (arg_count + 1) * kPointerSize));
2842
  __ Set(rax, arg_count);
2843 2844
  __ Call(isolate()->builtins()->Call(ConvertReceiverMode::kNullOrUndefined),
          RelocInfo::CODE_TARGET);
2845
  OperandStackDepthDecrement(arg_count + 1);
2846
  RestoreContext();
2847 2848 2849
}


2850
void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
2851
  switch (expr->op()) {
2852 2853
    case Token::DELETE: {
      Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
2854 2855
      Property* property = expr->expression()->AsProperty();
      VariableProxy* proxy = expr->expression()->AsVariableProxy();
2856

2857 2858 2859
      if (property != NULL) {
        VisitForStackValue(property->obj());
        VisitForStackValue(property->key());
2860 2861 2862
        CallRuntimeWithOperands(is_strict(language_mode())
                                    ? Runtime::kDeleteProperty_Strict
                                    : Runtime::kDeleteProperty_Sloppy);
2863
        context()->Plug(rax);
2864 2865
      } else if (proxy != NULL) {
        Variable* var = proxy->var();
2866 2867
        // Delete of an unqualified identifier is disallowed in strict mode but
        // "delete this" is allowed.
2868
        bool is_this = var->is_this();
2869
        DCHECK(is_sloppy(language_mode()) || is_this);
2870
        if (var->IsUnallocated()) {
2871 2872
          __ movp(rax, NativeContextOperand());
          __ Push(ContextOperand(rax, Context::EXTENSION_INDEX));
2873
          __ Push(var->name());
2874
          __ CallRuntime(Runtime::kDeleteProperty_Sloppy);
2875
          context()->Plug(rax);
2876 2877 2878 2879
        } else if (var->IsStackAllocated() || var->IsContextSlot()) {
          // 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.
2880
          context()->Plug(is_this);
2881 2882 2883 2884
        } else {
          // Non-global variable.  Call the runtime to try to delete from the
          // context where the variable was introduced.
          __ Push(var->name());
2885
          __ CallRuntime(Runtime::kDeleteLookupSlot);
2886 2887
          context()->Plug(rax);
        }
2888
      } else {
2889 2890 2891 2892
        // Result of deleting non-property, non-variable reference is true.
        // The subexpression may have side effects.
        VisitForEffect(expr->expression());
        context()->Plug(true);
2893 2894 2895 2896
      }
      break;
    }

2897 2898
    case Token::VOID: {
      Comment cmnt(masm_, "[ UnaryOperation (VOID)");
2899
      VisitForEffect(expr->expression());
2900
      context()->Plug(Heap::kUndefinedValueRootIndex);
2901
      break;
2902
    }
2903

2904
    case Token::NOT: {
2905
      Comment cmnt(masm_, "[ UnaryOperation (NOT)");
2906 2907 2908 2909
      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());
2910 2911 2912 2913 2914 2915 2916 2917
      } 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());
2918
      } else {
2919 2920 2921 2922
        // 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.
2923
        DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
2924 2925 2926 2927 2928
        Label materialize_true, materialize_false, done;
        VisitForControl(expr->expression(),
                        &materialize_false,
                        &materialize_true,
                        &materialize_true);
2929
        if (!context()->IsAccumulatorValue()) OperandStackDepthIncrement(1);
2930
        __ bind(&materialize_true);
2931 2932
        PrepareForBailoutForId(expr->MaterializeTrueId(),
                               BailoutState::NO_REGISTERS);
2933 2934 2935 2936 2937 2938 2939
        if (context()->IsAccumulatorValue()) {
          __ LoadRoot(rax, Heap::kTrueValueRootIndex);
        } else {
          __ PushRoot(Heap::kTrueValueRootIndex);
        }
        __ jmp(&done, Label::kNear);
        __ bind(&materialize_false);
2940 2941
        PrepareForBailoutForId(expr->MaterializeFalseId(),
                               BailoutState::NO_REGISTERS);
2942 2943 2944 2945 2946 2947
        if (context()->IsAccumulatorValue()) {
          __ LoadRoot(rax, Heap::kFalseValueRootIndex);
        } else {
          __ PushRoot(Heap::kFalseValueRootIndex);
        }
        __ bind(&done);
2948
      }
2949
      break;
2950 2951 2952 2953
    }

    case Token::TYPEOF: {
      Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
2954 2955
      {
        AccumulatorValueContext context(this);
2956 2957
        VisitForTypeofValue(expr->expression());
      }
2958 2959 2960
      __ movp(rbx, rax);
      TypeofStub typeof_stub(isolate());
      __ CallStub(&typeof_stub);
2961
      context()->Plug(rax);
2962
      break;
2963 2964
    }

2965 2966 2967 2968 2969 2970
    default:
      UNREACHABLE();
  }
}


2971
void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
2972
  DCHECK(expr->expression()->IsValidReferenceExpressionOrThis());
2973

2974 2975 2976
  Comment cmnt(masm_, "[ CountOperation");

  Property* prop = expr->expression()->AsProperty();
2977
  LhsKind assign_type = Property::GetAssignType(prop);
2978 2979 2980

  // Evaluate expression and get value.
  if (assign_type == VARIABLE) {
2981
    DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
2982
    AccumulatorValueContext context(this);
2983
    EmitVariableLoad(expr->expression()->AsVariableProxy());
2984
  } else {
2985
    // Reserve space for result of postfix operation.
2986
    if (expr->is_postfix() && !context()->IsEffect()) {
2987
      PushOperand(Smi::FromInt(0));
2988
    }
2989 2990 2991 2992 2993 2994 2995 2996 2997
    switch (assign_type) {
      case NAMED_PROPERTY: {
        VisitForStackValue(prop->obj());
        __ movp(LoadDescriptor::ReceiverRegister(), Operand(rsp, 0));
        EmitNamedPropertyLoad(prop);
        break;
      }

      case NAMED_SUPER_PROPERTY: {
2998
        VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
2999
        VisitForAccumulatorValue(
3000
            prop->obj()->AsSuperPropertyReference()->home_object());
3001 3002 3003
        PushOperand(result_register());
        PushOperand(MemOperand(rsp, kPointerSize));
        PushOperand(result_register());
3004 3005 3006 3007 3008
        EmitNamedSuperPropertyLoad(prop);
        break;
      }

      case KEYED_SUPER_PROPERTY: {
3009 3010
        VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
        VisitForStackValue(
3011
            prop->obj()->AsSuperPropertyReference()->home_object());
3012
        VisitForAccumulatorValue(prop->key());
3013 3014 3015 3016
        PushOperand(result_register());
        PushOperand(MemOperand(rsp, 2 * kPointerSize));
        PushOperand(MemOperand(rsp, 2 * kPointerSize));
        PushOperand(result_register());
3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033
        EmitKeyedSuperPropertyLoad(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;
      }

      case VARIABLE:
        UNREACHABLE();
3034 3035 3036
    }
  }

3037 3038
  // We need a second deoptimization point after loading the value
  // in case evaluating the property load my have a side effect.
3039
  if (assign_type == VARIABLE) {
3040
    PrepareForBailout(expr->expression(), BailoutState::TOS_REGISTER);
3041
  } else {
3042
    PrepareForBailoutForId(prop->LoadId(), BailoutState::TOS_REGISTER);
3043
  }
3044

3045 3046 3047
  // Inline smi case if we are in a loop.
  Label done, stub_call;
  JumpPatchSite patch_site(masm_);
3048
  if (ShouldInlineSmiCase(expr->op())) {
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059
    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:
3060
            __ Push(rax);
3061 3062
            break;
          case NAMED_PROPERTY:
3063
            __ movp(Operand(rsp, kPointerSize), rax);
3064
            break;
3065 3066 3067
          case NAMED_SUPER_PROPERTY:
            __ movp(Operand(rsp, 2 * kPointerSize), rax);
            break;
3068
          case KEYED_PROPERTY:
3069
            __ movp(Operand(rsp, 2 * kPointerSize), rax);
3070
            break;
3071 3072 3073
          case KEYED_SUPER_PROPERTY:
            __ movp(Operand(rsp, 3 * kPointerSize), rax);
            break;
3074 3075 3076 3077
        }
      }
    }

3078 3079 3080
    SmiOperationConstraints constraints =
        SmiOperationConstraint::kPreserveSourceRegister |
        SmiOperationConstraint::kBailoutOnNoOverflow;
3081
    if (expr->op() == Token::INC) {
3082 3083
      __ SmiAddConstant(rax, rax, Smi::FromInt(1), constraints, &done,
                        Label::kNear);
3084
    } else {
3085 3086
      __ SmiSubConstant(rax, rax, Smi::FromInt(1), constraints, &done,
                        Label::kNear);
3087 3088 3089
    }
    __ jmp(&stub_call, Label::kNear);
    __ bind(&slow);
3090
  }
3091 3092

  // Convert old value into a number.
3093
  __ Call(isolate()->builtins()->ToNumber(), RelocInfo::CODE_TARGET);
3094
  RestoreContext();
3095
  PrepareForBailoutForId(expr->ToNumberId(), BailoutState::TOS_REGISTER);
3096 3097 3098

  // Save result for postfix expressions.
  if (expr->is_postfix()) {
3099 3100 3101 3102 3103 3104
    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:
3105
          PushOperand(rax);
3106 3107
          break;
        case NAMED_PROPERTY:
3108
          __ movp(Operand(rsp, kPointerSize), rax);
3109
          break;
3110 3111 3112
        case NAMED_SUPER_PROPERTY:
          __ movp(Operand(rsp, 2 * kPointerSize), rax);
          break;
3113
        case KEYED_PROPERTY:
3114
          __ movp(Operand(rsp, 2 * kPointerSize), rax);
3115
          break;
3116 3117 3118
        case KEYED_SUPER_PROPERTY:
          __ movp(Operand(rsp, 3 * kPointerSize), rax);
          break;
3119
      }
3120 3121 3122
    }
  }

3123
  SetExpressionPosition(expr);
3124

3125
  // Call stub for +1/-1.
3126
  __ bind(&stub_call);
3127
  __ movp(rdx, rax);
3128
  __ Move(rax, Smi::FromInt(1));
3129 3130
  Handle<Code> code =
      CodeFactory::BinaryOpIC(isolate(), expr->binary_op()).code();
3131
  CallIC(code, expr->CountBinOpFeedbackId());
3132
  patch_site.EmitPatchInfo();
3133
  __ bind(&done);
3134

3135 3136 3137 3138
  // Store the value returned in rax.
  switch (assign_type) {
    case VARIABLE:
      if (expr->is_postfix()) {
3139
        // Perform the assignment as if via '='.
3140 3141
        { EffectContext context(this);
          EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
3142
                                 Token::ASSIGN, expr->CountSlot());
3143 3144
          PrepareForBailoutForId(expr->AssignmentId(),
                                 BailoutState::TOS_REGISTER);
3145
          context.Plug(rax);
3146
        }
3147 3148
        // For all contexts except kEffect: We have the result on
        // top of the stack.
3149 3150
        if (!context()->IsEffect()) {
          context()->PlugTOS();
3151 3152
        }
      } else {
3153
        // Perform the assignment as if via '='.
3154
        EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
3155
                               Token::ASSIGN, expr->CountSlot());
3156 3157
        PrepareForBailoutForId(expr->AssignmentId(),
                               BailoutState::TOS_REGISTER);
3158
        context()->Plug(rax);
3159 3160 3161
      }
      break;
    case NAMED_PROPERTY: {
3162
      PopOperand(StoreDescriptor::ReceiverRegister());
3163
      CallStoreIC(expr->CountSlot(), prop->key()->AsLiteral()->value());
3164
      PrepareForBailoutForId(expr->AssignmentId(), BailoutState::TOS_REGISTER);
3165
      if (expr->is_postfix()) {
3166 3167
        if (!context()->IsEffect()) {
          context()->PlugTOS();
3168 3169
        }
      } else {
3170
        context()->Plug(rax);
3171 3172 3173
      }
      break;
    }
3174 3175
    case NAMED_SUPER_PROPERTY: {
      EmitNamedSuperPropertyStore(prop);
3176
      PrepareForBailoutForId(expr->AssignmentId(), BailoutState::TOS_REGISTER);
3177 3178 3179 3180 3181 3182 3183 3184 3185
      if (expr->is_postfix()) {
        if (!context()->IsEffect()) {
          context()->PlugTOS();
        }
      } else {
        context()->Plug(rax);
      }
      break;
    }
3186 3187
    case KEYED_SUPER_PROPERTY: {
      EmitKeyedSuperPropertyStore(prop);
3188
      PrepareForBailoutForId(expr->AssignmentId(), BailoutState::TOS_REGISTER);
3189 3190 3191 3192 3193 3194 3195 3196 3197
      if (expr->is_postfix()) {
        if (!context()->IsEffect()) {
          context()->PlugTOS();
        }
      } else {
        context()->Plug(rax);
      }
      break;
    }
3198
    case KEYED_PROPERTY: {
3199 3200
      PopOperand(StoreDescriptor::NameRegister());
      PopOperand(StoreDescriptor::ReceiverRegister());
3201
      CallKeyedStoreIC(expr->CountSlot());
3202
      PrepareForBailoutForId(expr->AssignmentId(), BailoutState::TOS_REGISTER);
3203
      if (expr->is_postfix()) {
3204 3205
        if (!context()->IsEffect()) {
          context()->PlugTOS();
3206 3207
        }
      } else {
3208
        context()->Plug(rax);
3209 3210 3211 3212 3213 3214
      }
      break;
    }
  }
}

3215

3216
void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
3217
                                                 Expression* sub_expr,
3218 3219 3220 3221 3222 3223 3224 3225
                                                 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);

3226
  { AccumulatorValueContext context(this);
3227
    VisitForTypeofValue(sub_expr);
3228
  }
3229
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3230

3231 3232
  Factory* factory = isolate()->factory();
  if (String::Equals(check, factory->number_string())) {
3233
    __ JumpIfSmi(rax, if_true);
3234
    __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));
3235 3236
    __ CompareRoot(rax, Heap::kHeapNumberMapRootIndex);
    Split(equal, if_true, if_false, fall_through);
3237
  } else if (String::Equals(check, factory->string_string())) {
3238 3239
    __ JumpIfSmi(rax, if_false);
    __ CmpObjectType(rax, FIRST_NONSTRING_TYPE, rdx);
3240
    Split(below, if_true, if_false, fall_through);
3241
  } else if (String::Equals(check, factory->symbol_string())) {
3242 3243 3244
    __ JumpIfSmi(rax, if_false);
    __ CmpObjectType(rax, SYMBOL_TYPE, rdx);
    Split(equal, if_true, if_false, fall_through);
3245
  } else if (String::Equals(check, factory->boolean_string())) {
3246 3247 3248 3249
    __ CompareRoot(rax, Heap::kTrueValueRootIndex);
    __ j(equal, if_true);
    __ CompareRoot(rax, Heap::kFalseValueRootIndex);
    Split(equal, if_true, if_false, fall_through);
3250
  } else if (String::Equals(check, factory->undefined_string())) {
3251 3252
    __ CompareRoot(rax, Heap::kNullValueRootIndex);
    __ j(equal, if_false);
3253
    __ JumpIfSmi(rax, if_false);
3254
    // Check for undetectable objects => true.
3255
    __ movp(rdx, FieldOperand(rax, HeapObject::kMapOffset));
3256 3257 3258
    __ testb(FieldOperand(rdx, Map::kBitFieldOffset),
             Immediate(1 << Map::kIsUndetectable));
    Split(not_zero, if_true, if_false, fall_through);
3259
  } else if (String::Equals(check, factory->function_string())) {
3260
    __ JumpIfSmi(rax, if_false);
3261 3262 3263 3264 3265 3266
    // 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));
3267
    Split(equal, if_true, if_false, fall_through);
3268
  } else if (String::Equals(check, factory->object_string())) {
3269
    __ JumpIfSmi(rax, if_false);
3270 3271
    __ CompareRoot(rax, Heap::kNullValueRootIndex);
    __ j(equal, if_true);
3272 3273
    STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
    __ CmpObjectType(rax, FIRST_JS_RECEIVER_TYPE, rdx);
3274
    __ j(below, if_false);
3275
    // Check for callable or undetectable objects => false.
3276
    __ testb(FieldOperand(rdx, Map::kBitFieldOffset),
3277
             Immediate((1 << Map::kIsCallable) | (1 << Map::kIsUndetectable)));
3278
    Split(zero, if_true, if_false, fall_through);
3279 3280 3281 3282 3283 3284 3285 3286 3287 3288
// clang-format off
#define SIMD128_TYPE(TYPE, Type, type, lane_count, lane_type)   \
  } else if (String::Equals(check, factory->type##_string())) { \
    __ JumpIfSmi(rax, if_false);                                \
    __ movp(rax, FieldOperand(rax, HeapObject::kMapOffset));    \
    __ CompareRoot(rax, Heap::k##Type##MapRootIndex);           \
    Split(equal, if_true, if_false, fall_through);
  SIMD128_TYPES(SIMD128_TYPE)
#undef SIMD128_TYPE
    // clang-format on
3289 3290
  } else {
    if (if_false != fall_through) __ jmp(if_false);
3291
  }
3292
  context()->Plug(if_true, if_false);
3293
}
3294 3295


3296
void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
3297
  Comment cmnt(masm_, "[ CompareOperation");
3298

3299 3300 3301 3302
  // First we try a fast inlined version of the compare when one of
  // the operands is a literal.
  if (TryLiteralCompare(expr)) return;

3303 3304
  // Always perform the comparison for its control flow.  Pack the result
  // into the expression's context after the comparison is performed.
3305 3306 3307
  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
3308
  Label* fall_through = NULL;
3309 3310
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);
3311

3312
  Token::Value op = expr->op();
3313
  VisitForStackValue(expr->left());
3314
  switch (op) {
3315
    case Token::IN:
3316
      VisitForStackValue(expr->right());
3317
      SetExpressionPosition(expr);
3318
      EmitHasProperty();
3319
      PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
3320
      __ CompareRoot(rax, Heap::kTrueValueRootIndex);
3321
      Split(equal, if_true, if_false, fall_through);
3322 3323 3324
      break;

    case Token::INSTANCEOF: {
3325
      VisitForAccumulatorValue(expr->right());
3326
      SetExpressionPosition(expr);
3327
      PopOperand(rdx);
3328
      InstanceOfStub stub(isolate());
3329
      __ CallStub(&stub);
3330 3331 3332
      PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
      __ CompareRoot(rax, Heap::kTrueValueRootIndex);
      Split(equal, if_true, if_false, fall_through);
3333 3334 3335 3336
      break;
    }

    default: {
3337
      VisitForAccumulatorValue(expr->right());
3338
      SetExpressionPosition(expr);
3339
      Condition cc = CompareIC::ComputeCondition(op);
3340
      PopOperand(rdx);
3341

3342
      bool inline_smi_code = ShouldInlineSmiCase(op);
3343
      JumpPatchSite patch_site(masm_);
3344
      if (inline_smi_code) {
3345
        Label slow_case;
3346
        __ movp(rcx, rdx);
3347
        __ orp(rcx, rax);
3348
        patch_site.EmitJumpIfNotSmi(rcx, &slow_case, Label::kNear);
3349
        __ cmpp(rdx, rax);
3350 3351 3352
        Split(cc, if_true, if_false, NULL);
        __ bind(&slow_case);
      }
3353

3354
      Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
3355
      CallIC(ic, expr->CompareOperationFeedbackId());
3356
      patch_site.EmitPatchInfo();
3357

3358
      PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3359
      __ testp(rax, rax);
3360
      Split(cc, if_true, if_false, fall_through);
3361 3362 3363
    }
  }

3364 3365
  // Convert the result of the comparison into one expected for this
  // expression's context.
3366
  context()->Plug(if_true, if_false);
3367 3368 3369
}


3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380
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);
3381
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3382
  if (expr->op() == Token::EQ_STRICT) {
3383 3384 3385 3386
    Heap::RootListIndex nil_value = nil == kNullValue ?
        Heap::kNullValueRootIndex :
        Heap::kUndefinedValueRootIndex;
    __ CompareRoot(rax, nil_value);
3387
    Split(equal, if_true, if_false, fall_through);
3388
  } else {
3389 3390 3391 3392 3393
    __ 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);
3394
  }
3395
  context()->Plug(if_true, if_false);
3396 3397 3398
}


3399 3400 3401 3402 3403 3404 3405 3406 3407
Register FullCodeGenerator::result_register() {
  return rax;
}


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

3408 3409 3410 3411
void FullCodeGenerator::LoadFromFrameField(int frame_offset, Register value) {
  DCHECK(IsAligned(frame_offset, kPointerSize));
  __ movp(value, Operand(rbp, frame_offset));
}
3412

3413
void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
3414
  DCHECK(IsAligned(frame_offset, kPointerSize));
3415
  __ movp(Operand(rbp, frame_offset), value);
3416 3417 3418
}


3419
void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
3420
  __ movp(dst, ContextOperand(rsi, context_index));
3421 3422 3423
}


3424
void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
3425
  DeclarationScope* closure_scope = scope()->GetClosureScope();
3426 3427
  if (closure_scope->is_script_scope() ||
      closure_scope->is_module_scope()) {
3428
    // Contexts nested in the native context have a canonical empty function
3429
    // as their closure, not the anonymous closure containing the global
3430
    // code.
3431
    __ movp(rax, NativeContextOperand());
3432
    PushOperand(ContextOperand(rax, Context::CLOSURE_INDEX));
3433
  } else if (closure_scope->is_eval_scope()) {
3434 3435 3436
    // 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.
3437
    PushOperand(ContextOperand(rsi, Context::CLOSURE_INDEX));
3438
  } else {
3439
    DCHECK(closure_scope->is_function_scope());
3440
    PushOperand(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
3441 3442 3443 3444
  }
}


3445 3446 3447 3448
// ----------------------------------------------------------------------------
// Non-local control flow support.


3449
void FullCodeGenerator::EnterFinallyBlock() {
3450
  DCHECK(!result_register().is(rdx));
3451 3452 3453 3454 3455

  // Store pending message while executing finally block.
  ExternalReference pending_message_obj =
      ExternalReference::address_of_pending_message_obj(isolate());
  __ Load(rdx, pending_message_obj);
3456
  PushOperand(rdx);
3457 3458

  ClearPendingMessage();
3459 3460 3461
}


3462
void FullCodeGenerator::ExitFinallyBlock() {
3463
  DCHECK(!result_register().is(rdx));
3464
  // Restore pending message from stack.
3465
  PopOperand(rdx);
3466 3467 3468
  ExternalReference pending_message_obj =
      ExternalReference::address_of_pending_message_obj(isolate());
  __ Store(pending_message_obj, rdx);
3469 3470 3471
}


3472 3473 3474 3475 3476 3477 3478 3479 3480
void FullCodeGenerator::ClearPendingMessage() {
  DCHECK(!result_register().is(rdx));
  ExternalReference pending_message_obj =
      ExternalReference::address_of_pending_message_obj(isolate());
  __ LoadRoot(rdx, Heap::kTheHoleValueRootIndex);
  __ Store(pending_message_obj, rdx);
}


3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505
void FullCodeGenerator::DeferredCommands::EmitCommands() {
  __ Pop(result_register());  // Restore the accumulator.
  __ Pop(rdx);                // Get the token.
  for (DeferredCommand cmd : commands_) {
    Label skip;
    __ SmiCompare(rdx, Smi::FromInt(cmd.token));
    __ j(not_equal, &skip);
    switch (cmd.command) {
      case kReturn:
        codegen_->EmitUnwindAndReturn();
        break;
      case kThrow:
        __ Push(result_register());
        __ CallRuntime(Runtime::kReThrow);
        break;
      case kContinue:
        codegen_->EmitContinue(cmd.target);
        break;
      case kBreak:
        codegen_->EmitBreak(cmd.target);
        break;
    }
    __ bind(&skip);
  }
}
3506

3507
#undef __
3508

3509 3510 3511 3512

static const byte kJnsInstruction = 0x79;
static const byte kNopByteOne = 0x66;
static const byte kNopByteTwo = 0x90;
3513 3514 3515
#ifdef DEBUG
static const byte kCallInstruction = 0xe8;
#endif
3516 3517 3518


void BackEdgeTable::PatchAt(Code* unoptimized_code,
3519 3520
                            Address pc,
                            BackEdgeState target_state,
3521
                            Code* replacement_code) {
3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545
  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;
  }

3546 3547
  Assembler::set_target_address_at(unoptimized_code->GetIsolate(),
                                   call_target_address, unoptimized_code,
3548 3549 3550 3551 3552 3553 3554 3555 3556
                                   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,
3557 3558 3559
    Address pc) {
  Address call_target_address = pc - kIntSize;
  Address jns_instr_address = call_target_address - 3;
3560
  DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
3561 3562

  if (*jns_instr_address == kJnsInstruction) {
3563 3564
    DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
    DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
3565 3566
              Assembler::target_address_at(call_target_address,
                                           unoptimized_code));
3567 3568
    return INTERRUPT;
  }
3569

3570 3571
  DCHECK_EQ(kNopByteOne, *jns_instr_address);
  DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
3572

3573 3574 3575 3576
  DCHECK_EQ(
      isolate->builtins()->OnStackReplacement()->entry(),
      Assembler::target_address_at(call_target_address, unoptimized_code));
  return ON_STACK_REPLACEMENT;
3577 3578
}

3579 3580
}  // namespace internal
}  // namespace v8
3581 3582

#endif  // V8_TARGET_ARCH_X64