lithium-codegen-x87.cc 208 KB
Newer Older
danno@chromium.org's avatar
danno@chromium.org committed
1 2 3 4
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/v8.h"
danno@chromium.org's avatar
danno@chromium.org committed
6 7 8

#if V8_TARGET_ARCH_X87

9
#include "src/base/bits.h"
10
#include "src/code-factory.h"
11 12
#include "src/code-stubs.h"
#include "src/codegen.h"
13
#include "src/cpu-profiler.h"
14
#include "src/deoptimizer.h"
15
#include "src/hydrogen-osr.h"
16
#include "src/ic/ic.h"
17
#include "src/ic/stub-cache.h"
18
#include "src/x87/lithium-codegen-x87.h"
danno@chromium.org's avatar
danno@chromium.org committed
19 20 21 22 23 24 25

namespace v8 {
namespace internal {


// When invoking builtins, we need to record the safepoint in the middle of
// the invoke instruction sequence generated by the macro assembler.
26
class SafepointGenerator FINAL : public CallWrapper {
danno@chromium.org's avatar
danno@chromium.org committed
27 28 29 30 31 32 33 34 35
 public:
  SafepointGenerator(LCodeGen* codegen,
                     LPointerMap* pointers,
                     Safepoint::DeoptMode mode)
      : codegen_(codegen),
        pointers_(pointers),
        deopt_mode_(mode) {}
  virtual ~SafepointGenerator() {}

36
  void BeforeCall(int call_size) const OVERRIDE {}
danno@chromium.org's avatar
danno@chromium.org committed
37

38
  void AfterCall() const OVERRIDE {
danno@chromium.org's avatar
danno@chromium.org committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52
    codegen_->RecordSafepoint(pointers_, deopt_mode_);
  }

 private:
  LCodeGen* codegen_;
  LPointerMap* pointers_;
  Safepoint::DeoptMode deopt_mode_;
};


#define __ masm()->

bool LCodeGen::GenerateCode() {
  LPhase phase("Z_Code generation", chunk());
53
  DCHECK(is_unused());
danno@chromium.org's avatar
danno@chromium.org committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
  status_ = GENERATING;

  // 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 in GeneratePrologue).
  FrameScope frame_scope(masm_, StackFrame::MANUAL);

  support_aligned_spilled_doubles_ = info()->IsOptimizing();

  dynamic_frame_alignment_ = info()->IsOptimizing() &&
      ((chunk()->num_double_slots() > 2 &&
        !chunk()->graph()->is_recursive()) ||
       !info()->osr_ast_id().IsNone());

  return GeneratePrologue() &&
      GenerateBody() &&
      GenerateDeferredCode() &&
      GenerateJumpTable() &&
      GenerateSafepointTable();
}


void LCodeGen::FinishCode(Handle<Code> code) {
77
  DCHECK(is_done());
danno@chromium.org's avatar
danno@chromium.org committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  code->set_stack_slots(GetStackSlotCount());
  code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
  PopulateDeoptimizationData(code);
  if (!info()->IsStub()) {
    Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(code);
  }
}


#ifdef _MSC_VER
void LCodeGen::MakeSureStackPagesMapped(int offset) {
  const int kPageSize = 4 * KB;
  for (offset -= kPageSize; offset > 0; offset -= kPageSize) {
    __ mov(Operand(esp, offset), eax);
  }
}
#endif


bool LCodeGen::GeneratePrologue() {
98
  DCHECK(is_generating());
danno@chromium.org's avatar
danno@chromium.org committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112

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

#ifdef DEBUG
    if (strlen(FLAG_stop_at) > 0 &&
        info_->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
      __ int3();
    }
#endif

    // Sloppy mode functions and builtins need to replace the receiver with the
    // global proxy when called as functions (without an explicit receiver
    // object).
113
    if (graph()->this_has_uses() && is_sloppy(info_->language_mode()) &&
danno@chromium.org's avatar
danno@chromium.org committed
114 115 116 117 118 119 120 121 122 123
        !info_->is_native()) {
      Label ok;
      // +1 for return address.
      int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
      __ mov(ecx, Operand(esp, receiver_offset));

      __ cmp(ecx, isolate()->factory()->undefined_value());
      __ j(not_equal, &ok, Label::kNear);

      __ mov(ecx, GlobalObjectOperand());
124
      __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
danno@chromium.org's avatar
danno@chromium.org committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

      __ mov(Operand(esp, receiver_offset), ecx);

      __ bind(&ok);
    }

    if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
      // Move state of dynamic frame alignment into edx.
      __ Move(edx, Immediate(kNoAlignmentPadding));

      Label do_not_pad, align_loop;
      STATIC_ASSERT(kDoubleSize == 2 * kPointerSize);
      // Align esp + 4 to a multiple of 2 * kPointerSize.
      __ test(esp, Immediate(kPointerSize));
      __ j(not_zero, &do_not_pad, Label::kNear);
      __ push(Immediate(0));
      __ mov(ebx, esp);
      __ mov(edx, Immediate(kAlignmentPaddingPushed));
      // Copy arguments, receiver, and return address.
      __ mov(ecx, Immediate(scope()->num_parameters() + 2));

      __ bind(&align_loop);
      __ mov(eax, Operand(ebx, 1 * kPointerSize));
      __ mov(Operand(ebx, 0), eax);
      __ add(Operand(ebx), Immediate(kPointerSize));
      __ dec(ecx);
      __ j(not_zero, &align_loop, Label::kNear);
      __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
      __ bind(&do_not_pad);
    }
  }

  info()->set_prologue_offset(masm_->pc_offset());
  if (NeedsEagerFrame()) {
159
    DCHECK(!frame_is_built_);
danno@chromium.org's avatar
danno@chromium.org committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    frame_is_built_ = true;
    if (info()->IsStub()) {
      __ StubPrologue();
    } else {
      __ Prologue(info()->IsCodePreAgingActive());
    }
    info()->AddNoFrameRange(0, masm_->pc_offset());
  }

  if (info()->IsOptimizing() &&
      dynamic_frame_alignment_ &&
      FLAG_debug_code) {
    __ test(esp, Immediate(kPointerSize));
    __ Assert(zero, kFrameIsExpectedToBeAligned);
  }

  // Reserve space for the stack slots needed by the code.
  int slots = GetStackSlotCount();
178
  DCHECK(slots != 0 || !info()->IsOptimizing());
danno@chromium.org's avatar
danno@chromium.org committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
  if (slots > 0) {
    if (slots == 1) {
      if (dynamic_frame_alignment_) {
        __ push(edx);
      } else {
        __ push(Immediate(kNoAlignmentPadding));
      }
    } else {
      if (FLAG_debug_code) {
        __ sub(Operand(esp), Immediate(slots * kPointerSize));
#ifdef _MSC_VER
        MakeSureStackPagesMapped(slots * kPointerSize);
#endif
        __ push(eax);
        __ mov(Operand(eax), Immediate(slots));
        Label loop;
        __ bind(&loop);
        __ mov(MemOperand(esp, eax, times_4, 0),
               Immediate(kSlotsZapValue));
        __ dec(eax);
        __ j(not_zero, &loop);
        __ pop(eax);
      } else {
        __ sub(Operand(esp), Immediate(slots * kPointerSize));
#ifdef _MSC_VER
        MakeSureStackPagesMapped(slots * kPointerSize);
#endif
      }

      if (support_aligned_spilled_doubles_) {
        Comment(";;; Store dynamic frame alignment tag for spilled doubles");
        // Store dynamic frame alignment state in the first local.
        int offset = JavaScriptFrameConstants::kDynamicAlignmentStateOffset;
        if (dynamic_frame_alignment_) {
          __ mov(Operand(ebp, offset), edx);
        } else {
          __ mov(Operand(ebp, offset), Immediate(kNoAlignmentPadding));
        }
      }
    }
  }

  // Possibly allocate a local context.
  int heap_slots = info_->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
  if (heap_slots > 0) {
    Comment(";;; Allocate local context");
225
    bool need_write_barrier = true;
danno@chromium.org's avatar
danno@chromium.org committed
226
    // Argument to NewContext is the function, which is still in edi.
227
    DCHECK(!info()->scope()->is_script_scope());
danno@chromium.org's avatar
danno@chromium.org committed
228 229 230
    if (heap_slots <= FastNewContextStub::kMaximumSlots) {
      FastNewContextStub stub(isolate(), heap_slots);
      __ CallStub(&stub);
231 232
      // Result of FastNewContextStub is always in new space.
      need_write_barrier = false;
danno@chromium.org's avatar
danno@chromium.org committed
233 234
    } else {
      __ push(edi);
235
      __ CallRuntime(Runtime::kNewFunctionContext, 1);
danno@chromium.org's avatar
danno@chromium.org committed
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    }
    RecordSafepoint(Safepoint::kNoLazyDeopt);
    // Context is returned in eax.  It replaces the context passed to us.
    // It's saved in the stack and kept live in esi.
    __ mov(esi, eax);
    __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);

    // Copy parameters into context if necessary.
    int num_parameters = scope()->num_parameters();
    for (int i = 0; i < num_parameters; i++) {
      Variable* var = scope()->parameter(i);
      if (var->IsContextSlot()) {
        int parameter_offset = StandardFrameConstants::kCallerSPOffset +
            (num_parameters - 1 - i) * kPointerSize;
        // Load parameter from stack.
        __ mov(eax, Operand(ebp, parameter_offset));
        // Store it in the context.
        int context_offset = Context::SlotOffset(var->index());
        __ mov(Operand(esi, context_offset), eax);
        // Update the write barrier. This clobbers eax and ebx.
256
        if (need_write_barrier) {
257 258
          __ RecordWriteContextSlot(esi, context_offset, eax, ebx,
                                    kDontSaveFPRegs);
259 260 261 262 263 264
        } else if (FLAG_debug_code) {
          Label done;
          __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
          __ Abort(kExpectedNewSpaceObject);
          __ bind(&done);
        }
danno@chromium.org's avatar
danno@chromium.org committed
265 266 267 268 269
      }
    }
    Comment(";;; End allocate local context");
  }

270 271
  // Initailize FPU state.
  __ fninit();
danno@chromium.org's avatar
danno@chromium.org committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
  // Trace the call.
  if (FLAG_trace && info()->IsOptimizing()) {
    // We have not executed any compiled code yet, so esi still holds the
    // incoming context.
    __ CallRuntime(Runtime::kTraceEnter, 0);
  }
  return !is_aborted();
}


void LCodeGen::GenerateOsrPrologue() {
  // Generate the OSR entry prologue at the first unknown OSR value, or if there
  // are none, at the OSR entrypoint instruction.
  if (osr_pc_offset_ >= 0) return;

  osr_pc_offset_ = masm()->pc_offset();

    // Move state of dynamic frame alignment into edx.
  __ Move(edx, Immediate(kNoAlignmentPadding));

  if (support_aligned_spilled_doubles_ && dynamic_frame_alignment_) {
    Label do_not_pad, align_loop;
    // Align ebp + 4 to a multiple of 2 * kPointerSize.
    __ test(ebp, Immediate(kPointerSize));
    __ j(zero, &do_not_pad, Label::kNear);
    __ push(Immediate(0));
    __ mov(ebx, esp);
    __ mov(edx, Immediate(kAlignmentPaddingPushed));

    // Move all parts of the frame over one word. The frame consists of:
    // unoptimized frame slots, alignment state, context, frame pointer, return
    // address, receiver, and the arguments.
    __ mov(ecx, Immediate(scope()->num_parameters() +
           5 + graph()->osr()->UnoptimizedFrameSlots()));

    __ bind(&align_loop);
    __ mov(eax, Operand(ebx, 1 * kPointerSize));
    __ mov(Operand(ebx, 0), eax);
    __ add(Operand(ebx), Immediate(kPointerSize));
    __ dec(ecx);
    __ j(not_zero, &align_loop, Label::kNear);
    __ mov(Operand(ebx, 0), Immediate(kAlignmentZapValue));
    __ sub(Operand(ebp), Immediate(kPointerSize));
    __ bind(&do_not_pad);
  }

  // Save the first local, which is overwritten by the alignment state.
  Operand alignment_loc = MemOperand(ebp, -3 * kPointerSize);
  __ push(alignment_loc);

  // Set the dynamic frame alignment state.
  __ mov(alignment_loc, edx);

  // Adjust the frame size, subsuming the unoptimized frame into the
  // optimized frame.
  int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
328
  DCHECK(slots >= 1);
danno@chromium.org's avatar
danno@chromium.org committed
329
  __ sub(esp, Immediate((slots - 1) * kPointerSize));
330 331 332

  // Initailize FPU state.
  __ fninit();
danno@chromium.org's avatar
danno@chromium.org committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
}


void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
  if (instr->IsCall()) {
    EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
  }
  if (!instr->IsLazyBailout() && !instr->IsGap()) {
    safepoints_.BumpLastLazySafepointIndex();
  }
  FlushX87StackIfNecessary(instr);
}


void LCodeGen::GenerateBodyInstructionPost(LInstruction* instr) {
348 349 350 351 352 353 354 355 356 357 358 359 360
  // When return from function call, FPU should be initialized again.
  if (instr->IsCall() && instr->ClobbersDoubleRegisters(isolate())) {
    bool double_result = instr->HasDoubleRegisterResult();
    if (double_result) {
      __ lea(esp, Operand(esp, -kDoubleSize));
      __ fstp_d(Operand(esp, 0));
    }
    __ fninit();
    if (double_result) {
      __ fld_d(Operand(esp, 0));
      __ lea(esp, Operand(esp, kDoubleSize));
    }
  }
danno@chromium.org's avatar
danno@chromium.org committed
361
  if (instr->IsGoto()) {
362
    x87_stack_.LeavingBlock(current_block_, LGoto::cast(instr), this);
danno@chromium.org's avatar
danno@chromium.org committed
363 364 365 366
  } else if (FLAG_debug_code && FLAG_enable_slow_asserts &&
             !instr->IsGap() && !instr->IsReturn()) {
    if (instr->ClobbersDoubleRegisters(isolate())) {
      if (instr->HasDoubleRegisterResult()) {
367
        DCHECK_EQ(1, x87_stack_.depth());
danno@chromium.org's avatar
danno@chromium.org committed
368
      } else {
369
        DCHECK_EQ(0, x87_stack_.depth());
danno@chromium.org's avatar
danno@chromium.org committed
370 371 372 373 374 375 376 377
      }
    }
    __ VerifyX87StackDepth(x87_stack_.depth());
  }
}


bool LCodeGen::GenerateJumpTable() {
378 379
  if (!jump_table_.length()) return !is_aborted();

danno@chromium.org's avatar
danno@chromium.org committed
380
  Label needs_frame;
381 382
  Comment(";;; -------------------- Jump table --------------------");

danno@chromium.org's avatar
danno@chromium.org committed
383
  for (int i = 0; i < jump_table_.length(); i++) {
384 385 386
    Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
    __ bind(&table_entry->label);
    Address entry = table_entry->address;
387
    DeoptComment(table_entry->deopt_info);
388
    if (table_entry->needs_frame) {
389
      DCHECK(!info()->saves_caller_doubles());
danno@chromium.org's avatar
danno@chromium.org committed
390
      __ push(Immediate(ExternalReference::ForDeoptEntry(entry)));
391
      __ call(&needs_frame);
danno@chromium.org's avatar
danno@chromium.org committed
392 393 394
    } else {
      __ call(entry, RelocInfo::RUNTIME_ENTRY);
    }
395 396
    info()->LogDeoptCallPosition(masm()->pc_offset(),
                                 table_entry->deopt_info.inlining_id);
danno@chromium.org's avatar
danno@chromium.org committed
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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
  if (needs_frame.is_linked()) {
    __ bind(&needs_frame);

    /* stack layout
       4: entry address
       3: return address  <-- esp
       2: garbage
       1: garbage
       0: garbage
    */
    __ sub(esp, Immediate(kPointerSize));    // Reserve space for stub marker.
    __ push(MemOperand(esp, kPointerSize));  // Copy return address.
    __ push(MemOperand(esp, 3 * kPointerSize));  // Copy entry address.

    /* stack layout
       4: entry address
       3: return address
       2: garbage
       1: return address
       0: entry address  <-- esp
    */
    __ mov(MemOperand(esp, 4 * kPointerSize), ebp);  // Save ebp.

    // Copy context.
    __ mov(ebp, MemOperand(ebp, StandardFrameConstants::kContextOffset));
    __ mov(MemOperand(esp, 3 * kPointerSize), ebp);
    // Fill ebp with the right stack frame address.
    __ lea(ebp, MemOperand(esp, 4 * kPointerSize));

    // This variant of deopt can only be used with stubs. Since we don't
    // have a function pointer to install in the stack frame that we're
    // building, install a special marker there instead.
    DCHECK(info()->IsStub());
    __ mov(MemOperand(esp, 2 * kPointerSize),
           Immediate(Smi::FromInt(StackFrame::STUB)));

    /* stack layout
       4: old ebp
       3: context pointer
       2: stub marker
       1: return address
       0: entry address  <-- esp
    */
    __ ret(0);  // Call the continuation without clobbering registers.
  }
danno@chromium.org's avatar
danno@chromium.org committed
443 444 445 446 447
  return !is_aborted();
}


bool LCodeGen::GenerateDeferredCode() {
448
  DCHECK(is_generating());
danno@chromium.org's avatar
danno@chromium.org committed
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
  if (deferred_.length() > 0) {
    for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
      LDeferredCode* code = deferred_[i];
      X87Stack copy(code->x87_stack());
      x87_stack_ = copy;

      HValue* value =
          instructions_->at(code->instruction_index())->hydrogen_value();
      RecordAndWritePosition(
          chunk()->graph()->SourcePositionToScriptPosition(value->position()));

      Comment(";;; <@%d,#%d> "
              "-------------------- Deferred %s --------------------",
              code->instruction_index(),
              code->instr()->hydrogen_value()->id(),
              code->instr()->Mnemonic());
      __ bind(code->entry());
      if (NeedsDeferredFrame()) {
        Comment(";;; Build frame");
468 469
        DCHECK(!frame_is_built_);
        DCHECK(info()->IsStub());
danno@chromium.org's avatar
danno@chromium.org committed
470 471 472 473 474 475 476 477 478 479 480 481
        frame_is_built_ = true;
        // Build the frame in such a way that esi isn't trashed.
        __ push(ebp);  // Caller's frame pointer.
        __ push(Operand(ebp, StandardFrameConstants::kContextOffset));
        __ push(Immediate(Smi::FromInt(StackFrame::STUB)));
        __ lea(ebp, Operand(esp, 2 * kPointerSize));
        Comment(";;; Deferred code");
      }
      code->Generate();
      if (NeedsDeferredFrame()) {
        __ bind(code->done());
        Comment(";;; Destroy frame");
482
        DCHECK(frame_is_built_);
danno@chromium.org's avatar
danno@chromium.org committed
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
        frame_is_built_ = false;
        __ mov(esp, ebp);
        __ pop(ebp);
      }
      __ jmp(code->exit());
    }
  }

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


bool LCodeGen::GenerateSafepointTable() {
499
  DCHECK(is_done());
danno@chromium.org's avatar
danno@chromium.org committed
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
  if (!info()->IsStub()) {
    // For lazy deoptimization we need space to patch a call after every call.
    // Ensure there is always space for such patching, even if the code ends
    // in a call.
    int target_offset = masm()->pc_offset() + Deoptimizer::patch_size();
    while (masm()->pc_offset() < target_offset) {
      masm()->nop();
    }
  }
  safepoints_.Emit(masm(), GetStackSlotCount());
  return !is_aborted();
}


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


X87Register LCodeGen::ToX87Register(int index) const {
  return X87Register::FromAllocationIndex(index);
}


void LCodeGen::X87LoadForUsage(X87Register reg) {
525
  DCHECK(x87_stack_.Contains(reg));
danno@chromium.org's avatar
danno@chromium.org committed
526 527 528 529 530 531
  x87_stack_.Fxch(reg);
  x87_stack_.pop();
}


void LCodeGen::X87LoadForUsage(X87Register reg1, X87Register reg2) {
532 533
  DCHECK(x87_stack_.Contains(reg1));
  DCHECK(x87_stack_.Contains(reg2));
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
  if (reg1.is(reg2) && x87_stack_.depth() == 1) {
    __ fld(x87_stack_.st(reg1));
    x87_stack_.push(reg1);
    x87_stack_.pop();
    x87_stack_.pop();
  } else {
    x87_stack_.Fxch(reg1, 1);
    x87_stack_.Fxch(reg2);
    x87_stack_.pop();
    x87_stack_.pop();
  }
}


int LCodeGen::X87Stack::GetLayout() {
  int layout = stack_depth_;
  for (int i = 0; i < stack_depth_; i++) {
    layout |= (stack_[stack_depth_ - 1 - i].code() << ((i + 1) * 3));
  }

  return layout;
danno@chromium.org's avatar
danno@chromium.org committed
555 556 557 558
}


void LCodeGen::X87Stack::Fxch(X87Register reg, int other_slot) {
559 560
  DCHECK(is_mutable_);
  DCHECK(Contains(reg) && stack_depth_ > other_slot);
danno@chromium.org's avatar
danno@chromium.org committed
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
  int i  = ArrayIndex(reg);
  int st = st2idx(i);
  if (st != other_slot) {
    int other_i = st2idx(other_slot);
    X87Register other = stack_[other_i];
    stack_[other_i]   = reg;
    stack_[i]         = other;
    if (st == 0) {
      __ fxch(other_slot);
    } else if (other_slot == 0) {
      __ fxch(st);
    } else {
      __ fxch(st);
      __ fxch(other_slot);
      __ fxch(st);
    }
  }
}


int LCodeGen::X87Stack::st2idx(int pos) {
  return stack_depth_ - pos - 1;
}


int LCodeGen::X87Stack::ArrayIndex(X87Register reg) {
  for (int i = 0; i < stack_depth_; i++) {
    if (stack_[i].is(reg)) return i;
  }
  UNREACHABLE();
  return -1;
}


bool LCodeGen::X87Stack::Contains(X87Register reg) {
  for (int i = 0; i < stack_depth_; i++) {
    if (stack_[i].is(reg)) return true;
  }
  return false;
}


void LCodeGen::X87Stack::Free(X87Register reg) {
604 605
  DCHECK(is_mutable_);
  DCHECK(Contains(reg));
danno@chromium.org's avatar
danno@chromium.org committed
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
  int i  = ArrayIndex(reg);
  int st = st2idx(i);
  if (st > 0) {
    // keep track of how fstp(i) changes the order of elements
    int tos_i = st2idx(0);
    stack_[i] = stack_[tos_i];
  }
  pop();
  __ fstp(st);
}


void LCodeGen::X87Mov(X87Register dst, Operand src, X87OperandType opts) {
  if (x87_stack_.Contains(dst)) {
    x87_stack_.Fxch(dst);
    __ fstp(0);
  } else {
    x87_stack_.push(dst);
  }
  X87Fld(src, opts);
}


629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
void LCodeGen::X87Mov(X87Register dst, X87Register src, X87OperandType opts) {
  if (x87_stack_.Contains(dst)) {
    x87_stack_.Fxch(dst);
    __ fstp(0);
    x87_stack_.pop();
    // Push ST(i) onto the FPU register stack
    __ fld(x87_stack_.st(src));
    x87_stack_.push(dst);
  } else {
    // Push ST(i) onto the FPU register stack
    __ fld(x87_stack_.st(src));
    x87_stack_.push(dst);
  }
}


danno@chromium.org's avatar
danno@chromium.org committed
645
void LCodeGen::X87Fld(Operand src, X87OperandType opts) {
646
  DCHECK(!src.is_reg_only());
danno@chromium.org's avatar
danno@chromium.org committed
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
  switch (opts) {
    case kX87DoubleOperand:
      __ fld_d(src);
      break;
    case kX87FloatOperand:
      __ fld_s(src);
      break;
    case kX87IntOperand:
      __ fild_s(src);
      break;
    default:
      UNREACHABLE();
  }
}


void LCodeGen::X87Mov(Operand dst, X87Register src, X87OperandType opts) {
664
  DCHECK(!dst.is_reg_only());
danno@chromium.org's avatar
danno@chromium.org committed
665 666 667 668 669
  x87_stack_.Fxch(src);
  switch (opts) {
    case kX87DoubleOperand:
      __ fst_d(dst);
      break;
670 671 672
    case kX87FloatOperand:
      __ fst_s(dst);
      break;
danno@chromium.org's avatar
danno@chromium.org committed
673 674 675 676 677 678 679 680 681 682
    case kX87IntOperand:
      __ fist_s(dst);
      break;
    default:
      UNREACHABLE();
  }
}


void LCodeGen::X87Stack::PrepareToWrite(X87Register reg) {
683
  DCHECK(is_mutable_);
danno@chromium.org's avatar
danno@chromium.org committed
684 685 686 687 688 689 690 691 692
  if (Contains(reg)) {
    Free(reg);
  }
  // Mark this register as the next register to write to
  stack_[stack_depth_] = reg;
}


void LCodeGen::X87Stack::CommitWrite(X87Register reg) {
693
  DCHECK(is_mutable_);
danno@chromium.org's avatar
danno@chromium.org committed
694
  // Assert the reg is prepared to write, but not on the virtual stack yet
695
  DCHECK(!Contains(reg) && stack_[stack_depth_].is(reg) &&
danno@chromium.org's avatar
danno@chromium.org committed
696 697 698 699 700 701 702 703
      stack_depth_ < X87Register::kMaxNumAllocatableRegisters);
  stack_depth_++;
}


void LCodeGen::X87PrepareBinaryOp(
    X87Register left, X87Register right, X87Register result) {
  // You need to use DefineSameAsFirst for x87 instructions
704
  DCHECK(result.is(left));
danno@chromium.org's avatar
danno@chromium.org committed
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
  x87_stack_.Fxch(right, 1);
  x87_stack_.Fxch(left);
}


void LCodeGen::X87Stack::FlushIfNecessary(LInstruction* instr, LCodeGen* cgen) {
  if (stack_depth_ > 0 && instr->ClobbersDoubleRegisters(isolate())) {
    bool double_inputs = instr->HasDoubleRegisterInput();

    // Flush stack from tos down, since FreeX87() will mess with tos
    for (int i = stack_depth_-1; i >= 0; i--) {
      X87Register reg = stack_[i];
      // Skip registers which contain the inputs for the next instruction
      // when flushing the stack
      if (double_inputs && instr->IsDoubleInput(reg, cgen)) {
        continue;
      }
      Free(reg);
      if (i < stack_depth_-1) i++;
    }
  }
  if (instr->IsReturn()) {
    while (stack_depth_ > 0) {
      __ fstp(0);
      stack_depth_--;
    }
    if (FLAG_debug_code && FLAG_enable_slow_asserts) __ VerifyX87StackDepth(0);
  }
}


736 737 738 739 740 741 742 743
void LCodeGen::X87Stack::LeavingBlock(int current_block_id, LGoto* goto_instr,
                                      LCodeGen* cgen) {
  // For going to a joined block, an explicit LClobberDoubles is inserted before
  // LGoto. Because all used x87 registers are spilled to stack slots. The
  // ResolvePhis phase of register allocator could guarantee the two input's x87
  // stacks have the same layout. So don't check stack_depth_ <= 1 here.
  int goto_block_id = goto_instr->block_id();
  if (current_block_id + 1 != goto_block_id) {
danno@chromium.org's avatar
danno@chromium.org committed
744 745 746
    // If we have a value on the x87 stack on leaving a block, it must be a
    // phi input. If the next block we compile is not the join block, we have
    // to discard the stack state.
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    // Before discarding the stack state, we need to save it if the "goto block"
    // has unreachable last predecessor when FLAG_unreachable_code_elimination.
    if (FLAG_unreachable_code_elimination) {
      int length = goto_instr->block()->predecessors()->length();
      bool has_unreachable_last_predecessor = false;
      for (int i = 0; i < length; i++) {
        HBasicBlock* block = goto_instr->block()->predecessors()->at(i);
        if (block->IsUnreachable() &&
            (block->block_id() + 1) == goto_block_id) {
          has_unreachable_last_predecessor = true;
        }
      }
      if (has_unreachable_last_predecessor) {
        if (cgen->x87_stack_map_.find(goto_block_id) ==
            cgen->x87_stack_map_.end()) {
          X87Stack* stack = new (cgen->zone()) X87Stack(*this);
          cgen->x87_stack_map_.insert(std::make_pair(goto_block_id, stack));
        }
      }
    }

    // Discard the stack state.
danno@chromium.org's avatar
danno@chromium.org committed
769 770 771 772 773 774 775 776 777
    stack_depth_ = 0;
  }
}


void LCodeGen::EmitFlushX87ForDeopt() {
  // The deoptimizer does not support X87 Registers. But as long as we
  // deopt from a stub its not a problem, since we will re-materialize the
  // original stub inputs, which can't be double registers.
778
  // DCHECK(info()->IsStub());
danno@chromium.org's avatar
danno@chromium.org committed
779 780 781 782 783
  if (FLAG_debug_code && FLAG_enable_slow_asserts) {
    __ pushfd();
    __ VerifyX87StackDepth(x87_stack_.depth());
    __ popfd();
  }
784 785

  // Flush X87 stack in the deoptimizer entry.
danno@chromium.org's avatar
danno@chromium.org committed
786 787 788 789
}


Register LCodeGen::ToRegister(LOperand* op) const {
790
  DCHECK(op->IsRegister());
danno@chromium.org's avatar
danno@chromium.org committed
791 792 793 794 795
  return ToRegister(op->index());
}


X87Register LCodeGen::ToX87Register(LOperand* op) const {
796
  DCHECK(op->IsDoubleRegister());
danno@chromium.org's avatar
danno@chromium.org committed
797 798 799 800 801 802 803 804 805 806 807 808 809 810
  return ToX87Register(op->index());
}


int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
  return ToRepresentation(op, Representation::Integer32());
}


int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
                                   const Representation& r) const {
  HConstant* constant = chunk_->LookupConstant(op);
  int32_t value = constant->Integer32Value();
  if (r.IsInteger32()) return value;
811
  DCHECK(r.IsSmiOrTagged());
danno@chromium.org's avatar
danno@chromium.org committed
812 813 814 815 816 817
  return reinterpret_cast<int32_t>(Smi::FromInt(value));
}


Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
  HConstant* constant = chunk_->LookupConstant(op);
818
  DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
danno@chromium.org's avatar
danno@chromium.org committed
819 820 821 822 823 824
  return constant->handle(isolate());
}


double LCodeGen::ToDouble(LConstantOperand* op) const {
  HConstant* constant = chunk_->LookupConstant(op);
825
  DCHECK(constant->HasDoubleValue());
danno@chromium.org's avatar
danno@chromium.org committed
826 827 828 829 830 831
  return constant->DoubleValue();
}


ExternalReference LCodeGen::ToExternalReference(LConstantOperand* op) const {
  HConstant* constant = chunk_->LookupConstant(op);
832
  DCHECK(constant->HasExternalReferenceValue());
danno@chromium.org's avatar
danno@chromium.org committed
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
  return constant->ExternalReferenceValue();
}


bool LCodeGen::IsInteger32(LConstantOperand* op) const {
  return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
}


bool LCodeGen::IsSmi(LConstantOperand* op) const {
  return chunk_->LookupLiteralRepresentation(op).IsSmi();
}


static int ArgumentsOffsetWithoutFrame(int index) {
848
  DCHECK(index < 0);
danno@chromium.org's avatar
danno@chromium.org committed
849 850 851 852 853 854
  return -(index + 1) * kPointerSize + kPCOnStackSize;
}


Operand LCodeGen::ToOperand(LOperand* op) const {
  if (op->IsRegister()) return Operand(ToRegister(op));
855 856
  DCHECK(!op->IsDoubleRegister());
  DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
danno@chromium.org's avatar
danno@chromium.org committed
857 858 859 860 861 862 863 864 865 866 867
  if (NeedsEagerFrame()) {
    return Operand(ebp, StackSlotOffset(op->index()));
  } else {
    // Retrieve parameter without eager stack-frame relative to the
    // stack-pointer.
    return Operand(esp, ArgumentsOffsetWithoutFrame(op->index()));
  }
}


Operand LCodeGen::HighOperand(LOperand* op) {
868
  DCHECK(op->IsDoubleStackSlot());
danno@chromium.org's avatar
danno@chromium.org committed
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
  if (NeedsEagerFrame()) {
    return Operand(ebp, StackSlotOffset(op->index()) + kPointerSize);
  } else {
    // Retrieve parameter without eager stack-frame relative to the
    // stack-pointer.
    return Operand(
        esp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
  }
}


void LCodeGen::WriteTranslation(LEnvironment* environment,
                                Translation* translation) {
  if (environment == NULL) return;

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

  WriteTranslation(environment->outer(), translation);
  bool has_closure_id = !info()->closure().is_null() &&
      !info()->closure().is_identical_to(environment->closure());
  int closure_id = has_closure_id
      ? DefineDeoptimizationLiteral(environment->closure())
      : Translation::kSelfLiteralId;
  switch (environment->frame_type()) {
    case JS_FUNCTION:
      translation->BeginJSFrame(environment->ast_id(), closure_id, height);
      break;
    case JS_CONSTRUCT:
      translation->BeginConstructStubFrame(closure_id, translation_size);
      break;
    case JS_GETTER:
903 904
      DCHECK(translation_size == 1);
      DCHECK(height == 0);
danno@chromium.org's avatar
danno@chromium.org committed
905 906 907
      translation->BeginGetterStubFrame(closure_id);
      break;
    case JS_SETTER:
908 909
      DCHECK(translation_size == 2);
      DCHECK(height == 0);
danno@chromium.org's avatar
danno@chromium.org committed
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
      translation->BeginSetterStubFrame(closure_id);
      break;
    case ARGUMENTS_ADAPTOR:
      translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
      break;
    case STUB:
      translation->BeginCompiledStubFrame();
      break;
    default:
      UNREACHABLE();
  }

  int object_index = 0;
  int dematerialized_index = 0;
  for (int i = 0; i < translation_size; ++i) {
    LOperand* value = environment->values()->at(i);
    AddToTranslation(environment,
                     translation,
                     value,
                     environment->HasTaggedValueAt(i),
                     environment->HasUint32ValueAt(i),
                     &object_index,
                     &dematerialized_index);
  }
}


void LCodeGen::AddToTranslation(LEnvironment* environment,
                                Translation* translation,
                                LOperand* op,
                                bool is_tagged,
                                bool is_uint32,
                                int* object_index_pointer,
                                int* dematerialized_index_pointer) {
  if (op == LEnvironment::materialization_marker()) {
    int object_index = (*object_index_pointer)++;
    if (environment->ObjectIsDuplicateAt(object_index)) {
      int dupe_of = environment->ObjectDuplicateOfAt(object_index);
      translation->DuplicateObject(dupe_of);
      return;
    }
    int object_length = environment->ObjectLengthAt(object_index);
    if (environment->ObjectIsArgumentsAt(object_index)) {
      translation->BeginArgumentsObject(object_length);
    } else {
      translation->BeginCapturedObject(object_length);
    }
    int dematerialized_index = *dematerialized_index_pointer;
    int env_offset = environment->translation_size() + dematerialized_index;
    *dematerialized_index_pointer += object_length;
    for (int i = 0; i < object_length; ++i) {
      LOperand* value = environment->values()->at(env_offset + i);
      AddToTranslation(environment,
                       translation,
                       value,
                       environment->HasTaggedValueAt(env_offset + i),
                       environment->HasUint32ValueAt(env_offset + i),
                       object_index_pointer,
                       dematerialized_index_pointer);
    }
    return;
  }

  if (op->IsStackSlot()) {
    if (is_tagged) {
      translation->StoreStackSlot(op->index());
    } else if (is_uint32) {
      translation->StoreUint32StackSlot(op->index());
    } else {
      translation->StoreInt32StackSlot(op->index());
    }
  } else if (op->IsDoubleStackSlot()) {
    translation->StoreDoubleStackSlot(op->index());
  } else if (op->IsRegister()) {
    Register reg = ToRegister(op);
    if (is_tagged) {
      translation->StoreRegister(reg);
    } else if (is_uint32) {
      translation->StoreUint32Register(reg);
    } else {
      translation->StoreInt32Register(reg);
    }
992 993 994
  } else if (op->IsDoubleRegister()) {
    X87Register reg = ToX87Register(op);
    translation->StoreDoubleRegister(reg);
danno@chromium.org's avatar
danno@chromium.org committed
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
  } else if (op->IsConstantOperand()) {
    HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
    int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
    translation->StoreLiteral(src_index);
  } else {
    UNREACHABLE();
  }
}


void LCodeGen::CallCodeGeneric(Handle<Code> code,
                               RelocInfo::Mode mode,
                               LInstruction* instr,
                               SafepointMode safepoint_mode) {
1009
  DCHECK(instr != NULL);
danno@chromium.org's avatar
danno@chromium.org committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
  __ call(code, mode);
  RecordSafepointWithLazyDeopt(instr, safepoint_mode);

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


void LCodeGen::CallCode(Handle<Code> code,
                        RelocInfo::Mode mode,
                        LInstruction* instr) {
  CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
}


1029 1030
void LCodeGen::CallRuntime(const Runtime::Function* fun, int argc,
                           LInstruction* instr, SaveFPRegsMode save_doubles) {
1031 1032
  DCHECK(instr != NULL);
  DCHECK(instr->HasPointerMap());
danno@chromium.org's avatar
danno@chromium.org committed
1033

1034
  __ CallRuntime(fun, argc, save_doubles);
danno@chromium.org's avatar
danno@chromium.org committed
1035 1036 1037

  RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);

1038
  DCHECK(info()->is_calling());
danno@chromium.org's avatar
danno@chromium.org committed
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
}


void LCodeGen::LoadContextFromDeferred(LOperand* context) {
  if (context->IsRegister()) {
    if (!ToRegister(context).is(esi)) {
      __ mov(esi, ToRegister(context));
    }
  } else if (context->IsStackSlot()) {
    __ mov(esi, ToOperand(context));
  } else if (context->IsConstantOperand()) {
    HConstant* constant =
        chunk_->LookupConstant(LConstantOperand::cast(context));
    __ LoadObject(esi, Handle<Object>::cast(constant->handle(isolate())));
  } else {
    UNREACHABLE();
  }
}

void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
                                       int argc,
                                       LInstruction* instr,
                                       LOperand* context) {
  LoadContextFromDeferred(context);

1064
  __ CallRuntimeSaveDoubles(id);
danno@chromium.org's avatar
danno@chromium.org committed
1065 1066 1067
  RecordSafepointWithRegisters(
      instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);

1068
  DCHECK(info()->is_calling());
danno@chromium.org's avatar
danno@chromium.org committed
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
}


void LCodeGen::RegisterEnvironmentForDeoptimization(
    LEnvironment* environment, Safepoint::DeoptMode mode) {
  environment->set_has_been_used();
  if (!environment->HasBeenRegistered()) {
    // Physical stack frame layout:
    // -x ............. -4  0 ..................................... y
    // [incoming arguments] [spill slots] [pushed outgoing arguments]

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

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

    int frame_count = 0;
    int jsframe_count = 0;
    for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
      ++frame_count;
      if (e->frame_type() == JS_FUNCTION) {
        ++jsframe_count;
      }
    }
    Translation translation(&translations_, frame_count, jsframe_count, zone());
    WriteTranslation(environment, &translation);
    int deoptimization_index = deoptimizations_.length();
    int pc_offset = masm()->pc_offset();
    environment->Register(deoptimization_index,
                          translation.index(),
                          (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
    deoptimizations_.Add(environment, zone());
  }
}


1109
void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1110
                            Deoptimizer::DeoptReason deopt_reason,
danno@chromium.org's avatar
danno@chromium.org committed
1111
                            Deoptimizer::BailoutType bailout_type) {
1112
  LEnvironment* environment = instr->environment();
danno@chromium.org's avatar
danno@chromium.org committed
1113
  RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
1114
  DCHECK(environment->HasBeenRegistered());
danno@chromium.org's avatar
danno@chromium.org committed
1115
  int id = environment->deoptimization_index();
1116
  DCHECK(info()->IsOptimizing() || info()->IsStub());
danno@chromium.org's avatar
danno@chromium.org committed
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
  Address entry =
      Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
  if (entry == NULL) {
    Abort(kBailoutWasNotPrepared);
    return;
  }

  if (DeoptEveryNTimes()) {
    ExternalReference count = ExternalReference::stress_deopt_count(isolate());
    Label no_deopt;
    __ pushfd();
    __ push(eax);
    __ mov(eax, Operand::StaticVariable(count));
    __ sub(eax, Immediate(1));
    __ j(not_zero, &no_deopt, Label::kNear);
    if (FLAG_trap_on_deopt) __ int3();
    __ mov(eax, Immediate(FLAG_deopt_every_n_times));
    __ mov(Operand::StaticVariable(count), eax);
    __ pop(eax);
    __ popfd();
1137
    DCHECK(frame_is_built_);
1138 1139 1140 1141 1142 1143
    // Put the x87 stack layout in TOS.
    if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();
    __ push(Immediate(x87_stack_.GetLayout()));
    __ fild_s(MemOperand(esp, 0));
    // Don't touch eflags.
    __ lea(esp, Operand(esp, kPointerSize));
danno@chromium.org's avatar
danno@chromium.org committed
1144 1145 1146 1147 1148 1149 1150
    __ call(entry, RelocInfo::RUNTIME_ENTRY);
    __ bind(&no_deopt);
    __ mov(Operand::StaticVariable(count), eax);
    __ pop(eax);
    __ popfd();
  }

1151 1152 1153
  // Put the x87 stack layout in TOS, so that we can save x87 fp registers in
  // the correct location.
  {
danno@chromium.org's avatar
danno@chromium.org committed
1154 1155
    Label done;
    if (cc != no_condition) __ j(NegateCondition(cc), &done, Label::kNear);
1156 1157 1158 1159 1160 1161 1162
    if (x87_stack_.depth() > 0) EmitFlushX87ForDeopt();

    int x87_stack_layout = x87_stack_.GetLayout();
    __ push(Immediate(x87_stack_layout));
    __ fild_s(MemOperand(esp, 0));
    // Don't touch eflags.
    __ lea(esp, Operand(esp, kPointerSize));
danno@chromium.org's avatar
danno@chromium.org committed
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
    __ bind(&done);
  }

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

1173 1174
  Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason);

1175
  DCHECK(info()->IsStub() || frame_is_built_);
danno@chromium.org's avatar
danno@chromium.org committed
1176
  if (cc == no_condition && frame_is_built_) {
1177
    DeoptComment(deopt_info);
danno@chromium.org's avatar
danno@chromium.org committed
1178
    __ call(entry, RelocInfo::RUNTIME_ENTRY);
1179
    info()->LogDeoptCallPosition(masm()->pc_offset(), deopt_info.inlining_id);
danno@chromium.org's avatar
danno@chromium.org committed
1180
  } else {
1181
    Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
1182
                                            !frame_is_built_);
danno@chromium.org's avatar
danno@chromium.org committed
1183 1184
    // We often have several deopts to the same entry, reuse the last
    // jump entry if this is the case.
1185 1186
    if (FLAG_trace_deopt || isolate()->cpu_profiler()->is_profiling() ||
        jump_table_.is_empty() ||
1187
        !table_entry.IsEquivalentTo(jump_table_.last())) {
danno@chromium.org's avatar
danno@chromium.org committed
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
      jump_table_.Add(table_entry, zone());
    }
    if (cc == no_condition) {
      __ jmp(&jump_table_.last().label);
    } else {
      __ j(cc, &jump_table_.last().label);
    }
  }
}


1199
void LCodeGen::DeoptimizeIf(Condition cc, LInstruction* instr,
1200
                            Deoptimizer::DeoptReason deopt_reason) {
danno@chromium.org's avatar
danno@chromium.org committed
1201 1202 1203
  Deoptimizer::BailoutType bailout_type = info()->IsStub()
      ? Deoptimizer::LAZY
      : Deoptimizer::EAGER;
1204
  DeoptimizeIf(cc, instr, deopt_reason, bailout_type);
danno@chromium.org's avatar
danno@chromium.org committed
1205 1206 1207 1208 1209 1210 1211
}


void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
  int length = deoptimizations_.length();
  if (length == 0) return;
  Handle<DeoptimizationInputData> data =
1212
      DeoptimizationInputData::New(isolate(), length, TENURED);
danno@chromium.org's avatar
danno@chromium.org committed
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225

  Handle<ByteArray> translations =
      translations_.CreateByteArray(isolate()->factory());
  data->SetTranslationByteArray(*translations);
  data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
  data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
  if (info_->IsOptimizing()) {
    // Reference to shared function info does not change between phases.
    AllowDeferredHandleDereference allow_handle_dereference;
    data->SetSharedFunctionInfo(*info_->shared_info());
  } else {
    data->SetSharedFunctionInfo(Smi::FromInt(0));
  }
1226
  data->SetWeakCellCache(Smi::FromInt(0));
danno@chromium.org's avatar
danno@chromium.org committed
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263

  Handle<FixedArray> literals =
      factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
  { AllowDeferredHandleDereference copy_handles;
    for (int i = 0; i < deoptimization_literals_.length(); i++) {
      literals->set(i, *deoptimization_literals_[i]);
    }
    data->SetLiteralArray(*literals);
  }

  data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
  data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));

  // Populate the deoptimization entries.
  for (int i = 0; i < length; i++) {
    LEnvironment* env = deoptimizations_[i];
    data->SetAstId(i, env->ast_id());
    data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
    data->SetArgumentsStackHeight(i,
                                  Smi::FromInt(env->arguments_stack_height()));
    data->SetPc(i, Smi::FromInt(env->pc_offset()));
  }
  code->set_deoptimization_data(*data);
}


int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
  int result = deoptimization_literals_.length();
  for (int i = 0; i < deoptimization_literals_.length(); ++i) {
    if (deoptimization_literals_[i].is_identical_to(literal)) return i;
  }
  deoptimization_literals_.Add(literal, zone());
  return result;
}


void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
1264
  DCHECK(deoptimization_literals_.length() == 0);
danno@chromium.org's avatar
danno@chromium.org committed
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283

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

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

  inlined_function_count_ = deoptimization_literals_.length();
}


void LCodeGen::RecordSafepointWithLazyDeopt(
    LInstruction* instr, SafepointMode safepoint_mode) {
  if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
    RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
  } else {
1284
    DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
danno@chromium.org's avatar
danno@chromium.org committed
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
    RecordSafepointWithRegisters(
        instr->pointer_map(), 0, Safepoint::kLazyDeopt);
  }
}


void LCodeGen::RecordSafepoint(
    LPointerMap* pointers,
    Safepoint::Kind kind,
    int arguments,
    Safepoint::DeoptMode deopt_mode) {
1296
  DCHECK(kind == expected_safepoint_kind_);
danno@chromium.org's avatar
danno@chromium.org committed
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
  const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
  Safepoint safepoint =
      safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode);
  for (int i = 0; i < operands->length(); i++) {
    LOperand* pointer = operands->at(i);
    if (pointer->IsStackSlot()) {
      safepoint.DefinePointerSlot(pointer->index(), zone());
    } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
      safepoint.DefinePointerRegister(ToRegister(pointer), zone());
    }
  }
}


void LCodeGen::RecordSafepoint(LPointerMap* pointers,
                               Safepoint::DeoptMode mode) {
  RecordSafepoint(pointers, Safepoint::kSimple, 0, mode);
}


void LCodeGen::RecordSafepoint(Safepoint::DeoptMode mode) {
  LPointerMap empty_pointers(zone());
  RecordSafepoint(&empty_pointers, mode);
}


void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
                                            int arguments,
                                            Safepoint::DeoptMode mode) {
  RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, mode);
}


void LCodeGen::RecordAndWritePosition(int position) {
  if (position == RelocInfo::kNoPosition) return;
  masm()->positions_recorder()->RecordPosition(position);
  masm()->positions_recorder()->WriteRecordedPositions();
}


static const char* LabelType(LLabel* label) {
  if (label->is_loop_header()) return " (loop header)";
  if (label->is_osr_entry()) return " (OSR entry)";
  return "";
}


void LCodeGen::DoLabel(LLabel* label) {
  Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
          current_instruction_,
          label->hydrogen_value()->id(),
          label->block_id(),
          LabelType(label));
  __ bind(label->label());
  current_block_ = label->block_id();
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
  if (label->block()->predecessors()->length() > 1) {
    // A join block's x87 stack is that of its last visited predecessor.
    // If the last visited predecessor block is unreachable, the stack state
    // will be wrong. In such case, use the x87 stack of reachable predecessor.
    X87StackMap::const_iterator it = x87_stack_map_.find(current_block_);
    // Restore x87 stack.
    if (it != x87_stack_map_.end()) {
      x87_stack_ = *(it->second);
    }
  }
danno@chromium.org's avatar
danno@chromium.org committed
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
  DoGap(label);
}


void LCodeGen::DoParallelMove(LParallelMove* move) {
  resolver_.Resolve(move);
}


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


void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
  DoGap(instr);
}


void LCodeGen::DoParameter(LParameter* instr) {
  // Nothing to do.
}


void LCodeGen::DoCallStub(LCallStub* instr) {
1393 1394
  DCHECK(ToRegister(instr->context()).is(esi));
  DCHECK(ToRegister(instr->result()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
  switch (instr->hydrogen()->major_key()) {
    case CodeStub::RegExpExec: {
      RegExpExecStub stub(isolate());
      CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
      break;
    }
    case CodeStub::SubString: {
      SubStringStub stub(isolate());
      CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
      break;
    }
    case CodeStub::StringCompare: {
      StringCompareStub stub(isolate());
      CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
      break;
    }
    default:
      UNREACHABLE();
  }
}


void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
  GenerateOsrPrologue();
}


void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
  Register dividend = ToRegister(instr->dividend());
  int32_t divisor = instr->divisor();
1425
  DCHECK(dividend.is(ToRegister(instr->result())));
danno@chromium.org's avatar
danno@chromium.org committed
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443

  // Theoretically, a variation of the branch-free code for integer division by
  // a power of 2 (calculating the remainder via an additional multiplication
  // (which gets simplified to an 'and') and subtraction) should be faster, and
  // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
  // indicate that positive dividends are heavily favored, so the branching
  // version performs better.
  HMod* hmod = instr->hydrogen();
  int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
  Label dividend_is_not_negative, done;
  if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
    __ test(dividend, dividend);
    __ j(not_sign, &dividend_is_not_negative, Label::kNear);
    // Note that this is correct even for kMinInt operands.
    __ neg(dividend);
    __ and_(dividend, mask);
    __ neg(dividend);
    if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1444
      DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
    }
    __ jmp(&done, Label::kNear);
  }

  __ bind(&dividend_is_not_negative);
  __ and_(dividend, mask);
  __ bind(&done);
}


void LCodeGen::DoModByConstI(LModByConstI* instr) {
  Register dividend = ToRegister(instr->dividend());
  int32_t divisor = instr->divisor();
1458
  DCHECK(ToRegister(instr->result()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
1459 1460

  if (divisor == 0) {
1461
    DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
danno@chromium.org's avatar
danno@chromium.org committed
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
    return;
  }

  __ TruncatingDiv(dividend, Abs(divisor));
  __ imul(edx, edx, Abs(divisor));
  __ mov(eax, dividend);
  __ sub(eax, edx);

  // Check for negative zero.
  HMod* hmod = instr->hydrogen();
  if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
    Label remainder_not_zero;
    __ j(not_zero, &remainder_not_zero, Label::kNear);
    __ cmp(dividend, Immediate(0));
1476
    DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1477 1478 1479 1480 1481 1482 1483 1484 1485
    __ bind(&remainder_not_zero);
  }
}


void LCodeGen::DoModI(LModI* instr) {
  HMod* hmod = instr->hydrogen();

  Register left_reg = ToRegister(instr->left());
1486
  DCHECK(left_reg.is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
1487
  Register right_reg = ToRegister(instr->right());
1488 1489
  DCHECK(!right_reg.is(eax));
  DCHECK(!right_reg.is(edx));
danno@chromium.org's avatar
danno@chromium.org committed
1490
  Register result_reg = ToRegister(instr->result());
1491
  DCHECK(result_reg.is(edx));
danno@chromium.org's avatar
danno@chromium.org committed
1492 1493 1494 1495 1496 1497

  Label done;
  // Check for x % 0, idiv would signal a divide error. We have to
  // deopt in this case because we can't return a NaN.
  if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
    __ test(right_reg, Operand(right_reg));
1498
    DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
danno@chromium.org's avatar
danno@chromium.org committed
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
  }

  // Check for kMinInt % -1, idiv would signal a divide error. We
  // have to deopt if we care about -0, because we can't return that.
  if (hmod->CheckFlag(HValue::kCanOverflow)) {
    Label no_overflow_possible;
    __ cmp(left_reg, kMinInt);
    __ j(not_equal, &no_overflow_possible, Label::kNear);
    __ cmp(right_reg, -1);
    if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1509
      DeoptimizeIf(equal, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
    } else {
      __ j(not_equal, &no_overflow_possible, Label::kNear);
      __ Move(result_reg, Immediate(0));
      __ jmp(&done, Label::kNear);
    }
    __ bind(&no_overflow_possible);
  }

  // Sign extend dividend in eax into edx:eax.
  __ cdq();

  // If we care about -0, test if the dividend is <0 and the result is 0.
  if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
    Label positive_left;
    __ test(left_reg, Operand(left_reg));
    __ j(not_sign, &positive_left, Label::kNear);
    __ idiv(right_reg);
    __ test(result_reg, Operand(result_reg));
1528
    DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
    __ jmp(&done, Label::kNear);
    __ bind(&positive_left);
  }
  __ idiv(right_reg);
  __ bind(&done);
}


void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
  Register dividend = ToRegister(instr->dividend());
  int32_t divisor = instr->divisor();
  Register result = ToRegister(instr->result());
1541
  DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1542
  DCHECK(!result.is(dividend));
danno@chromium.org's avatar
danno@chromium.org committed
1543 1544 1545 1546 1547

  // Check for (0 / -x) that will produce negative zero.
  HDiv* hdiv = instr->hydrogen();
  if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
    __ test(dividend, dividend);
1548
    DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1549 1550 1551 1552
  }
  // Check for (kMinInt / -1).
  if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
    __ cmp(dividend, kMinInt);
1553
    DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
danno@chromium.org's avatar
danno@chromium.org committed
1554 1555 1556 1557 1558 1559
  }
  // Deoptimize if remainder will not be 0.
  if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
      divisor != 1 && divisor != -1) {
    int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
    __ test(dividend, Immediate(mask));
1560
    DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
danno@chromium.org's avatar
danno@chromium.org committed
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
  }
  __ Move(result, dividend);
  int32_t shift = WhichPowerOf2Abs(divisor);
  if (shift > 0) {
    // The arithmetic shift is always OK, the 'if' is an optimization only.
    if (shift > 1) __ sar(result, 31);
    __ shr(result, 32 - shift);
    __ add(result, dividend);
    __ sar(result, shift);
  }
  if (divisor < 0) __ neg(result);
}


void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
  Register dividend = ToRegister(instr->dividend());
  int32_t divisor = instr->divisor();
1578
  DCHECK(ToRegister(instr->result()).is(edx));
danno@chromium.org's avatar
danno@chromium.org committed
1579 1580

  if (divisor == 0) {
1581
    DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
danno@chromium.org's avatar
danno@chromium.org committed
1582 1583 1584 1585 1586 1587 1588
    return;
  }

  // Check for (0 / -x) that will produce negative zero.
  HDiv* hdiv = instr->hydrogen();
  if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
    __ test(dividend, dividend);
1589
    DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1590 1591 1592 1593 1594 1595 1596 1597 1598
  }

  __ TruncatingDiv(dividend, Abs(divisor));
  if (divisor < 0) __ neg(edx);

  if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
    __ mov(eax, edx);
    __ imul(eax, eax, divisor);
    __ sub(eax, dividend);
1599
    DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
danno@chromium.org's avatar
danno@chromium.org committed
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
  }
}


// TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
void LCodeGen::DoDivI(LDivI* instr) {
  HBinaryOperation* hdiv = instr->hydrogen();
  Register dividend = ToRegister(instr->dividend());
  Register divisor = ToRegister(instr->divisor());
  Register remainder = ToRegister(instr->temp());
1610 1611 1612 1613 1614
  DCHECK(dividend.is(eax));
  DCHECK(remainder.is(edx));
  DCHECK(ToRegister(instr->result()).is(eax));
  DCHECK(!divisor.is(eax));
  DCHECK(!divisor.is(edx));
danno@chromium.org's avatar
danno@chromium.org committed
1615 1616 1617 1618

  // Check for x / 0.
  if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
    __ test(divisor, divisor);
1619
    DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
danno@chromium.org's avatar
danno@chromium.org committed
1620 1621 1622 1623 1624 1625 1626 1627
  }

  // Check for (0 / -x) that will produce negative zero.
  if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
    Label dividend_not_zero;
    __ test(dividend, dividend);
    __ j(not_zero, &dividend_not_zero, Label::kNear);
    __ test(divisor, divisor);
1628
    DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1629 1630 1631 1632 1633 1634 1635 1636 1637
    __ bind(&dividend_not_zero);
  }

  // Check for (kMinInt / -1).
  if (hdiv->CheckFlag(HValue::kCanOverflow)) {
    Label dividend_not_min_int;
    __ cmp(dividend, kMinInt);
    __ j(not_zero, &dividend_not_min_int, Label::kNear);
    __ cmp(divisor, -1);
1638
    DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
danno@chromium.org's avatar
danno@chromium.org committed
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
    __ bind(&dividend_not_min_int);
  }

  // Sign extend to edx (= remainder).
  __ cdq();
  __ idiv(divisor);

  if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
    // Deoptimize if remainder is not 0.
    __ test(remainder, remainder);
1649
    DeoptimizeIf(not_zero, instr, Deoptimizer::kLostPrecision);
danno@chromium.org's avatar
danno@chromium.org committed
1650 1651 1652 1653 1654 1655 1656
  }
}


void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
  Register dividend = ToRegister(instr->dividend());
  int32_t divisor = instr->divisor();
1657
  DCHECK(dividend.is(ToRegister(instr->result())));
danno@chromium.org's avatar
danno@chromium.org committed
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670

  // If the divisor is positive, things are easy: There can be no deopts and we
  // can simply do an arithmetic right shift.
  if (divisor == 1) return;
  int32_t shift = WhichPowerOf2Abs(divisor);
  if (divisor > 1) {
    __ sar(dividend, shift);
    return;
  }

  // If the divisor is negative, we have to negate and handle edge cases.
  __ neg(dividend);
  if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1671
    DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1672 1673
  }

1674 1675 1676
  // Dividing by -1 is basically negation, unless we overflow.
  if (divisor == -1) {
    if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1677
      DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
1678
    }
danno@chromium.org's avatar
danno@chromium.org committed
1679 1680 1681
    return;
  }

1682 1683 1684
  // If the negation could not overflow, simply shifting is OK.
  if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
    __ sar(dividend, shift);
danno@chromium.org's avatar
danno@chromium.org committed
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
    return;
  }

  Label not_kmin_int, done;
  __ j(no_overflow, &not_kmin_int, Label::kNear);
  __ mov(dividend, Immediate(kMinInt / divisor));
  __ jmp(&done, Label::kNear);
  __ bind(&not_kmin_int);
  __ sar(dividend, shift);
  __ bind(&done);
}


void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
  Register dividend = ToRegister(instr->dividend());
  int32_t divisor = instr->divisor();
1701
  DCHECK(ToRegister(instr->result()).is(edx));
danno@chromium.org's avatar
danno@chromium.org committed
1702 1703

  if (divisor == 0) {
1704
    DeoptimizeIf(no_condition, instr, Deoptimizer::kDivisionByZero);
danno@chromium.org's avatar
danno@chromium.org committed
1705 1706 1707 1708 1709 1710 1711
    return;
  }

  // Check for (0 / -x) that will produce negative zero.
  HMathFloorOfDiv* hdiv = instr->hydrogen();
  if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
    __ test(dividend, dividend);
1712
    DeoptimizeIf(zero, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
  }

  // Easy case: We need no dynamic check for the dividend and the flooring
  // division is the same as the truncating division.
  if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
      (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
    __ TruncatingDiv(dividend, Abs(divisor));
    if (divisor < 0) __ neg(edx);
    return;
  }

  // In the general case we may need to adjust before and after the truncating
  // division to get a flooring division.
  Register temp = ToRegister(instr->temp3());
1727
  DCHECK(!temp.is(dividend) && !temp.is(eax) && !temp.is(edx));
danno@chromium.org's avatar
danno@chromium.org committed
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
  Label needs_adjustment, done;
  __ cmp(dividend, Immediate(0));
  __ j(divisor > 0 ? less : greater, &needs_adjustment, Label::kNear);
  __ TruncatingDiv(dividend, Abs(divisor));
  if (divisor < 0) __ neg(edx);
  __ jmp(&done, Label::kNear);
  __ bind(&needs_adjustment);
  __ lea(temp, Operand(dividend, divisor > 0 ? 1 : -1));
  __ TruncatingDiv(temp, Abs(divisor));
  if (divisor < 0) __ neg(edx);
  __ dec(edx);
  __ bind(&done);
}


// TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
  HBinaryOperation* hdiv = instr->hydrogen();
  Register dividend = ToRegister(instr->dividend());
  Register divisor = ToRegister(instr->divisor());
  Register remainder = ToRegister(instr->temp());
  Register result = ToRegister(instr->result());
1750 1751 1752 1753 1754
  DCHECK(dividend.is(eax));
  DCHECK(remainder.is(edx));
  DCHECK(result.is(eax));
  DCHECK(!divisor.is(eax));
  DCHECK(!divisor.is(edx));
danno@chromium.org's avatar
danno@chromium.org committed
1755 1756 1757 1758

  // Check for x / 0.
  if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
    __ test(divisor, divisor);
1759
    DeoptimizeIf(zero, instr, Deoptimizer::kDivisionByZero);
danno@chromium.org's avatar
danno@chromium.org committed
1760 1761 1762 1763 1764 1765 1766 1767
  }

  // Check for (0 / -x) that will produce negative zero.
  if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
    Label dividend_not_zero;
    __ test(dividend, dividend);
    __ j(not_zero, &dividend_not_zero, Label::kNear);
    __ test(divisor, divisor);
1768
    DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1769 1770 1771 1772 1773 1774 1775 1776 1777
    __ bind(&dividend_not_zero);
  }

  // Check for (kMinInt / -1).
  if (hdiv->CheckFlag(HValue::kCanOverflow)) {
    Label dividend_not_min_int;
    __ cmp(dividend, kMinInt);
    __ j(not_zero, &dividend_not_min_int, Label::kNear);
    __ cmp(divisor, -1);
1778
    DeoptimizeIf(zero, instr, Deoptimizer::kOverflow);
danno@chromium.org's avatar
danno@chromium.org committed
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 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 1850 1851 1852 1853 1854 1855
    __ bind(&dividend_not_min_int);
  }

  // Sign extend to edx (= remainder).
  __ cdq();
  __ idiv(divisor);

  Label done;
  __ test(remainder, remainder);
  __ j(zero, &done, Label::kNear);
  __ xor_(remainder, divisor);
  __ sar(remainder, 31);
  __ add(result, remainder);
  __ bind(&done);
}


void LCodeGen::DoMulI(LMulI* instr) {
  Register left = ToRegister(instr->left());
  LOperand* right = instr->right();

  if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
    __ mov(ToRegister(instr->temp()), left);
  }

  if (right->IsConstantOperand()) {
    // Try strength reductions on the multiplication.
    // All replacement instructions are at most as long as the imul
    // and have better latency.
    int constant = ToInteger32(LConstantOperand::cast(right));
    if (constant == -1) {
      __ neg(left);
    } else if (constant == 0) {
      __ xor_(left, Operand(left));
    } else if (constant == 2) {
      __ add(left, Operand(left));
    } else if (!instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
      // If we know that the multiplication can't overflow, it's safe to
      // use instructions that don't set the overflow flag for the
      // multiplication.
      switch (constant) {
        case 1:
          // Do nothing.
          break;
        case 3:
          __ lea(left, Operand(left, left, times_2, 0));
          break;
        case 4:
          __ shl(left, 2);
          break;
        case 5:
          __ lea(left, Operand(left, left, times_4, 0));
          break;
        case 8:
          __ shl(left, 3);
          break;
        case 9:
          __ lea(left, Operand(left, left, times_8, 0));
          break;
        case 16:
          __ shl(left, 4);
          break;
        default:
          __ imul(left, left, constant);
          break;
      }
    } else {
      __ imul(left, left, constant);
    }
  } else {
    if (instr->hydrogen()->representation().IsSmi()) {
      __ SmiUntag(left);
    }
    __ imul(left, ToOperand(right));
  }

  if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
1856
    DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
danno@chromium.org's avatar
danno@chromium.org committed
1857 1858 1859 1860 1861 1862
  }

  if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
    // Bail out if the result is supposed to be negative zero.
    Label done;
    __ test(left, Operand(left));
1863
    __ j(not_zero, &done);
danno@chromium.org's avatar
danno@chromium.org committed
1864 1865
    if (right->IsConstantOperand()) {
      if (ToInteger32(LConstantOperand::cast(right)) < 0) {
1866
        DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1867 1868
      } else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
        __ cmp(ToRegister(instr->temp()), Immediate(0));
1869
        DeoptimizeIf(less, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1870 1871 1872 1873
      }
    } else {
      // Test the non-zero operand for negative sign.
      __ or_(ToRegister(instr->temp()), ToOperand(right));
1874
      DeoptimizeIf(sign, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
1875 1876 1877 1878 1879 1880 1881 1882 1883
    }
    __ bind(&done);
  }
}


void LCodeGen::DoBitI(LBitI* instr) {
  LOperand* left = instr->left();
  LOperand* right = instr->right();
1884 1885
  DCHECK(left->Equals(instr->result()));
  DCHECK(left->IsRegister());
danno@chromium.org's avatar
danno@chromium.org committed
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930

  if (right->IsConstantOperand()) {
    int32_t right_operand =
        ToRepresentation(LConstantOperand::cast(right),
                         instr->hydrogen()->representation());
    switch (instr->op()) {
      case Token::BIT_AND:
        __ and_(ToRegister(left), right_operand);
        break;
      case Token::BIT_OR:
        __ or_(ToRegister(left), right_operand);
        break;
      case Token::BIT_XOR:
        if (right_operand == int32_t(~0)) {
          __ not_(ToRegister(left));
        } else {
          __ xor_(ToRegister(left), right_operand);
        }
        break;
      default:
        UNREACHABLE();
        break;
    }
  } else {
    switch (instr->op()) {
      case Token::BIT_AND:
        __ and_(ToRegister(left), ToOperand(right));
        break;
      case Token::BIT_OR:
        __ or_(ToRegister(left), ToOperand(right));
        break;
      case Token::BIT_XOR:
        __ xor_(ToRegister(left), ToOperand(right));
        break;
      default:
        UNREACHABLE();
        break;
    }
  }
}


void LCodeGen::DoShiftI(LShiftI* instr) {
  LOperand* left = instr->left();
  LOperand* right = instr->right();
1931 1932
  DCHECK(left->Equals(instr->result()));
  DCHECK(left->IsRegister());
danno@chromium.org's avatar
danno@chromium.org committed
1933
  if (right->IsRegister()) {
1934
    DCHECK(ToRegister(right).is(ecx));
danno@chromium.org's avatar
danno@chromium.org committed
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946

    switch (instr->op()) {
      case Token::ROR:
        __ ror_cl(ToRegister(left));
        break;
      case Token::SAR:
        __ sar_cl(ToRegister(left));
        break;
      case Token::SHR:
        __ shr_cl(ToRegister(left));
        if (instr->can_deopt()) {
          __ test(ToRegister(left), ToRegister(left));
1947
          DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
danno@chromium.org's avatar
danno@chromium.org committed
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
        }
        break;
      case Token::SHL:
        __ shl_cl(ToRegister(left));
        break;
      default:
        UNREACHABLE();
        break;
    }
  } else {
    int value = ToInteger32(LConstantOperand::cast(right));
    uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
    switch (instr->op()) {
      case Token::ROR:
        if (shift_count == 0 && instr->can_deopt()) {
          __ test(ToRegister(left), ToRegister(left));
1964
          DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
danno@chromium.org's avatar
danno@chromium.org committed
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
        } else {
          __ ror(ToRegister(left), shift_count);
        }
        break;
      case Token::SAR:
        if (shift_count != 0) {
          __ sar(ToRegister(left), shift_count);
        }
        break;
      case Token::SHR:
        if (shift_count != 0) {
          __ shr(ToRegister(left), shift_count);
        } else if (instr->can_deopt()) {
          __ test(ToRegister(left), ToRegister(left));
1979
          DeoptimizeIf(sign, instr, Deoptimizer::kNegativeValue);
danno@chromium.org's avatar
danno@chromium.org committed
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
        }
        break;
      case Token::SHL:
        if (shift_count != 0) {
          if (instr->hydrogen_value()->representation().IsSmi() &&
              instr->can_deopt()) {
            if (shift_count != 1) {
              __ shl(ToRegister(left), shift_count - 1);
            }
            __ SmiTag(ToRegister(left));
1990
            DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
danno@chromium.org's avatar
danno@chromium.org committed
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
          } else {
            __ shl(ToRegister(left), shift_count);
          }
        }
        break;
      default:
        UNREACHABLE();
        break;
    }
  }
}


void LCodeGen::DoSubI(LSubI* instr) {
  LOperand* left = instr->left();
  LOperand* right = instr->right();
2007
  DCHECK(left->Equals(instr->result()));
danno@chromium.org's avatar
danno@chromium.org committed
2008 2009 2010 2011 2012 2013 2014 2015

  if (right->IsConstantOperand()) {
    __ sub(ToOperand(left),
           ToImmediate(right, instr->hydrogen()->representation()));
  } else {
    __ sub(ToRegister(left), ToOperand(right));
  }
  if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
2016
    DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
danno@chromium.org's avatar
danno@chromium.org committed
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
  }
}


void LCodeGen::DoConstantI(LConstantI* instr) {
  __ Move(ToRegister(instr->result()), Immediate(instr->value()));
}


void LCodeGen::DoConstantS(LConstantS* instr) {
  __ Move(ToRegister(instr->result()), Immediate(instr->value()));
}


void LCodeGen::DoConstantD(LConstantD* instr) {
2032 2033 2034
  uint64_t const bits = instr->bits();
  uint32_t const lower = static_cast<uint32_t>(bits);
  uint32_t const upper = static_cast<uint32_t>(bits >> 32);
2035
  DCHECK(instr->result()->IsDoubleRegister());
danno@chromium.org's avatar
danno@chromium.org committed
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070

  __ push(Immediate(upper));
  __ push(Immediate(lower));
  X87Register reg = ToX87Register(instr->result());
  X87Mov(reg, Operand(esp, 0));
  __ add(Operand(esp), Immediate(kDoubleSize));
}


void LCodeGen::DoConstantE(LConstantE* instr) {
  __ lea(ToRegister(instr->result()), Operand::StaticVariable(instr->value()));
}


void LCodeGen::DoConstantT(LConstantT* instr) {
  Register reg = ToRegister(instr->result());
  Handle<Object> object = instr->value(isolate());
  AllowDeferredHandleDereference smi_check;
  __ LoadObject(reg, object);
}


void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
  Register result = ToRegister(instr->result());
  Register map = ToRegister(instr->value());
  __ EnumLength(result, map);
}


void LCodeGen::DoDateField(LDateField* instr) {
  Register object = ToRegister(instr->date());
  Register result = ToRegister(instr->result());
  Register scratch = ToRegister(instr->temp());
  Smi* index = instr->index();
  Label runtime, done;
2071 2072
  DCHECK(object.is(result));
  DCHECK(object.is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
2073 2074

  __ test(object, Immediate(kSmiTagMask));
2075
  DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
danno@chromium.org's avatar
danno@chromium.org committed
2076
  __ CmpObjectType(object, JS_DATE_TYPE, scratch);
2077
  DeoptimizeIf(not_equal, instr, Deoptimizer::kNotADateObject);
danno@chromium.org's avatar
danno@chromium.org committed
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166

  if (index->value() == 0) {
    __ mov(result, FieldOperand(object, JSDate::kValueOffset));
  } else {
    if (index->value() < JSDate::kFirstUncachedField) {
      ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
      __ mov(scratch, Operand::StaticVariable(stamp));
      __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
      __ j(not_equal, &runtime, Label::kNear);
      __ mov(result, FieldOperand(object, JSDate::kValueOffset +
                                          kPointerSize * index->value()));
      __ jmp(&done, Label::kNear);
    }
    __ bind(&runtime);
    __ PrepareCallCFunction(2, scratch);
    __ mov(Operand(esp, 0), object);
    __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
    __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
    __ bind(&done);
  }
}


Operand LCodeGen::BuildSeqStringOperand(Register string,
                                        LOperand* index,
                                        String::Encoding encoding) {
  if (index->IsConstantOperand()) {
    int offset = ToRepresentation(LConstantOperand::cast(index),
                                  Representation::Integer32());
    if (encoding == String::TWO_BYTE_ENCODING) {
      offset *= kUC16Size;
    }
    STATIC_ASSERT(kCharSize == 1);
    return FieldOperand(string, SeqString::kHeaderSize + offset);
  }
  return FieldOperand(
      string, ToRegister(index),
      encoding == String::ONE_BYTE_ENCODING ? times_1 : times_2,
      SeqString::kHeaderSize);
}


void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
  String::Encoding encoding = instr->hydrogen()->encoding();
  Register result = ToRegister(instr->result());
  Register string = ToRegister(instr->string());

  if (FLAG_debug_code) {
    __ push(string);
    __ mov(string, FieldOperand(string, HeapObject::kMapOffset));
    __ movzx_b(string, FieldOperand(string, Map::kInstanceTypeOffset));

    __ and_(string, Immediate(kStringRepresentationMask | kStringEncodingMask));
    static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
    static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
    __ cmp(string, Immediate(encoding == String::ONE_BYTE_ENCODING
                             ? one_byte_seq_type : two_byte_seq_type));
    __ Check(equal, kUnexpectedStringType);
    __ pop(string);
  }

  Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
  if (encoding == String::ONE_BYTE_ENCODING) {
    __ movzx_b(result, operand);
  } else {
    __ movzx_w(result, operand);
  }
}


void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
  String::Encoding encoding = instr->hydrogen()->encoding();
  Register string = ToRegister(instr->string());

  if (FLAG_debug_code) {
    Register value = ToRegister(instr->value());
    Register index = ToRegister(instr->index());
    static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
    static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
    int encoding_mask =
        instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
        ? one_byte_seq_type : two_byte_seq_type;
    __ EmitSeqStringSetCharCheck(string, index, value, encoding_mask);
  }

  Operand operand = BuildSeqStringOperand(string, instr->index(), encoding);
  if (instr->value()->IsConstantOperand()) {
    int value = ToRepresentation(LConstantOperand::cast(instr->value()),
                                 Representation::Integer32());
2167
    DCHECK_LE(0, value);
danno@chromium.org's avatar
danno@chromium.org committed
2168
    if (encoding == String::ONE_BYTE_ENCODING) {
2169
      DCHECK_LE(value, String::kMaxOneByteCharCode);
danno@chromium.org's avatar
danno@chromium.org committed
2170 2171
      __ mov_b(operand, static_cast<int8_t>(value));
    } else {
2172
      DCHECK_LE(value, String::kMaxUtf16CodeUnit);
danno@chromium.org's avatar
danno@chromium.org committed
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
      __ mov_w(operand, static_cast<int16_t>(value));
    }
  } else {
    Register value = ToRegister(instr->value());
    if (encoding == String::ONE_BYTE_ENCODING) {
      __ mov_b(operand, value);
    } else {
      __ mov_w(operand, value);
    }
  }
}


void LCodeGen::DoAddI(LAddI* instr) {
  LOperand* left = instr->left();
  LOperand* right = instr->right();

  if (LAddI::UseLea(instr->hydrogen()) && !left->Equals(instr->result())) {
    if (right->IsConstantOperand()) {
      int32_t offset = ToRepresentation(LConstantOperand::cast(right),
                                        instr->hydrogen()->representation());
      __ lea(ToRegister(instr->result()), MemOperand(ToRegister(left), offset));
    } else {
      Operand address(ToRegister(left), ToRegister(right), times_1, 0);
      __ lea(ToRegister(instr->result()), address);
    }
  } else {
    if (right->IsConstantOperand()) {
      __ add(ToOperand(left),
             ToImmediate(right, instr->hydrogen()->representation()));
    } else {
      __ add(ToRegister(left), ToOperand(right));
    }
    if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
2207
      DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
danno@chromium.org's avatar
danno@chromium.org committed
2208 2209 2210 2211 2212 2213 2214 2215
    }
  }
}


void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
  LOperand* left = instr->left();
  LOperand* right = instr->right();
2216
  DCHECK(left->Equals(instr->result()));
danno@chromium.org's avatar
danno@chromium.org committed
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
  HMathMinMax::Operation operation = instr->hydrogen()->operation();
  if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
    Label return_left;
    Condition condition = (operation == HMathMinMax::kMathMin)
        ? less_equal
        : greater_equal;
    if (right->IsConstantOperand()) {
      Operand left_op = ToOperand(left);
      Immediate immediate = ToImmediate(LConstantOperand::cast(instr->right()),
                                        instr->hydrogen()->representation());
      __ cmp(left_op, immediate);
      __ j(condition, &return_left, Label::kNear);
      __ mov(left_op, immediate);
    } else {
      Register left_reg = ToRegister(left);
      Operand right_op = ToOperand(right);
      __ cmp(left_reg, right_op);
      __ j(condition, &return_left, Label::kNear);
      __ mov(left_reg, right_op);
    }
    __ bind(&return_left);
  } else {
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
    DCHECK(instr->hydrogen()->representation().IsDouble());
    Label check_nan_left, check_zero, return_left, return_right;
    Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
    X87Register left_reg = ToX87Register(left);
    X87Register right_reg = ToX87Register(right);

    X87PrepareBinaryOp(left_reg, right_reg, ToX87Register(instr->result()));
    __ fld(1);
    __ fld(1);
    __ FCmp();
    __ j(parity_even, &check_nan_left, Label::kNear);  // At least one NaN.
    __ j(equal, &check_zero, Label::kNear);            // left == right.
    __ j(condition, &return_left, Label::kNear);
    __ jmp(&return_right, Label::kNear);

    __ bind(&check_zero);
    __ fld(0);
    __ fldz();
    __ FCmp();
    __ j(not_equal, &return_left, Label::kNear);  // left == right != 0.
    // At this point, both left and right are either 0 or -0.
    if (operation == HMathMinMax::kMathMin) {
      // Push st0 and st1 to stack, then pop them to temp registers and OR them,
      // load it to left.
      Register scratch_reg = ToRegister(instr->temp());
      __ fld(1);
      __ fld(1);
      __ sub(esp, Immediate(2 * kPointerSize));
      __ fstp_s(MemOperand(esp, 0));
      __ fstp_s(MemOperand(esp, kPointerSize));
      __ pop(scratch_reg);
      __ xor_(MemOperand(esp, 0), scratch_reg);
      X87Mov(left_reg, MemOperand(esp, 0), kX87FloatOperand);
      __ pop(scratch_reg);  // restore esp
    } else {
      // Since we operate on +0 and/or -0, addsd and andsd have the same effect.
      X87Fxch(left_reg);
      __ fadd(1);
    }
    __ jmp(&return_left, Label::kNear);

    __ bind(&check_nan_left);
    __ fld(0);
    __ fld(0);
    __ FCmp();                                      // NaN check.
    __ j(parity_even, &return_left, Label::kNear);  // left == NaN.

    __ bind(&return_right);
    X87Fxch(left_reg);
    X87Mov(left_reg, right_reg);

    __ bind(&return_left);
danno@chromium.org's avatar
danno@chromium.org committed
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
  }
}


void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
  X87Register left = ToX87Register(instr->left());
  X87Register right = ToX87Register(instr->right());
  X87Register result = ToX87Register(instr->result());
  if (instr->op() != Token::MOD) {
    X87PrepareBinaryOp(left, right, result);
  }
2302 2303
  // Set the precision control to double-precision.
  __ X87SetFPUCW(0x027F);
danno@chromium.org's avatar
danno@chromium.org committed
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
  switch (instr->op()) {
    case Token::ADD:
      __ fadd_i(1);
      break;
    case Token::SUB:
      __ fsub_i(1);
      break;
    case Token::MUL:
      __ fmul_i(1);
      break;
    case Token::DIV:
      __ fdiv_i(1);
      break;
    case Token::MOD: {
      // Pass two doubles as arguments on the stack.
      __ PrepareCallCFunction(4, eax);
      X87Mov(Operand(esp, 1 * kDoubleSize), right);
      X87Mov(Operand(esp, 0), left);
      X87Free(right);
2323
      DCHECK(left.is(result));
danno@chromium.org's avatar
danno@chromium.org committed
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
      X87PrepareToWrite(result);
      __ CallCFunction(
          ExternalReference::mod_two_doubles_operation(isolate()),
          4);

      // Return value is in st(0) on ia32.
      X87CommitWrite(result);
      break;
    }
    default:
      UNREACHABLE();
      break;
  }
2337

2338 2339
  // Restore the default value of control word.
  __ X87SetFPUCW(0x037F);
danno@chromium.org's avatar
danno@chromium.org committed
2340 2341 2342 2343
}


void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
2344 2345 2346 2347
  DCHECK(ToRegister(instr->context()).is(esi));
  DCHECK(ToRegister(instr->left()).is(edx));
  DCHECK(ToRegister(instr->right()).is(eax));
  DCHECK(ToRegister(instr->result()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
2348

2349
  Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), instr->op()).code();
2350
  CallCode(code, RelocInfo::CODE_TARGET, instr);
danno@chromium.org's avatar
danno@chromium.org committed
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391
}


template<class InstrType>
void LCodeGen::EmitBranch(InstrType instr, Condition cc) {
  int left_block = instr->TrueDestination(chunk_);
  int right_block = instr->FalseDestination(chunk_);

  int next_block = GetNextEmittedBlock();

  if (right_block == left_block || cc == no_condition) {
    EmitGoto(left_block);
  } else if (left_block == next_block) {
    __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
  } else if (right_block == next_block) {
    __ j(cc, chunk_->GetAssemblyLabel(left_block));
  } else {
    __ j(cc, chunk_->GetAssemblyLabel(left_block));
    __ jmp(chunk_->GetAssemblyLabel(right_block));
  }
}


template<class InstrType>
void LCodeGen::EmitFalseBranch(InstrType instr, Condition cc) {
  int false_block = instr->FalseDestination(chunk_);
  if (cc == no_condition) {
    __ jmp(chunk_->GetAssemblyLabel(false_block));
  } else {
    __ j(cc, chunk_->GetAssemblyLabel(false_block));
  }
}


void LCodeGen::DoBranch(LBranch* instr) {
  Representation r = instr->hydrogen()->value()->representation();
  if (r.IsSmiOrInteger32()) {
    Register reg = ToRegister(instr->value());
    __ test(reg, Operand(reg));
    EmitBranch(instr, not_zero);
  } else if (r.IsDouble()) {
2392 2393 2394 2395 2396
    X87Register reg = ToX87Register(instr->value());
    X87LoadForUsage(reg);
    __ fldz();
    __ FCmp();
    EmitBranch(instr, not_zero);
danno@chromium.org's avatar
danno@chromium.org committed
2397
  } else {
2398
    DCHECK(r.IsTagged());
danno@chromium.org's avatar
danno@chromium.org committed
2399 2400 2401
    Register reg = ToRegister(instr->value());
    HType type = instr->hydrogen()->value()->type();
    if (type.IsBoolean()) {
2402
      DCHECK(!info()->IsStub());
danno@chromium.org's avatar
danno@chromium.org committed
2403 2404 2405
      __ cmp(reg, factory()->true_value());
      EmitBranch(instr, equal);
    } else if (type.IsSmi()) {
2406
      DCHECK(!info()->IsStub());
danno@chromium.org's avatar
danno@chromium.org committed
2407 2408 2409
      __ test(reg, Operand(reg));
      EmitBranch(instr, not_equal);
    } else if (type.IsJSArray()) {
2410
      DCHECK(!info()->IsStub());
danno@chromium.org's avatar
danno@chromium.org committed
2411 2412 2413 2414
      EmitBranch(instr, no_condition);
    } else if (type.IsHeapNumber()) {
      UNREACHABLE();
    } else if (type.IsString()) {
2415
      DCHECK(!info()->IsStub());
danno@chromium.org's avatar
danno@chromium.org committed
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448
      __ cmp(FieldOperand(reg, String::kLengthOffset), Immediate(0));
      EmitBranch(instr, not_equal);
    } else {
      ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
      if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();

      if (expected.Contains(ToBooleanStub::UNDEFINED)) {
        // undefined -> false.
        __ cmp(reg, factory()->undefined_value());
        __ j(equal, instr->FalseLabel(chunk_));
      }
      if (expected.Contains(ToBooleanStub::BOOLEAN)) {
        // true -> true.
        __ cmp(reg, factory()->true_value());
        __ j(equal, instr->TrueLabel(chunk_));
        // false -> false.
        __ cmp(reg, factory()->false_value());
        __ j(equal, instr->FalseLabel(chunk_));
      }
      if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
        // 'null' -> false.
        __ cmp(reg, factory()->null_value());
        __ j(equal, instr->FalseLabel(chunk_));
      }

      if (expected.Contains(ToBooleanStub::SMI)) {
        // Smis: 0 -> false, all other -> true.
        __ test(reg, Operand(reg));
        __ j(equal, instr->FalseLabel(chunk_));
        __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
      } else if (expected.NeedsMap()) {
        // If we need a map later and have a Smi -> deopt.
        __ test(reg, Immediate(kSmiTagMask));
2449
        DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
danno@chromium.org's avatar
danno@chromium.org committed
2450 2451 2452 2453 2454
      }

      Register map = no_reg;  // Keep the compiler happy.
      if (expected.NeedsMap()) {
        map = ToRegister(instr->temp());
2455
        DCHECK(!map.is(reg));
danno@chromium.org's avatar
danno@chromium.org committed
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505
        __ mov(map, FieldOperand(reg, HeapObject::kMapOffset));

        if (expected.CanBeUndetectable()) {
          // Undetectable -> false.
          __ test_b(FieldOperand(map, Map::kBitFieldOffset),
                    1 << Map::kIsUndetectable);
          __ j(not_zero, instr->FalseLabel(chunk_));
        }
      }

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

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

      if (expected.Contains(ToBooleanStub::SYMBOL)) {
        // Symbol value -> true.
        __ CmpInstanceType(map, SYMBOL_TYPE);
        __ j(equal, instr->TrueLabel(chunk_));
      }

      if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
        // heap number -> false iff +0, -0, or NaN.
        Label not_heap_number;
        __ cmp(FieldOperand(reg, HeapObject::kMapOffset),
               factory()->heap_number_map());
        __ j(not_equal, &not_heap_number, Label::kNear);
        __ fldz();
        __ fld_d(FieldOperand(reg, HeapNumber::kValueOffset));
        __ FCmp();
        __ j(zero, instr->FalseLabel(chunk_));
        __ jmp(instr->TrueLabel(chunk_));
        __ bind(&not_heap_number);
      }

      if (!expected.IsGeneric()) {
        // We've seen something for the first time -> deopt.
        // This can only happen if we are not generic already.
2506
        DeoptimizeIf(no_condition, instr, Deoptimizer::kUnexpectedObject);
danno@chromium.org's avatar
danno@chromium.org committed
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 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 2562 2563 2564
      }
    }
  }
}


void LCodeGen::EmitGoto(int block) {
  if (!IsNextEmittedBlock(block)) {
    __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
  }
}


void LCodeGen::DoClobberDoubles(LClobberDoubles* instr) {
}


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


Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
  Condition cond = no_condition;
  switch (op) {
    case Token::EQ:
    case Token::EQ_STRICT:
      cond = equal;
      break;
    case Token::NE:
    case Token::NE_STRICT:
      cond = not_equal;
      break;
    case Token::LT:
      cond = is_unsigned ? below : less;
      break;
    case Token::GT:
      cond = is_unsigned ? above : greater;
      break;
    case Token::LTE:
      cond = is_unsigned ? below_equal : less_equal;
      break;
    case Token::GTE:
      cond = is_unsigned ? above_equal : greater_equal;
      break;
    case Token::IN:
    case Token::INSTANCEOF:
    default:
      UNREACHABLE();
  }
  return cond;
}


void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
  LOperand* left = instr->left();
  LOperand* right = instr->right();
  bool is_unsigned =
2565 2566 2567
      instr->is_double() ||
      instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
      instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
danno@chromium.org's avatar
danno@chromium.org committed
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
  Condition cc = TokenToCondition(instr->op(), is_unsigned);

  if (left->IsConstantOperand() && right->IsConstantOperand()) {
    // We can statically evaluate the comparison.
    double left_val = ToDouble(LConstantOperand::cast(left));
    double right_val = ToDouble(LConstantOperand::cast(right));
    int next_block = EvalComparison(instr->op(), left_val, right_val) ?
        instr->TrueDestination(chunk_) : instr->FalseDestination(chunk_);
    EmitGoto(next_block);
  } else {
    if (instr->is_double()) {
      X87LoadForUsage(ToX87Register(right), ToX87Register(left));
      __ FCmp();
      // Don't base result on EFLAGS when a NaN is involved. Instead
      // jump to the false block.
      __ j(parity_even, instr->FalseLabel(chunk_));
    } else {
      if (right->IsConstantOperand()) {
        __ cmp(ToOperand(left),
               ToImmediate(right, instr->hydrogen()->representation()));
      } else if (left->IsConstantOperand()) {
        __ cmp(ToOperand(right),
               ToImmediate(left, instr->hydrogen()->representation()));
2591 2592
        // We commuted the operands, so commute the condition.
        cc = CommuteCondition(cc);
danno@chromium.org's avatar
danno@chromium.org committed
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641
      } else {
        __ cmp(ToRegister(left), ToOperand(right));
      }
    }
    EmitBranch(instr, cc);
  }
}


void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
  Register left = ToRegister(instr->left());

  if (instr->right()->IsConstantOperand()) {
    Handle<Object> right = ToHandle(LConstantOperand::cast(instr->right()));
    __ CmpObject(left, right);
  } else {
    Operand right = ToOperand(instr->right());
    __ cmp(left, right);
  }
  EmitBranch(instr, equal);
}


void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
  if (instr->hydrogen()->representation().IsTagged()) {
    Register input_reg = ToRegister(instr->object());
    __ cmp(input_reg, factory()->the_hole_value());
    EmitBranch(instr, equal);
    return;
  }

  // Put the value to the top of stack
  X87Register src = ToX87Register(instr->object());
  X87LoadForUsage(src);
  __ fld(0);
  __ fld(0);
  __ FCmp();
  Label ok;
  __ j(parity_even, &ok, Label::kNear);
  __ fstp(0);
  EmitFalseBranch(instr, no_condition);
  __ bind(&ok);


  __ sub(esp, Immediate(kDoubleSize));
  __ fstp_d(MemOperand(esp, 0));

  __ add(esp, Immediate(kDoubleSize));
  int offset = sizeof(kHoleNanUpper32);
2642 2643 2644
  // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
  // so we check the upper with 0xffffffff for hole as a temporary fix.
  __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
danno@chromium.org's avatar
danno@chromium.org committed
2645 2646 2647 2648 2649 2650
  EmitBranch(instr, equal);
}


void LCodeGen::DoCompareMinusZeroAndBranch(LCompareMinusZeroAndBranch* instr) {
  Representation rep = instr->hydrogen()->value()->representation();
2651
  DCHECK(!rep.IsInteger32());
danno@chromium.org's avatar
danno@chromium.org committed
2652 2653

  if (rep.IsDouble()) {
2654 2655 2656 2657
    X87Register input = ToX87Register(instr->value());
    X87LoadForUsage(input);
    __ FXamMinusZero();
    EmitBranch(instr, equal);
danno@chromium.org's avatar
danno@chromium.org committed
2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
  } else {
    Register value = ToRegister(instr->value());
    Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
    __ CheckMap(value, map, instr->FalseLabel(chunk()), DO_SMI_CHECK);
    __ cmp(FieldOperand(value, HeapNumber::kExponentOffset),
           Immediate(0x1));
    EmitFalseBranch(instr, no_overflow);
    __ cmp(FieldOperand(value, HeapNumber::kMantissaOffset),
           Immediate(0x00000000));
    EmitBranch(instr, equal);
  }
}


Condition LCodeGen::EmitIsObject(Register input,
                                 Register temp1,
                                 Label* is_not_object,
                                 Label* is_object) {
  __ JumpIfSmi(input, is_not_object);

  __ cmp(input, isolate()->factory()->null_value());
  __ j(equal, is_object);

  __ mov(temp1, FieldOperand(input, HeapObject::kMapOffset));
  // Undetectable objects behave like undefined.
  __ test_b(FieldOperand(temp1, Map::kBitFieldOffset),
            1 << Map::kIsUndetectable);
  __ j(not_zero, is_not_object);

  __ movzx_b(temp1, FieldOperand(temp1, Map::kInstanceTypeOffset));
  __ cmp(temp1, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE);
  __ j(below, is_not_object);
  __ cmp(temp1, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
  return below_equal;
}


void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
  Register reg = ToRegister(instr->value());
  Register temp = ToRegister(instr->temp());

  Condition true_cond = EmitIsObject(
      reg, temp, instr->FalseLabel(chunk_), instr->TrueLabel(chunk_));

  EmitBranch(instr, true_cond);
}


Condition LCodeGen::EmitIsString(Register input,
                                 Register temp1,
                                 Label* is_not_string,
                                 SmiCheck check_needed = INLINE_SMI_CHECK) {
  if (check_needed == INLINE_SMI_CHECK) {
    __ JumpIfSmi(input, is_not_string);
  }

  Condition cond = masm_->IsObjectStringType(input, temp1, temp1);

  return cond;
}


void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
  Register reg = ToRegister(instr->value());
  Register temp = ToRegister(instr->temp());

  SmiCheck check_needed =
2725
      instr->hydrogen()->value()->type().IsHeapObject()
danno@chromium.org's avatar
danno@chromium.org committed
2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746
          ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;

  Condition true_cond = EmitIsString(
      reg, temp, instr->FalseLabel(chunk_), check_needed);

  EmitBranch(instr, true_cond);
}


void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
  Operand input = ToOperand(instr->value());

  __ test(input, Immediate(kSmiTagMask));
  EmitBranch(instr, zero);
}


void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
  Register input = ToRegister(instr->value());
  Register temp = ToRegister(instr->temp());

2747
  if (!instr->hydrogen()->value()->type().IsHeapObject()) {
danno@chromium.org's avatar
danno@chromium.org committed
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
    STATIC_ASSERT(kSmiTag == 0);
    __ JumpIfSmi(input, instr->FalseLabel(chunk_));
  }
  __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
  __ test_b(FieldOperand(temp, Map::kBitFieldOffset),
            1 << Map::kIsUndetectable);
  EmitBranch(instr, not_zero);
}


static Condition ComputeCompareCondition(Token::Value op) {
  switch (op) {
    case Token::EQ_STRICT:
    case Token::EQ:
      return equal;
    case Token::LT:
      return less;
    case Token::GT:
      return greater;
    case Token::LTE:
      return less_equal;
    case Token::GTE:
      return greater_equal;
    default:
      UNREACHABLE();
      return no_condition;
  }
}


void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
  Token::Value op = instr->op();

2781
  Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
danno@chromium.org's avatar
danno@chromium.org committed
2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
  CallCode(ic, RelocInfo::CODE_TARGET, instr);

  Condition condition = ComputeCompareCondition(op);
  __ test(eax, Operand(eax));

  EmitBranch(instr, condition);
}


static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
  InstanceType from = instr->from();
  InstanceType to = instr->to();
  if (from == FIRST_TYPE) return to;
2795
  DCHECK(from == to || to == LAST_TYPE);
danno@chromium.org's avatar
danno@chromium.org committed
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814
  return from;
}


static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
  InstanceType from = instr->from();
  InstanceType to = instr->to();
  if (from == to) return equal;
  if (to == LAST_TYPE) return above_equal;
  if (from == FIRST_TYPE) return below_equal;
  UNREACHABLE();
  return equal;
}


void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
  Register input = ToRegister(instr->value());
  Register temp = ToRegister(instr->temp());

2815
  if (!instr->hydrogen()->value()->type().IsHeapObject()) {
danno@chromium.org's avatar
danno@chromium.org committed
2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852
    __ JumpIfSmi(input, instr->FalseLabel(chunk_));
  }

  __ CmpObjectType(input, TestType(instr->hydrogen()), temp);
  EmitBranch(instr, BranchCondition(instr->hydrogen()));
}


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

  __ AssertString(input);

  __ mov(result, FieldOperand(input, String::kHashFieldOffset));
  __ IndexFromHash(result, result);
}


void LCodeGen::DoHasCachedArrayIndexAndBranch(
    LHasCachedArrayIndexAndBranch* instr) {
  Register input = ToRegister(instr->value());

  __ test(FieldOperand(input, String::kHashFieldOffset),
          Immediate(String::kContainsCachedArrayIndexMask));
  EmitBranch(instr, equal);
}


// Branches to a label or falls through with the answer in the z flag.  Trashes
// the temp registers, but not the input.
void LCodeGen::EmitClassOfTest(Label* is_true,
                               Label* is_false,
                               Handle<String>class_name,
                               Register input,
                               Register temp,
                               Register temp2) {
2853 2854 2855
  DCHECK(!input.is(temp));
  DCHECK(!input.is(temp2));
  DCHECK(!temp.is(temp2));
danno@chromium.org's avatar
danno@chromium.org committed
2856 2857
  __ JumpIfSmi(input, is_false);

2858
  if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
danno@chromium.org's avatar
danno@chromium.org committed
2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884
    // Assuming the following assertions, we can use the same compares to test
    // for both being a function type and being in the object type range.
    STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
    STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
                  FIRST_SPEC_OBJECT_TYPE + 1);
    STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
                  LAST_SPEC_OBJECT_TYPE - 1);
    STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
    __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
    __ j(below, is_false);
    __ j(equal, is_true);
    __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
    __ j(equal, is_true);
  } else {
    // Faster code path to avoid two compares: subtract lower bound from the
    // actual type and do a signed compare with the width of the type range.
    __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));
    __ movzx_b(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
    __ sub(Operand(temp2), Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
    __ cmp(Operand(temp2), Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
                                     FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
    __ j(above, is_false);
  }

  // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
  // Check if the constructor in the map is a function.
2885
  __ GetMapConstructor(temp, temp, temp2);
danno@chromium.org's avatar
danno@chromium.org committed
2886
  // Objects with a non-function constructor have class 'Object'.
2887
  __ CmpInstanceType(temp2, JS_FUNCTION_TYPE);
2888
  if (String::Equals(class_name, isolate()->factory()->Object_string())) {
danno@chromium.org's avatar
danno@chromium.org committed
2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932
    __ j(not_equal, is_true);
  } else {
    __ j(not_equal, is_false);
  }

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


void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
  Register input = ToRegister(instr->value());
  Register temp = ToRegister(instr->temp());
  Register temp2 = ToRegister(instr->temp2());

  Handle<String> class_name = instr->hydrogen()->class_name();

  EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
      class_name, input, temp, temp2);

  EmitBranch(instr, equal);
}


void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
  Register reg = ToRegister(instr->value());
  __ cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
  EmitBranch(instr, equal);
}


void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
  // Object and function are in fixed registers defined by the stub.
2933
  DCHECK(ToRegister(instr->context()).is(esi));
danno@chromium.org's avatar
danno@chromium.org committed
2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948
  InstanceofStub stub(isolate(), InstanceofStub::kArgsInRegisters);
  CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);

  Label true_value, done;
  __ test(eax, Operand(eax));
  __ j(zero, &true_value, Label::kNear);
  __ mov(ToRegister(instr->result()), factory()->false_value());
  __ jmp(&done, Label::kNear);
  __ bind(&true_value);
  __ mov(ToRegister(instr->result()), factory()->true_value());
  __ bind(&done);
}


void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
2949
  class DeferredInstanceOfKnownGlobal FINAL : public LDeferredCode {
danno@chromium.org's avatar
danno@chromium.org committed
2950 2951 2952 2953 2954
   public:
    DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
                                  LInstanceOfKnownGlobal* instr,
                                  const X87Stack& x87_stack)
        : LDeferredCode(codegen, x87_stack), instr_(instr) { }
2955
    void Generate() OVERRIDE {
danno@chromium.org's avatar
danno@chromium.org committed
2956 2957
      codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
    }
2958
    LInstruction* instr() OVERRIDE { return instr_; }
danno@chromium.org's avatar
danno@chromium.org committed
2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029
    Label* map_check() { return &map_check_; }
   private:
    LInstanceOfKnownGlobal* instr_;
    Label map_check_;
  };

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

  Label done, false_result;
  Register object = ToRegister(instr->value());
  Register temp = ToRegister(instr->temp());

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

  // This is the inlined call site instanceof cache. The two occurences of the
  // hole value will be patched to the last map/result pair generated by the
  // instanceof stub.
  Label cache_miss;
  Register map = ToRegister(instr->temp());
  __ mov(map, FieldOperand(object, HeapObject::kMapOffset));
  __ bind(deferred->map_check());  // Label for calculating code patching.
  Handle<Cell> cache_cell = factory()->NewCell(factory()->the_hole_value());
  __ cmp(map, Operand::ForCell(cache_cell));  // Patched to cached map.
  __ j(not_equal, &cache_miss, Label::kNear);
  __ mov(eax, factory()->the_hole_value());  // Patched to either true or false.
  __ jmp(&done, Label::kNear);

  // The inlined call site cache did not match. Check for null and string
  // before calling the deferred code.
  __ bind(&cache_miss);
  // Null is not an instance of anything.
  __ cmp(object, factory()->null_value());
  __ j(equal, &false_result, Label::kNear);

  // String values are not instances of anything.
  Condition is_string = masm_->IsObjectStringType(object, temp, temp);
  __ j(is_string, &false_result, Label::kNear);

  // Go to the deferred code.
  __ jmp(deferred->entry());

  __ bind(&false_result);
  __ mov(ToRegister(instr->result()), factory()->false_value());

  // Here result has either true or false. Deferred code also produces true or
  // false object.
  __ bind(deferred->exit());
  __ bind(&done);
}


void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
                                               Label* map_check) {
  PushSafepointRegistersScope scope(this);

  InstanceofStub::Flags flags = InstanceofStub::kNoFlags;
  flags = static_cast<InstanceofStub::Flags>(
      flags | InstanceofStub::kArgsInRegisters);
  flags = static_cast<InstanceofStub::Flags>(
      flags | InstanceofStub::kCallSiteInlineCheck);
  flags = static_cast<InstanceofStub::Flags>(
      flags | InstanceofStub::kReturnTrueFalseObject);
  InstanceofStub stub(isolate(), flags);

  // Get the temp register reserved by the instruction. This needs to be a
  // register which is pushed last by PushSafepointRegisters as top of the
  // stack is used to pass the offset to the location of the map check to
  // the stub.
  Register temp = ToRegister(instr->temp());
3030
  DCHECK(MacroAssembler::SafepointRegisterStackIndex(temp) == 0);
danno@chromium.org's avatar
danno@chromium.org committed
3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052
  __ LoadHeapObject(InstanceofStub::right(), instr->function());
  static const int kAdditionalDelta = 13;
  int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
  __ mov(temp, Immediate(delta));
  __ StoreToSafepointRegisterSlot(temp, temp);
  CallCodeGeneric(stub.GetCode(),
                  RelocInfo::CODE_TARGET,
                  instr,
                  RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
  // Get the deoptimization index of the LLazyBailout-environment that
  // corresponds to this instruction.
  LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
  safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());

  // Put the result value into the eax slot and restore all registers.
  __ StoreToSafepointRegisterSlot(eax, eax);
}


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

3053
  Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
danno@chromium.org's avatar
danno@chromium.org committed
3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
  CallCode(ic, RelocInfo::CODE_TARGET, instr);

  Condition condition = ComputeCompareCondition(op);
  Label true_value, done;
  __ test(eax, Operand(eax));
  __ j(condition, &true_value, Label::kNear);
  __ mov(ToRegister(instr->result()), factory()->false_value());
  __ jmp(&done, Label::kNear);
  __ bind(&true_value);
  __ mov(ToRegister(instr->result()), factory()->true_value());
  __ bind(&done);
}


void LCodeGen::EmitReturn(LReturn* instr, bool dynamic_frame_alignment) {
  int extra_value_count = dynamic_frame_alignment ? 2 : 1;

  if (instr->has_constant_parameter_count()) {
    int parameter_count = ToInteger32(instr->constant_parameter_count());
    if (dynamic_frame_alignment && FLAG_debug_code) {
      __ cmp(Operand(esp,
                     (parameter_count + extra_value_count) * kPointerSize),
             Immediate(kAlignmentZapValue));
      __ Assert(equal, kExpectedAlignmentMarker);
    }
    __ Ret((parameter_count + extra_value_count) * kPointerSize, ecx);
  } else {
3081
    DCHECK(info()->IsStub());  // Functions would need to drop one more value.
danno@chromium.org's avatar
danno@chromium.org committed
3082 3083 3084 3085 3086
    Register reg = ToRegister(instr->parameter_count());
    // The argument count parameter is a smi
    __ SmiUntag(reg);
    Register return_addr_reg = reg.is(ecx) ? ebx : ecx;
    if (dynamic_frame_alignment && FLAG_debug_code) {
3087
      DCHECK(extra_value_count == 2);
danno@chromium.org's avatar
danno@chromium.org committed
3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142
      __ cmp(Operand(esp, reg, times_pointer_size,
                     extra_value_count * kPointerSize),
             Immediate(kAlignmentZapValue));
      __ Assert(equal, kExpectedAlignmentMarker);
    }

    // emit code to restore stack based on instr->parameter_count()
    __ pop(return_addr_reg);  // save return address
    if (dynamic_frame_alignment) {
      __ inc(reg);  // 1 more for alignment
    }
    __ shl(reg, kPointerSizeLog2);
    __ add(esp, reg);
    __ jmp(return_addr_reg);
  }
}


void LCodeGen::DoReturn(LReturn* instr) {
  if (FLAG_trace && info()->IsOptimizing()) {
    // Preserve the return value on the stack and rely on the runtime call
    // to return the value in the same register.  We're leaving the code
    // managed by the register allocator and tearing down the frame, it's
    // safe to write to the context register.
    __ push(eax);
    __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
    __ CallRuntime(Runtime::kTraceExit, 1);
  }
  if (dynamic_frame_alignment_) {
    // Fetch the state of the dynamic frame alignment.
    __ mov(edx, Operand(ebp,
      JavaScriptFrameConstants::kDynamicAlignmentStateOffset));
  }
  int no_frame_start = -1;
  if (NeedsEagerFrame()) {
    __ mov(esp, ebp);
    __ pop(ebp);
    no_frame_start = masm_->pc_offset();
  }
  if (dynamic_frame_alignment_) {
    Label no_padding;
    __ cmp(edx, Immediate(kNoAlignmentPadding));
    __ j(equal, &no_padding, Label::kNear);

    EmitReturn(instr, true);
    __ bind(&no_padding);
  }

  EmitReturn(instr, false);
  if (no_frame_start != -1) {
    info()->AddNoFrameRange(no_frame_start, masm_->pc_offset());
  }
}


3143 3144 3145
template <class T>
void LCodeGen::EmitVectorLoadICRegisters(T* instr) {
  DCHECK(FLAG_vector_ics);
3146
  Register vector_register = ToRegister(instr->temp_vector());
3147
  Register slot_register = VectorLoadICDescriptor::SlotRegister();
3148
  DCHECK(vector_register.is(VectorLoadICDescriptor::VectorRegister()));
3149 3150 3151
  DCHECK(slot_register.is(eax));

  AllowDeferredHandleDereference vector_structure_check;
3152 3153
  Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
  __ mov(vector_register, vector);
3154
  // No need to allocate this register.
3155 3156 3157
  FeedbackVectorICSlot slot = instr->hydrogen()->slot();
  int index = vector->GetIndex(slot);
  __ mov(slot_register, Immediate(Smi::FromInt(index)));
3158 3159 3160
}


danno@chromium.org's avatar
danno@chromium.org committed
3161
void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
3162
  DCHECK(ToRegister(instr->context()).is(esi));
3163
  DCHECK(ToRegister(instr->global_object())
3164
             .is(LoadDescriptor::ReceiverRegister()));
3165
  DCHECK(ToRegister(instr->result()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
3166

3167
  __ mov(LoadDescriptor::NameRegister(), instr->name());
3168
  if (FLAG_vector_ics) {
3169
    EmitVectorLoadICRegisters<LLoadGlobalGeneric>(instr);
3170
  }
danno@chromium.org's avatar
danno@chromium.org committed
3171
  ContextualMode mode = instr->for_typeof() ? NOT_CONTEXTUAL : CONTEXTUAL;
3172 3173
  Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(isolate(), mode,
                                                       PREMONOMORPHIC).code();
danno@chromium.org's avatar
danno@chromium.org committed
3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185
  CallCode(ic, RelocInfo::CODE_TARGET, instr);
}


void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
  Register context = ToRegister(instr->context());
  Register result = ToRegister(instr->result());
  __ mov(result, ContextOperand(context, instr->slot_index()));

  if (instr->hydrogen()->RequiresHoleCheck()) {
    __ cmp(result, factory()->the_hole_value());
    if (instr->hydrogen()->DeoptimizesOnHole()) {
3186
      DeoptimizeIf(equal, instr, Deoptimizer::kHole);
danno@chromium.org's avatar
danno@chromium.org committed
3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
    } else {
      Label is_not_hole;
      __ j(not_equal, &is_not_hole, Label::kNear);
      __ mov(result, factory()->undefined_value());
      __ bind(&is_not_hole);
    }
  }
}


void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
  Register context = ToRegister(instr->context());
  Register value = ToRegister(instr->value());

  Label skip_assignment;

  Operand target = ContextOperand(context, instr->slot_index());
  if (instr->hydrogen()->RequiresHoleCheck()) {
    __ cmp(target, factory()->the_hole_value());
    if (instr->hydrogen()->DeoptimizesOnHole()) {
3207
      DeoptimizeIf(equal, instr, Deoptimizer::kHole);
danno@chromium.org's avatar
danno@chromium.org committed
3208 3209 3210 3211 3212 3213 3214 3215
    } else {
      __ j(not_equal, &skip_assignment, Label::kNear);
    }
  }

  __ mov(target, value);
  if (instr->hydrogen()->NeedsWriteBarrier()) {
    SmiCheck check_needed =
3216
        instr->hydrogen()->value()->type().IsHeapObject()
danno@chromium.org's avatar
danno@chromium.org committed
3217 3218 3219
            ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
    Register temp = ToRegister(instr->temp());
    int offset = Context::SlotOffset(instr->slot_index());
3220 3221
    __ RecordWriteContextSlot(context, offset, value, temp, kSaveFPRegs,
                              EMIT_REMEMBERED_SET, check_needed);
danno@chromium.org's avatar
danno@chromium.org committed
3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
  }

  __ bind(&skip_assignment);
}


void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
  HObjectAccess access = instr->hydrogen()->access();
  int offset = access.offset();

  if (access.IsExternalMemory()) {
    Register result = ToRegister(instr->result());
    MemOperand operand = instr->object()->IsConstantOperand()
        ? MemOperand::StaticVariable(ToExternalReference(
                LConstantOperand::cast(instr->object())))
        : MemOperand(ToRegister(instr->object()), offset);
    __ Load(result, operand, access.representation());
    return;
  }

  Register object = ToRegister(instr->object());
  if (instr->hydrogen()->representation().IsDouble()) {
    X87Mov(ToX87Register(instr->result()), FieldOperand(object, offset));
    return;
  }

  Register result = ToRegister(instr->result());
  if (!access.IsInobject()) {
    __ mov(result, FieldOperand(object, JSObject::kPropertiesOffset));
    object = result;
  }
  __ Load(result, FieldOperand(object, offset), access.representation());
}


void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
3258
  DCHECK(!operand->IsDoubleRegister());
danno@chromium.org's avatar
danno@chromium.org committed
3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
  if (operand->IsConstantOperand()) {
    Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
    AllowDeferredHandleDereference smi_check;
    if (object->IsSmi()) {
      __ Push(Handle<Smi>::cast(object));
    } else {
      __ PushHeapObject(Handle<HeapObject>::cast(object));
    }
  } else if (operand->IsRegister()) {
    __ push(ToRegister(operand));
  } else {
    __ push(ToOperand(operand));
  }
}


void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
3276
  DCHECK(ToRegister(instr->context()).is(esi));
3277
  DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
3278
  DCHECK(ToRegister(instr->result()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
3279

3280
  __ mov(LoadDescriptor::NameRegister(), instr->name());
3281
  if (FLAG_vector_ics) {
3282
    EmitVectorLoadICRegisters<LLoadNamedGeneric>(instr);
3283
  }
3284 3285 3286
  Handle<Code> ic = CodeFactory::LoadICInOptimizedCode(
                        isolate(), NOT_CONTEXTUAL,
                        instr->hydrogen()->initialization_state()).code();
danno@chromium.org's avatar
danno@chromium.org committed
3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301
  CallCode(ic, RelocInfo::CODE_TARGET, instr);
}


void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
  Register function = ToRegister(instr->function());
  Register temp = ToRegister(instr->temp());
  Register result = ToRegister(instr->result());

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

  // Check that the function has a prototype or an initial map.
  __ cmp(Operand(result), Immediate(factory()->the_hole_value()));
3302
  DeoptimizeIf(equal, instr, Deoptimizer::kHole);
danno@chromium.org's avatar
danno@chromium.org committed
3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392

  // If the function does not have an initial map, we're done.
  Label done;
  __ CmpObjectType(result, MAP_TYPE, temp);
  __ j(not_equal, &done, Label::kNear);

  // Get the prototype from the initial map.
  __ mov(result, FieldOperand(result, Map::kPrototypeOffset));

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


void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
  Register result = ToRegister(instr->result());
  __ LoadRoot(result, instr->index());
}


void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
  Register arguments = ToRegister(instr->arguments());
  Register result = ToRegister(instr->result());
  if (instr->length()->IsConstantOperand() &&
      instr->index()->IsConstantOperand()) {
    int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
    int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
    int index = (const_length - const_index) + 1;
    __ mov(result, Operand(arguments, index * kPointerSize));
  } else {
    Register length = ToRegister(instr->length());
    Operand index = ToOperand(instr->index());
    // There are two words between the frame pointer and the last argument.
    // Subtracting from length accounts for one of them add one more.
    __ sub(length, index);
    __ mov(result, Operand(arguments, length, times_4, kPointerSize));
  }
}


void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
  ElementsKind elements_kind = instr->elements_kind();
  LOperand* key = instr->key();
  if (!key->IsConstantOperand() &&
      ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
                                  elements_kind)) {
    __ SmiUntag(ToRegister(key));
  }
  Operand operand(BuildFastArrayOperand(
      instr->elements(),
      key,
      instr->hydrogen()->key()->representation(),
      elements_kind,
      instr->base_offset()));
  if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
      elements_kind == FLOAT32_ELEMENTS) {
    X87Mov(ToX87Register(instr->result()), operand, kX87FloatOperand);
  } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
             elements_kind == FLOAT64_ELEMENTS) {
    X87Mov(ToX87Register(instr->result()), operand);
  } else {
    Register result(ToRegister(instr->result()));
    switch (elements_kind) {
      case EXTERNAL_INT8_ELEMENTS:
      case INT8_ELEMENTS:
        __ movsx_b(result, operand);
        break;
      case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
      case EXTERNAL_UINT8_ELEMENTS:
      case UINT8_ELEMENTS:
      case UINT8_CLAMPED_ELEMENTS:
        __ movzx_b(result, operand);
        break;
      case EXTERNAL_INT16_ELEMENTS:
      case INT16_ELEMENTS:
        __ movsx_w(result, operand);
        break;
      case EXTERNAL_UINT16_ELEMENTS:
      case UINT16_ELEMENTS:
        __ movzx_w(result, operand);
        break;
      case EXTERNAL_INT32_ELEMENTS:
      case INT32_ELEMENTS:
        __ mov(result, operand);
        break;
      case EXTERNAL_UINT32_ELEMENTS:
      case UINT32_ELEMENTS:
        __ mov(result, operand);
        if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
          __ test(result, Operand(result));
3393
          DeoptimizeIf(negative, instr, Deoptimizer::kNegativeValue);
danno@chromium.org's avatar
danno@chromium.org committed
3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422
        }
        break;
      case EXTERNAL_FLOAT32_ELEMENTS:
      case EXTERNAL_FLOAT64_ELEMENTS:
      case FLOAT32_ELEMENTS:
      case FLOAT64_ELEMENTS:
      case FAST_SMI_ELEMENTS:
      case FAST_ELEMENTS:
      case FAST_DOUBLE_ELEMENTS:
      case FAST_HOLEY_SMI_ELEMENTS:
      case FAST_HOLEY_ELEMENTS:
      case FAST_HOLEY_DOUBLE_ELEMENTS:
      case DICTIONARY_ELEMENTS:
      case SLOPPY_ARGUMENTS_ELEMENTS:
        UNREACHABLE();
        break;
    }
  }
}


void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
  if (instr->hydrogen()->RequiresHoleCheck()) {
    Operand hole_check_operand = BuildFastArrayOperand(
        instr->elements(), instr->key(),
        instr->hydrogen()->key()->representation(),
        FAST_DOUBLE_ELEMENTS,
        instr->base_offset() + sizeof(kHoleNanLower32));
    __ cmp(hole_check_operand, Immediate(kHoleNanUpper32));
3423
    DeoptimizeIf(equal, instr, Deoptimizer::kHole);
danno@chromium.org's avatar
danno@chromium.org committed
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440
  }

  Operand double_load_operand = BuildFastArrayOperand(
      instr->elements(),
      instr->key(),
      instr->hydrogen()->key()->representation(),
      FAST_DOUBLE_ELEMENTS,
      instr->base_offset());
  X87Mov(ToX87Register(instr->result()), double_load_operand);
}


void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
  Register result = ToRegister(instr->result());

  // Load the result.
  __ mov(result,
3441
         BuildFastArrayOperand(instr->elements(), instr->key(),
danno@chromium.org's avatar
danno@chromium.org committed
3442
                               instr->hydrogen()->key()->representation(),
3443
                               FAST_ELEMENTS, instr->base_offset()));
danno@chromium.org's avatar
danno@chromium.org committed
3444 3445 3446 3447 3448

  // Check for the hole value.
  if (instr->hydrogen()->RequiresHoleCheck()) {
    if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
      __ test(result, Immediate(kSmiTagMask));
3449
      DeoptimizeIf(not_equal, instr, Deoptimizer::kNotASmi);
danno@chromium.org's avatar
danno@chromium.org committed
3450 3451
    } else {
      __ cmp(result, factory()->the_hole_value());
3452
      DeoptimizeIf(equal, instr, Deoptimizer::kHole);
danno@chromium.org's avatar
danno@chromium.org committed
3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500
    }
  }
}


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


Operand LCodeGen::BuildFastArrayOperand(
    LOperand* elements_pointer,
    LOperand* key,
    Representation key_representation,
    ElementsKind elements_kind,
    uint32_t base_offset) {
  Register elements_pointer_reg = ToRegister(elements_pointer);
  int element_shift_size = ElementsKindToShiftSize(elements_kind);
  int shift_size = element_shift_size;
  if (key->IsConstantOperand()) {
    int constant_value = ToInteger32(LConstantOperand::cast(key));
    if (constant_value & 0xF0000000) {
      Abort(kArrayIndexConstantValueTooBig);
    }
    return Operand(elements_pointer_reg,
                   ((constant_value) << shift_size)
                       + base_offset);
  } else {
    // Take the tag bit into account while computing the shift size.
    if (key_representation.IsSmi() && (shift_size >= 1)) {
      shift_size -= kSmiTagSize;
    }
    ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
    return Operand(elements_pointer_reg,
                   ToRegister(key),
                   scale_factor,
                   base_offset);
  }
}


void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
3501
  DCHECK(ToRegister(instr->context()).is(esi));
3502 3503
  DCHECK(ToRegister(instr->object()).is(LoadDescriptor::ReceiverRegister()));
  DCHECK(ToRegister(instr->key()).is(LoadDescriptor::NameRegister()));
danno@chromium.org's avatar
danno@chromium.org committed
3504

3505
  if (instr->hydrogen()->HasVectorAndSlot()) {
3506
    EmitVectorLoadICRegisters<LLoadKeyedGeneric>(instr);
3507 3508
  }

3509 3510 3511
  Handle<Code> ic =
      CodeFactory::KeyedLoadICInOptimizedCode(
          isolate(), instr->hydrogen()->initialization_state()).code();
danno@chromium.org's avatar
danno@chromium.org committed
3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583
  CallCode(ic, RelocInfo::CODE_TARGET, instr);
}


void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
  Register result = ToRegister(instr->result());

  if (instr->hydrogen()->from_inlined()) {
    __ lea(result, Operand(esp, -2 * kPointerSize));
  } else {
    // Check for arguments adapter frame.
    Label done, adapted;
    __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
    __ mov(result, Operand(result, StandardFrameConstants::kContextOffset));
    __ cmp(Operand(result),
           Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
    __ j(equal, &adapted, Label::kNear);

    // No arguments adaptor frame.
    __ mov(result, Operand(ebp));
    __ jmp(&done, Label::kNear);

    // Arguments adaptor frame present.
    __ bind(&adapted);
    __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));

    // Result is the frame pointer for the frame if not adapted and for the real
    // frame below the adaptor frame if adapted.
    __ bind(&done);
  }
}


void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
  Operand elem = ToOperand(instr->elements());
  Register result = ToRegister(instr->result());

  Label done;

  // If no arguments adaptor frame the number of arguments is fixed.
  __ cmp(ebp, elem);
  __ mov(result, Immediate(scope()->num_parameters()));
  __ j(equal, &done, Label::kNear);

  // Arguments adaptor frame present. Get argument length from there.
  __ mov(result, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
  __ mov(result, Operand(result,
                         ArgumentsAdaptorFrameConstants::kLengthOffset));
  __ SmiUntag(result);

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


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

  // If the receiver is null or undefined, we have to pass the global
  // object as a receiver to normal functions. Values have to be
  // passed unchanged to builtins and strict-mode functions.
  Label receiver_ok, global_object;
  Register scratch = ToRegister(instr->temp());

  if (!instr->hydrogen()->known_function()) {
    // Do not transform the receiver to object for strict mode
    // functions.
    __ mov(scratch,
           FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
    __ test_b(FieldOperand(scratch, SharedFunctionInfo::kStrictModeByteOffset),
              1 << SharedFunctionInfo::kStrictModeBitWithinByte);
3584
    __ j(not_equal, &receiver_ok);
danno@chromium.org's avatar
danno@chromium.org committed
3585 3586 3587 3588

    // Do not transform the receiver to object for builtins.
    __ test_b(FieldOperand(scratch, SharedFunctionInfo::kNativeByteOffset),
              1 << SharedFunctionInfo::kNativeBitWithinByte);
3589
    __ j(not_equal, &receiver_ok);
danno@chromium.org's avatar
danno@chromium.org committed
3590 3591 3592 3593
  }

  // Normal function. Replace undefined or null with global receiver.
  __ cmp(receiver, factory()->null_value());
3594
  __ j(equal, &global_object);
danno@chromium.org's avatar
danno@chromium.org committed
3595
  __ cmp(receiver, factory()->undefined_value());
3596
  __ j(equal, &global_object);
danno@chromium.org's avatar
danno@chromium.org committed
3597 3598 3599

  // The receiver should be a JS object.
  __ test(receiver, Immediate(kSmiTagMask));
3600
  DeoptimizeIf(equal, instr, Deoptimizer::kSmi);
danno@chromium.org's avatar
danno@chromium.org committed
3601
  __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, scratch);
3602
  DeoptimizeIf(below, instr, Deoptimizer::kNotAJavaScriptObject);
danno@chromium.org's avatar
danno@chromium.org committed
3603 3604 3605 3606 3607 3608

  __ jmp(&receiver_ok, Label::kNear);
  __ bind(&global_object);
  __ mov(receiver, FieldOperand(function, JSFunction::kContextOffset));
  const int global_offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
  __ mov(receiver, Operand(receiver, global_offset));
3609 3610
  const int proxy_offset = GlobalObject::kGlobalProxyOffset;
  __ mov(receiver, FieldOperand(receiver, proxy_offset));
danno@chromium.org's avatar
danno@chromium.org committed
3611 3612 3613 3614 3615 3616 3617 3618 3619
  __ bind(&receiver_ok);
}


void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
  Register receiver = ToRegister(instr->receiver());
  Register function = ToRegister(instr->function());
  Register length = ToRegister(instr->length());
  Register elements = ToRegister(instr->elements());
3620 3621 3622
  DCHECK(receiver.is(eax));  // Used for parameter count.
  DCHECK(function.is(edi));  // Required by InvokeFunction.
  DCHECK(ToRegister(instr->result()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
3623 3624 3625 3626 3627

  // Copy the arguments to this function possibly from the
  // adaptor frame below it.
  const uint32_t kArgumentsLimit = 1 * KB;
  __ cmp(length, kArgumentsLimit);
3628
  DeoptimizeIf(above, instr, Deoptimizer::kTooManyArguments);
danno@chromium.org's avatar
danno@chromium.org committed
3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645

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

  // Loop through the arguments pushing them onto the execution
  // stack.
  Label invoke, loop;
  // length is a small non-negative integer, due to the test above.
  __ test(length, Operand(length));
  __ j(zero, &invoke, Label::kNear);
  __ bind(&loop);
  __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
  __ dec(length);
  __ j(not_zero, &loop);

  // Invoke the function.
  __ bind(&invoke);
3646
  DCHECK(instr->HasPointerMap());
danno@chromium.org's avatar
danno@chromium.org committed
3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682
  LPointerMap* pointers = instr->pointer_map();
  SafepointGenerator safepoint_generator(
      this, pointers, Safepoint::kLazyDeopt);
  ParameterCount actual(eax);
  __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator);
}


void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
  __ int3();
}


void LCodeGen::DoPushArgument(LPushArgument* instr) {
  LOperand* argument = instr->value();
  EmitPushTaggedOperand(argument);
}


void LCodeGen::DoDrop(LDrop* instr) {
  __ Drop(instr->count());
}


void LCodeGen::DoThisFunction(LThisFunction* instr) {
  Register result = ToRegister(instr->result());
  __ mov(result, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
}


void LCodeGen::DoContext(LContext* instr) {
  Register result = ToRegister(instr->result());
  if (info()->IsOptimizing()) {
    __ mov(result, Operand(ebp, StandardFrameConstants::kContextOffset));
  } else {
    // If there is no frame, the context must be in esi.
3683
    DCHECK(result.is(esi));
danno@chromium.org's avatar
danno@chromium.org committed
3684 3685 3686 3687 3688
  }
}


void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3689
  DCHECK(ToRegister(instr->context()).is(esi));
danno@chromium.org's avatar
danno@chromium.org committed
3690 3691 3692
  __ push(esi);  // The context is the first argument.
  __ push(Immediate(instr->hydrogen()->pairs()));
  __ push(Immediate(Smi::FromInt(instr->hydrogen()->flags())));
3693
  CallRuntime(Runtime::kDeclareGlobals, 3, instr);
danno@chromium.org's avatar
danno@chromium.org committed
3694 3695 3696 3697
}


void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3698 3699
                                 int formal_parameter_count, int arity,
                                 LInstruction* instr) {
danno@chromium.org's avatar
danno@chromium.org committed
3700 3701 3702 3703 3704
  bool dont_adapt_arguments =
      formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
  bool can_invoke_directly =
      dont_adapt_arguments || formal_parameter_count == arity;

3705
  Register function_reg = edi;
danno@chromium.org's avatar
danno@chromium.org committed
3706

3707
  if (can_invoke_directly) {
danno@chromium.org's avatar
danno@chromium.org committed
3708
    // Change context.
3709
    __ mov(esi, FieldOperand(function_reg, JSFunction::kContextOffset));
danno@chromium.org's avatar
danno@chromium.org committed
3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720

    // Set eax to arguments count if adaption is not needed. Assumes that eax
    // is available to write to at this point.
    if (dont_adapt_arguments) {
      __ mov(eax, arity);
    }

    // Invoke function directly.
    if (function.is_identical_to(info()->closure())) {
      __ CallSelf();
    } else {
3721
      __ call(FieldOperand(function_reg, JSFunction::kCodeEntryOffset));
danno@chromium.org's avatar
danno@chromium.org committed
3722 3723 3724 3725 3726 3727 3728 3729 3730
    }
    RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
  } else {
    // We need to adapt arguments.
    LPointerMap* pointers = instr->pointer_map();
    SafepointGenerator generator(
        this, pointers, Safepoint::kLazyDeopt);
    ParameterCount count(arity);
    ParameterCount expected(formal_parameter_count);
3731
    __ InvokeFunction(function_reg, expected, count, CALL_FUNCTION, generator);
danno@chromium.org's avatar
danno@chromium.org committed
3732 3733 3734 3735
  }
}


3736 3737 3738 3739 3740 3741 3742
void LCodeGen::DoTailCallThroughMegamorphicCache(
    LTailCallThroughMegamorphicCache* instr) {
  Register receiver = ToRegister(instr->receiver());
  Register name = ToRegister(instr->name());
  DCHECK(receiver.is(LoadDescriptor::ReceiverRegister()));
  DCHECK(name.is(LoadDescriptor::NameRegister()));
  Register scratch = ebx;
3743
  Register extra = edi;
3744 3745 3746
  DCHECK(!scratch.is(receiver) && !scratch.is(name));
  DCHECK(!extra.is(receiver) && !extra.is(name));

3747 3748 3749 3750 3751
  // The probe will tail call to a handler if found.
  // If --vector-ics is on, then it knows to pop the two args first.
  isolate()->stub_cache()->GenerateProbe(masm(), Code::LOAD_IC,
                                         instr->hydrogen()->flags(), false,
                                         receiver, name, scratch, extra);
3752

3753
  LoadIC::GenerateMiss(masm());
3754 3755 3756
}


danno@chromium.org's avatar
danno@chromium.org committed
3757
void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3758
  DCHECK(ToRegister(instr->result()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
3759

3760 3761
  if (instr->hydrogen()->IsTailCall()) {
    if (NeedsEagerFrame()) __ leave();
danno@chromium.org's avatar
danno@chromium.org committed
3762

3763 3764 3765 3766 3767 3768 3769 3770 3771 3772
    if (instr->target()->IsConstantOperand()) {
      LConstantOperand* target = LConstantOperand::cast(instr->target());
      Handle<Code> code = Handle<Code>::cast(ToHandle(target));
      __ jmp(code, RelocInfo::CODE_TARGET);
    } else {
      DCHECK(instr->target()->IsRegister());
      Register target = ToRegister(instr->target());
      __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
      __ jmp(target);
    }
danno@chromium.org's avatar
danno@chromium.org committed
3773
  } else {
3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789
    LPointerMap* pointers = instr->pointer_map();
    SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);

    if (instr->target()->IsConstantOperand()) {
      LConstantOperand* target = LConstantOperand::cast(instr->target());
      Handle<Code> code = Handle<Code>::cast(ToHandle(target));
      generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
      __ call(code, RelocInfo::CODE_TARGET);
    } else {
      DCHECK(instr->target()->IsRegister());
      Register target = ToRegister(instr->target());
      generator.BeforeCall(__ CallSize(Operand(target)));
      __ add(target, Immediate(Code::kHeaderSize - kHeapObjectTag));
      __ call(target);
    }
    generator.AfterCall();
danno@chromium.org's avatar
danno@chromium.org committed
3790 3791 3792 3793 3794
  }
}


void LCodeGen::DoCallJSFunction(LCallJSFunction* instr) {
3795 3796
  DCHECK(ToRegister(instr->function()).is(edi));
  DCHECK(ToRegister(instr->result()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826

  if (instr->hydrogen()->pass_argument_count()) {
    __ mov(eax, instr->arity());
  }

  // Change context.
  __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));

  bool is_self_call = false;
  if (instr->hydrogen()->function()->IsConstant()) {
    HConstant* fun_const = HConstant::cast(instr->hydrogen()->function());
    Handle<JSFunction> jsfun =
      Handle<JSFunction>::cast(fun_const->handle(isolate()));
    is_self_call = jsfun.is_identical_to(info()->closure());
  }

  if (is_self_call) {
    __ CallSelf();
  } else {
    __ call(FieldOperand(edi, JSFunction::kCodeEntryOffset));
  }

  RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
}


void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
  Register input_reg = ToRegister(instr->value());
  __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
         factory()->heap_number_map());
3827
  DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
danno@chromium.org's avatar
danno@chromium.org committed
3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848

  Label slow, allocated, done;
  Register tmp = input_reg.is(eax) ? ecx : eax;
  Register tmp2 = tmp.is(ecx) ? edx : input_reg.is(ecx) ? edx : ecx;

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

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

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

  // Slow case: Call the runtime system to do the number allocation.
  __ bind(&slow);
3849
  CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0,
danno@chromium.org's avatar
danno@chromium.org committed
3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873
                          instr, instr->context());
  // Set the pointer to the new heap number in tmp.
  if (!tmp.is(eax)) __ mov(tmp, eax);
  // Restore input_reg after call to runtime.
  __ LoadFromSafepointRegisterSlot(input_reg, input_reg);

  __ bind(&allocated);
  __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kExponentOffset));
  __ and_(tmp2, ~HeapNumber::kSignMask);
  __ mov(FieldOperand(tmp, HeapNumber::kExponentOffset), tmp2);
  __ mov(tmp2, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
  __ mov(FieldOperand(tmp, HeapNumber::kMantissaOffset), tmp2);
  __ StoreToSafepointRegisterSlot(input_reg, tmp);

  __ bind(&done);
}


void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
  Register input_reg = ToRegister(instr->value());
  __ test(input_reg, Operand(input_reg));
  Label is_positive;
  __ j(not_sign, &is_positive, Label::kNear);
  __ neg(input_reg);  // Sets flags.
3874
  DeoptimizeIf(negative, instr, Deoptimizer::kOverflow);
danno@chromium.org's avatar
danno@chromium.org committed
3875 3876 3877 3878 3879 3880
  __ bind(&is_positive);
}


void LCodeGen::DoMathAbs(LMathAbs* instr) {
  // Class for deferred case.
3881
  class DeferredMathAbsTaggedHeapNumber FINAL : public LDeferredCode {
danno@chromium.org's avatar
danno@chromium.org committed
3882 3883 3884 3885 3886
   public:
    DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
                                    LMathAbs* instr,
                                    const X87Stack& x87_stack)
        : LDeferredCode(codegen, x87_stack), instr_(instr) { }
3887
    void Generate() OVERRIDE {
danno@chromium.org's avatar
danno@chromium.org committed
3888 3889
      codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
    }
3890 3891
    LInstruction* instr() OVERRIDE { return instr_; }

danno@chromium.org's avatar
danno@chromium.org committed
3892 3893 3894 3895
   private:
    LMathAbs* instr_;
  };

3896
  DCHECK(instr->value()->Equals(instr->result()));
danno@chromium.org's avatar
danno@chromium.org committed
3897 3898 3899
  Representation r = instr->hydrogen()->value()->representation();

  if (r.IsDouble()) {
3900 3901 3902
    X87Register value = ToX87Register(instr->value());
    X87Fxch(value);
    __ fabs();
danno@chromium.org's avatar
danno@chromium.org committed
3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917
  } else if (r.IsSmiOrInteger32()) {
    EmitIntegerMathAbs(instr);
  } else {  // Tagged case.
    DeferredMathAbsTaggedHeapNumber* deferred =
        new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr, x87_stack_);
    Register input_reg = ToRegister(instr->value());
    // Smi check.
    __ JumpIfNotSmi(input_reg, deferred->entry());
    EmitIntegerMathAbs(instr);
    __ bind(deferred->exit());
  }
}


void LCodeGen::DoMathFloor(LMathFloor* instr) {
3918 3919 3920 3921 3922 3923 3924 3925 3926
  Register output_reg = ToRegister(instr->result());
  X87Register input_reg = ToX87Register(instr->value());
  X87Fxch(input_reg);

  Label not_minus_zero, done;
  // Deoptimize on unordered.
  __ fldz();
  __ fld(1);
  __ FCmp();
3927
  DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
3928 3929 3930 3931 3932 3933 3934 3935
  __ j(below, &not_minus_zero, Label::kNear);

  if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
    // Check for negative zero.
    __ j(not_equal, &not_minus_zero, Label::kNear);
    // +- 0.0.
    __ fld(0);
    __ FXamSign();
3936
    DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949
    __ Move(output_reg, Immediate(0));
    __ jmp(&done, Label::kFar);
  }

  // Positive input.
  // rc=01B, round down.
  __ bind(&not_minus_zero);
  __ fnclex();
  __ X87SetRC(0x0400);
  __ sub(esp, Immediate(kPointerSize));
  __ fist_s(Operand(esp, 0));
  __ pop(output_reg);
  __ X87CheckIA();
3950
  DeoptimizeIf(equal, instr, Deoptimizer::kOverflow);
3951 3952 3953
  __ fnclex();
  __ X87SetRC(0x0000);
  __ bind(&done);
danno@chromium.org's avatar
danno@chromium.org committed
3954 3955 3956 3957
}


void LCodeGen::DoMathRound(LMathRound* instr) {
3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983
  X87Register input_reg = ToX87Register(instr->value());
  Register result = ToRegister(instr->result());
  X87Fxch(input_reg);
  Label below_one_half, below_minus_one_half, done;

  ExternalReference one_half = ExternalReference::address_of_one_half();
  ExternalReference minus_one_half =
      ExternalReference::address_of_minus_one_half();

  __ fld_d(Operand::StaticVariable(one_half));
  __ fld(1);
  __ FCmp();
  __ j(carry, &below_one_half);

  // Use rounds towards zero, since 0.5 <= x, we use floor(0.5 + x)
  __ fld(0);
  __ fadd_d(Operand::StaticVariable(one_half));
  // rc=11B, round toward zero.
  __ X87SetRC(0x0c00);
  __ sub(esp, Immediate(kPointerSize));
  // Clear exception bits.
  __ fnclex();
  __ fistp_s(MemOperand(esp, 0));
  // Check overflow.
  __ X87CheckIA();
  __ pop(result);
3984
  DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000
  __ fnclex();
  // Restore round mode.
  __ X87SetRC(0x0000);
  __ jmp(&done);

  __ bind(&below_one_half);
  __ fld_d(Operand::StaticVariable(minus_one_half));
  __ fld(1);
  __ FCmp();
  __ j(carry, &below_minus_one_half);
  // We return 0 for the input range [+0, 0.5[, or [-0.5, 0.5[ if
  // we can ignore the difference between a result of -0 and +0.
  if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
    // If the sign is positive, we return +0.
    __ fld(0);
    __ FXamSign();
4001
    DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017
  }
  __ Move(result, Immediate(0));
  __ jmp(&done);

  __ bind(&below_minus_one_half);
  __ fld(0);
  __ fadd_d(Operand::StaticVariable(one_half));
  // rc=01B, round down.
  __ X87SetRC(0x0400);
  __ sub(esp, Immediate(kPointerSize));
  // Clear exception bits.
  __ fnclex();
  __ fistp_s(MemOperand(esp, 0));
  // Check overflow.
  __ X87CheckIA();
  __ pop(result);
4018
  DeoptimizeIf(equal, instr, Deoptimizer::kConversionOverflow);
4019 4020 4021 4022 4023
  __ fnclex();
  // Restore round mode.
  __ X87SetRC(0x0000);

  __ bind(&done);
danno@chromium.org's avatar
danno@chromium.org committed
4024 4025
}

4026

4027
void LCodeGen::DoMathFround(LMathFround* instr) {
4028 4029 4030 4031 4032 4033
  X87Register input_reg = ToX87Register(instr->value());
  X87Fxch(input_reg);
  __ sub(esp, Immediate(kPointerSize));
  __ fstp_s(MemOperand(esp, 0));
  X87Fld(MemOperand(esp, 0), kX87FloatOperand);
  __ add(esp, Immediate(kPointerSize));
4034 4035
}

danno@chromium.org's avatar
danno@chromium.org committed
4036 4037

void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077
  X87Register input = ToX87Register(instr->value());
  X87Register result_reg = ToX87Register(instr->result());
  Register temp_result = ToRegister(instr->temp1());
  Register temp = ToRegister(instr->temp2());
  Label slow, done, smi, finish;
  DCHECK(result_reg.is(input));

  // Store input into Heap number and call runtime function kMathExpRT.
  if (FLAG_inline_new) {
    __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
    __ jmp(&done, Label::kNear);
  }

  // Slow case: Call the runtime system to do the number allocation.
  __ bind(&slow);
  {
    // TODO(3095996): Put a valid pointer value in the stack slot where the
    // result register is stored, as this register is in the pointer map, but
    // contains an integer value.
    __ Move(temp_result, Immediate(0));

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

    __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
    __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
    RecordSafepointWithRegisters(
       instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
    __ StoreToSafepointRegisterSlot(temp_result, eax);
  }
  __ bind(&done);
  X87LoadForUsage(input);
  __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));

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

    __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
    __ push(temp_result);
4078
    __ CallRuntimeSaveDoubles(Runtime::kMathSqrt);
4079 4080
    RecordSafepointWithRegisters(instr->pointer_map(), 1,
                                 Safepoint::kNoLazyDeopt);
4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096
    __ StoreToSafepointRegisterSlot(temp_result, eax);
  }
  X87PrepareToWrite(result_reg);
  // return value of MathExpRT is Smi or Heap Number.
  __ JumpIfSmi(temp_result, &smi);
  // Heap number(double)
  __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
  __ jmp(&finish);
  // SMI
  __ bind(&smi);
  __ SmiUntag(temp_result);
  __ push(temp_result);
  __ fild_s(MemOperand(esp, 0));
  __ pop(temp_result);
  __ bind(&finish);
  X87CommitWrite(result_reg);
danno@chromium.org's avatar
danno@chromium.org committed
4097 4098 4099 4100
}


void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125
  X87Register input_reg = ToX87Register(instr->value());
  DCHECK(ToX87Register(instr->result()).is(input_reg));
  X87Fxch(input_reg);
  // Note that according to ECMA-262 15.8.2.13:
  // Math.pow(-Infinity, 0.5) == Infinity
  // Math.sqrt(-Infinity) == NaN
  Label done, sqrt;
  // Check base for -Infinity. C3 == 0, C2 == 1, C1 == 1 and C0 == 1
  __ fxam();
  __ push(eax);
  __ fnstsw_ax();
  __ and_(eax, Immediate(0x4700));
  __ cmp(eax, Immediate(0x0700));
  __ j(not_equal, &sqrt, Label::kNear);
  // If input is -Infinity, return Infinity.
  __ fchs();
  __ jmp(&done, Label::kNear);

  // Square root.
  __ bind(&sqrt);
  __ fldz();
  __ faddp();  // Convert -0 to +0.
  __ fsqrt();
  __ bind(&done);
  __ pop(eax);
danno@chromium.org's avatar
danno@chromium.org committed
4126 4127 4128 4129
}


void LCodeGen::DoPower(LPower* instr) {
4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149
  Representation exponent_type = instr->hydrogen()->right()->representation();
  X87Register result = ToX87Register(instr->result());
  // Having marked this as a call, we can use any registers.
  X87Register base = ToX87Register(instr->left());
  ExternalReference one_half = ExternalReference::address_of_one_half();

  if (exponent_type.IsSmi()) {
    Register exponent = ToRegister(instr->right());
    X87LoadForUsage(base);
    __ SmiUntag(exponent);
    __ push(exponent);
    __ fild_s(MemOperand(esp, 0));
    __ pop(exponent);
  } else if (exponent_type.IsTagged()) {
    Register exponent = ToRegister(instr->right());
    Register temp = exponent.is(ecx) ? eax : ecx;
    Label no_deopt, done;
    X87LoadForUsage(base);
    __ JumpIfSmi(exponent, &no_deopt);
    __ CmpObjectType(exponent, HEAP_NUMBER_TYPE, temp);
4150
    DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196
    // Heap number(double)
    __ fld_d(FieldOperand(exponent, HeapNumber::kValueOffset));
    __ jmp(&done);
    // SMI
    __ bind(&no_deopt);
    __ SmiUntag(exponent);
    __ push(exponent);
    __ fild_s(MemOperand(esp, 0));
    __ pop(exponent);
    __ bind(&done);
  } else if (exponent_type.IsInteger32()) {
    Register exponent = ToRegister(instr->right());
    X87LoadForUsage(base);
    __ push(exponent);
    __ fild_s(MemOperand(esp, 0));
    __ pop(exponent);
  } else {
    DCHECK(exponent_type.IsDouble());
    X87Register exponent_double = ToX87Register(instr->right());
    X87LoadForUsage(base, exponent_double);
  }

  // FP data stack {base, exponent(TOS)}.
  // Handle (exponent==+-0.5 && base == -0).
  Label not_plus_0;
  __ fld(0);
  __ fabs();
  X87Fld(Operand::StaticVariable(one_half), kX87DoubleOperand);
  __ FCmp();
  __ j(parity_even, &not_plus_0, Label::kNear);  // NaN.
  __ j(not_equal, &not_plus_0, Label::kNear);
  __ fldz();
  // FP data stack {base, exponent(TOS), zero}.
  __ faddp(2);
  __ bind(&not_plus_0);

  {
    __ PrepareCallCFunction(4, eax);
    __ fstp_d(MemOperand(esp, kDoubleSize));  // Exponent value.
    __ fstp_d(MemOperand(esp, 0));            // Base value.
    X87PrepareToWrite(result);
    __ CallCFunction(ExternalReference::power_double_double_function(isolate()),
                     4);
    // Return value is in st(0) on ia32.
    X87CommitWrite(result);
  }
danno@chromium.org's avatar
danno@chromium.org committed
4197 4198 4199 4200
}


void LCodeGen::DoMathLog(LMathLog* instr) {
4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221
  DCHECK(instr->value()->Equals(instr->result()));
  X87Register input_reg = ToX87Register(instr->value());
  X87Fxch(input_reg);

  Label positive, done, zero, nan_result;
  __ fldz();
  __ fld(1);
  __ FCmp();
  __ j(below, &nan_result, Label::kNear);
  __ j(equal, &zero, Label::kNear);
  // Positive input.
  // {input, ln2}.
  __ fldln2();
  // {ln2, input}.
  __ fxch();
  // {result}.
  __ fyl2x();
  __ jmp(&done, Label::kNear);

  __ bind(&nan_result);
  X87PrepareToWrite(input_reg);
4222 4223 4224 4225
  __ push(Immediate(0xffffffff));
  __ push(Immediate(0x7fffffff));
  __ fld_d(MemOperand(esp, 0));
  __ lea(esp, Operand(esp, kDoubleSize));
4226 4227 4228 4229 4230 4231 4232 4233 4234 4235
  X87CommitWrite(input_reg);
  __ jmp(&done, Label::kNear);

  __ bind(&zero);
  ExternalReference ninf = ExternalReference::address_of_negative_infinity();
  X87PrepareToWrite(input_reg);
  __ fld_d(Operand::StaticVariable(ninf));
  X87CommitWrite(input_reg);

  __ bind(&done);
danno@chromium.org's avatar
danno@chromium.org committed
4236 4237 4238 4239
}


void LCodeGen::DoMathClz32(LMathClz32* instr) {
4240 4241 4242
  Register input = ToRegister(instr->value());
  Register result = ToRegister(instr->result());

4243
  __ Lzcnt(result, input);
danno@chromium.org's avatar
danno@chromium.org committed
4244 4245 4246 4247
}


void LCodeGen::DoMathExp(LMathExp* instr) {
4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288
  X87Register input = ToX87Register(instr->value());
  X87Register result_reg = ToX87Register(instr->result());
  Register temp_result = ToRegister(instr->temp1());
  Register temp = ToRegister(instr->temp2());
  Label slow, done, smi, finish;
  DCHECK(result_reg.is(input));

  // Store input into Heap number and call runtime function kMathExpRT.
  if (FLAG_inline_new) {
    __ AllocateHeapNumber(temp_result, temp, no_reg, &slow);
    __ jmp(&done, Label::kNear);
  }

  // Slow case: Call the runtime system to do the number allocation.
  __ bind(&slow);
  {
    // TODO(3095996): Put a valid pointer value in the stack slot where the
    // result register is stored, as this register is in the pointer map, but
    // contains an integer value.
    __ Move(temp_result, Immediate(0));

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

    __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
    __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
    RecordSafepointWithRegisters(instr->pointer_map(), 0,
                                 Safepoint::kNoLazyDeopt);
    __ StoreToSafepointRegisterSlot(temp_result, eax);
  }
  __ bind(&done);
  X87LoadForUsage(input);
  __ fstp_d(FieldOperand(temp_result, HeapNumber::kValueOffset));

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

    __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
    __ push(temp_result);
    __ CallRuntimeSaveDoubles(Runtime::kMathExpRT);
4289
    RecordSafepointWithRegisters(instr->pointer_map(), 1,
4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306
                                 Safepoint::kNoLazyDeopt);
    __ StoreToSafepointRegisterSlot(temp_result, eax);
  }
  X87PrepareToWrite(result_reg);
  // return value of MathExpRT is Smi or Heap Number.
  __ JumpIfSmi(temp_result, &smi);
  // Heap number(double)
  __ fld_d(FieldOperand(temp_result, HeapNumber::kValueOffset));
  __ jmp(&finish);
  // SMI
  __ bind(&smi);
  __ SmiUntag(temp_result);
  __ push(temp_result);
  __ fild_s(MemOperand(esp, 0));
  __ pop(temp_result);
  __ bind(&finish);
  X87CommitWrite(result_reg);
danno@chromium.org's avatar
danno@chromium.org committed
4307 4308 4309 4310
}


void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
4311 4312 4313
  DCHECK(ToRegister(instr->context()).is(esi));
  DCHECK(ToRegister(instr->function()).is(edi));
  DCHECK(instr->HasPointerMap());
danno@chromium.org's avatar
danno@chromium.org committed
4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324

  Handle<JSFunction> known_function = instr->hydrogen()->known_function();
  if (known_function.is_null()) {
    LPointerMap* pointers = instr->pointer_map();
    SafepointGenerator generator(
        this, pointers, Safepoint::kLazyDeopt);
    ParameterCount count(instr->arity());
    __ InvokeFunction(edi, count, CALL_FUNCTION, generator);
  } else {
    CallKnownFunction(known_function,
                      instr->hydrogen()->formal_parameter_count(),
4325
                      instr->arity(), instr);
danno@chromium.org's avatar
danno@chromium.org committed
4326 4327 4328 4329 4330
  }
}


void LCodeGen::DoCallFunction(LCallFunction* instr) {
4331 4332 4333
  DCHECK(ToRegister(instr->context()).is(esi));
  DCHECK(ToRegister(instr->function()).is(edi));
  DCHECK(ToRegister(instr->result()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
4334 4335

  int arity = instr->arity();
4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359
  CallFunctionFlags flags = instr->hydrogen()->function_flags();
  if (instr->hydrogen()->HasVectorAndSlot()) {
    Register slot_register = ToRegister(instr->temp_slot());
    Register vector_register = ToRegister(instr->temp_vector());
    DCHECK(slot_register.is(edx));
    DCHECK(vector_register.is(ebx));

    AllowDeferredHandleDereference vector_structure_check;
    Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
    int index = vector->GetIndex(instr->hydrogen()->slot());

    __ mov(vector_register, vector);
    __ mov(slot_register, Immediate(Smi::FromInt(index)));

    CallICState::CallType call_type =
        (flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;

    Handle<Code> ic =
        CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
    CallCode(ic, RelocInfo::CODE_TARGET, instr);
  } else {
    CallFunctionStub stub(isolate(), arity, flags);
    CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
  }
danno@chromium.org's avatar
danno@chromium.org committed
4360 4361 4362 4363
}


void LCodeGen::DoCallNew(LCallNew* instr) {
4364 4365 4366
  DCHECK(ToRegister(instr->context()).is(esi));
  DCHECK(ToRegister(instr->constructor()).is(edi));
  DCHECK(ToRegister(instr->result()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
4367 4368 4369 4370 4371 4372 4373 4374 4375 4376

  // No cell in ebx for construct type feedback in optimized code
  __ mov(ebx, isolate()->factory()->undefined_value());
  CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
  __ Move(eax, Immediate(instr->arity()));
  CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
}


void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
4377 4378 4379
  DCHECK(ToRegister(instr->context()).is(esi));
  DCHECK(ToRegister(instr->constructor()).is(edi));
  DCHECK(ToRegister(instr->result()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
4380 4381

  __ Move(eax, Immediate(instr->arity()));
4382 4383 4384 4385 4386 4387 4388 4389 4390
  if (instr->arity() == 1) {
    // We only need the allocation site for the case we have a length argument.
    // The case may bail out to the runtime, which will determine the correct
    // elements kind with the site.
    __ mov(ebx, instr->hydrogen()->site());
  } else {
    __ mov(ebx, isolate()->factory()->undefined_value());
  }

danno@chromium.org's avatar
danno@chromium.org committed
4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429
  ElementsKind kind = instr->hydrogen()->elements_kind();
  AllocationSiteOverrideMode override_mode =
      (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
          ? DISABLE_ALLOCATION_SITES
          : DONT_OVERRIDE;

  if (instr->arity() == 0) {
    ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
    CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
  } else if (instr->arity() == 1) {
    Label done;
    if (IsFastPackedElementsKind(kind)) {
      Label packed_case;
      // We might need a change here
      // look at the first argument
      __ mov(ecx, Operand(esp, 0));
      __ test(ecx, ecx);
      __ j(zero, &packed_case, Label::kNear);

      ElementsKind holey_kind = GetHoleyElementsKind(kind);
      ArraySingleArgumentConstructorStub stub(isolate(),
                                              holey_kind,
                                              override_mode);
      CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
      __ jmp(&done, Label::kNear);
      __ bind(&packed_case);
    }

    ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
    CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
    __ bind(&done);
  } else {
    ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
    CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
  }
}


void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
4430
  DCHECK(ToRegister(instr->context()).is(esi));
4431
  CallRuntime(instr->function(), instr->arity(), instr, instr->save_doubles());
danno@chromium.org's avatar
danno@chromium.org committed
4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462
}


void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
  Register function = ToRegister(instr->function());
  Register code_object = ToRegister(instr->code_object());
  __ lea(code_object, FieldOperand(code_object, Code::kHeaderSize));
  __ mov(FieldOperand(function, JSFunction::kCodeEntryOffset), code_object);
}


void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
  Register result = ToRegister(instr->result());
  Register base = ToRegister(instr->base_object());
  if (instr->offset()->IsConstantOperand()) {
    LConstantOperand* offset = LConstantOperand::cast(instr->offset());
    __ lea(result, Operand(base, ToInteger32(offset)));
  } else {
    Register offset = ToRegister(instr->offset());
    __ lea(result, Operand(base, offset, times_1, 0));
  }
}


void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
  Representation representation = instr->hydrogen()->field_representation();

  HObjectAccess access = instr->hydrogen()->access();
  int offset = access.offset();

  if (access.IsExternalMemory()) {
4463
    DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
danno@chromium.org's avatar
danno@chromium.org committed
4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478
    MemOperand operand = instr->object()->IsConstantOperand()
        ? MemOperand::StaticVariable(
            ToExternalReference(LConstantOperand::cast(instr->object())))
        : MemOperand(ToRegister(instr->object()), offset);
    if (instr->value()->IsConstantOperand()) {
      LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
      __ mov(operand, Immediate(ToInteger32(operand_value)));
    } else {
      Register value = ToRegister(instr->value());
      __ Store(value, operand, representation);
    }
    return;
  }

  Register object = ToRegister(instr->object());
4479
  __ AssertNotSmi(object);
4480
  DCHECK(!representation.IsSmi() ||
4481 4482 4483
         !instr->value()->IsConstantOperand() ||
         IsSmi(LConstantOperand::cast(instr->value())));
  if (representation.IsDouble()) {
4484 4485 4486
    DCHECK(access.IsInobject());
    DCHECK(!instr->hydrogen()->has_transition());
    DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
danno@chromium.org's avatar
danno@chromium.org committed
4487 4488 4489 4490 4491 4492 4493 4494
    X87Register value = ToX87Register(instr->value());
    X87Mov(FieldOperand(object, offset), value);
    return;
  }

  if (instr->hydrogen()->has_transition()) {
    Handle<Map> transition = instr->hydrogen()->transition_map();
    AddDeprecationDependency(transition);
4495 4496
    __ mov(FieldOperand(object, HeapObject::kMapOffset), transition);
    if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
danno@chromium.org's avatar
danno@chromium.org committed
4497 4498 4499 4500 4501
      Register temp = ToRegister(instr->temp());
      Register temp_map = ToRegister(instr->temp_map());
      __ mov(temp_map, transition);
      __ mov(FieldOperand(object, HeapObject::kMapOffset), temp_map);
      // Update the write barrier for the map field.
4502
      __ RecordWriteForMap(object, transition, temp_map, temp, kSaveFPRegs);
danno@chromium.org's avatar
danno@chromium.org committed
4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520
    }
  }

  // Do the store.
  Register write_register = object;
  if (!access.IsInobject()) {
    write_register = ToRegister(instr->temp());
    __ mov(write_register, FieldOperand(object, JSObject::kPropertiesOffset));
  }

  MemOperand operand = FieldOperand(write_register, offset);
  if (instr->value()->IsConstantOperand()) {
    LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
    if (operand_value->IsRegister()) {
      Register value = ToRegister(operand_value);
      __ Store(value, operand, representation);
    } else if (representation.IsInteger32()) {
      Immediate immediate = ToImmediate(operand_value, representation);
4521
      DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
danno@chromium.org's avatar
danno@chromium.org committed
4522 4523 4524
      __ mov(operand, immediate);
    } else {
      Handle<Object> handle_value = ToHandle(operand_value);
4525
      DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
danno@chromium.org's avatar
danno@chromium.org committed
4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536
      __ mov(operand, handle_value);
    }
  } else {
    Register value = ToRegister(instr->value());
    __ Store(value, operand, representation);
  }

  if (instr->hydrogen()->NeedsWriteBarrier()) {
    Register value = ToRegister(instr->value());
    Register temp = access.IsInobject() ? ToRegister(instr->temp()) : object;
    // Update the write barrier for the object for in-object properties.
4537
    __ RecordWriteField(write_register, offset, value, temp, kSaveFPRegs,
danno@chromium.org's avatar
danno@chromium.org committed
4538
                        EMIT_REMEMBERED_SET,
4539 4540
                        instr->hydrogen()->SmiCheckForWriteBarrier(),
                        instr->hydrogen()->PointersToHereCheckForValue());
danno@chromium.org's avatar
danno@chromium.org committed
4541 4542 4543 4544 4545
  }
}


void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
4546
  DCHECK(ToRegister(instr->context()).is(esi));
4547 4548
  DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
  DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
danno@chromium.org's avatar
danno@chromium.org committed
4549

4550
  __ mov(StoreDescriptor::NameRegister(), instr->name());
4551 4552 4553
  Handle<Code> ic =
      StoreIC::initialize_stub(isolate(), instr->language_mode(),
                               instr->hydrogen()->initialization_state());
danno@chromium.org's avatar
danno@chromium.org committed
4554 4555 4556 4557 4558 4559 4560 4561 4562 4563
  CallCode(ic, RelocInfo::CODE_TARGET, instr);
}


void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
  Condition cc = instr->hydrogen()->allow_equality() ? above : above_equal;
  if (instr->index()->IsConstantOperand()) {
    __ cmp(ToOperand(instr->length()),
           ToImmediate(LConstantOperand::cast(instr->index()),
                       instr->hydrogen()->length()->representation()));
4564
    cc = CommuteCondition(cc);
danno@chromium.org's avatar
danno@chromium.org committed
4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577
  } else if (instr->length()->IsConstantOperand()) {
    __ cmp(ToOperand(instr->index()),
           ToImmediate(LConstantOperand::cast(instr->length()),
                       instr->hydrogen()->index()->representation()));
  } else {
    __ cmp(ToRegister(instr->index()), ToOperand(instr->length()));
  }
  if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
    Label done;
    __ j(NegateCondition(cc), &done, Label::kNear);
    __ int3();
    __ bind(&done);
  } else {
4578
    DeoptimizeIf(cc, instr, Deoptimizer::kOutOfBounds);
danno@chromium.org's avatar
danno@chromium.org committed
4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598
  }
}


void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
  ElementsKind elements_kind = instr->elements_kind();
  LOperand* key = instr->key();
  if (!key->IsConstantOperand() &&
      ExternalArrayOpRequiresTemp(instr->hydrogen()->key()->representation(),
                                  elements_kind)) {
    __ SmiUntag(ToRegister(key));
  }
  Operand operand(BuildFastArrayOperand(
      instr->elements(),
      key,
      instr->hydrogen()->key()->representation(),
      elements_kind,
      instr->base_offset()));
  if (elements_kind == EXTERNAL_FLOAT32_ELEMENTS ||
      elements_kind == FLOAT32_ELEMENTS) {
4599
    X87Mov(operand, ToX87Register(instr->value()), kX87FloatOperand);
danno@chromium.org's avatar
danno@chromium.org committed
4600 4601
  } else if (elements_kind == EXTERNAL_FLOAT64_ELEMENTS ||
             elements_kind == FLOAT64_ELEMENTS) {
4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627
    uint64_t int_val = kHoleNanInt64;
    int32_t lower = static_cast<int32_t>(int_val);
    int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
    Operand operand2 = BuildFastArrayOperand(
        instr->elements(), instr->key(),
        instr->hydrogen()->key()->representation(), elements_kind,
        instr->base_offset() + kPointerSize);

    Label no_special_nan_handling, done;
    X87Register value = ToX87Register(instr->value());
    X87Fxch(value);
    __ lea(esp, Operand(esp, -kDoubleSize));
    __ fst_d(MemOperand(esp, 0));
    __ lea(esp, Operand(esp, kDoubleSize));
    int offset = sizeof(kHoleNanUpper32);
    // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
    // so we check the upper with 0xffffffff for hole as a temporary fix.
    __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
    __ j(not_equal, &no_special_nan_handling, Label::kNear);
    __ mov(operand, Immediate(lower));
    __ mov(operand2, Immediate(upper));
    __ jmp(&done, Label::kNear);

    __ bind(&no_special_nan_handling);
    __ fst_d(operand);
    __ bind(&done);
danno@chromium.org's avatar
danno@chromium.org committed
4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677
  } else {
    Register value = ToRegister(instr->value());
    switch (elements_kind) {
      case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
      case EXTERNAL_UINT8_ELEMENTS:
      case EXTERNAL_INT8_ELEMENTS:
      case UINT8_ELEMENTS:
      case INT8_ELEMENTS:
      case UINT8_CLAMPED_ELEMENTS:
        __ mov_b(operand, value);
        break;
      case EXTERNAL_INT16_ELEMENTS:
      case EXTERNAL_UINT16_ELEMENTS:
      case UINT16_ELEMENTS:
      case INT16_ELEMENTS:
        __ mov_w(operand, value);
        break;
      case EXTERNAL_INT32_ELEMENTS:
      case EXTERNAL_UINT32_ELEMENTS:
      case UINT32_ELEMENTS:
      case INT32_ELEMENTS:
        __ mov(operand, value);
        break;
      case EXTERNAL_FLOAT32_ELEMENTS:
      case EXTERNAL_FLOAT64_ELEMENTS:
      case FLOAT32_ELEMENTS:
      case FLOAT64_ELEMENTS:
      case FAST_SMI_ELEMENTS:
      case FAST_ELEMENTS:
      case FAST_DOUBLE_ELEMENTS:
      case FAST_HOLEY_SMI_ELEMENTS:
      case FAST_HOLEY_ELEMENTS:
      case FAST_HOLEY_DOUBLE_ELEMENTS:
      case DICTIONARY_ELEMENTS:
      case SLOPPY_ARGUMENTS_ELEMENTS:
        UNREACHABLE();
        break;
    }
  }
}


void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
  Operand double_store_operand = BuildFastArrayOperand(
      instr->elements(),
      instr->key(),
      instr->hydrogen()->key()->representation(),
      FAST_DOUBLE_ELEMENTS,
      instr->base_offset());

4678 4679 4680 4681 4682 4683 4684 4685
  uint64_t int_val = kHoleNanInt64;
  int32_t lower = static_cast<int32_t>(int_val);
  int32_t upper = static_cast<int32_t>(int_val >> (kBitsPerInt));
  Operand double_store_operand2 = BuildFastArrayOperand(
      instr->elements(), instr->key(),
      instr->hydrogen()->key()->representation(), FAST_DOUBLE_ELEMENTS,
      instr->base_offset() + kPointerSize);

danno@chromium.org's avatar
danno@chromium.org committed
4686 4687 4688 4689 4690 4691
  if (instr->hydrogen()->IsConstantHoleStore()) {
    // This means we should store the (double) hole. No floating point
    // registers required.
    __ mov(double_store_operand, Immediate(lower));
    __ mov(double_store_operand2, Immediate(upper));
  } else {
4692
    Label no_special_nan_handling, done;
danno@chromium.org's avatar
danno@chromium.org committed
4693 4694 4695 4696 4697 4698 4699 4700
    X87Register value = ToX87Register(instr->value());
    X87Fxch(value);

    if (instr->NeedsCanonicalization()) {
      __ fld(0);
      __ fld(0);
      __ FCmp();
      __ j(parity_odd, &no_special_nan_handling, Label::kNear);
4701 4702 4703 4704 4705 4706
      // All NaNs are Canonicalized to 0x7fffffffffffffff
      __ mov(double_store_operand, Immediate(0xffffffff));
      __ mov(double_store_operand2, Immediate(0x7fffffff));
      __ jmp(&done, Label::kNear);
    } else {
      __ lea(esp, Operand(esp, -kDoubleSize));
danno@chromium.org's avatar
danno@chromium.org committed
4707
      __ fst_d(MemOperand(esp, 0));
4708 4709 4710 4711 4712 4713 4714 4715 4716
      __ lea(esp, Operand(esp, kDoubleSize));
      int offset = sizeof(kHoleNanUpper32);
      // x87 converts sNaN(0xfff7fffffff7ffff) to QNaN(0xfffffffffff7ffff),
      // so we check the upper with 0xffffffff for hole as a temporary fix.
      __ cmp(MemOperand(esp, -offset), Immediate(0xffffffff));
      __ j(not_equal, &no_special_nan_handling, Label::kNear);
      __ mov(double_store_operand, Immediate(lower));
      __ mov(double_store_operand2, Immediate(upper));
      __ jmp(&done, Label::kNear);
danno@chromium.org's avatar
danno@chromium.org committed
4717 4718 4719
    }
    __ bind(&no_special_nan_handling);
    __ fst_d(double_store_operand);
4720
    __ bind(&done);
danno@chromium.org's avatar
danno@chromium.org committed
4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742
  }
}


void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
  Register elements = ToRegister(instr->elements());
  Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg;

  Operand operand = BuildFastArrayOperand(
      instr->elements(),
      instr->key(),
      instr->hydrogen()->key()->representation(),
      FAST_ELEMENTS,
      instr->base_offset());
  if (instr->value()->IsRegister()) {
    __ mov(operand, ToRegister(instr->value()));
  } else {
    LConstantOperand* operand_value = LConstantOperand::cast(instr->value());
    if (IsSmi(operand_value)) {
      Immediate immediate = ToImmediate(operand_value, Representation::Smi());
      __ mov(operand, immediate);
    } else {
4743
      DCHECK(!IsInteger32(operand_value));
danno@chromium.org's avatar
danno@chromium.org committed
4744 4745 4746 4747 4748 4749
      Handle<Object> handle_value = ToHandle(operand_value);
      __ mov(operand, handle_value);
    }
  }

  if (instr->hydrogen()->NeedsWriteBarrier()) {
4750
    DCHECK(instr->value()->IsRegister());
danno@chromium.org's avatar
danno@chromium.org committed
4751
    Register value = ToRegister(instr->value());
4752
    DCHECK(!instr->key()->IsConstantOperand());
danno@chromium.org's avatar
danno@chromium.org committed
4753
    SmiCheck check_needed =
4754
        instr->hydrogen()->value()->type().IsHeapObject()
danno@chromium.org's avatar
danno@chromium.org committed
4755 4756 4757
          ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
    // Compute address of modified element and store it into key register.
    __ lea(key, operand);
4758
    __ RecordWrite(elements, key, value, kSaveFPRegs, EMIT_REMEMBERED_SET,
4759 4760
                   check_needed,
                   instr->hydrogen()->PointersToHereCheckForValue());
danno@chromium.org's avatar
danno@chromium.org committed
4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777
  }
}


void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
  // By cases...external, fast-double, fast
  if (instr->is_typed_elements()) {
    DoStoreKeyedExternalArray(instr);
  } else if (instr->hydrogen()->value()->representation().IsDouble()) {
    DoStoreKeyedFixedDoubleArray(instr);
  } else {
    DoStoreKeyedFixedArray(instr);
  }
}


void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
4778
  DCHECK(ToRegister(instr->context()).is(esi));
4779 4780 4781
  DCHECK(ToRegister(instr->object()).is(StoreDescriptor::ReceiverRegister()));
  DCHECK(ToRegister(instr->key()).is(StoreDescriptor::NameRegister()));
  DCHECK(ToRegister(instr->value()).is(StoreDescriptor::ValueRegister()));
danno@chromium.org's avatar
danno@chromium.org committed
4782

4783 4784 4785
  Handle<Code> ic = CodeFactory::KeyedStoreICInOptimizedCode(
                        isolate(), instr->language_mode(),
                        instr->hydrogen()->initialization_state()).code();
danno@chromium.org's avatar
danno@chromium.org committed
4786 4787 4788 4789 4790 4791 4792 4793 4794
  CallCode(ic, RelocInfo::CODE_TARGET, instr);
}


void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
  Register object = ToRegister(instr->object());
  Register temp = ToRegister(instr->temp());
  Label no_memento_found;
  __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4795
  DeoptimizeIf(equal, instr, Deoptimizer::kMementoFound);
danno@chromium.org's avatar
danno@chromium.org committed
4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819
  __ bind(&no_memento_found);
}


void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
  Register object_reg = ToRegister(instr->object());

  Handle<Map> from_map = instr->original_map();
  Handle<Map> to_map = instr->transitioned_map();
  ElementsKind from_kind = instr->from_kind();
  ElementsKind to_kind = instr->to_kind();

  Label not_applicable;
  bool is_simple_map_transition =
      IsSimpleMapChangeTransition(from_kind, to_kind);
  Label::Distance branch_distance =
      is_simple_map_transition ? Label::kNear : Label::kFar;
  __ cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
  __ j(not_equal, &not_applicable, branch_distance);
  if (is_simple_map_transition) {
    Register new_map_reg = ToRegister(instr->new_map_temp());
    __ mov(FieldOperand(object_reg, HeapObject::kMapOffset),
           Immediate(to_map));
    // Write barrier.
4820
    DCHECK_NOT_NULL(instr->temp());
danno@chromium.org's avatar
danno@chromium.org committed
4821
    __ RecordWriteForMap(object_reg, to_map, new_map_reg,
4822
                         ToRegister(instr->temp()), kDontSaveFPRegs);
danno@chromium.org's avatar
danno@chromium.org committed
4823
  } else {
4824 4825
    DCHECK(ToRegister(instr->context()).is(esi));
    DCHECK(object_reg.is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838
    PushSafepointRegistersScope scope(this);
    __ mov(ebx, to_map);
    bool is_js_array = from_map->instance_type() == JS_ARRAY_TYPE;
    TransitionElementsKindStub stub(isolate(), from_kind, to_kind, is_js_array);
    __ CallStub(&stub);
    RecordSafepointWithLazyDeopt(instr,
        RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
  }
  __ bind(&not_applicable);
}


void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4839
  class DeferredStringCharCodeAt FINAL : public LDeferredCode {
danno@chromium.org's avatar
danno@chromium.org committed
4840 4841 4842 4843 4844
   public:
    DeferredStringCharCodeAt(LCodeGen* codegen,
                             LStringCharCodeAt* instr,
                             const X87Stack& x87_stack)
        : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4845 4846 4847
    void Generate() OVERRIDE { codegen()->DoDeferredStringCharCodeAt(instr_); }
    LInstruction* instr() OVERRIDE { return instr_; }

danno@chromium.org's avatar
danno@chromium.org committed
4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887
   private:
    LStringCharCodeAt* instr_;
  };

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

  StringCharLoadGenerator::Generate(masm(),
                                    factory(),
                                    ToRegister(instr->string()),
                                    ToRegister(instr->index()),
                                    ToRegister(instr->result()),
                                    deferred->entry());
  __ bind(deferred->exit());
}


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

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

  PushSafepointRegistersScope scope(this);
  __ push(string);
  // Push the index as a smi. This is safe because of the checks in
  // DoStringCharCodeAt above.
  STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
  if (instr->index()->IsConstantOperand()) {
    Immediate immediate = ToImmediate(LConstantOperand::cast(instr->index()),
                                      Representation::Smi());
    __ push(immediate);
  } else {
    Register index = ToRegister(instr->index());
    __ SmiTag(index);
    __ push(index);
  }
4888
  CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2,
danno@chromium.org's avatar
danno@chromium.org committed
4889 4890 4891 4892 4893 4894 4895 4896
                          instr, instr->context());
  __ AssertSmi(eax);
  __ SmiUntag(eax);
  __ StoreToSafepointRegisterSlot(result, eax);
}


void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4897
  class DeferredStringCharFromCode FINAL : public LDeferredCode {
danno@chromium.org's avatar
danno@chromium.org committed
4898 4899 4900 4901 4902
   public:
    DeferredStringCharFromCode(LCodeGen* codegen,
                               LStringCharFromCode* instr,
                               const X87Stack& x87_stack)
        : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4903
    void Generate() OVERRIDE {
danno@chromium.org's avatar
danno@chromium.org committed
4904 4905
      codegen()->DoDeferredStringCharFromCode(instr_);
    }
4906 4907
    LInstruction* instr() OVERRIDE { return instr_; }

danno@chromium.org's avatar
danno@chromium.org committed
4908 4909 4910 4911 4912 4913 4914
   private:
    LStringCharFromCode* instr_;
  };

  DeferredStringCharFromCode* deferred =
      new(zone()) DeferredStringCharFromCode(this, instr, x87_stack_);

4915
  DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
danno@chromium.org's avatar
danno@chromium.org committed
4916 4917
  Register char_code = ToRegister(instr->char_code());
  Register result = ToRegister(instr->result());
4918
  DCHECK(!char_code.is(result));
danno@chromium.org's avatar
danno@chromium.org committed
4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949

  __ cmp(char_code, String::kMaxOneByteCharCode);
  __ j(above, deferred->entry());
  __ Move(result, Immediate(factory()->single_character_string_cache()));
  __ mov(result, FieldOperand(result,
                              char_code, times_pointer_size,
                              FixedArray::kHeaderSize));
  __ cmp(result, factory()->undefined_value());
  __ j(equal, deferred->entry());
  __ bind(deferred->exit());
}


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

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

  PushSafepointRegistersScope scope(this);
  __ SmiTag(char_code);
  __ push(char_code);
  CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr, instr->context());
  __ StoreToSafepointRegisterSlot(result, eax);
}


void LCodeGen::DoStringAdd(LStringAdd* instr) {
4950 4951 4952
  DCHECK(ToRegister(instr->context()).is(esi));
  DCHECK(ToRegister(instr->left()).is(edx));
  DCHECK(ToRegister(instr->right()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
4953 4954 4955 4956 4957 4958 4959 4960 4961 4962
  StringAddStub stub(isolate(),
                     instr->hydrogen()->flags(),
                     instr->hydrogen()->pretenure_flag());
  CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
}


void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
  LOperand* input = instr->value();
  LOperand* output = instr->result();
4963 4964
  DCHECK(input->IsRegister() || input->IsStackSlot());
  DCHECK(output->IsDoubleRegister());
danno@chromium.org's avatar
danno@chromium.org committed
4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986
  if (input->IsRegister()) {
    Register input_reg = ToRegister(input);
    __ push(input_reg);
    X87Mov(ToX87Register(output), Operand(esp, 0), kX87IntOperand);
    __ pop(input_reg);
  } else {
    X87Mov(ToX87Register(output), ToOperand(input), kX87IntOperand);
  }
}


void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
  LOperand* input = instr->value();
  LOperand* output = instr->result();
  X87Register res = ToX87Register(output);
  X87PrepareToWrite(res);
  __ LoadUint32NoSSE2(ToRegister(input));
  X87CommitWrite(res);
}


void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4987
  class DeferredNumberTagI FINAL : public LDeferredCode {
danno@chromium.org's avatar
danno@chromium.org committed
4988 4989 4990 4991 4992
   public:
    DeferredNumberTagI(LCodeGen* codegen,
                       LNumberTagI* instr,
                       const X87Stack& x87_stack)
        : LDeferredCode(codegen, x87_stack), instr_(instr) { }
4993
    void Generate() OVERRIDE {
danno@chromium.org's avatar
danno@chromium.org committed
4994 4995 4996
      codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
                                       SIGNED_INT32);
    }
4997 4998
    LInstruction* instr() OVERRIDE { return instr_; }

danno@chromium.org's avatar
danno@chromium.org committed
4999 5000 5001 5002 5003
   private:
    LNumberTagI* instr_;
  };

  LOperand* input = instr->value();
5004
  DCHECK(input->IsRegister() && input->Equals(instr->result()));
danno@chromium.org's avatar
danno@chromium.org committed
5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015
  Register reg = ToRegister(input);

  DeferredNumberTagI* deferred =
      new(zone()) DeferredNumberTagI(this, instr, x87_stack_);
  __ SmiTag(reg);
  __ j(overflow, deferred->entry());
  __ bind(deferred->exit());
}


void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
5016
  class DeferredNumberTagU FINAL : public LDeferredCode {
danno@chromium.org's avatar
danno@chromium.org committed
5017 5018 5019 5020 5021
   public:
    DeferredNumberTagU(LCodeGen* codegen,
                       LNumberTagU* instr,
                       const X87Stack& x87_stack)
        : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5022
    void Generate() OVERRIDE {
danno@chromium.org's avatar
danno@chromium.org committed
5023 5024 5025
      codegen()->DoDeferredNumberTagIU(instr_, instr_->value(), instr_->temp(),
                                       UNSIGNED_INT32);
    }
5026 5027
    LInstruction* instr() OVERRIDE { return instr_; }

danno@chromium.org's avatar
danno@chromium.org committed
5028 5029 5030 5031 5032
   private:
    LNumberTagU* instr_;
  };

  LOperand* input = instr->value();
5033
  DCHECK(input->IsRegister() && input->Equals(instr->result()));
danno@chromium.org's avatar
danno@chromium.org committed
5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089
  Register reg = ToRegister(input);

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


void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
                                     LOperand* value,
                                     LOperand* temp,
                                     IntegerSignedness signedness) {
  Label done, slow;
  Register reg = ToRegister(value);
  Register tmp = ToRegister(temp);

  if (signedness == SIGNED_INT32) {
    // There was overflow, so bits 30 and 31 of the original integer
    // disagree. Try to allocate a heap number in new space and store
    // the value in there. If that fails, call the runtime system.
    __ SmiUntag(reg);
    __ xor_(reg, 0x80000000);
    __ push(reg);
    __ fild_s(Operand(esp, 0));
    __ pop(reg);
  } else {
    // There's no fild variant for unsigned values, so zero-extend to a 64-bit
    // int manually.
    __ push(Immediate(0));
    __ push(reg);
    __ fild_d(Operand(esp, 0));
    __ pop(reg);
    __ pop(reg);
  }

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

  // Slow case: Call the runtime system to do the number allocation.
  __ bind(&slow);
  {
    // TODO(3095996): Put a valid pointer value in the stack slot where the
    // result register is stored, as this register is in the pointer map, but
    // contains an integer value.
    __ Move(reg, Immediate(0));

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

    // NumberTagI and NumberTagD use the context from the frame, rather than
    // the environment's HContext or HInlinedContext value.
5090
    // They only call Runtime::kAllocateHeapNumber.
danno@chromium.org's avatar
danno@chromium.org committed
5091 5092 5093
    // The corresponding HChange instructions are added in a phase that does
    // not have easy access to the local context.
    __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5094
    __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
danno@chromium.org's avatar
danno@chromium.org committed
5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105
    RecordSafepointWithRegisters(
        instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
    __ StoreToSafepointRegisterSlot(reg, eax);
  }

  __ bind(&done);
  __ fstp_d(FieldOperand(reg, HeapNumber::kValueOffset));
}


void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
5106
  class DeferredNumberTagD FINAL : public LDeferredCode {
danno@chromium.org's avatar
danno@chromium.org committed
5107 5108 5109 5110 5111
   public:
    DeferredNumberTagD(LCodeGen* codegen,
                       LNumberTagD* instr,
                       const X87Stack& x87_stack)
        : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5112 5113 5114
    void Generate() OVERRIDE { codegen()->DoDeferredNumberTagD(instr_); }
    LInstruction* instr() OVERRIDE { return instr_; }

danno@chromium.org's avatar
danno@chromium.org committed
5115 5116 5117 5118 5119 5120 5121 5122
   private:
    LNumberTagD* instr_;
  };

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

  // Put the value to the top of stack
  X87Register src = ToX87Register(instr->value());
5123 5124 5125
  // Don't use X87LoadForUsage here, which is only used by Instruction which
  // clobbers fp registers.
  x87_stack_.Fxch(src);
danno@chromium.org's avatar
danno@chromium.org committed
5126 5127 5128 5129 5130 5131 5132 5133 5134 5135

  DeferredNumberTagD* deferred =
      new(zone()) DeferredNumberTagD(this, instr, x87_stack_);
  if (FLAG_inline_new) {
    Register tmp = ToRegister(instr->temp());
    __ AllocateHeapNumber(reg, tmp, no_reg, deferred->entry());
  } else {
    __ jmp(deferred->entry());
  }
  __ bind(deferred->exit());
5136
  __ fst_d(FieldOperand(reg, HeapNumber::kValueOffset));
danno@chromium.org's avatar
danno@chromium.org committed
5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149
}


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

  PushSafepointRegistersScope scope(this);
  // NumberTagI and NumberTagD use the context from the frame, rather than
  // the environment's HContext or HInlinedContext value.
5150
  // They only call Runtime::kAllocateHeapNumber.
danno@chromium.org's avatar
danno@chromium.org committed
5151 5152 5153
  // The corresponding HChange instructions are added in a phase that does
  // not have easy access to the local context.
  __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
5154
  __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
danno@chromium.org's avatar
danno@chromium.org committed
5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166
  RecordSafepointWithRegisters(
      instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
  __ StoreToSafepointRegisterSlot(reg, eax);
}


void LCodeGen::DoSmiTag(LSmiTag* instr) {
  HChange* hchange = instr->hydrogen();
  Register input = ToRegister(instr->value());
  if (hchange->CheckFlag(HValue::kCanOverflow) &&
      hchange->value()->CheckFlag(HValue::kUint32)) {
    __ test(input, Immediate(0xc0000000));
5167
    DeoptimizeIf(not_zero, instr, Deoptimizer::kOverflow);
danno@chromium.org's avatar
danno@chromium.org committed
5168 5169 5170 5171
  }
  __ SmiTag(input);
  if (hchange->CheckFlag(HValue::kCanOverflow) &&
      !hchange->value()->CheckFlag(HValue::kUint32)) {
5172
    DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
danno@chromium.org's avatar
danno@chromium.org committed
5173 5174 5175 5176 5177 5178 5179
  }
}


void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
  LOperand* input = instr->value();
  Register result = ToRegister(input);
5180
  DCHECK(input->IsRegister() && input->Equals(instr->result()));
danno@chromium.org's avatar
danno@chromium.org committed
5181 5182
  if (instr->needs_check()) {
    __ test(result, Immediate(kSmiTagMask));
5183
    DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
danno@chromium.org's avatar
danno@chromium.org committed
5184 5185 5186 5187 5188 5189 5190
  } else {
    __ AssertSmi(result);
  }
  __ SmiUntag(result);
}


5191 5192
void LCodeGen::EmitNumberUntagDNoSSE2(LNumberUntagD* instr, Register input_reg,
                                      Register temp_reg, X87Register res_reg,
danno@chromium.org's avatar
danno@chromium.org committed
5193
                                      NumberUntagDMode mode) {
5194 5195 5196 5197
  bool can_convert_undefined_to_nan =
      instr->hydrogen()->can_convert_undefined_to_nan();
  bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();

danno@chromium.org's avatar
danno@chromium.org committed
5198 5199 5200 5201 5202
  Label load_smi, done;

  X87PrepareToWrite(res_reg);
  if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
    // Smi check.
5203
    __ JumpIfSmi(input_reg, &load_smi);
danno@chromium.org's avatar
danno@chromium.org committed
5204 5205 5206 5207 5208

    // Heap number map check.
    __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
           factory()->heap_number_map());
    if (!can_convert_undefined_to_nan) {
5209
      DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
danno@chromium.org's avatar
danno@chromium.org committed
5210 5211
    } else {
      Label heap_number, convert;
5212
      __ j(equal, &heap_number);
danno@chromium.org's avatar
danno@chromium.org committed
5213 5214 5215

      // Convert undefined (or hole) to NaN.
      __ cmp(input_reg, factory()->undefined_value());
5216
      DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
danno@chromium.org's avatar
danno@chromium.org committed
5217 5218

      __ bind(&convert);
5219 5220 5221 5222
      __ push(Immediate(0xffffffff));
      __ push(Immediate(0x7fffffff));
      __ fld_d(MemOperand(esp, 0));
      __ lea(esp, Operand(esp, kDoubleSize));
danno@chromium.org's avatar
danno@chromium.org committed
5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241
      __ jmp(&done, Label::kNear);

      __ bind(&heap_number);
    }
    // Heap number to x87 conversion.
    __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
    if (deoptimize_on_minus_zero) {
      __ fldz();
      __ FCmp();
      __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));
      __ j(not_zero, &done, Label::kNear);

      // Use general purpose registers to check if we have -0.0
      __ mov(temp_reg, FieldOperand(input_reg, HeapNumber::kExponentOffset));
      __ test(temp_reg, Immediate(HeapNumber::kSignMask));
      __ j(zero, &done, Label::kNear);

      // Pop FPU stack before deoptimizing.
      __ fstp(0);
5242
      DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
5243 5244 5245
    }
    __ jmp(&done, Label::kNear);
  } else {
5246
    DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
danno@chromium.org's avatar
danno@chromium.org committed
5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294
  }

  __ bind(&load_smi);
  // Clobbering a temp is faster than re-tagging the
  // input register since we avoid dependencies.
  __ mov(temp_reg, input_reg);
  __ SmiUntag(temp_reg);  // Untag smi before converting to float.
  __ push(temp_reg);
  __ fild_s(Operand(esp, 0));
  __ add(esp, Immediate(kPointerSize));
  __ bind(&done);
  X87CommitWrite(res_reg);
}


void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr, Label* done) {
  Register input_reg = ToRegister(instr->value());

  // The input was optimistically untagged; revert it.
  STATIC_ASSERT(kSmiTagSize == 1);
  __ lea(input_reg, Operand(input_reg, times_2, kHeapObjectTag));

  if (instr->truncating()) {
    Label no_heap_number, check_bools, check_false;

    // Heap number map check.
    __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
           factory()->heap_number_map());
    __ j(not_equal, &no_heap_number, Label::kNear);
    __ TruncateHeapNumberToI(input_reg, input_reg);
    __ jmp(done);

    __ bind(&no_heap_number);
    // Check for Oddballs. Undefined/False is converted to zero and True to one
    // for truncating conversions.
    __ cmp(input_reg, factory()->undefined_value());
    __ j(not_equal, &check_bools, Label::kNear);
    __ Move(input_reg, Immediate(0));
    __ jmp(done);

    __ bind(&check_bools);
    __ cmp(input_reg, factory()->true_value());
    __ j(not_equal, &check_false, Label::kNear);
    __ Move(input_reg, Immediate(1));
    __ jmp(done);

    __ bind(&check_false);
    __ cmp(input_reg, factory()->false_value());
5295
    DeoptimizeIf(not_equal, instr,
5296
                 Deoptimizer::kNotAHeapNumberUndefinedBoolean);
danno@chromium.org's avatar
danno@chromium.org committed
5297 5298
    __ Move(input_reg, Immediate(0));
  } else {
5299 5300 5301 5302
    // TODO(olivf) Converting a number on the fpu is actually quite slow. We
    // should first try a fast conversion and then bailout to this slow case.
    __ cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
           isolate()->factory()->heap_number_map());
5303
    DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumber);
5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318

    __ sub(esp, Immediate(kPointerSize));
    __ fld_d(FieldOperand(input_reg, HeapNumber::kValueOffset));

    if (instr->hydrogen()->GetMinusZeroMode() == FAIL_ON_MINUS_ZERO) {
      Label no_precision_lost, not_nan, zero_check;
      __ fld(0);

      __ fist_s(MemOperand(esp, 0));
      __ fild_s(MemOperand(esp, 0));
      __ FCmp();
      __ pop(input_reg);

      __ j(equal, &no_precision_lost, Label::kNear);
      __ fstp(0);
5319
      DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5320 5321 5322 5323
      __ bind(&no_precision_lost);

      __ j(parity_odd, &not_nan);
      __ fstp(0);
5324
      DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338
      __ bind(&not_nan);

      __ test(input_reg, Operand(input_reg));
      __ j(zero, &zero_check, Label::kNear);
      __ fstp(0);
      __ jmp(done);

      __ bind(&zero_check);
      // To check for minus zero, we load the value again as float, and check
      // if that is still 0.
      __ sub(esp, Immediate(kPointerSize));
      __ fstp_s(Operand(esp, 0));
      __ pop(input_reg);
      __ test(input_reg, Operand(input_reg));
5339
      DeoptimizeIf(not_zero, instr, Deoptimizer::kMinusZero);
5340 5341 5342 5343 5344
    } else {
      __ fist_s(MemOperand(esp, 0));
      __ fild_s(MemOperand(esp, 0));
      __ FCmp();
      __ pop(input_reg);
5345 5346
      DeoptimizeIf(not_equal, instr, Deoptimizer::kLostPrecision);
      DeoptimizeIf(parity_even, instr, Deoptimizer::kNaN);
5347
    }
danno@chromium.org's avatar
danno@chromium.org committed
5348 5349 5350 5351 5352
  }
}


void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
5353
  class DeferredTaggedToI FINAL : public LDeferredCode {
danno@chromium.org's avatar
danno@chromium.org committed
5354 5355 5356 5357 5358
   public:
    DeferredTaggedToI(LCodeGen* codegen,
                      LTaggedToI* instr,
                      const X87Stack& x87_stack)
        : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5359 5360 5361
    void Generate() OVERRIDE { codegen()->DoDeferredTaggedToI(instr_, done()); }
    LInstruction* instr() OVERRIDE { return instr_; }

danno@chromium.org's avatar
danno@chromium.org committed
5362 5363 5364 5365 5366
   private:
    LTaggedToI* instr_;
  };

  LOperand* input = instr->value();
5367
  DCHECK(input->IsRegister());
danno@chromium.org's avatar
danno@chromium.org committed
5368
  Register input_reg = ToRegister(input);
5369
  DCHECK(input_reg.is(ToRegister(instr->result())));
danno@chromium.org's avatar
danno@chromium.org committed
5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389

  if (instr->hydrogen()->value()->representation().IsSmi()) {
    __ SmiUntag(input_reg);
  } else {
    DeferredTaggedToI* deferred =
        new(zone()) DeferredTaggedToI(this, instr, x87_stack_);
    // Optimistically untag the input.
    // If the input is a HeapObject, SmiUntag will set the carry flag.
    STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
    __ SmiUntag(input_reg);
    // Branch to deferred code if the input was tagged.
    // The deferred code will take care of restoring the tag.
    __ j(carry, deferred->entry());
    __ bind(deferred->exit());
  }
}


void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
  LOperand* input = instr->value();
5390
  DCHECK(input->IsRegister());
danno@chromium.org's avatar
danno@chromium.org committed
5391
  LOperand* temp = instr->temp();
5392
  DCHECK(temp->IsRegister());
danno@chromium.org's avatar
danno@chromium.org committed
5393
  LOperand* result = instr->result();
5394
  DCHECK(result->IsDoubleRegister());
danno@chromium.org's avatar
danno@chromium.org committed
5395 5396 5397 5398 5399 5400 5401 5402

  Register input_reg = ToRegister(input);
  Register temp_reg = ToRegister(temp);

  HValue* value = instr->hydrogen()->value();
  NumberUntagDMode mode = value->representation().IsSmi()
      ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;

5403
  EmitNumberUntagDNoSSE2(instr, input_reg, temp_reg, ToX87Register(result),
danno@chromium.org's avatar
danno@chromium.org committed
5404 5405 5406 5407 5408 5409
                         mode);
}


void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
  LOperand* input = instr->value();
5410
  DCHECK(input->IsDoubleRegister());
danno@chromium.org's avatar
danno@chromium.org committed
5411
  LOperand* result = instr->result();
5412
  DCHECK(result->IsRegister());
danno@chromium.org's avatar
danno@chromium.org committed
5413 5414 5415 5416 5417 5418 5419
  Register result_reg = ToRegister(result);

  if (instr->truncating()) {
    X87Register input_reg = ToX87Register(input);
    X87Fxch(input_reg);
    __ TruncateX87TOSToI(result_reg);
  } else {
5420
    Label lost_precision, is_nan, minus_zero, done;
danno@chromium.org's avatar
danno@chromium.org committed
5421 5422 5423
    X87Register input_reg = ToX87Register(input);
    X87Fxch(input_reg);
    __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5424
                 &lost_precision, &is_nan, &minus_zero);
5425
    __ jmp(&done);
5426
    __ bind(&lost_precision);
5427
    DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5428
    __ bind(&is_nan);
5429
    DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5430
    __ bind(&minus_zero);
5431
    DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
5432 5433 5434 5435 5436 5437 5438
    __ bind(&done);
  }
}


void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
  LOperand* input = instr->value();
5439
  DCHECK(input->IsDoubleRegister());
danno@chromium.org's avatar
danno@chromium.org committed
5440
  LOperand* result = instr->result();
5441
  DCHECK(result->IsRegister());
danno@chromium.org's avatar
danno@chromium.org committed
5442 5443
  Register result_reg = ToRegister(result);

5444
  Label lost_precision, is_nan, minus_zero, done;
danno@chromium.org's avatar
danno@chromium.org committed
5445 5446 5447
  X87Register input_reg = ToX87Register(input);
  X87Fxch(input_reg);
  __ X87TOSToI(result_reg, instr->hydrogen()->GetMinusZeroMode(),
5448
               &lost_precision, &is_nan, &minus_zero);
5449
  __ jmp(&done);
5450
  __ bind(&lost_precision);
5451
  DeoptimizeIf(no_condition, instr, Deoptimizer::kLostPrecision);
5452
  __ bind(&is_nan);
5453
  DeoptimizeIf(no_condition, instr, Deoptimizer::kNaN);
5454
  __ bind(&minus_zero);
5455
  DeoptimizeIf(no_condition, instr, Deoptimizer::kMinusZero);
danno@chromium.org's avatar
danno@chromium.org committed
5456 5457
  __ bind(&done);
  __ SmiTag(result_reg);
5458
  DeoptimizeIf(overflow, instr, Deoptimizer::kOverflow);
danno@chromium.org's avatar
danno@chromium.org committed
5459 5460 5461 5462 5463 5464
}


void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
  LOperand* input = instr->value();
  __ test(ToOperand(input), Immediate(kSmiTagMask));
5465
  DeoptimizeIf(not_zero, instr, Deoptimizer::kNotASmi);
danno@chromium.org's avatar
danno@chromium.org committed
5466 5467 5468 5469
}


void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
5470
  if (!instr->hydrogen()->value()->type().IsHeapObject()) {
danno@chromium.org's avatar
danno@chromium.org committed
5471 5472
    LOperand* input = instr->value();
    __ test(ToOperand(input), Immediate(kSmiTagMask));
5473
    DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
danno@chromium.org's avatar
danno@chromium.org committed
5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493
  }
}


void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
  Register input = ToRegister(instr->value());
  Register temp = ToRegister(instr->temp());

  __ mov(temp, FieldOperand(input, HeapObject::kMapOffset));

  if (instr->hydrogen()->is_interval_check()) {
    InstanceType first;
    InstanceType last;
    instr->hydrogen()->GetCheckInterval(&first, &last);

    __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
            static_cast<int8_t>(first));

    // If there is only one type in the interval check for equality.
    if (first == last) {
5494
      DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
danno@chromium.org's avatar
danno@chromium.org committed
5495
    } else {
5496
      DeoptimizeIf(below, instr, Deoptimizer::kWrongInstanceType);
danno@chromium.org's avatar
danno@chromium.org committed
5497 5498 5499 5500
      // Omit check for the last type.
      if (last != LAST_TYPE) {
        __ cmpb(FieldOperand(temp, Map::kInstanceTypeOffset),
                static_cast<int8_t>(last));
5501
        DeoptimizeIf(above, instr, Deoptimizer::kWrongInstanceType);
danno@chromium.org's avatar
danno@chromium.org committed
5502 5503 5504 5505 5506 5507 5508
      }
    }
  } else {
    uint8_t mask;
    uint8_t tag;
    instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);

5509 5510
    if (base::bits::IsPowerOfTwo32(mask)) {
      DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
danno@chromium.org's avatar
danno@chromium.org committed
5511
      __ test_b(FieldOperand(temp, Map::kInstanceTypeOffset), mask);
5512 5513
      DeoptimizeIf(tag == 0 ? not_zero : zero, instr,
                   Deoptimizer::kWrongInstanceType);
danno@chromium.org's avatar
danno@chromium.org committed
5514 5515 5516 5517
    } else {
      __ movzx_b(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
      __ and_(temp, mask);
      __ cmp(temp, tag);
5518
      DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongInstanceType);
danno@chromium.org's avatar
danno@chromium.org committed
5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533
    }
  }
}


void LCodeGen::DoCheckValue(LCheckValue* instr) {
  Handle<HeapObject> object = instr->hydrogen()->object().handle();
  if (instr->hydrogen()->object_in_new_space()) {
    Register reg = ToRegister(instr->value());
    Handle<Cell> cell = isolate()->factory()->NewCell(object);
    __ cmp(reg, Operand::ForCell(cell));
  } else {
    Operand operand = ToOperand(instr->value());
    __ cmp(operand, object);
  }
5534
  DeoptimizeIf(not_equal, instr, Deoptimizer::kValueMismatch);
danno@chromium.org's avatar
danno@chromium.org committed
5535 5536 5537 5538 5539 5540 5541 5542
}


void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
  {
    PushSafepointRegistersScope scope(this);
    __ push(object);
    __ xor_(esi, esi);
5543
    __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
danno@chromium.org's avatar
danno@chromium.org committed
5544 5545 5546 5547 5548
    RecordSafepointWithRegisters(
        instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);

    __ test(eax, Immediate(kSmiTagMask));
  }
5549
  DeoptimizeIf(zero, instr, Deoptimizer::kInstanceMigrationFailed);
danno@chromium.org's avatar
danno@chromium.org committed
5550 5551 5552 5553
}


void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
5554
  class DeferredCheckMaps FINAL : public LDeferredCode {
danno@chromium.org's avatar
danno@chromium.org committed
5555 5556 5557 5558 5559 5560 5561 5562
   public:
    DeferredCheckMaps(LCodeGen* codegen,
                      LCheckMaps* instr,
                      Register object,
                      const X87Stack& x87_stack)
        : LDeferredCode(codegen, x87_stack), instr_(instr), object_(object) {
      SetExit(check_maps());
    }
5563
    void Generate() OVERRIDE {
danno@chromium.org's avatar
danno@chromium.org committed
5564 5565 5566
      codegen()->DoDeferredInstanceMigration(instr_, object_);
    }
    Label* check_maps() { return &check_maps_; }
5567 5568
    LInstruction* instr() OVERRIDE { return instr_; }

danno@chromium.org's avatar
danno@chromium.org committed
5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583
   private:
    LCheckMaps* instr_;
    Label check_maps_;
    Register object_;
  };

  if (instr->hydrogen()->IsStabilityCheck()) {
    const UniqueSet<Map>* maps = instr->hydrogen()->maps();
    for (int i = 0; i < maps->size(); ++i) {
      AddStabilityDependency(maps->at(i).handle());
    }
    return;
  }

  LOperand* input = instr->value();
5584
  DCHECK(input->IsRegister());
danno@chromium.org's avatar
danno@chromium.org committed
5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605
  Register reg = ToRegister(input);

  DeferredCheckMaps* deferred = NULL;
  if (instr->hydrogen()->HasMigrationTarget()) {
    deferred = new(zone()) DeferredCheckMaps(this, instr, reg, x87_stack_);
    __ bind(deferred->check_maps());
  }

  const UniqueSet<Map>* maps = instr->hydrogen()->maps();
  Label success;
  for (int i = 0; i < maps->size() - 1; i++) {
    Handle<Map> map = maps->at(i).handle();
    __ CompareMap(reg, map);
    __ j(equal, &success, Label::kNear);
  }

  Handle<Map> map = maps->at(maps->size() - 1).handle();
  __ CompareMap(reg, map);
  if (instr->hydrogen()->HasMigrationTarget()) {
    __ j(not_equal, deferred->entry());
  } else {
5606
    DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
danno@chromium.org's avatar
danno@chromium.org committed
5607 5608 5609 5610 5611 5612 5613
  }

  __ bind(&success);
}


void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
5614 5615 5616 5617
  X87Register value_reg = ToX87Register(instr->unclamped());
  Register result_reg = ToRegister(instr->result());
  X87Fxch(value_reg);
  __ ClampTOSToUint8(result_reg);
danno@chromium.org's avatar
danno@chromium.org committed
5618 5619 5620 5621
}


void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
5622
  DCHECK(instr->unclamped()->Equals(instr->result()));
danno@chromium.org's avatar
danno@chromium.org committed
5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646
  Register value_reg = ToRegister(instr->result());
  __ ClampUint8(value_reg);
}


void LCodeGen::DoClampTToUint8NoSSE2(LClampTToUint8NoSSE2* instr) {
  Register input_reg = ToRegister(instr->unclamped());
  Register result_reg = ToRegister(instr->result());
  Register scratch = ToRegister(instr->scratch());
  Register scratch2 = ToRegister(instr->scratch2());
  Register scratch3 = ToRegister(instr->scratch3());
  Label is_smi, done, heap_number, valid_exponent,
      largest_value, zero_result, maybe_nan_or_infinity;

  __ JumpIfSmi(input_reg, &is_smi);

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

  // Check for undefined. Undefined is converted to zero for clamping
  // conversions.
  __ cmp(input_reg, factory()->undefined_value());
5647
  DeoptimizeIf(not_equal, instr, Deoptimizer::kNotAHeapNumberUndefined);
danno@chromium.org's avatar
danno@chromium.org committed
5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750
  __ jmp(&zero_result, Label::kNear);

  // Heap number
  __ bind(&heap_number);

  // Surprisingly, all of the hand-crafted bit-manipulations below are much
  // faster than the x86 FPU built-in instruction, especially since "banker's
  // rounding" would be additionally very expensive

  // Get exponent word.
  __ mov(scratch, FieldOperand(input_reg, HeapNumber::kExponentOffset));
  __ mov(scratch3, FieldOperand(input_reg, HeapNumber::kMantissaOffset));

  // Test for negative values --> clamp to zero
  __ test(scratch, scratch);
  __ j(negative, &zero_result, Label::kNear);

  // Get exponent alone in scratch2.
  __ mov(scratch2, scratch);
  __ and_(scratch2, HeapNumber::kExponentMask);
  __ shr(scratch2, HeapNumber::kExponentShift);
  __ j(zero, &zero_result, Label::kNear);
  __ sub(scratch2, Immediate(HeapNumber::kExponentBias - 1));
  __ j(negative, &zero_result, Label::kNear);

  const uint32_t non_int8_exponent = 7;
  __ cmp(scratch2, Immediate(non_int8_exponent + 1));
  // If the exponent is too big, check for special values.
  __ j(greater, &maybe_nan_or_infinity, Label::kNear);

  __ bind(&valid_exponent);
  // Exponent word in scratch, exponent in scratch2. We know that 0 <= exponent
  // < 7. The shift bias is the number of bits to shift the mantissa such that
  // with an exponent of 7 such the that top-most one is in bit 30, allowing
  // detection the rounding overflow of a 255.5 to 256 (bit 31 goes from 0 to
  // 1).
  int shift_bias = (30 - HeapNumber::kExponentShift) - 7 - 1;
  __ lea(result_reg, MemOperand(scratch2, shift_bias));
  // Here result_reg (ecx) is the shift, scratch is the exponent word.  Get the
  // top bits of the mantissa.
  __ and_(scratch, HeapNumber::kMantissaMask);
  // Put back the implicit 1 of the mantissa
  __ or_(scratch, 1 << HeapNumber::kExponentShift);
  // Shift up to round
  __ shl_cl(scratch);
  // Use "banker's rounding" to spec: If fractional part of number is 0.5, then
  // use the bit in the "ones" place and add it to the "halves" place, which has
  // the effect of rounding to even.
  __ mov(scratch2, scratch);
  const uint32_t one_half_bit_shift = 30 - sizeof(uint8_t) * 8;
  const uint32_t one_bit_shift = one_half_bit_shift + 1;
  __ and_(scratch2, Immediate((1 << one_bit_shift) - 1));
  __ cmp(scratch2, Immediate(1 << one_half_bit_shift));
  Label no_round;
  __ j(less, &no_round, Label::kNear);
  Label round_up;
  __ mov(scratch2, Immediate(1 << one_half_bit_shift));
  __ j(greater, &round_up, Label::kNear);
  __ test(scratch3, scratch3);
  __ j(not_zero, &round_up, Label::kNear);
  __ mov(scratch2, scratch);
  __ and_(scratch2, Immediate(1 << one_bit_shift));
  __ shr(scratch2, 1);
  __ bind(&round_up);
  __ add(scratch, scratch2);
  __ j(overflow, &largest_value, Label::kNear);
  __ bind(&no_round);
  __ shr(scratch, 23);
  __ mov(result_reg, scratch);
  __ jmp(&done, Label::kNear);

  __ bind(&maybe_nan_or_infinity);
  // Check for NaN/Infinity, all other values map to 255
  __ cmp(scratch2, Immediate(HeapNumber::kInfinityOrNanExponent + 1));
  __ j(not_equal, &largest_value, Label::kNear);

  // Check for NaN, which differs from Infinity in that at least one mantissa
  // bit is set.
  __ and_(scratch, HeapNumber::kMantissaMask);
  __ or_(scratch, FieldOperand(input_reg, HeapNumber::kMantissaOffset));
  __ j(not_zero, &zero_result, Label::kNear);  // M!=0 --> NaN
  // Infinity -> Fall through to map to 255.

  __ bind(&largest_value);
  __ mov(result_reg, Immediate(255));
  __ jmp(&done, Label::kNear);

  __ bind(&zero_result);
  __ xor_(result_reg, result_reg);
  __ jmp(&done, Label::kNear);

  // smi
  __ bind(&is_smi);
  if (!input_reg.is(result_reg)) {
    __ mov(result_reg, input_reg);
  }
  __ SmiUntag(result_reg);
  __ ClampUint8(result_reg);
  __ bind(&done);
}


void LCodeGen::DoDoubleBits(LDoubleBits* instr) {
5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761
  X87Register value_reg = ToX87Register(instr->value());
  Register result_reg = ToRegister(instr->result());
  X87Fxch(value_reg);
  __ sub(esp, Immediate(kDoubleSize));
  __ fst_d(Operand(esp, 0));
  if (instr->hydrogen()->bits() == HDoubleBits::HIGH) {
    __ mov(result_reg, Operand(esp, kPointerSize));
  } else {
    __ mov(result_reg, Operand(esp, 0));
  }
  __ add(esp, Immediate(kDoubleSize));
danno@chromium.org's avatar
danno@chromium.org committed
5762 5763 5764 5765
}


void LCodeGen::DoConstructDouble(LConstructDouble* instr) {
5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776
  Register hi_reg = ToRegister(instr->hi());
  Register lo_reg = ToRegister(instr->lo());
  X87Register result_reg = ToX87Register(instr->result());
  // Follow below pattern to write a x87 fp register.
  X87PrepareToWrite(result_reg);
  __ sub(esp, Immediate(kDoubleSize));
  __ mov(Operand(esp, 0), lo_reg);
  __ mov(Operand(esp, kPointerSize), hi_reg);
  __ fld_d(Operand(esp, 0));
  __ add(esp, Immediate(kDoubleSize));
  X87CommitWrite(result_reg);
danno@chromium.org's avatar
danno@chromium.org committed
5777 5778 5779 5780
}


void LCodeGen::DoAllocate(LAllocate* instr) {
5781
  class DeferredAllocate FINAL : public LDeferredCode {
danno@chromium.org's avatar
danno@chromium.org committed
5782 5783 5784 5785 5786
   public:
    DeferredAllocate(LCodeGen* codegen,
                     LAllocate* instr,
                     const X87Stack& x87_stack)
        : LDeferredCode(codegen, x87_stack), instr_(instr) { }
5787 5788 5789
    void Generate() OVERRIDE { codegen()->DoDeferredAllocate(instr_); }
    LInstruction* instr() OVERRIDE { return instr_; }

danno@chromium.org's avatar
danno@chromium.org committed
5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804
   private:
    LAllocate* instr_;
  };

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

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

  // Allocate memory for the object.
  AllocationFlags flags = TAG_OBJECT;
  if (instr->hydrogen()->MustAllocateDoubleAligned()) {
    flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
  }
5805
  if (instr->hydrogen()->IsOldSpaceAllocation()) {
5806
    DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5807
    flags = static_cast<AllocationFlags>(flags | PRETENURE);
danno@chromium.org's avatar
danno@chromium.org committed
5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853
  }

  if (instr->size()->IsConstantOperand()) {
    int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
    if (size <= Page::kMaxRegularHeapObjectSize) {
      __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
    } else {
      __ jmp(deferred->entry());
    }
  } else {
    Register size = ToRegister(instr->size());
    __ Allocate(size, result, temp, no_reg, deferred->entry(), flags);
  }

  __ bind(deferred->exit());

  if (instr->hydrogen()->MustPrefillWithFiller()) {
    if (instr->size()->IsConstantOperand()) {
      int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
      __ mov(temp, (size / kPointerSize) - 1);
    } else {
      temp = ToRegister(instr->size());
      __ shr(temp, kPointerSizeLog2);
      __ dec(temp);
    }
    Label loop;
    __ bind(&loop);
    __ mov(FieldOperand(result, temp, times_pointer_size, 0),
        isolate()->factory()->one_pointer_filler_map());
    __ dec(temp);
    __ j(not_zero, &loop);
  }
}


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

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

  PushSafepointRegistersScope scope(this);
  if (instr->size()->IsRegister()) {
    Register size = ToRegister(instr->size());
5854
    DCHECK(!size.is(result));
danno@chromium.org's avatar
danno@chromium.org committed
5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869
    __ SmiTag(ToRegister(instr->size()));
    __ push(size);
  } else {
    int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
    if (size >= 0 && size <= Smi::kMaxValue) {
      __ push(Immediate(Smi::FromInt(size)));
    } else {
      // We should never get here at runtime => abort
      __ int3();
      return;
    }
  }

  int flags = AllocateDoubleAlignFlag::encode(
      instr->hydrogen()->MustAllocateDoubleAligned());
5870
  if (instr->hydrogen()->IsOldSpaceAllocation()) {
5871
    DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5872
    flags = AllocateTargetSpace::update(flags, OLD_SPACE);
danno@chromium.org's avatar
danno@chromium.org committed
5873 5874 5875 5876 5877 5878
  } else {
    flags = AllocateTargetSpace::update(flags, NEW_SPACE);
  }
  __ push(Immediate(Smi::FromInt(flags)));

  CallRuntimeFromDeferred(
5879
      Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
danno@chromium.org's avatar
danno@chromium.org committed
5880 5881 5882 5883 5884
  __ StoreToSafepointRegisterSlot(result, eax);
}


void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
5885
  DCHECK(ToRegister(instr->value()).is(eax));
danno@chromium.org's avatar
danno@chromium.org committed
5886 5887 5888 5889 5890 5891
  __ push(eax);
  CallRuntime(Runtime::kToFastProperties, 1, instr);
}


void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
5892
  DCHECK(ToRegister(instr->context()).is(esi));
danno@chromium.org's avatar
danno@chromium.org committed
5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911
  Label materialized;
  // Registers will be used as follows:
  // ecx = literals array.
  // ebx = regexp literal.
  // eax = regexp literal clone.
  // esi = context.
  int literal_offset =
      FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
  __ LoadHeapObject(ecx, instr->hydrogen()->literals());
  __ mov(ebx, FieldOperand(ecx, literal_offset));
  __ cmp(ebx, factory()->undefined_value());
  __ j(not_equal, &materialized, Label::kNear);

  // Create regexp literal using runtime function
  // Result will be in eax.
  __ push(ecx);
  __ push(Immediate(Smi::FromInt(instr->hydrogen()->literal_index())));
  __ push(Immediate(instr->hydrogen()->pattern()));
  __ push(Immediate(instr->hydrogen()->flags()));
5912
  CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
danno@chromium.org's avatar
danno@chromium.org committed
5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923
  __ mov(ebx, eax);

  __ bind(&materialized);
  int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
  Label allocated, runtime_allocate;
  __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
  __ jmp(&allocated, Label::kNear);

  __ bind(&runtime_allocate);
  __ push(ebx);
  __ push(Immediate(Smi::FromInt(size)));
5924
  CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
danno@chromium.org's avatar
danno@chromium.org committed
5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943
  __ pop(ebx);

  __ bind(&allocated);
  // Copy the content into the newly allocated memory.
  // (Unroll copy loop once for better throughput).
  for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
    __ mov(edx, FieldOperand(ebx, i));
    __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
    __ mov(FieldOperand(eax, i), edx);
    __ mov(FieldOperand(eax, i + kPointerSize), ecx);
  }
  if ((size % (2 * kPointerSize)) != 0) {
    __ mov(edx, FieldOperand(ebx, size - kPointerSize));
    __ mov(FieldOperand(eax, size - kPointerSize), edx);
  }
}


void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
5944
  DCHECK(ToRegister(instr->context()).is(esi));
danno@chromium.org's avatar
danno@chromium.org committed
5945 5946 5947 5948
  // Use the fast case closure allocation code that allocates in new
  // space for nested functions that don't need literals cloning.
  bool pretenure = instr->hydrogen()->pretenure();
  if (!pretenure && instr->hydrogen()->has_no_literals()) {
5949
    FastNewClosureStub stub(isolate(), instr->hydrogen()->language_mode(),
5950
                            instr->hydrogen()->kind());
danno@chromium.org's avatar
danno@chromium.org committed
5951 5952 5953 5954 5955 5956 5957
    __ mov(ebx, Immediate(instr->hydrogen()->shared_info()));
    CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
  } else {
    __ push(esi);
    __ push(Immediate(instr->hydrogen()->shared_info()));
    __ push(Immediate(pretenure ? factory()->true_value()
                                : factory()->false_value()));
5958
    CallRuntime(Runtime::kNewClosure, 3, instr);
danno@chromium.org's avatar
danno@chromium.org committed
5959 5960 5961 5962 5963
  }
}


void LCodeGen::DoTypeof(LTypeof* instr) {
5964
  DCHECK(ToRegister(instr->context()).is(esi));
danno@chromium.org's avatar
danno@chromium.org committed
5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037
  LOperand* input = instr->value();
  EmitPushTaggedOperand(input);
  CallRuntime(Runtime::kTypeof, 1, instr);
}


void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
  Register input = ToRegister(instr->value());
  Condition final_branch_condition = EmitTypeofIs(instr, input);
  if (final_branch_condition != no_condition) {
    EmitBranch(instr, final_branch_condition);
  }
}


Condition LCodeGen::EmitTypeofIs(LTypeofIsAndBranch* instr, Register input) {
  Label* true_label = instr->TrueLabel(chunk_);
  Label* false_label = instr->FalseLabel(chunk_);
  Handle<String> type_name = instr->type_literal();
  int left_block = instr->TrueDestination(chunk_);
  int right_block = instr->FalseDestination(chunk_);
  int next_block = GetNextEmittedBlock();

  Label::Distance true_distance = left_block == next_block ? Label::kNear
                                                           : Label::kFar;
  Label::Distance false_distance = right_block == next_block ? Label::kNear
                                                             : Label::kFar;
  Condition final_branch_condition = no_condition;
  if (String::Equals(type_name, factory()->number_string())) {
    __ JumpIfSmi(input, true_label, true_distance);
    __ cmp(FieldOperand(input, HeapObject::kMapOffset),
           factory()->heap_number_map());
    final_branch_condition = equal;

  } else if (String::Equals(type_name, factory()->string_string())) {
    __ JumpIfSmi(input, false_label, false_distance);
    __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
    __ j(above_equal, false_label, false_distance);
    __ test_b(FieldOperand(input, Map::kBitFieldOffset),
              1 << Map::kIsUndetectable);
    final_branch_condition = zero;

  } else if (String::Equals(type_name, factory()->symbol_string())) {
    __ JumpIfSmi(input, false_label, false_distance);
    __ CmpObjectType(input, SYMBOL_TYPE, input);
    final_branch_condition = equal;

  } else if (String::Equals(type_name, factory()->boolean_string())) {
    __ cmp(input, factory()->true_value());
    __ j(equal, true_label, true_distance);
    __ cmp(input, factory()->false_value());
    final_branch_condition = equal;

  } else if (String::Equals(type_name, factory()->undefined_string())) {
    __ cmp(input, factory()->undefined_value());
    __ j(equal, true_label, true_distance);
    __ JumpIfSmi(input, false_label, false_distance);
    // Check for undetectable objects => true.
    __ mov(input, FieldOperand(input, HeapObject::kMapOffset));
    __ test_b(FieldOperand(input, Map::kBitFieldOffset),
              1 << Map::kIsUndetectable);
    final_branch_condition = not_zero;

  } else if (String::Equals(type_name, factory()->function_string())) {
    STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
    __ JumpIfSmi(input, false_label, false_distance);
    __ CmpObjectType(input, JS_FUNCTION_TYPE, input);
    __ j(equal, true_label, true_distance);
    __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
    final_branch_condition = equal;

  } else if (String::Equals(type_name, factory()->object_string())) {
    __ JumpIfSmi(input, false_label, false_distance);
6038 6039
    __ cmp(input, factory()->null_value());
    __ j(equal, true_label, true_distance);
danno@chromium.org's avatar
danno@chromium.org committed
6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097
    __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
    __ j(below, false_label, false_distance);
    __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
    __ j(above, false_label, false_distance);
    // Check for undetectable objects => false.
    __ test_b(FieldOperand(input, Map::kBitFieldOffset),
              1 << Map::kIsUndetectable);
    final_branch_condition = zero;

  } else {
    __ jmp(false_label, false_distance);
  }
  return final_branch_condition;
}


void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
  Register temp = ToRegister(instr->temp());

  EmitIsConstructCall(temp);
  EmitBranch(instr, equal);
}


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

  // Skip the arguments adaptor frame if it exists.
  Label check_frame_marker;
  __ cmp(Operand(temp, StandardFrameConstants::kContextOffset),
         Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
  __ j(not_equal, &check_frame_marker, Label::kNear);
  __ mov(temp, Operand(temp, StandardFrameConstants::kCallerFPOffset));

  // Check the marker in the calling frame.
  __ bind(&check_frame_marker);
  __ cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
         Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
}


void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
  if (!info()->IsStub()) {
    // Ensure that we have enough space after the previous lazy-bailout
    // instruction for patching the code here.
    int current_pc = masm()->pc_offset();
    if (current_pc < last_lazy_deopt_pc_ + space_needed) {
      int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
      __ Nop(padding_size);
    }
  }
  last_lazy_deopt_pc_ = masm()->pc_offset();
}


void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
  last_lazy_deopt_pc_ = masm()->pc_offset();
6098
  DCHECK(instr->HasEnvironment());
danno@chromium.org's avatar
danno@chromium.org committed
6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113
  LEnvironment* env = instr->environment();
  RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
  safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
}


void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
  Deoptimizer::BailoutType type = instr->hydrogen()->type();
  // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
  // needed return address), even though the implementation of LAZY and EAGER is
  // now identical. When LAZY is eventually completely folded into EAGER, remove
  // the special case below.
  if (info()->IsStub() && type == Deoptimizer::EAGER) {
    type = Deoptimizer::LAZY;
  }
6114
  DeoptimizeIf(no_condition, instr, instr->hydrogen()->reason(), type);
danno@chromium.org's avatar
danno@chromium.org committed
6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130
}


void LCodeGen::DoDummy(LDummy* instr) {
  // Nothing to see here, move on!
}


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


void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
  PushSafepointRegistersScope scope(this);
  __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
6131
  __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
danno@chromium.org's avatar
danno@chromium.org committed
6132 6133
  RecordSafepointWithLazyDeopt(
      instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
6134
  DCHECK(instr->HasEnvironment());
danno@chromium.org's avatar
danno@chromium.org committed
6135 6136 6137 6138 6139 6140
  LEnvironment* env = instr->environment();
  safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
}


void LCodeGen::DoStackCheck(LStackCheck* instr) {
6141
  class DeferredStackCheck FINAL : public LDeferredCode {
danno@chromium.org's avatar
danno@chromium.org committed
6142 6143 6144 6145 6146
   public:
    DeferredStackCheck(LCodeGen* codegen,
                       LStackCheck* instr,
                       const X87Stack& x87_stack)
        : LDeferredCode(codegen, x87_stack), instr_(instr) { }
6147 6148 6149
    void Generate() OVERRIDE { codegen()->DoDeferredStackCheck(instr_); }
    LInstruction* instr() OVERRIDE { return instr_; }

danno@chromium.org's avatar
danno@chromium.org committed
6150 6151 6152 6153
   private:
    LStackCheck* instr_;
  };

6154
  DCHECK(instr->HasEnvironment());
danno@chromium.org's avatar
danno@chromium.org committed
6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165
  LEnvironment* env = instr->environment();
  // There is no LLazyBailout instruction for stack-checks. We have to
  // prepare for lazy deoptimization explicitly here.
  if (instr->hydrogen()->is_function_entry()) {
    // Perform stack overflow check.
    Label done;
    ExternalReference stack_limit =
        ExternalReference::address_of_stack_limit(isolate());
    __ cmp(esp, Operand::StaticVariable(stack_limit));
    __ j(above_equal, &done, Label::kNear);

6166 6167
    DCHECK(instr->context()->IsRegister());
    DCHECK(ToRegister(instr->context()).is(esi));
danno@chromium.org's avatar
danno@chromium.org committed
6168 6169 6170 6171 6172
    CallCode(isolate()->builtins()->StackCheck(),
             RelocInfo::CODE_TARGET,
             instr);
    __ bind(&done);
  } else {
6173
    DCHECK(instr->hydrogen()->is_backwards_branch());
danno@chromium.org's avatar
danno@chromium.org committed
6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199
    // Perform stack overflow check if this goto needs it before jumping.
    DeferredStackCheck* deferred_stack_check =
        new(zone()) DeferredStackCheck(this, instr, x87_stack_);
    ExternalReference stack_limit =
        ExternalReference::address_of_stack_limit(isolate());
    __ cmp(esp, Operand::StaticVariable(stack_limit));
    __ j(below, deferred_stack_check->entry());
    EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
    __ bind(instr->done_label());
    deferred_stack_check->SetExit(instr->done_label());
    RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
    // Don't record a deoptimization index for the safepoint here.
    // This will be done explicitly when emitting call and the safepoint in
    // the deferred code.
  }
}


void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
  // This is a pseudo-instruction that ensures that the environment here is
  // properly registered for deoptimization and records the assembler's PC
  // offset.
  LEnvironment* environment = instr->environment();

  // If the environment were already registered, we would have no way of
  // backpatching it with the spill slot operands.
6200
  DCHECK(!environment->HasBeenRegistered());
danno@chromium.org's avatar
danno@chromium.org committed
6201 6202 6203 6204 6205 6206 6207
  RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);

  GenerateOsrPrologue();
}


void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
6208
  DCHECK(ToRegister(instr->context()).is(esi));
danno@chromium.org's avatar
danno@chromium.org committed
6209
  __ test(eax, Immediate(kSmiTagMask));
6210
  DeoptimizeIf(zero, instr, Deoptimizer::kSmi);
danno@chromium.org's avatar
danno@chromium.org committed
6211 6212 6213

  STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
  __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
6214
  DeoptimizeIf(below_equal, instr, Deoptimizer::kWrongInstanceType);
danno@chromium.org's avatar
danno@chromium.org committed
6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228

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

  __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
  __ jmp(&use_cache, Label::kNear);

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

  __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
         isolate()->factory()->meta_map());
6229
  DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
danno@chromium.org's avatar
danno@chromium.org committed
6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251
  __ bind(&use_cache);
}


void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
  Register map = ToRegister(instr->map());
  Register result = ToRegister(instr->result());
  Label load_cache, done;
  __ EnumLength(result, map);
  __ cmp(result, Immediate(Smi::FromInt(0)));
  __ j(not_equal, &load_cache, Label::kNear);
  __ mov(result, isolate()->factory()->empty_fixed_array());
  __ jmp(&done, Label::kNear);

  __ bind(&load_cache);
  __ LoadInstanceDescriptors(map, result);
  __ mov(result,
         FieldOperand(result, DescriptorArray::kEnumCacheOffset));
  __ mov(result,
         FieldOperand(result, FixedArray::SizeFor(instr->idx())));
  __ bind(&done);
  __ test(result, result);
6252
  DeoptimizeIf(equal, instr, Deoptimizer::kNoCache);
danno@chromium.org's avatar
danno@chromium.org committed
6253 6254 6255 6256 6257 6258 6259
}


void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
  Register object = ToRegister(instr->value());
  __ cmp(ToRegister(instr->map()),
         FieldOperand(object, HeapObject::kMapOffset));
6260
  DeoptimizeIf(not_equal, instr, Deoptimizer::kWrongMap);
danno@chromium.org's avatar
danno@chromium.org committed
6261 6262 6263 6264 6265 6266 6267 6268 6269 6270
}


void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
                                           Register object,
                                           Register index) {
  PushSafepointRegistersScope scope(this);
  __ push(object);
  __ push(index);
  __ xor_(esi, esi);
6271
  __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
danno@chromium.org's avatar
danno@chromium.org committed
6272 6273 6274 6275 6276 6277 6278
  RecordSafepointWithRegisters(
      instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
  __ StoreToSafepointRegisterSlot(object, eax);
}


void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
6279
  class DeferredLoadMutableDouble FINAL : public LDeferredCode {
danno@chromium.org's avatar
danno@chromium.org committed
6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290
   public:
    DeferredLoadMutableDouble(LCodeGen* codegen,
                              LLoadFieldByIndex* instr,
                              Register object,
                              Register index,
                              const X87Stack& x87_stack)
        : LDeferredCode(codegen, x87_stack),
          instr_(instr),
          object_(object),
          index_(index) {
    }
6291
    void Generate() OVERRIDE {
danno@chromium.org's avatar
danno@chromium.org committed
6292 6293
      codegen()->DoDeferredLoadMutableDouble(instr_, object_, index_);
    }
6294 6295
    LInstruction* instr() OVERRIDE { return instr_; }

danno@chromium.org's avatar
danno@chromium.org committed
6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335
   private:
    LLoadFieldByIndex* instr_;
    Register object_;
    Register index_;
  };

  Register object = ToRegister(instr->object());
  Register index = ToRegister(instr->index());

  DeferredLoadMutableDouble* deferred;
  deferred = new(zone()) DeferredLoadMutableDouble(
      this, instr, object, index, x87_stack_);

  Label out_of_object, done;
  __ test(index, Immediate(Smi::FromInt(1)));
  __ j(not_zero, deferred->entry());

  __ sar(index, 1);

  __ cmp(index, Immediate(0));
  __ j(less, &out_of_object, Label::kNear);
  __ mov(object, FieldOperand(object,
                              index,
                              times_half_pointer_size,
                              JSObject::kHeaderSize));
  __ jmp(&done, Label::kNear);

  __ bind(&out_of_object);
  __ mov(object, FieldOperand(object, JSObject::kPropertiesOffset));
  __ neg(index);
  // Index is now equal to out of object property index plus 1.
  __ mov(object, FieldOperand(object,
                              index,
                              times_half_pointer_size,
                              FixedArray::kHeaderSize - kPointerSize));
  __ bind(deferred->exit());
  __ bind(&done);
}


6336 6337 6338 6339 6340 6341 6342 6343 6344 6345
void LCodeGen::DoStoreFrameContext(LStoreFrameContext* instr) {
  Register context = ToRegister(instr->context());
  __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), context);
}


void LCodeGen::DoAllocateBlockContext(LAllocateBlockContext* instr) {
  Handle<ScopeInfo> scope_info = instr->scope_info();
  __ Push(scope_info);
  __ push(ToRegister(instr->function()));
6346
  CallRuntime(Runtime::kPushBlockContext, 2, instr);
6347 6348 6349 6350
  RecordSafepoint(Safepoint::kNoLazyDeopt);
}


danno@chromium.org's avatar
danno@chromium.org committed
6351 6352 6353 6354 6355
#undef __

} }  // namespace v8::internal

#endif  // V8_TARGET_ARCH_X87