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

5
#include <limits.h>  // For LONG_MIN, LONG_MAX.
6

7
#if V8_TARGET_ARCH_MIPS
8

9
#include "src/base/bits.h"
10
#include "src/base/division-by-constant.h"
11
#include "src/codegen/assembler-inl.h"
12
#include "src/codegen/callable.h"
13
#include "src/codegen/code-factory.h"
14
#include "src/codegen/external-reference-table.h"
15
#include "src/codegen/interface-descriptors-inl.h"
16 17
#include "src/codegen/macro-assembler.h"
#include "src/codegen/register-configuration.h"
18
#include "src/debug/debug.h"
19
#include "src/deoptimizer/deoptimizer.h"
20
#include "src/execution/frames-inl.h"
21
#include "src/heap/memory-chunk.h"
22
#include "src/init/bootstrapper.h"
23
#include "src/logging/counters.h"
24
#include "src/objects/heap-number.h"
25
#include "src/runtime/runtime.h"
26
#include "src/snapshot/snapshot.h"
27 28

#if V8_ENABLE_WEBASSEMBLY
29
#include "src/wasm/wasm-code-manager.h"
30
#endif  // V8_ENABLE_WEBASSEMBLY
31

32 33 34
// Satisfy cpplint check, but don't include platform-specific header. It is
// included recursively via macro-assembler.h.
#if 0
35
#include "src/codegen/mips/macro-assembler-mips.h"
36 37
#endif

38 39 40
namespace v8 {
namespace internal {

41 42 43 44 45 46 47 48
static inline bool IsZero(const Operand& rt) {
  if (rt.is_reg()) {
    return rt.rm() == zero_reg;
  } else {
    return rt.immediate() == 0;
  }
}

49 50 51 52 53
int TurboAssembler::RequiredStackSizeForCallerSaved(SaveFPRegsMode fp_mode,
                                                    Register exclusion1,
                                                    Register exclusion2,
                                                    Register exclusion3) const {
  int bytes = 0;
54

55 56 57
  RegList exclusions = {exclusion1, exclusion2, exclusion3};
  RegList list = kJSCallerSaved - exclusions;
  bytes += list.Count() * kPointerSize;
58

59
  if (fp_mode == SaveFPRegsMode::kSave) {
60
    bytes += kCallerSavedFPU.Count() * kDoubleSize;
61
  }
62 63

  return bytes;
64 65
}

66
int TurboAssembler::PushCallerSaved(SaveFPRegsMode fp_mode, Register exclusion1,
67
                                    Register exclusion2, Register exclusion3) {
68
  ASM_CODE_COMMENT(this);
69 70
  int bytes = 0;

71 72
  RegList exclusions = {exclusion1, exclusion2, exclusion3};
  RegList list = kJSCallerSaved - exclusions;
73
  MultiPush(list);
74
  bytes += list.Count() * kPointerSize;
75

76
  if (fp_mode == SaveFPRegsMode::kSave) {
77
    MultiPushFPU(kCallerSavedFPU);
78
    bytes += kCallerSavedFPU.Count() * kDoubleSize;
79 80 81 82 83 84 85
  }

  return bytes;
}

int TurboAssembler::PopCallerSaved(SaveFPRegsMode fp_mode, Register exclusion1,
                                   Register exclusion2, Register exclusion3) {
86
  ASM_CODE_COMMENT(this);
87
  int bytes = 0;
88
  if (fp_mode == SaveFPRegsMode::kSave) {
89
    MultiPopFPU(kCallerSavedFPU);
90
    bytes += kCallerSavedFPU.Count() * kDoubleSize;
91 92
  }

93 94
  RegList exclusions = {exclusion1, exclusion2, exclusion3};
  RegList list = kJSCallerSaved - exclusions;
95
  MultiPop(list);
96
  bytes += list.Count() * kPointerSize;
97 98

  return bytes;
99 100
}

101
void TurboAssembler::LoadRoot(Register destination, RootIndex index) {
102 103
  lw(destination,
     MemOperand(kRootRegister, RootRegisterOffsetForRootIndex(index)));
104 105
}

106
void TurboAssembler::LoadRoot(Register destination, RootIndex index,
107 108
                              Condition cond, Register src1,
                              const Operand& src2) {
109
  Branch(2, NegateCondition(cond), src1, src2);
110 111
  lw(destination,
     MemOperand(kRootRegister, RootRegisterOffsetForRootIndex(index)));
112 113
}

114
void TurboAssembler::PushCommonFrame(Register marker_reg) {
115 116 117 118 119 120 121 122 123
  if (marker_reg.is_valid()) {
    Push(ra, fp, marker_reg);
    Addu(fp, sp, Operand(kPointerSize));
  } else {
    Push(ra, fp);
    mov(fp, sp);
  }
}

124
void TurboAssembler::PushStandardFrame(Register function_reg) {
125 126
  int offset = -StandardFrameConstants::kContextOffset;
  if (function_reg.is_valid()) {
127 128
    Push(ra, fp, cp, function_reg, kJavaScriptCallArgCountRegister);
    offset += 2 * kPointerSize;
129
  } else {
130 131
    Push(ra, fp, cp, kJavaScriptCallArgCountRegister);
    offset += kPointerSize;
132 133 134
  }
  Addu(fp, sp, Operand(offset));
}
135

136 137 138
// Clobbers object, dst, value, and ra, if (ra_status == kRAHasBeenSaved)
// The register 'object' contains a heap object pointer.  The heap object
// tag is shifted away.
139 140 141 142 143 144
void MacroAssembler::RecordWriteField(Register object, int offset,
                                      Register value, Register dst,
                                      RAStatus ra_status,
                                      SaveFPRegsMode save_fp,
                                      RememberedSetAction remembered_set_action,
                                      SmiCheck smi_check) {
145
  ASM_CODE_COMMENT(this);
146
  DCHECK(!AreAliased(value, dst, t8, object));
147 148
  // First, check if a write barrier is even needed. The tests below
  // catch stores of Smis.
149 150
  Label done;

151
  // Skip barrier if writing a smi.
152
  if (smi_check == SmiCheck::kInline) {
153 154
    JumpIfSmi(value, &done);
  }
155

156
  // Although the object register is tagged, the offset is relative to the start
157
  // of the object, so offset must be a multiple of kPointerSize.
158
  DCHECK(IsAligned(offset, kPointerSize));
159

160
  Addu(dst, object, Operand(offset - kHeapObjectTag));
161
  if (FLAG_debug_code) {
162
    BlockTrampolinePoolScope block_trampoline_pool(this);
163
    Label ok;
164
    And(t8, dst, Operand(kPointerSize - 1));
165
    Branch(&ok, eq, t8, Operand(zero_reg));
166
    stop();
167 168 169
    bind(&ok);
  }

170
  RecordWrite(object, dst, value, ra_status, save_fp, remembered_set_action,
171
              SmiCheck::kOmit);
172 173 174

  bind(&done);

175
  // Clobber clobbered input registers when running with the debug-code flag
176
  // turned on to provoke errors.
177
  if (FLAG_debug_code) {
178 179
    li(value, Operand(bit_cast<int32_t>(kZapValue + 4)));
    li(dst, Operand(bit_cast<int32_t>(kZapValue + 8)));
180 181 182
  }
}

183
void TurboAssembler::MaybeSaveRegisters(RegList registers) {
184 185
  if (registers.is_empty()) return;
  MultiPush(registers);
186 187
}

188
void TurboAssembler::MaybeRestoreRegisters(RegList registers) {
189 190
  if (registers.is_empty()) return;
  MultiPop(registers);
191 192
}

193 194
void TurboAssembler::CallEphemeronKeyBarrier(Register object,
                                             Register slot_address,
195
                                             SaveFPRegsMode fp_mode) {
196
  ASM_CODE_COMMENT(this);
197 198 199 200
  DCHECK(!AreAliased(object, slot_address));
  RegList registers =
      WriteBarrierDescriptor::ComputeSavedRegisters(object, slot_address);
  MaybeSaveRegisters(registers);
201

202 203 204
  Register object_parameter = WriteBarrierDescriptor::ObjectRegister();
  Register slot_address_parameter =
      WriteBarrierDescriptor::SlotAddressRegister();
205 206

  Push(object);
207 208
  Push(slot_address);
  Pop(slot_address_parameter);
209 210
  Pop(object_parameter);

211
  Call(isolate()->builtins()->code_handle(
212
           Builtins::GetEphemeronKeyBarrierStub(fp_mode)),
213
       RelocInfo::CODE_TARGET);
214
  MaybeRestoreRegisters(registers);
215 216
}

217 218
void TurboAssembler::CallRecordWriteStubSaveRegisters(
    Register object, Register slot_address,
219
    RememberedSetAction remembered_set_action, SaveFPRegsMode fp_mode,
220
    StubCallMode mode) {
221 222 223 224
  DCHECK(!AreAliased(object, slot_address));
  RegList registers =
      WriteBarrierDescriptor::ComputeSavedRegisters(object, slot_address);
  MaybeSaveRegisters(registers);
225

226 227 228
  Register object_parameter = WriteBarrierDescriptor::ObjectRegister();
  Register slot_address_parameter =
      WriteBarrierDescriptor::SlotAddressRegister();
229 230

  Push(object);
231 232
  Push(slot_address);
  Pop(slot_address_parameter);
233 234
  Pop(object_parameter);

235 236 237 238 239 240 241 242 243 244 245 246 247 248
  CallRecordWriteStub(object_parameter, slot_address_parameter,
                      remembered_set_action, fp_mode, mode);

  MaybeRestoreRegisters(registers);
}

void TurboAssembler::CallRecordWriteStub(
    Register object, Register slot_address,
    RememberedSetAction remembered_set_action, SaveFPRegsMode fp_mode,
    StubCallMode mode) {
  // Use CallRecordWriteStubSaveRegisters if the object and slot registers
  // need to be caller saved.
  DCHECK_EQ(WriteBarrierDescriptor::ObjectRegister(), object);
  DCHECK_EQ(WriteBarrierDescriptor::SlotAddressRegister(), slot_address);
249
#if V8_ENABLE_WEBASSEMBLY
250 251 252
  if (mode == StubCallMode::kCallWasmRuntimeStub) {
    auto wasm_target =
        wasm::WasmCode::GetRecordWriteStub(remembered_set_action, fp_mode);
253
    Call(wasm_target, RelocInfo::WASM_STUB_CALL);
254 255 256
#else
  if (false) {
#endif
257
  } else {
Liu Yu's avatar
Liu Yu committed
258
    Builtin builtin =
259 260 261
        Builtins::GetRecordWriteStub(remembered_set_action, fp_mode);
    if (options().inline_offheap_trampolines) {
      // Inline the trampoline.
Liu Yu's avatar
Liu Yu committed
262
      RecordCommentForOffHeapTrampoline(builtin);
263
      li(t9, Operand(BuiltinEntry(builtin), RelocInfo::OFF_HEAP_TARGET));
264
      Call(t9);
265
      RecordComment("]");
266
    } else {
Liu Yu's avatar
Liu Yu committed
267
      Handle<Code> code_target = isolate()->builtins()->code_handle(builtin);
268 269
      Call(code_target, RelocInfo::CODE_TARGET);
    }
270
  }
271
}
272

273 274
// Clobbers object, address, value, and ra, if (ra_status == kRAHasBeenSaved)
// The register 'object' contains a heap object pointer.  The heap object
275
// tag is shifted away.
276 277 278 279 280
void MacroAssembler::RecordWrite(Register object, Register address,
                                 Register value, RAStatus ra_status,
                                 SaveFPRegsMode fp_mode,
                                 RememberedSetAction remembered_set_action,
                                 SmiCheck smi_check) {
281 282
  DCHECK(!AreAliased(object, address, value, t8));
  DCHECK(!AreAliased(object, address, value, t9));
283

284
  if (FLAG_debug_code) {
285 286
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
287
    DCHECK(!AreAliased(object, value, scratch));
288
    lw(scratch, MemOperand(address));
289
    Assert(eq, AbortReason::kWrongAddressOrValuePassedToRecordWrite, scratch,
290
           Operand(value));
291 292
  }

293
  if ((remembered_set_action == RememberedSetAction::kOmit &&
294 295
       !FLAG_incremental_marking) ||
      FLAG_disable_write_barriers) {
296 297 298
    return;
  }

299 300
  // First, check if a write barrier is even needed. The tests below
  // catch stores of smis and stores into the young generation.
301 302
  Label done;

303
  if (smi_check == SmiCheck::kInline) {
304
    DCHECK_EQ(0, kSmiTag);
305
    JumpIfSmi(value, &done);
306 307
  }

308 309 310
  CheckPageFlag(value,
                value,  // Used as scratch.
                MemoryChunk::kPointersToHereAreInterestingMask, eq, &done);
311 312
  CheckPageFlag(object,
                value,  // Used as scratch.
313
                MemoryChunk::kPointersFromHereAreInterestingMask, eq, &done);
314 315

  // Record the actual write.
316 317 318
  if (ra_status == kRAHasNotBeenSaved) {
    push(ra);
  }
319 320 321 322 323 324

  Register slot_address = WriteBarrierDescriptor::SlotAddressRegister();
  DCHECK(!AreAliased(object, slot_address, value));
  mov(slot_address, address);
  CallRecordWriteStub(object, slot_address, remembered_set_action, fp_mode);

325 326 327
  if (ra_status == kRAHasNotBeenSaved) {
    pop(ra);
  }
328 329 330

  bind(&done);

331
  // Clobber clobbered registers when running with the debug-code flag
332
  // turned on to provoke errors.
333
  if (FLAG_debug_code) {
334 335
    li(address, Operand(bit_cast<int32_t>(kZapValue + 12)));
    li(value, Operand(bit_cast<int32_t>(kZapValue + 16)));
336
    li(slot_address, Operand(bit_cast<int32_t>(kZapValue + 20)));
337 338 339
  }
}

340
// ---------------------------------------------------------------------------
341
// Instruction macros.
342

343
void TurboAssembler::Addu(Register rd, Register rs, const Operand& rt) {
344
  if (rt.is_reg()) {
345
    addu(rd, rs, rt.rm());
346
  } else {
347
    if (is_int16(rt.immediate()) && !MustUseReg(rt.rmode())) {
348
      addiu(rd, rs, rt.immediate());
349 350
    } else {
      // li handles the relocation.
351 352
      UseScratchRegisterScope temps(this);
      Register scratch = temps.Acquire();
353
      DCHECK(rs != scratch);
354 355
      li(scratch, rt);
      addu(rd, rs, scratch);
356 357 358 359
    }
  }
}

360
void TurboAssembler::Subu(Register rd, Register rs, const Operand& rt) {
361
  if (rt.is_reg()) {
362
    subu(rd, rs, rt.rm());
363
  } else {
364
    if (is_int16(-rt.immediate()) && !MustUseReg(rt.rmode())) {
365 366
      addiu(rd, rs, -rt.immediate());  // No subiu instr, use addiu(x, y, -imm).
    } else if (!(-rt.immediate() & kHiMask) &&
367
               !MustUseReg(rt.rmode())) {  // Use load
368
      // -imm and addu for cases where loading -imm generates one instruction.
369 370
      UseScratchRegisterScope temps(this);
      Register scratch = temps.Acquire();
371
      DCHECK(rs != scratch);
372 373
      li(scratch, -rt.immediate());
      addu(rd, rs, scratch);
374 375
    } else {
      // li handles the relocation.
376 377
      UseScratchRegisterScope temps(this);
      Register scratch = temps.Acquire();
378
      DCHECK(rs != scratch);
379 380
      li(scratch, rt);
      subu(rd, rs, scratch);
381 382 383 384
    }
  }
}

385
void TurboAssembler::Mul(Register rd, Register rs, const Operand& rt) {
386
  if (rt.is_reg()) {
387
    if (IsMipsArchVariant(kLoongson)) {
388 389 390 391 392
      mult(rs, rt.rm());
      mflo(rd);
    } else {
      mul(rd, rs, rt.rm());
    }
393 394
  } else {
    // li handles the relocation.
395 396
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
397
    DCHECK(rs != scratch);
398
    li(scratch, rt);
399
    if (IsMipsArchVariant(kLoongson)) {
400
      mult(rs, scratch);
401 402
      mflo(rd);
    } else {
403
      mul(rd, rs, scratch);
404
    }
405 406 407
  }
}

408 409
void TurboAssembler::Mul(Register rd_hi, Register rd_lo, Register rs,
                         const Operand& rt) {
410 411 412 413 414 415
  if (rt.is_reg()) {
    if (!IsMipsArchVariant(kMips32r6)) {
      mult(rs, rt.rm());
      mflo(rd_lo);
      mfhi(rd_hi);
    } else {
416 417 418
      if (rd_lo == rs) {
        DCHECK(rd_hi != rs);
        DCHECK(rd_hi != rt.rm() && rd_lo != rt.rm());
419 420 421
        muh(rd_hi, rs, rt.rm());
        mul(rd_lo, rs, rt.rm());
      } else {
422
        DCHECK(rd_hi != rt.rm() && rd_lo != rt.rm());
423 424 425 426 427 428
        mul(rd_lo, rs, rt.rm());
        muh(rd_hi, rs, rt.rm());
      }
    }
  } else {
    // li handles the relocation.
429 430
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
431
    DCHECK(rs != scratch);
432
    li(scratch, rt);
433
    if (!IsMipsArchVariant(kMips32r6)) {
434
      mult(rs, scratch);
435 436 437
      mflo(rd_lo);
      mfhi(rd_hi);
    } else {
438 439 440
      if (rd_lo == rs) {
        DCHECK(rd_hi != rs);
        DCHECK(rd_hi != scratch && rd_lo != scratch);
441 442
        muh(rd_hi, rs, scratch);
        mul(rd_lo, rs, scratch);
443
      } else {
444
        DCHECK(rd_hi != scratch && rd_lo != scratch);
445 446
        mul(rd_lo, rs, scratch);
        muh(rd_hi, rs, scratch);
447 448 449 450 451
      }
    }
  }
}

452
void TurboAssembler::Mulu(Register rd_hi, Register rd_lo, Register rs,
453
                          const Operand& rt) {
454
  Register reg = no_reg;
455 456
  UseScratchRegisterScope temps(this);
  Register scratch = temps.Acquire();
457 458 459
  if (rt.is_reg()) {
    reg = rt.rm();
  } else {
460
    DCHECK(rs != scratch);
461
    reg = scratch;
462 463 464 465 466 467 468 469
    li(reg, rt);
  }

  if (!IsMipsArchVariant(kMips32r6)) {
    multu(rs, reg);
    mflo(rd_lo);
    mfhi(rd_hi);
  } else {
470 471 472
    if (rd_lo == rs) {
      DCHECK(rd_hi != rs);
      DCHECK(rd_hi != reg && rd_lo != reg);
473 474 475
      muhu(rd_hi, rs, reg);
      mulu(rd_lo, rs, reg);
    } else {
476
      DCHECK(rd_hi != reg && rd_lo != reg);
477 478 479 480 481
      mulu(rd_lo, rs, reg);
      muhu(rd_hi, rs, reg);
    }
  }
}
482

483
void TurboAssembler::Mulh(Register rd, Register rs, const Operand& rt) {
484 485 486 487 488 489 490 491 492
  if (rt.is_reg()) {
    if (!IsMipsArchVariant(kMips32r6)) {
      mult(rs, rt.rm());
      mfhi(rd);
    } else {
      muh(rd, rs, rt.rm());
    }
  } else {
    // li handles the relocation.
493 494
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
495
    DCHECK(rs != scratch);
496
    li(scratch, rt);
497
    if (!IsMipsArchVariant(kMips32r6)) {
498
      mult(rs, scratch);
499 500
      mfhi(rd);
    } else {
501
      muh(rd, rs, scratch);
502 503 504 505
    }
  }
}

506
void TurboAssembler::Mult(Register rs, const Operand& rt) {
507 508 509 510
  if (rt.is_reg()) {
    mult(rs, rt.rm());
  } else {
    // li handles the relocation.
511 512
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
513
    DCHECK(rs != scratch);
514 515
    li(scratch, rt);
    mult(rs, scratch);
516 517 518
  }
}

519
void TurboAssembler::Mulhu(Register rd, Register rs, const Operand& rt) {
520 521 522 523 524 525 526 527 528
  if (rt.is_reg()) {
    if (!IsMipsArchVariant(kMips32r6)) {
      multu(rs, rt.rm());
      mfhi(rd);
    } else {
      muhu(rd, rs, rt.rm());
    }
  } else {
    // li handles the relocation.
529 530
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
531
    DCHECK(rs != scratch);
532
    li(scratch, rt);
533
    if (!IsMipsArchVariant(kMips32r6)) {
534
      multu(rs, scratch);
535 536
      mfhi(rd);
    } else {
537
      muhu(rd, rs, scratch);
538 539 540 541
    }
  }
}

542
void TurboAssembler::Multu(Register rs, const Operand& rt) {
543 544 545 546
  if (rt.is_reg()) {
    multu(rs, rt.rm());
  } else {
    // li handles the relocation.
547 548
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
549
    DCHECK(rs != scratch);
550 551
    li(scratch, rt);
    multu(rs, scratch);
552 553 554
  }
}

555
void TurboAssembler::Div(Register rs, const Operand& rt) {
556 557 558 559
  if (rt.is_reg()) {
    div(rs, rt.rm());
  } else {
    // li handles the relocation.
560 561
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
562
    DCHECK(rs != scratch);
563 564
    li(scratch, rt);
    div(rs, scratch);
565 566 567
  }
}

568 569
void TurboAssembler::Div(Register rem, Register res, Register rs,
                         const Operand& rt) {
570 571 572 573 574 575 576 577 578 579 580
  if (rt.is_reg()) {
    if (!IsMipsArchVariant(kMips32r6)) {
      div(rs, rt.rm());
      mflo(res);
      mfhi(rem);
    } else {
      div(res, rs, rt.rm());
      mod(rem, rs, rt.rm());
    }
  } else {
    // li handles the relocation.
581 582
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
583
    DCHECK(rs != scratch);
584
    li(scratch, rt);
585
    if (!IsMipsArchVariant(kMips32r6)) {
586
      div(rs, scratch);
587 588 589
      mflo(res);
      mfhi(rem);
    } else {
590 591
      div(res, rs, scratch);
      mod(rem, rs, scratch);
592 593 594 595
    }
  }
}

596
void TurboAssembler::Div(Register res, Register rs, const Operand& rt) {
597 598 599 600 601 602 603 604 605
  if (rt.is_reg()) {
    if (!IsMipsArchVariant(kMips32r6)) {
      div(rs, rt.rm());
      mflo(res);
    } else {
      div(res, rs, rt.rm());
    }
  } else {
    // li handles the relocation.
606 607
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
608
    DCHECK(rs != scratch);
609
    li(scratch, rt);
610
    if (!IsMipsArchVariant(kMips32r6)) {
611
      div(rs, scratch);
612 613
      mflo(res);
    } else {
614
      div(res, rs, scratch);
615 616 617 618
    }
  }
}

619
void TurboAssembler::Mod(Register rd, Register rs, const Operand& rt) {
620 621 622 623 624 625 626 627 628
  if (rt.is_reg()) {
    if (!IsMipsArchVariant(kMips32r6)) {
      div(rs, rt.rm());
      mfhi(rd);
    } else {
      mod(rd, rs, rt.rm());
    }
  } else {
    // li handles the relocation.
629 630
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
631
    DCHECK(rs != scratch);
632
    li(scratch, rt);
633
    if (!IsMipsArchVariant(kMips32r6)) {
634
      div(rs, scratch);
635 636
      mfhi(rd);
    } else {
637
      mod(rd, rs, scratch);
638 639 640 641
    }
  }
}

642
void TurboAssembler::Modu(Register rd, Register rs, const Operand& rt) {
643 644 645 646 647 648 649 650 651
  if (rt.is_reg()) {
    if (!IsMipsArchVariant(kMips32r6)) {
      divu(rs, rt.rm());
      mfhi(rd);
    } else {
      modu(rd, rs, rt.rm());
    }
  } else {
    // li handles the relocation.
652 653
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
654
    DCHECK(rs != scratch);
655
    li(scratch, rt);
656
    if (!IsMipsArchVariant(kMips32r6)) {
657
      divu(rs, scratch);
658 659
      mfhi(rd);
    } else {
660
      modu(rd, rs, scratch);
661 662 663 664
    }
  }
}

665
void TurboAssembler::Divu(Register rs, const Operand& rt) {
666 667 668 669
  if (rt.is_reg()) {
    divu(rs, rt.rm());
  } else {
    // li handles the relocation.
670 671
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
672
    DCHECK(rs != scratch);
673 674
    li(scratch, rt);
    divu(rs, scratch);
675 676 677
  }
}

678
void TurboAssembler::Divu(Register res, Register rs, const Operand& rt) {
679 680 681 682 683 684 685 686 687
  if (rt.is_reg()) {
    if (!IsMipsArchVariant(kMips32r6)) {
      divu(rs, rt.rm());
      mflo(res);
    } else {
      divu(res, rs, rt.rm());
    }
  } else {
    // li handles the relocation.
688 689
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
690
    DCHECK(rs != scratch);
691
    li(scratch, rt);
692
    if (!IsMipsArchVariant(kMips32r6)) {
693
      divu(rs, scratch);
694 695
      mflo(res);
    } else {
696
      divu(res, rs, scratch);
697 698 699 700
    }
  }
}

701
void TurboAssembler::And(Register rd, Register rs, const Operand& rt) {
702 703 704
  if (rt.is_reg()) {
    and_(rd, rs, rt.rm());
  } else {
705
    if (is_uint16(rt.immediate()) && !MustUseReg(rt.rmode())) {
706
      andi(rd, rs, rt.immediate());
707 708
    } else {
      // li handles the relocation.
709 710
      UseScratchRegisterScope temps(this);
      Register scratch = temps.Acquire();
711
      DCHECK(rs != scratch);
712 713
      li(scratch, rt);
      and_(rd, rs, scratch);
714 715 716 717
    }
  }
}

718
void TurboAssembler::Or(Register rd, Register rs, const Operand& rt) {
719 720 721
  if (rt.is_reg()) {
    or_(rd, rs, rt.rm());
  } else {
722
    if (is_uint16(rt.immediate()) && !MustUseReg(rt.rmode())) {
723
      ori(rd, rs, rt.immediate());
724 725
    } else {
      // li handles the relocation.
726 727
      UseScratchRegisterScope temps(this);
      Register scratch = temps.Acquire();
728
      DCHECK(rs != scratch);
729 730
      li(scratch, rt);
      or_(rd, rs, scratch);
731 732 733 734
    }
  }
}

735
void TurboAssembler::Xor(Register rd, Register rs, const Operand& rt) {
736 737 738
  if (rt.is_reg()) {
    xor_(rd, rs, rt.rm());
  } else {
739
    if (is_uint16(rt.immediate()) && !MustUseReg(rt.rmode())) {
740
      xori(rd, rs, rt.immediate());
741 742
    } else {
      // li handles the relocation.
743 744
      UseScratchRegisterScope temps(this);
      Register scratch = temps.Acquire();
745
      DCHECK(rs != scratch);
746 747
      li(scratch, rt);
      xor_(rd, rs, scratch);
748 749 750 751
    }
  }
}

752
void TurboAssembler::Nor(Register rd, Register rs, const Operand& rt) {
753 754 755 756
  if (rt.is_reg()) {
    nor(rd, rs, rt.rm());
  } else {
    // li handles the relocation.
757 758
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
759
    DCHECK(rs != scratch);
760 761
    li(scratch, rt);
    nor(rd, rs, scratch);
762 763 764
  }
}

765
void TurboAssembler::Neg(Register rs, const Operand& rt) {
766
  subu(rs, zero_reg, rt.rm());
767 768
}

769
void TurboAssembler::Slt(Register rd, Register rs, const Operand& rt) {
770 771 772
  if (rt.is_reg()) {
    slt(rd, rs, rt.rm());
  } else {
773
    if (is_int16(rt.immediate()) && !MustUseReg(rt.rmode())) {
774
      slti(rd, rs, rt.immediate());
775 776
    } else {
      // li handles the relocation.
777
      BlockTrampolinePoolScope block_trampoline_pool(this);
778
      UseScratchRegisterScope temps(this);
779 780
      Register scratch = rd == at ? t8 : temps.Acquire();
      DCHECK(rs != scratch);
781 782
      li(scratch, rt);
      slt(rd, rs, scratch);
783 784 785 786
    }
  }
}

787
void TurboAssembler::Sltu(Register rd, Register rs, const Operand& rt) {
788 789 790
  if (rt.is_reg()) {
    sltu(rd, rs, rt.rm());
  } else {
791
    const uint32_t int16_min = std::numeric_limits<int16_t>::min();
792
    if (is_uint15(rt.immediate()) && !MustUseReg(rt.rmode())) {
793
      // Imm range is: [0, 32767].
794 795
      sltiu(rd, rs, rt.immediate());
    } else if (is_uint15(rt.immediate() - int16_min) &&
796
               !MustUseReg(rt.rmode())) {
797
      // Imm range is: [max_unsigned-32767,max_unsigned].
798
      sltiu(rd, rs, static_cast<uint16_t>(rt.immediate()));
799 800
    } else {
      // li handles the relocation.
801
      BlockTrampolinePoolScope block_trampoline_pool(this);
802
      UseScratchRegisterScope temps(this);
803 804
      Register scratch = rd == at ? t8 : temps.Acquire();
      DCHECK(rs != scratch);
805 806
      li(scratch, rt);
      sltu(rd, rs, scratch);
807 808 809 810
    }
  }
}

811 812 813 814 815
void TurboAssembler::Sle(Register rd, Register rs, const Operand& rt) {
  if (rt.is_reg()) {
    slt(rd, rt.rm(), rs);
  } else {
    // li handles the relocation.
816
    BlockTrampolinePoolScope block_trampoline_pool(this);
817 818 819 820 821 822 823 824 825 826 827 828 829 830
    UseScratchRegisterScope temps(this);
    Register scratch = temps.hasAvailable() ? temps.Acquire() : t8;
    DCHECK(rs != scratch);
    li(scratch, rt);
    slt(rd, scratch, rs);
  }
  xori(rd, rd, 1);
}

void TurboAssembler::Sleu(Register rd, Register rs, const Operand& rt) {
  if (rt.is_reg()) {
    sltu(rd, rt.rm(), rs);
  } else {
    // li handles the relocation.
831
    BlockTrampolinePoolScope block_trampoline_pool(this);
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
    UseScratchRegisterScope temps(this);
    Register scratch = temps.hasAvailable() ? temps.Acquire() : t8;
    DCHECK(rs != scratch);
    li(scratch, rt);
    sltu(rd, scratch, rs);
  }
  xori(rd, rd, 1);
}

void TurboAssembler::Sge(Register rd, Register rs, const Operand& rt) {
  Slt(rd, rs, rt);
  xori(rd, rd, 1);
}

void TurboAssembler::Sgeu(Register rd, Register rs, const Operand& rt) {
  Sltu(rd, rs, rt);
  xori(rd, rd, 1);
}

851 852 853 854 855
void TurboAssembler::Sgt(Register rd, Register rs, const Operand& rt) {
  if (rt.is_reg()) {
    slt(rd, rt.rm(), rs);
  } else {
    // li handles the relocation.
856
    BlockTrampolinePoolScope block_trampoline_pool(this);
857 858 859 860 861 862 863 864 865 866 867 868 869
    UseScratchRegisterScope temps(this);
    Register scratch = temps.hasAvailable() ? temps.Acquire() : t8;
    DCHECK(rs != scratch);
    li(scratch, rt);
    slt(rd, scratch, rs);
  }
}

void TurboAssembler::Sgtu(Register rd, Register rs, const Operand& rt) {
  if (rt.is_reg()) {
    sltu(rd, rt.rm(), rs);
  } else {
    // li handles the relocation.
870
    BlockTrampolinePoolScope block_trampoline_pool(this);
871 872 873 874 875 876 877 878
    UseScratchRegisterScope temps(this);
    Register scratch = temps.hasAvailable() ? temps.Acquire() : t8;
    DCHECK(rs != scratch);
    li(scratch, rt);
    sltu(rd, scratch, rs);
  }
}

879
void TurboAssembler::Ror(Register rd, Register rs, const Operand& rt) {
880
  if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
881 882 883
    if (rt.is_reg()) {
      rotrv(rd, rs, rt.rm());
    } else {
884
      rotr(rd, rs, rt.immediate() & 0x1F);
885 886 887
    }
  } else {
    if (rt.is_reg()) {
888
      BlockTrampolinePoolScope block_trampoline_pool(this);
889
      UseScratchRegisterScope temps(this);
890
      Register scratch = temps.hasAvailable() ? temps.Acquire() : t8;
891 892
      subu(scratch, zero_reg, rt.rm());
      sllv(scratch, rs, scratch);
893
      srlv(rd, rs, rt.rm());
894
      or_(rd, rd, scratch);
895
    } else {
896
      if (rt.immediate() == 0) {
897 898
        srl(rd, rs, 0);
      } else {
899 900
        UseScratchRegisterScope temps(this);
        Register scratch = temps.Acquire();
901 902
        srl(scratch, rs, rt.immediate() & 0x1F);
        sll(rd, rs, (0x20 - (rt.immediate() & 0x1F)) & 0x1F);
903
        or_(rd, rd, scratch);
904 905 906
      }
    }
  }
907 908
}

plind44@gmail.com's avatar
plind44@gmail.com committed
909
void MacroAssembler::Pref(int32_t hint, const MemOperand& rs) {
910
  if (IsMipsArchVariant(kLoongson)) {
plind44@gmail.com's avatar
plind44@gmail.com committed
911 912 913 914 915 916
    lw(zero_reg, rs);
  } else {
    pref(hint, rs);
  }
}

917
void TurboAssembler::Lsa(Register rd, Register rt, Register rs, uint8_t sa,
918
                         Register scratch) {
919
  DCHECK(sa >= 1 && sa <= 31);
920
  if (IsMipsArchVariant(kMips32r6) && sa <= 4) {
921
    lsa(rd, rt, rs, sa - 1);
922
  } else {
923 924
    Register tmp = rd == rt ? scratch : rd;
    DCHECK(tmp != rt);
925 926 927 928 929
    sll(tmp, rs, sa);
    Addu(rd, rt, tmp);
  }
}

930
void TurboAssembler::Bovc(Register rs, Register rt, Label* L) {
931 932 933 934 935 936 937 938 939 940
  if (is_trampoline_emitted()) {
    Label skip;
    bnvc(rs, rt, &skip);
    BranchLong(L, PROTECT);
    bind(&skip);
  } else {
    bovc(rs, rt, L);
  }
}

941
void TurboAssembler::Bnvc(Register rs, Register rt, Label* L) {
942 943 944 945 946 947 948 949 950
  if (is_trampoline_emitted()) {
    Label skip;
    bovc(rs, rt, &skip);
    BranchLong(L, PROTECT);
    bind(&skip);
  } else {
    bnvc(rs, rt, L);
  }
}
951

952
// ------------Pseudo-instructions-------------
953

954
// Word Swap Byte
955
void TurboAssembler::ByteSwapSigned(Register dest, Register src,
956
                                    int operand_size) {
957
  DCHECK(operand_size == 2 || operand_size == 4);
958 959

  if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
960 961 962 963 964 965 966
    if (operand_size == 2) {
      wsbh(dest, src);
      seh(dest, dest);
    } else {
      wsbh(dest, src);
      rotr(dest, dest, 16);
    }
967
  } else if (IsMipsArchVariant(kMips32r1) || IsMipsArchVariant(kLoongson)) {
968 969 970 971 972 973 974 975 976 977 978
    if (operand_size == 2) {
      DCHECK(src != at && dest != at);
      srl(at, src, 8);
      andi(at, at, 0xFF);
      sll(dest, src, 8);
      or_(dest, dest, at);

      // Sign-extension
      sll(dest, dest, 16);
      sra(dest, dest, 16);
    } else {
979
      BlockTrampolinePoolScope block_trampoline_pool(this);
980 981 982 983
      Register tmp = at;
      Register tmp2 = t8;
      DCHECK(dest != tmp && dest != tmp2);
      DCHECK(src != tmp && src != tmp2);
984

985 986
      andi(tmp2, src, 0xFF);
      sll(tmp, tmp2, 24);
987

988 989 990
      andi(tmp2, src, 0xFF00);
      sll(tmp2, tmp2, 8);
      or_(tmp, tmp, tmp2);
991

992 993 994
      srl(tmp2, src, 8);
      andi(tmp2, tmp2, 0xFF00);
      or_(tmp, tmp, tmp2);
995

996 997 998
      srl(tmp2, src, 24);
      or_(dest, tmp, tmp2);
    }
999 1000 1001
  }
}

1002
void TurboAssembler::ByteSwapUnsigned(Register dest, Register src,
1003
                                      int operand_size) {
1004
  DCHECK_EQ(operand_size, 2);
1005 1006

  if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
1007 1008
    wsbh(dest, src);
    andi(dest, dest, 0xFFFF);
1009
  } else if (IsMipsArchVariant(kMips32r1) || IsMipsArchVariant(kLoongson)) {
1010 1011 1012 1013 1014 1015 1016 1017
    DCHECK(src != at && dest != at);
    srl(at, src, 8);
    andi(at, at, 0xFF);
    sll(dest, src, 8);
    or_(dest, dest, at);

    // Zero-extension
    andi(dest, dest, 0xFFFF);
1018 1019 1020
  }
}

1021
void TurboAssembler::Ulw(Register rd, const MemOperand& rs) {
1022 1023
  DCHECK(rd != at);
  DCHECK(rs.rm() != at);
1024 1025 1026 1027 1028
  if (IsMipsArchVariant(kMips32r6)) {
    lw(rd, rs);
  } else {
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r1) ||
           IsMipsArchVariant(kLoongson));
1029 1030 1031
    DCHECK(kMipsLwrOffset <= 3 && kMipsLwlOffset <= 3);
    MemOperand source = rs;
    // Adjust offset for two accesses and check if offset + 3 fits into int16_t.
1032
    AdjustBaseAndOffset(&source, OffsetAccessType::TWO_ACCESSES, 3);
1033
    if (rd != source.rm()) {
1034 1035 1036
      lwr(rd, MemOperand(source.rm(), source.offset() + kMipsLwrOffset));
      lwl(rd, MemOperand(source.rm(), source.offset() + kMipsLwlOffset));
    } else {
1037 1038 1039 1040 1041
      UseScratchRegisterScope temps(this);
      Register scratch = temps.Acquire();
      lwr(scratch, MemOperand(rs.rm(), rs.offset() + kMipsLwrOffset));
      lwl(scratch, MemOperand(rs.rm(), rs.offset() + kMipsLwlOffset));
      mov(rd, scratch);
1042 1043
    }
  }
plind44@gmail.com's avatar
plind44@gmail.com committed
1044 1045
}

1046
void TurboAssembler::Usw(Register rd, const MemOperand& rs) {
1047 1048 1049
  DCHECK(rd != at);
  DCHECK(rs.rm() != at);
  DCHECK(rd != rs.rm());
1050 1051 1052 1053 1054
  if (IsMipsArchVariant(kMips32r6)) {
    sw(rd, rs);
  } else {
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r1) ||
           IsMipsArchVariant(kLoongson));
1055 1056 1057
    DCHECK(kMipsSwrOffset <= 3 && kMipsSwlOffset <= 3);
    MemOperand source = rs;
    // Adjust offset for two accesses and check if offset + 3 fits into int16_t.
1058
    AdjustBaseAndOffset(&source, OffsetAccessType::TWO_ACCESSES, 3);
1059 1060
    swr(rd, MemOperand(source.rm(), source.offset() + kMipsSwrOffset));
    swl(rd, MemOperand(source.rm(), source.offset() + kMipsSwlOffset));
1061 1062 1063
  }
}

1064
void TurboAssembler::Ulh(Register rd, const MemOperand& rs) {
1065 1066
  DCHECK(rd != at);
  DCHECK(rs.rm() != at);
1067 1068 1069 1070 1071
  if (IsMipsArchVariant(kMips32r6)) {
    lh(rd, rs);
  } else {
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r1) ||
           IsMipsArchVariant(kLoongson));
1072 1073
    MemOperand source = rs;
    // Adjust offset for two accesses and check if offset + 1 fits into int16_t.
1074
    AdjustBaseAndOffset(&source, OffsetAccessType::TWO_ACCESSES, 1);
1075 1076
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
1077
    if (source.rm() == scratch) {
1078
#if defined(V8_TARGET_LITTLE_ENDIAN)
1079
      lb(rd, MemOperand(source.rm(), source.offset() + 1));
1080
      lbu(scratch, source);
1081
#elif defined(V8_TARGET_BIG_ENDIAN)
1082
      lb(rd, source);
1083
      lbu(scratch, MemOperand(source.rm(), source.offset() + 1));
1084
#endif
1085
    } else {
1086
#if defined(V8_TARGET_LITTLE_ENDIAN)
1087
      lbu(scratch, source);
1088
      lb(rd, MemOperand(source.rm(), source.offset() + 1));
1089
#elif defined(V8_TARGET_BIG_ENDIAN)
1090
      lbu(scratch, MemOperand(source.rm(), source.offset() + 1));
1091
      lb(rd, source);
1092 1093 1094
#endif
    }
    sll(rd, rd, 8);
1095
    or_(rd, rd, scratch);
1096 1097 1098
  }
}

1099
void TurboAssembler::Ulhu(Register rd, const MemOperand& rs) {
1100 1101
  DCHECK(rd != at);
  DCHECK(rs.rm() != at);
1102 1103 1104 1105 1106
  if (IsMipsArchVariant(kMips32r6)) {
    lhu(rd, rs);
  } else {
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r1) ||
           IsMipsArchVariant(kLoongson));
1107 1108
    MemOperand source = rs;
    // Adjust offset for two accesses and check if offset + 1 fits into int16_t.
1109
    AdjustBaseAndOffset(&source, OffsetAccessType::TWO_ACCESSES, 1);
1110 1111
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
1112
    if (source.rm() == scratch) {
1113
#if defined(V8_TARGET_LITTLE_ENDIAN)
1114
      lbu(rd, MemOperand(source.rm(), source.offset() + 1));
1115
      lbu(scratch, source);
1116
#elif defined(V8_TARGET_BIG_ENDIAN)
1117
      lbu(rd, source);
1118
      lbu(scratch, MemOperand(source.rm(), source.offset() + 1));
1119
#endif
1120
    } else {
1121
#if defined(V8_TARGET_LITTLE_ENDIAN)
1122
      lbu(scratch, source);
1123
      lbu(rd, MemOperand(source.rm(), source.offset() + 1));
1124
#elif defined(V8_TARGET_BIG_ENDIAN)
1125
      lbu(scratch, MemOperand(source.rm(), source.offset() + 1));
1126
      lbu(rd, source);
1127 1128 1129
#endif
    }
    sll(rd, rd, 8);
1130
    or_(rd, rd, scratch);
1131 1132 1133
  }
}

1134
void TurboAssembler::Ush(Register rd, const MemOperand& rs, Register scratch) {
1135 1136 1137 1138
  DCHECK(rd != at);
  DCHECK(rs.rm() != at);
  DCHECK(rs.rm() != scratch);
  DCHECK(scratch != at);
1139 1140 1141 1142 1143 1144
  if (IsMipsArchVariant(kMips32r6)) {
    sh(rd, rs);
  } else {
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r1) ||
           IsMipsArchVariant(kLoongson));
    MemOperand source = rs;
1145
    // Adjust offset for two accesses and check if offset + 1 fits into int16_t.
1146
    AdjustBaseAndOffset(&source, OffsetAccessType::TWO_ACCESSES, 1);
1147

1148
    if (scratch != rd) {
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
      mov(scratch, rd);
    }

#if defined(V8_TARGET_LITTLE_ENDIAN)
    sb(scratch, source);
    srl(scratch, scratch, 8);
    sb(scratch, MemOperand(source.rm(), source.offset() + 1));
#elif defined(V8_TARGET_BIG_ENDIAN)
    sb(scratch, MemOperand(source.rm(), source.offset() + 1));
    srl(scratch, scratch, 8);
    sb(scratch, source);
#endif
  }
}

1164
void TurboAssembler::Ulwc1(FPURegister fd, const MemOperand& rs,
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
                           Register scratch) {
  if (IsMipsArchVariant(kMips32r6)) {
    lwc1(fd, rs);
  } else {
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r1) ||
           IsMipsArchVariant(kLoongson));
    Ulw(scratch, rs);
    mtc1(scratch, fd);
  }
}

1176
void TurboAssembler::Uswc1(FPURegister fd, const MemOperand& rs,
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
                           Register scratch) {
  if (IsMipsArchVariant(kMips32r6)) {
    swc1(fd, rs);
  } else {
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r1) ||
           IsMipsArchVariant(kLoongson));
    mfc1(scratch, fd);
    Usw(scratch, rs);
  }
}

1188
void TurboAssembler::Uldc1(FPURegister fd, const MemOperand& rs,
1189
                           Register scratch) {
1190
  DCHECK(scratch != at);
1191
  if (IsMipsArchVariant(kMips32r6)) {
1192
    Ldc1(fd, rs);
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
  } else {
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r1) ||
           IsMipsArchVariant(kLoongson));
    Ulw(scratch, MemOperand(rs.rm(), rs.offset() + Register::kMantissaOffset));
    mtc1(scratch, fd);
    Ulw(scratch, MemOperand(rs.rm(), rs.offset() + Register::kExponentOffset));
    Mthc1(scratch, fd);
  }
}

1203
void TurboAssembler::Usdc1(FPURegister fd, const MemOperand& rs,
1204
                           Register scratch) {
1205
  DCHECK(scratch != at);
1206
  if (IsMipsArchVariant(kMips32r6)) {
1207
    Sdc1(fd, rs);
1208 1209 1210 1211 1212 1213 1214 1215
  } else {
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r1) ||
           IsMipsArchVariant(kLoongson));
    mfc1(scratch, fd);
    Usw(scratch, MemOperand(rs.rm(), rs.offset() + Register::kMantissaOffset));
    Mfhc1(scratch, fd);
    Usw(scratch, MemOperand(rs.rm(), rs.offset() + Register::kExponentOffset));
  }
plind44@gmail.com's avatar
plind44@gmail.com committed
1216 1217
}

1218
void TurboAssembler::Ldc1(FPURegister fd, const MemOperand& src) {
1219 1220
  // Workaround for non-8-byte alignment of HeapNumber, convert 64-bit
  // load to two 32-bit loads.
1221 1222 1223 1224
  {
    BlockTrampolinePoolScope block_trampoline_pool(this);
    DCHECK(Register::kMantissaOffset <= 4 && Register::kExponentOffset <= 4);
    MemOperand tmp = src;
1225
    AdjustBaseAndOffset(&tmp, OffsetAccessType::TWO_ACCESSES);
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
    lwc1(fd, MemOperand(tmp.rm(), tmp.offset() + Register::kMantissaOffset));
    if (IsFp32Mode()) {  // fp32 mode.
      FPURegister nextfpreg = FPURegister::from_code(fd.code() + 1);
      lwc1(nextfpreg,
           MemOperand(tmp.rm(), tmp.offset() + Register::kExponentOffset));
    } else {
      DCHECK(IsFp64Mode() || IsFpxxMode());
      // Currently we support FPXX and FP64 on Mips32r2 and Mips32r6
      DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6));
      UseScratchRegisterScope temps(this);
      Register scratch = temps.Acquire();
      DCHECK(src.rm() != scratch);
      lw(scratch,
1239
         MemOperand(tmp.rm(), tmp.offset() + Register::kExponentOffset));
1240 1241
      Mthc1(scratch, fd);
    }
1242
  }
1243
  CheckTrampolinePoolQuick(1);
1244 1245
}

1246
void TurboAssembler::Sdc1(FPURegister fd, const MemOperand& src) {
1247 1248
  // Workaround for non-8-byte alignment of HeapNumber, convert 64-bit
  // store to two 32-bit stores.
1249 1250 1251 1252
  {
    BlockTrampolinePoolScope block_trampoline_pool(this);
    DCHECK(Register::kMantissaOffset <= 4 && Register::kExponentOffset <= 4);
    MemOperand tmp = src;
1253
    AdjustBaseAndOffset(&tmp, OffsetAccessType::TWO_ACCESSES);
1254 1255 1256 1257 1258 1259
    swc1(fd, MemOperand(tmp.rm(), tmp.offset() + Register::kMantissaOffset));
    if (IsFp32Mode()) {  // fp32 mode.
      FPURegister nextfpreg = FPURegister::from_code(fd.code() + 1);
      swc1(nextfpreg,
           MemOperand(tmp.rm(), tmp.offset() + Register::kExponentOffset));
    } else {
1260
      BlockTrampolinePoolScope block_trampoline_pool(this);
1261 1262 1263 1264 1265 1266 1267
      DCHECK(IsFp64Mode() || IsFpxxMode());
      // Currently we support FPXX and FP64 on Mips32r2 and Mips32r6
      DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6));
      DCHECK(src.rm() != t8);
      Mfhc1(t8, fd);
      sw(t8, MemOperand(tmp.rm(), tmp.offset() + Register::kExponentOffset));
    }
1268
  }
1269
  CheckTrampolinePoolQuick(1);
1270
}
plind44@gmail.com's avatar
plind44@gmail.com committed
1271

1272 1273
void TurboAssembler::Lw(Register rd, const MemOperand& rs) {
  MemOperand source = rs;
1274
  AdjustBaseAndOffset(&source);
1275 1276 1277 1278 1279
  lw(rd, source);
}

void TurboAssembler::Sw(Register rd, const MemOperand& rs) {
  MemOperand dest = rs;
1280
  AdjustBaseAndOffset(&dest);
1281 1282 1283
  sw(rd, dest);
}

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
void TurboAssembler::Ll(Register rd, const MemOperand& rs) {
  bool is_one_instruction = IsMipsArchVariant(kMips32r6)
                                ? is_int9(rs.offset())
                                : is_int16(rs.offset());
  if (is_one_instruction) {
    ll(rd, rs);
  } else {
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
    li(scratch, rs.offset());
    addu(scratch, scratch, rs.rm());
    ll(rd, MemOperand(scratch, 0));
  }
}

void TurboAssembler::Sc(Register rd, const MemOperand& rs) {
  bool is_one_instruction = IsMipsArchVariant(kMips32r6)
                                ? is_int9(rs.offset())
                                : is_int16(rs.offset());
  if (is_one_instruction) {
    sc(rd, rs);
  } else {
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
    li(scratch, rs.offset());
    addu(scratch, scratch, rs.rm());
    sc(rd, MemOperand(scratch, 0));
  }
}

1314
void TurboAssembler::li(Register dst, Handle<HeapObject> value, LiFlags mode) {
1315 1316 1317 1318 1319 1320
  // TODO(jgruber,v8:8887): Also consider a root-relative load when generating
  // non-isolate-independent code. In many cases it might be cheaper than
  // embedding the relocatable value.
  if (root_array_available_ && options().isolate_independent_code) {
    IndirectLoadConstant(dst, value);
    return;
1321 1322 1323 1324 1325
  }
  li(dst, Operand(value), mode);
}

void TurboAssembler::li(Register dst, ExternalReference value, LiFlags mode) {
1326 1327 1328 1329 1330 1331
  // TODO(jgruber,v8:8887): Also consider a root-relative load when generating
  // non-isolate-independent code. In many cases it might be cheaper than
  // embedding the relocatable value.
  if (root_array_available_ && options().isolate_independent_code) {
    IndirectLoadExternalReference(dst, value);
    return;
1332
  }
1333
  li(dst, Operand(value), mode);
1334 1335
}

1336 1337 1338 1339 1340
void TurboAssembler::li(Register dst, const StringConstantBase* string,
                        LiFlags mode) {
  li(dst, Operand::EmbeddedStringConstant(string), mode);
}

1341
void TurboAssembler::li(Register rd, Operand j, LiFlags mode) {
1342
  DCHECK(!j.is_reg());
1343
  BlockTrampolinePoolScope block_trampoline_pool(this);
1344
  if (!MustUseReg(j.rmode()) && mode == OPTIMIZE_SIZE) {
1345
    // Normal load of an immediate value which does not need Relocation Info.
1346 1347 1348 1349
    if (is_int16(j.immediate())) {
      addiu(rd, zero_reg, j.immediate());
    } else if (!(j.immediate() & kHiMask)) {
      ori(rd, zero_reg, j.immediate());
1350
    } else {
1351 1352 1353
      lui(rd, (j.immediate() >> kLuiShift) & kImm16Mask);
      if (j.immediate() & kImm16Mask) {
        ori(rd, rd, (j.immediate() & kImm16Mask));
1354
      }
1355
    }
1356
  } else {
1357 1358 1359 1360 1361 1362 1363 1364
    int32_t immediate;
    if (j.IsHeapObjectRequest()) {
      RequestHeapObject(j.heap_object_request());
      immediate = 0;
    } else {
      immediate = j.immediate();
    }

1365 1366
    if (MustUseReg(j.rmode())) {
      RecordRelocInfo(j.rmode(), immediate);
1367
    }
1368
    // We always need the same number of instructions as we may need to patch
1369
    // this code to load another value which may need 2 instructions to load.
1370 1371 1372

    lui(rd, (immediate >> kLuiShift) & kImm16Mask);
    ori(rd, rd, (immediate & kImm16Mask));
1373 1374 1375
  }
}

1376
void TurboAssembler::MultiPush(RegList regs) {
1377
  int16_t num_to_push = regs.Count();
1378
  int16_t stack_offset = num_to_push * kPointerSize;
1379

1380
  Subu(sp, sp, Operand(stack_offset));
1381
  for (int16_t i = kNumRegisters - 1; i >= 0; i--) {
1382
    if ((regs.bits() & (1 << i)) != 0) {
1383 1384
      stack_offset -= kPointerSize;
      sw(ToRegister(i), MemOperand(sp, stack_offset));
1385 1386 1387 1388
    }
  }
}

1389
void TurboAssembler::MultiPop(RegList regs) {
1390
  int16_t stack_offset = 0;
1391

1392
  for (int16_t i = 0; i < kNumRegisters; i++) {
1393
    if ((regs.bits() & (1 << i)) != 0) {
1394 1395
      lw(ToRegister(i), MemOperand(sp, stack_offset));
      stack_offset += kPointerSize;
1396 1397
    }
  }
1398
  addiu(sp, sp, stack_offset);
1399 1400
}

1401 1402
void TurboAssembler::MultiPushFPU(DoubleRegList regs) {
  int16_t num_to_push = regs.Count();
1403 1404 1405
  int16_t stack_offset = num_to_push * kDoubleSize;

  Subu(sp, sp, Operand(stack_offset));
1406
  for (int16_t i = kNumRegisters - 1; i >= 0; i--) {
1407
    if ((regs.bits() & (1 << i)) != 0) {
1408
      stack_offset -= kDoubleSize;
1409
      Sdc1(FPURegister::from_code(i), MemOperand(sp, stack_offset));
1410 1411 1412 1413
    }
  }
}

1414
void TurboAssembler::MultiPopFPU(DoubleRegList regs) {
1415 1416 1417
  int16_t stack_offset = 0;

  for (int16_t i = 0; i < kNumRegisters; i++) {
1418
    if ((regs.bits() & (1 << i)) != 0) {
1419
      Ldc1(FPURegister::from_code(i), MemOperand(sp, stack_offset));
1420 1421 1422 1423 1424 1425
      stack_offset += kDoubleSize;
    }
  }
  addiu(sp, sp, stack_offset);
}

1426
void TurboAssembler::AddPair(Register dst_low, Register dst_high,
1427
                             Register left_low, Register left_high,
1428 1429 1430 1431 1432 1433 1434 1435 1436
                             Register right_low, Register right_high,
                             Register scratch1, Register scratch2) {
  BlockTrampolinePoolScope block_trampoline_pool(this);
  Register scratch3 = t8;
  Addu(scratch1, left_low, right_low);
  Sltu(scratch3, scratch1, left_low);
  Addu(scratch2, left_high, right_high);
  Addu(dst_high, scratch2, scratch3);
  Move(dst_low, scratch1);
1437 1438
}

1439
void TurboAssembler::AddPair(Register dst_low, Register dst_high,
1440
                             Register left_low, Register left_high, int32_t imm,
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
                             Register scratch1, Register scratch2) {
  BlockTrampolinePoolScope block_trampoline_pool(this);
  Register scratch3 = t8;
  li(dst_low, Operand(imm));
  sra(dst_high, dst_low, 31);
  Addu(scratch1, left_low, dst_low);
  Sltu(scratch3, scratch1, left_low);
  Addu(scratch2, left_high, dst_high);
  Addu(dst_high, scratch2, scratch3);
  Move(dst_low, scratch1);
}

1453
void TurboAssembler::SubPair(Register dst_low, Register dst_high,
1454
                             Register left_low, Register left_high,
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
                             Register right_low, Register right_high,
                             Register scratch1, Register scratch2) {
  BlockTrampolinePoolScope block_trampoline_pool(this);
  Register scratch3 = t8;
  Sltu(scratch3, left_low, right_low);
  Subu(scratch1, left_low, right_low);
  Subu(scratch2, left_high, right_high);
  Subu(dst_high, scratch2, scratch3);
  Move(dst_low, scratch1);
}

1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
void TurboAssembler::AndPair(Register dst_low, Register dst_high,
                             Register left_low, Register left_high,
                             Register right_low, Register right_high) {
  And(dst_low, left_low, right_low);
  And(dst_high, left_high, right_high);
}

void TurboAssembler::OrPair(Register dst_low, Register dst_high,
                            Register left_low, Register left_high,
                            Register right_low, Register right_high) {
  Or(dst_low, left_low, right_low);
  Or(dst_high, left_high, right_high);
}
void TurboAssembler::XorPair(Register dst_low, Register dst_high,
                             Register left_low, Register left_high,
                             Register right_low, Register right_high) {
  Xor(dst_low, left_low, right_low);
  Xor(dst_high, left_high, right_high);
}

1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
void TurboAssembler::MulPair(Register dst_low, Register dst_high,
                             Register left_low, Register left_high,
                             Register right_low, Register right_high,
                             Register scratch1, Register scratch2) {
  BlockTrampolinePoolScope block_trampoline_pool(this);
  Register scratch3 = t8;
  Mulu(scratch2, scratch1, left_low, right_low);
  Mul(scratch3, left_low, right_high);
  Addu(scratch2, scratch2, scratch3);
  Mul(scratch3, left_high, right_low);
  Addu(dst_high, scratch2, scratch3);
  Move(dst_low, scratch1);
1498 1499
}

1500
void TurboAssembler::ShlPair(Register dst_low, Register dst_high,
1501
                             Register src_low, Register src_high,
1502 1503 1504
                             Register shift, Register scratch1,
                             Register scratch2) {
  BlockTrampolinePoolScope block_trampoline_pool(this);
1505
  Label done;
1506 1507 1508 1509 1510 1511 1512 1513 1514
  Register scratch3 = t8;
  And(scratch3, shift, 0x3F);
  sllv(dst_low, src_low, scratch3);
  Nor(scratch2, zero_reg, scratch3);
  srl(scratch1, src_low, 1);
  srlv(scratch1, scratch1, scratch2);
  sllv(dst_high, src_high, scratch3);
  Or(dst_high, dst_high, scratch1);
  And(scratch1, scratch3, 32);
1515
  if (IsMipsArchVariant(kLoongson) || IsMipsArchVariant(kMips32r6)) {
1516
    Branch(&done, eq, scratch1, Operand(zero_reg));
1517 1518 1519
    mov(dst_high, dst_low);
    mov(dst_low, zero_reg);
  } else {
1520 1521
    movn(dst_high, dst_low, scratch1);
    movn(dst_low, zero_reg, scratch1);
1522
  }
1523 1524 1525
  bind(&done);
}

1526
void TurboAssembler::ShlPair(Register dst_low, Register dst_high,
1527
                             Register src_low, Register src_high,
1528
                             uint32_t shift, Register scratch) {
1529 1530
  DCHECK_NE(dst_low, src_low);
  DCHECK_NE(dst_high, src_low);
1531
  shift = shift & 0x3F;
1532 1533
  if (shift == 0) {
    mov(dst_high, src_high);
1534
    mov(dst_low, src_low);
1535 1536
  } else if (shift < 32) {
    if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
1537
      DCHECK_NE(dst_high, src_high);
1538
      srl(dst_high, src_low, 32 - shift);
1539
      Ins(dst_high, src_high, shift, 32 - shift);
1540
      sll(dst_low, src_low, shift);
1541 1542 1543
    } else {
      sll(dst_high, src_high, shift);
      sll(dst_low, src_low, shift);
1544 1545
      srl(scratch, src_low, 32 - shift);
      Or(dst_high, dst_high, scratch);
1546
    }
1547 1548 1549
  } else if (shift == 32) {
    mov(dst_low, zero_reg);
    mov(dst_high, src_low);
1550
  } else {
1551 1552 1553
    shift = shift - 32;
    mov(dst_low, zero_reg);
    sll(dst_high, src_low, shift);
1554 1555 1556
  }
}

1557
void TurboAssembler::ShrPair(Register dst_low, Register dst_high,
1558
                             Register src_low, Register src_high,
1559 1560 1561
                             Register shift, Register scratch1,
                             Register scratch2) {
  BlockTrampolinePoolScope block_trampoline_pool(this);
1562
  Label done;
1563 1564 1565 1566 1567 1568 1569 1570 1571
  Register scratch3 = t8;
  And(scratch3, shift, 0x3F);
  srlv(dst_high, src_high, scratch3);
  Nor(scratch2, zero_reg, scratch3);
  sll(scratch1, src_high, 1);
  sllv(scratch1, scratch1, scratch2);
  srlv(dst_low, src_low, scratch3);
  Or(dst_low, dst_low, scratch1);
  And(scratch1, scratch3, 32);
1572
  if (IsMipsArchVariant(kLoongson) || IsMipsArchVariant(kMips32r6)) {
1573
    Branch(&done, eq, scratch1, Operand(zero_reg));
1574 1575 1576
    mov(dst_low, dst_high);
    mov(dst_high, zero_reg);
  } else {
1577 1578
    movn(dst_low, dst_high, scratch1);
    movn(dst_high, zero_reg, scratch1);
1579
  }
1580 1581 1582
  bind(&done);
}

1583
void TurboAssembler::ShrPair(Register dst_low, Register dst_high,
1584
                             Register src_low, Register src_high,
1585
                             uint32_t shift, Register scratch) {
1586 1587
  DCHECK_NE(dst_low, src_high);
  DCHECK_NE(dst_high, src_high);
1588
  shift = shift & 0x3F;
1589 1590 1591 1592 1593 1594 1595 1596
  if (shift == 0) {
    mov(dst_low, src_low);
    mov(dst_high, src_high);
  } else if (shift < 32) {
    if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
      srl(dst_low, src_low, shift);
      Ins(dst_low, src_high, 32 - shift, shift);
      srl(dst_high, src_high, shift);
1597 1598
    } else {
      srl(dst_low, src_low, shift);
1599
      srl(dst_high, src_high, shift);
1600
      shift = 32 - shift;
1601 1602
      sll(scratch, src_high, shift);
      Or(dst_low, dst_low, scratch);
1603
    }
1604 1605 1606
  } else if (shift == 32) {
    mov(dst_high, zero_reg);
    mov(dst_low, src_high);
1607
  } else {
1608 1609 1610
    shift = shift - 32;
    mov(dst_high, zero_reg);
    srl(dst_low, src_high, shift);
1611 1612 1613
  }
}

1614
void TurboAssembler::SarPair(Register dst_low, Register dst_high,
1615
                             Register src_low, Register src_high,
1616 1617 1618
                             Register shift, Register scratch1,
                             Register scratch2) {
  BlockTrampolinePoolScope block_trampoline_pool(this);
1619
  Label done;
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
  Register scratch3 = t8;
  And(scratch3, shift, 0x3F);
  srav(dst_high, src_high, scratch3);
  Nor(scratch2, zero_reg, scratch3);
  sll(scratch1, src_high, 1);
  sllv(scratch1, scratch1, scratch2);
  srlv(dst_low, src_low, scratch3);
  Or(dst_low, dst_low, scratch1);
  And(scratch1, scratch3, 32);
  Branch(&done, eq, scratch1, Operand(zero_reg));
1630 1631
  mov(dst_low, dst_high);
  sra(dst_high, dst_high, 31);
1632 1633 1634
  bind(&done);
}

1635
void TurboAssembler::SarPair(Register dst_low, Register dst_high,
1636
                             Register src_low, Register src_high,
1637
                             uint32_t shift, Register scratch) {
1638 1639
  DCHECK_NE(dst_low, src_high);
  DCHECK_NE(dst_high, src_high);
1640
  shift = shift & 0x3F;
1641 1642 1643 1644 1645 1646 1647 1648
  if (shift == 0) {
    mov(dst_low, src_low);
    mov(dst_high, src_high);
  } else if (shift < 32) {
    if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
      srl(dst_low, src_low, shift);
      Ins(dst_low, src_high, 32 - shift, shift);
      sra(dst_high, src_high, shift);
1649 1650
    } else {
      srl(dst_low, src_low, shift);
1651
      sra(dst_high, src_high, shift);
1652
      shift = 32 - shift;
1653 1654
      sll(scratch, src_high, shift);
      Or(dst_low, dst_low, scratch);
1655
    }
1656 1657 1658
  } else if (shift == 32) {
    sra(dst_high, src_high, 31);
    mov(dst_low, src_high);
1659
  } else {
1660 1661 1662
    shift = shift - 32;
    sra(dst_high, src_high, 31);
    sra(dst_low, src_high, shift);
1663 1664
  }
}
1665

1666
void TurboAssembler::Ext(Register rt, Register rs, uint16_t pos,
1667
                         uint16_t size) {
1668 1669
  DCHECK_LT(pos, 32);
  DCHECK_LT(pos + size, 33);
1670

1671
  if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
1672 1673 1674 1675
    ext_(rt, rs, pos, size);
  } else {
    // Move rs to rt and shift it left then right to get the
    // desired bitfield on the right side and zeroes on the left.
1676
    int shift_left = 32 - (pos + size);
1677
    sll(rt, rs, shift_left);  // Acts as a move if shift_left == 0.
1678 1679 1680 1681 1682

    int shift_right = 32 - size;
    if (shift_right > 0) {
      srl(rt, rt, shift_right);
    }
1683
  }
1684
}
1685

1686
void TurboAssembler::Ins(Register rt, Register rs, uint16_t pos,
1687
                         uint16_t size) {
1688 1689 1690
  DCHECK_LT(pos, 32);
  DCHECK_LE(pos + size, 32);
  DCHECK_NE(size, 0);
1691

1692
  if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
1693 1694
    ins_(rt, rs, pos, size);
  } else {
1695
    DCHECK(rt != t8 && rs != t8);
1696
    BlockTrampolinePoolScope block_trampoline_pool(this);
1697 1698 1699 1700 1701
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
    Subu(scratch, zero_reg, Operand(1));
    srl(scratch, scratch, 32 - size);
    and_(t8, rs, scratch);
1702
    sll(t8, t8, pos);
1703 1704 1705 1706
    sll(scratch, scratch, pos);
    nor(scratch, scratch, zero_reg);
    and_(scratch, rt, scratch);
    or_(rt, t8, scratch);
1707 1708
  }
}
1709

1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
void TurboAssembler::ExtractBits(Register dest, Register source, Register pos,
                                 int size, bool sign_extend) {
  srav(dest, source, pos);
  Ext(dest, dest, 0, size);
  if (size == 8) {
    if (sign_extend) {
      Seb(dest, dest);
    }
  } else if (size == 16) {
    if (sign_extend) {
      Seh(dest, dest);
    }
  } else {
    UNREACHABLE();
  }
}

void TurboAssembler::InsertBits(Register dest, Register source, Register pos,
                                int size) {
  Ror(dest, dest, pos);
  Ins(dest, source, 0, size);
  {
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
1734
    Subu(scratch, zero_reg, pos);
1735 1736 1737 1738
    Ror(dest, dest, scratch);
  }
}

1739
void TurboAssembler::Seb(Register rd, Register rt) {
1740 1741 1742 1743 1744 1745 1746 1747 1748
  if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
    seb(rd, rt);
  } else {
    DCHECK(IsMipsArchVariant(kMips32r1) || IsMipsArchVariant(kLoongson));
    sll(rd, rt, 24);
    sra(rd, rd, 24);
  }
}

1749
void TurboAssembler::Seh(Register rd, Register rt) {
1750 1751 1752 1753 1754 1755 1756 1757 1758
  if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
    seh(rd, rt);
  } else {
    DCHECK(IsMipsArchVariant(kMips32r1) || IsMipsArchVariant(kLoongson));
    sll(rd, rt, 16);
    sra(rd, rd, 16);
  }
}

1759
void TurboAssembler::Neg_s(FPURegister fd, FPURegister fs) {
1760 1761 1762 1763 1764 1765
  if (IsMipsArchVariant(kMips32r6)) {
    // r6 neg_s changes the sign for NaN-like operands as well.
    neg_s(fd, fs);
  } else {
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r1) ||
           IsMipsArchVariant(kLoongson));
1766
    BlockTrampolinePoolScope block_trampoline_pool(this);
1767 1768 1769
    Label is_nan, done;
    Register scratch1 = t8;
    Register scratch2 = t9;
1770 1771
    CompareIsNanF32(fs, fs);
    BranchTrueShortF(&is_nan);
1772 1773 1774 1775 1776 1777
    Branch(USE_DELAY_SLOT, &done);
    // For NaN input, neg_s will return the same NaN value,
    // while the sign has to be changed separately.
    neg_s(fd, fs);  // In delay slot.
    bind(&is_nan);
    mfc1(scratch1, fs);
1778 1779 1780
    li(scratch2, kBinary32SignMask);
    Xor(scratch1, scratch1, scratch2);
    mtc1(scratch1, fd);
1781 1782 1783 1784
    bind(&done);
  }
}

1785
void TurboAssembler::Neg_d(FPURegister fd, FPURegister fs) {
1786 1787 1788 1789 1790 1791
  if (IsMipsArchVariant(kMips32r6)) {
    // r6 neg_d changes the sign for NaN-like operands as well.
    neg_d(fd, fs);
  } else {
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r1) ||
           IsMipsArchVariant(kLoongson));
1792
    BlockTrampolinePoolScope block_trampoline_pool(this);
1793
    Label is_nan, done;
1794 1795
    Register scratch1 = t8;
    Register scratch2 = t9;
1796 1797
    CompareIsNanF64(fs, fs);
    BranchTrueShortF(&is_nan);
1798 1799 1800 1801 1802
    Branch(USE_DELAY_SLOT, &done);
    // For NaN input, neg_d will return the same NaN value,
    // while the sign has to be changed separately.
    neg_d(fd, fs);  // In delay slot.
    bind(&is_nan);
1803 1804
    Move(fd, fs);
    Mfhc1(scratch1, fd);
1805 1806 1807
    li(scratch2, HeapNumber::kSignMask);
    Xor(scratch1, scratch1, scratch2);
    Mthc1(scratch1, fd);
1808 1809 1810
    bind(&done);
  }
}
1811

1812
void TurboAssembler::Cvt_d_uw(FPURegister fd, Register rs,
1813
                              FPURegister scratch) {
1814
  // In FP64Mode we do conversion from long.
1815 1816
  if (IsFp64Mode()) {
    mtc1(rs, scratch);
1817
    Mthc1(zero_reg, scratch);
1818 1819 1820
    cvt_d_l(fd, scratch);
  } else {
    // Convert rs to a FP value in fd.
1821 1822
    DCHECK(fd != scratch);
    DCHECK(rs != at);
1823

1824 1825 1826 1827
    Label msb_clear, conversion_done;
    // For a value which is < 2^31, regard it as a signed positve word.
    Branch(&msb_clear, ge, rs, Operand(zero_reg), USE_DELAY_SLOT);
    mtc1(rs, fd);
1828 1829 1830 1831
    {
      UseScratchRegisterScope temps(this);
      Register scratch1 = temps.Acquire();
      li(scratch1, 0x41F00000);  // FP value: 2^32.
1832

1833 1834 1835 1836 1837
      // For unsigned inputs > 2^31, we convert to double as a signed int32,
      // then add 2^32 to move it back to unsigned value in range 2^31..2^31-1.
      mtc1(zero_reg, scratch);
      Mthc1(scratch1, scratch);
    }
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848

    cvt_d_w(fd, fd);

    Branch(USE_DELAY_SLOT, &conversion_done);
    add_d(fd, fd, scratch);

    bind(&msb_clear);
    cvt_d_w(fd, fd);

    bind(&conversion_done);
  }
1849 1850
}

1851
void TurboAssembler::Trunc_uw_d(FPURegister fd, FPURegister fs,
1852
                                FPURegister scratch) {
1853 1854
  BlockTrampolinePoolScope block_trampoline_pool(this);
  Trunc_uw_d(t8, fs, scratch);
1855
  mtc1(t8, fd);
1856 1857
}

1858
void TurboAssembler::Trunc_uw_s(FPURegister fd, FPURegister fs,
1859
                                FPURegister scratch) {
1860 1861
  BlockTrampolinePoolScope block_trampoline_pool(this);
  Trunc_uw_s(t8, fs, scratch);
1862 1863
  mtc1(t8, fd);
}
1864

1865
void TurboAssembler::Trunc_w_d(FPURegister fd, FPURegister fs) {
1866
  if (IsMipsArchVariant(kLoongson) && fd == fs) {
1867
    BlockTrampolinePoolScope block_trampoline_pool(this);
1868
    Mfhc1(t8, fs);
1869
    trunc_w_d(fd, fs);
1870
    Mthc1(t8, fs);
1871 1872 1873 1874 1875
  } else {
    trunc_w_d(fd, fs);
  }
}

1876
void TurboAssembler::Round_w_d(FPURegister fd, FPURegister fs) {
1877
  if (IsMipsArchVariant(kLoongson) && fd == fs) {
1878
    BlockTrampolinePoolScope block_trampoline_pool(this);
1879
    Mfhc1(t8, fs);
1880
    round_w_d(fd, fs);
1881
    Mthc1(t8, fs);
1882 1883 1884 1885 1886
  } else {
    round_w_d(fd, fs);
  }
}

1887
void TurboAssembler::Floor_w_d(FPURegister fd, FPURegister fs) {
1888
  if (IsMipsArchVariant(kLoongson) && fd == fs) {
1889
    BlockTrampolinePoolScope block_trampoline_pool(this);
1890
    Mfhc1(t8, fs);
1891
    floor_w_d(fd, fs);
1892
    Mthc1(t8, fs);
1893 1894 1895 1896 1897
  } else {
    floor_w_d(fd, fs);
  }
}

1898
void TurboAssembler::Ceil_w_d(FPURegister fd, FPURegister fs) {
1899
  if (IsMipsArchVariant(kLoongson) && fd == fs) {
1900
    BlockTrampolinePoolScope block_trampoline_pool(this);
1901
    Mfhc1(t8, fs);
1902
    ceil_w_d(fd, fs);
1903
    Mthc1(t8, fs);
1904 1905 1906 1907 1908
  } else {
    ceil_w_d(fd, fs);
  }
}

1909
void TurboAssembler::Trunc_uw_d(Register rd, FPURegister fs,
1910
                                FPURegister scratch) {
1911 1912
  DCHECK(fs != scratch);
  DCHECK(rd != at);
1913

1914 1915 1916 1917 1918 1919 1920 1921
  {
    // Load 2^31 into scratch as its float representation.
    UseScratchRegisterScope temps(this);
    Register scratch1 = temps.Acquire();
    li(scratch1, 0x41E00000);
    mtc1(zero_reg, scratch);
    Mthc1(scratch1, scratch);
  }
1922 1923
  // Test if scratch > fs.
  // If fs < 2^31 we can convert it normally.
1924
  Label simple_convert;
1925
  CompareF64(OLT, fs, scratch);
1926
  BranchTrueShortF(&simple_convert);
1927

1928 1929 1930
  // First we subtract 2^31 from fs, then trunc it to rd
  // and add 2^31 to rd.
  sub_d(scratch, fs, scratch);
1931
  trunc_w_d(scratch, scratch);
1932 1933
  mfc1(rd, scratch);
  Or(rd, rd, 1 << 31);
1934 1935 1936 1937 1938

  Label done;
  Branch(&done);
  // Simple conversion.
  bind(&simple_convert);
1939 1940
  trunc_w_d(scratch, fs);
  mfc1(rd, scratch);
1941 1942 1943 1944

  bind(&done);
}

1945
void TurboAssembler::Trunc_uw_s(Register rd, FPURegister fs,
1946
                                FPURegister scratch) {
1947 1948
  DCHECK(fs != scratch);
  DCHECK(rd != at);
1949

1950 1951 1952 1953 1954 1955 1956
  {
    // Load 2^31 into scratch as its float representation.
    UseScratchRegisterScope temps(this);
    Register scratch1 = temps.Acquire();
    li(scratch1, 0x4F000000);
    mtc1(scratch1, scratch);
  }
1957 1958
  // Test if scratch > fs.
  // If fs < 2^31 we can convert it normally.
1959
  Label simple_convert;
1960
  CompareF32(OLT, fs, scratch);
1961
  BranchTrueShortF(&simple_convert);
1962

1963 1964 1965
  // First we subtract 2^31 from fs, then trunc it to rd
  // and add 2^31 to rd.
  sub_s(scratch, fs, scratch);
1966
  trunc_w_s(scratch, scratch);
1967 1968
  mfc1(rd, scratch);
  Or(rd, rd, 1 << 31);
1969 1970 1971 1972 1973

  Label done;
  Branch(&done);
  // Simple conversion.
  bind(&simple_convert);
1974 1975
  trunc_w_s(scratch, fs);
  mfc1(rd, scratch);
1976 1977 1978

  bind(&done);
}
1979

1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
template <typename RoundFunc>
void TurboAssembler::RoundDouble(FPURegister dst, FPURegister src,
                                 FPURoundingMode mode, RoundFunc round) {
  BlockTrampolinePoolScope block_trampoline_pool(this);
  Register scratch = t8;
  Register scratch2 = t9;
  if (IsMipsArchVariant(kMips32r6)) {
    cfc1(scratch, FCSR);
    li(at, Operand(mode));
    ctc1(at, FCSR);
    rint_d(dst, src);
    ctc1(scratch, FCSR);
  } else {
    Label done;
    Mfhc1(scratch, src);
    Ext(at, scratch, HeapNumber::kExponentShift, HeapNumber::kExponentBits);
    Branch(USE_DELAY_SLOT, &done, hs, at,
           Operand(HeapNumber::kExponentBias + HeapNumber::kMantissaBits));
    mov_d(dst, src);
    round(this, dst, src);
    Move(at, scratch2, dst);
    or_(at, at, scratch2);
    Branch(USE_DELAY_SLOT, &done, ne, at, Operand(zero_reg));
    cvt_d_l(dst, dst);
    srl(at, scratch, 31);
    sll(at, at, 31);
    Mthc1(at, dst);
    bind(&done);
  }
}

void TurboAssembler::Floor_d_d(FPURegister dst, FPURegister src) {
  RoundDouble(dst, src, mode_floor,
              [](TurboAssembler* tasm, FPURegister dst, FPURegister src) {
                tasm->floor_l_d(dst, src);
              });
}

void TurboAssembler::Ceil_d_d(FPURegister dst, FPURegister src) {
  RoundDouble(dst, src, mode_ceil,
              [](TurboAssembler* tasm, FPURegister dst, FPURegister src) {
                tasm->ceil_l_d(dst, src);
              });
}

void TurboAssembler::Trunc_d_d(FPURegister dst, FPURegister src) {
  RoundDouble(dst, src, mode_trunc,
              [](TurboAssembler* tasm, FPURegister dst, FPURegister src) {
                tasm->trunc_l_d(dst, src);
              });
}

void TurboAssembler::Round_d_d(FPURegister dst, FPURegister src) {
  RoundDouble(dst, src, mode_round,
              [](TurboAssembler* tasm, FPURegister dst, FPURegister src) {
                tasm->round_l_d(dst, src);
              });
}

template <typename RoundFunc>
void TurboAssembler::RoundFloat(FPURegister dst, FPURegister src,
                                FPURoundingMode mode, RoundFunc round) {
  BlockTrampolinePoolScope block_trampoline_pool(this);
  Register scratch = t8;
  if (IsMipsArchVariant(kMips32r6)) {
    cfc1(scratch, FCSR);
    li(at, Operand(mode));
    ctc1(at, FCSR);
    rint_s(dst, src);
    ctc1(scratch, FCSR);
  } else {
    int32_t kFloat32ExponentBias = 127;
    int32_t kFloat32MantissaBits = 23;
    int32_t kFloat32ExponentBits = 8;
    Label done;
2055 2056 2057
    if (!IsDoubleZeroRegSet()) {
      Move(kDoubleRegZero, 0.0);
    }
2058 2059 2060 2061
    mfc1(scratch, src);
    Ext(at, scratch, kFloat32MantissaBits, kFloat32ExponentBits);
    Branch(USE_DELAY_SLOT, &done, hs, at,
           Operand(kFloat32ExponentBias + kFloat32MantissaBits));
2062 2063
    // Canonicalize the result.
    sub_s(dst, src, kDoubleRegZero);
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 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
    round(this, dst, src);
    mfc1(at, dst);
    Branch(USE_DELAY_SLOT, &done, ne, at, Operand(zero_reg));
    cvt_s_w(dst, dst);
    srl(at, scratch, 31);
    sll(at, at, 31);
    mtc1(at, dst);
    bind(&done);
  }
}

void TurboAssembler::Floor_s_s(FPURegister dst, FPURegister src) {
  RoundFloat(dst, src, mode_floor,
             [](TurboAssembler* tasm, FPURegister dst, FPURegister src) {
               tasm->floor_w_s(dst, src);
             });
}

void TurboAssembler::Ceil_s_s(FPURegister dst, FPURegister src) {
  RoundFloat(dst, src, mode_ceil,
             [](TurboAssembler* tasm, FPURegister dst, FPURegister src) {
               tasm->ceil_w_s(dst, src);
             });
}

void TurboAssembler::Trunc_s_s(FPURegister dst, FPURegister src) {
  RoundFloat(dst, src, mode_trunc,
             [](TurboAssembler* tasm, FPURegister dst, FPURegister src) {
               tasm->trunc_w_s(dst, src);
             });
}

void TurboAssembler::Round_s_s(FPURegister dst, FPURegister src) {
  RoundFloat(dst, src, mode_round,
             [](TurboAssembler* tasm, FPURegister dst, FPURegister src) {
               tasm->round_w_s(dst, src);
             });
}

2103
void TurboAssembler::Mthc1(Register rt, FPURegister fs) {
2104
  if (IsFp32Mode()) {
2105
    mtc1(rt, fs.high());
2106 2107 2108 2109
  } else {
    DCHECK(IsFp64Mode() || IsFpxxMode());
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6));
    mthc1(rt, fs);
2110 2111 2112
  }
}

2113
void TurboAssembler::Mfhc1(Register rt, FPURegister fs) {
2114
  if (IsFp32Mode()) {
2115
    mfc1(rt, fs.high());
2116 2117 2118 2119
  } else {
    DCHECK(IsFp64Mode() || IsFpxxMode());
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6));
    mfhc1(rt, fs);
2120 2121 2122
  }
}

2123
void TurboAssembler::Madd_s(FPURegister fd, FPURegister fr, FPURegister fs,
2124 2125 2126 2127
                            FPURegister ft, FPURegister scratch) {
  if (IsMipsArchVariant(kMips32r2)) {
    madd_s(fd, fr, fs, ft);
  } else {
2128
    DCHECK(fr != scratch && fs != scratch && ft != scratch);
2129 2130 2131 2132 2133
    mul_s(scratch, fs, ft);
    add_s(fd, fr, scratch);
  }
}

2134
void TurboAssembler::Madd_d(FPURegister fd, FPURegister fr, FPURegister fs,
2135 2136 2137 2138
                            FPURegister ft, FPURegister scratch) {
  if (IsMipsArchVariant(kMips32r2)) {
    madd_d(fd, fr, fs, ft);
  } else {
2139
    DCHECK(fr != scratch && fs != scratch && ft != scratch);
2140 2141 2142 2143 2144
    mul_d(scratch, fs, ft);
    add_d(fd, fr, scratch);
  }
}

2145
void TurboAssembler::Msub_s(FPURegister fd, FPURegister fr, FPURegister fs,
2146 2147 2148 2149
                            FPURegister ft, FPURegister scratch) {
  if (IsMipsArchVariant(kMips32r2)) {
    msub_s(fd, fr, fs, ft);
  } else {
2150
    DCHECK(fr != scratch && fs != scratch && ft != scratch);
2151 2152 2153 2154 2155
    mul_s(scratch, fs, ft);
    sub_s(fd, scratch, fr);
  }
}

2156
void TurboAssembler::Msub_d(FPURegister fd, FPURegister fr, FPURegister fs,
2157 2158 2159 2160
                            FPURegister ft, FPURegister scratch) {
  if (IsMipsArchVariant(kMips32r2)) {
    msub_d(fd, fr, fs, ft);
  } else {
2161
    DCHECK(fr != scratch && fs != scratch && ft != scratch);
2162 2163 2164 2165
    mul_d(scratch, fs, ft);
    sub_d(fd, scratch, fr);
  }
}
2166

2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
void TurboAssembler::CompareF(SecondaryField sizeField, FPUCondition cc,
                              FPURegister cmp1, FPURegister cmp2) {
  if (IsMipsArchVariant(kMips32r6)) {
    sizeField = sizeField == D ? L : W;
    DCHECK(cmp1 != kDoubleCompareReg && cmp2 != kDoubleCompareReg);
    cmp(cc, sizeField, kDoubleCompareReg, cmp1, cmp2);
  } else {
    c(cc, sizeField, cmp1, cmp2);
  }
}
2177

2178 2179 2180 2181
void TurboAssembler::CompareIsNanF(SecondaryField sizeField, FPURegister cmp1,
                                   FPURegister cmp2) {
  CompareF(sizeField, UN, cmp1, cmp2);
}
2182

2183
void TurboAssembler::BranchTrueShortF(Label* target, BranchDelaySlot bd) {
2184 2185 2186 2187
  if (IsMipsArchVariant(kMips32r6)) {
    bc1nez(target, kDoubleCompareReg);
  } else {
    bc1t(target);
2188 2189
  }
  if (bd == PROTECT) {
2190
    nop();
2191
  }
2192
}
2193

2194
void TurboAssembler::BranchFalseShortF(Label* target, BranchDelaySlot bd) {
2195 2196
  if (IsMipsArchVariant(kMips32r6)) {
    bc1eqz(target, kDoubleCompareReg);
2197
  } else {
2198
    bc1f(target);
2199 2200
  }
  if (bd == PROTECT) {
2201 2202 2203 2204
    nop();
  }
}

2205
void TurboAssembler::BranchTrueF(Label* target, BranchDelaySlot bd) {
2206 2207 2208 2209 2210
  bool long_branch =
      target->is_bound() ? !is_near(target) : is_trampoline_emitted();
  if (long_branch) {
    Label skip;
    BranchFalseShortF(&skip);
2211
    BranchLong(target, bd);
2212 2213
    bind(&skip);
  } else {
2214
    BranchTrueShortF(target, bd);
2215 2216 2217
  }
}

2218
void TurboAssembler::BranchFalseF(Label* target, BranchDelaySlot bd) {
2219 2220 2221 2222 2223
  bool long_branch =
      target->is_bound() ? !is_near(target) : is_trampoline_emitted();
  if (long_branch) {
    Label skip;
    BranchTrueShortF(&skip);
2224
    BranchLong(target, bd);
2225 2226
    bind(&skip);
  } else {
2227
    BranchFalseShortF(target, bd);
2228 2229 2230
  }
}

2231
void TurboAssembler::BranchMSA(Label* target, MSABranchDF df,
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
                               MSABranchCondition cond, MSARegister wt,
                               BranchDelaySlot bd) {
  {
    BlockTrampolinePoolScope block_trampoline_pool(this);

    if (target) {
      bool long_branch =
          target->is_bound() ? !is_near(target) : is_trampoline_emitted();
      if (long_branch) {
        Label skip;
        MSABranchCondition neg_cond = NegateMSABranchCondition(cond);
        BranchShortMSA(df, &skip, neg_cond, wt, bd);
        BranchLong(target, bd);
        bind(&skip);
      } else {
        BranchShortMSA(df, target, cond, wt, bd);
      }
    }
  }
}

2253
void TurboAssembler::BranchShortMSA(MSABranchDF df, Label* target,
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 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306
                                    MSABranchCondition cond, MSARegister wt,
                                    BranchDelaySlot bd) {
  if (IsMipsArchVariant(kMips32r6)) {
    BlockTrampolinePoolScope block_trampoline_pool(this);
    if (target) {
      switch (cond) {
        case all_not_zero:
          switch (df) {
            case MSA_BRANCH_D:
              bnz_d(wt, target);
              break;
            case MSA_BRANCH_W:
              bnz_w(wt, target);
              break;
            case MSA_BRANCH_H:
              bnz_h(wt, target);
              break;
            case MSA_BRANCH_B:
            default:
              bnz_b(wt, target);
          }
          break;
        case one_elem_not_zero:
          bnz_v(wt, target);
          break;
        case one_elem_zero:
          switch (df) {
            case MSA_BRANCH_D:
              bz_d(wt, target);
              break;
            case MSA_BRANCH_W:
              bz_w(wt, target);
              break;
            case MSA_BRANCH_H:
              bz_h(wt, target);
              break;
            case MSA_BRANCH_B:
            default:
              bz_b(wt, target);
          }
          break;
        case all_zero:
          bz_v(wt, target);
          break;
        default:
          UNREACHABLE();
      }
    }
  }
  if (bd == PROTECT) {
    nop();
  }
}
2307

2308
void TurboAssembler::FmoveLow(FPURegister dst, Register src_low) {
2309 2310 2311 2312 2313
  if (IsFp32Mode()) {
    mtc1(src_low, dst);
  } else {
    DCHECK(IsFp64Mode() || IsFpxxMode());
    DCHECK(IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6));
2314 2315
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
2316
    DCHECK(src_low != scratch);
2317
    mfhc1(scratch, dst);
2318
    mtc1(src_low, dst);
2319
    mthc1(scratch, dst);
2320 2321 2322
  }
}

2323
void TurboAssembler::Move(FPURegister dst, uint32_t src) {
2324 2325
  UseScratchRegisterScope temps(this);
  Register scratch = temps.Acquire();
2326
  li(scratch, Operand(static_cast<int32_t>(src)));
2327
  mtc1(scratch, dst);
2328 2329
}

2330
void TurboAssembler::Move(FPURegister dst, uint64_t src) {
2331
  // Handle special values first.
2332
  if (src == bit_cast<uint64_t>(0.0) && has_double_zero_reg_set_) {
2333
    mov_d(dst, kDoubleRegZero);
2334
  } else if (src == bit_cast<uint64_t>(-0.0) && has_double_zero_reg_set_) {
2335
    Neg_d(dst, kDoubleRegZero);
2336
  } else {
2337 2338
    uint32_t lo = src & 0xFFFFFFFF;
    uint32_t hi = src >> 32;
2339 2340 2341
    // Move the low part of the double into the lower of the corresponding FPU
    // register of FPU register pair.
    if (lo != 0) {
2342 2343 2344 2345
      UseScratchRegisterScope temps(this);
      Register scratch = temps.Acquire();
      li(scratch, Operand(lo));
      mtc1(scratch, dst);
2346 2347 2348 2349 2350 2351
    } else {
      mtc1(zero_reg, dst);
    }
    // Move the high part of the double into the higher of the corresponding FPU
    // register of FPU register pair.
    if (hi != 0) {
2352 2353 2354 2355
      UseScratchRegisterScope temps(this);
      Register scratch = temps.Acquire();
      li(scratch, Operand(hi));
      Mthc1(scratch, dst);
2356
    } else {
2357
      Mthc1(zero_reg, dst);
2358
    }
2359
    if (dst == kDoubleRegZero) has_double_zero_reg_set_ = true;
2360 2361 2362
  }
}

2363 2364
void TurboAssembler::LoadZeroOnCondition(Register rd, Register rs,
                                         const Operand& rt, Condition cond) {
2365
  BlockTrampolinePoolScope block_trampoline_pool(this);
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 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 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 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
  switch (cond) {
    case cc_always:
      mov(rd, zero_reg);
      break;
    case eq:
      if (rs == zero_reg) {
        if (rt.is_reg()) {
          LoadZeroIfConditionZero(rd, rt.rm());
        } else {
          if (rt.immediate() == 0) {
            mov(rd, zero_reg);
          } else {
            nop();
          }
        }
      } else if (IsZero(rt)) {
        LoadZeroIfConditionZero(rd, rs);
      } else {
        Subu(t9, rs, rt);
        LoadZeroIfConditionZero(rd, t9);
      }
      break;
    case ne:
      if (rs == zero_reg) {
        if (rt.is_reg()) {
          LoadZeroIfConditionNotZero(rd, rt.rm());
        } else {
          if (rt.immediate() != 0) {
            mov(rd, zero_reg);
          } else {
            nop();
          }
        }
      } else if (IsZero(rt)) {
        LoadZeroIfConditionNotZero(rd, rs);
      } else {
        Subu(t9, rs, rt);
        LoadZeroIfConditionNotZero(rd, t9);
      }
      break;

    // Signed comparison.
    case greater:
      Sgt(t9, rs, rt);
      LoadZeroIfConditionNotZero(rd, t9);
      break;
    case greater_equal:
      Sge(t9, rs, rt);
      LoadZeroIfConditionNotZero(rd, t9);
      // rs >= rt
      break;
    case less:
      Slt(t9, rs, rt);
      LoadZeroIfConditionNotZero(rd, t9);
      // rs < rt
      break;
    case less_equal:
      Sle(t9, rs, rt);
      LoadZeroIfConditionNotZero(rd, t9);
      // rs <= rt
      break;

    // Unsigned comparison.
    case Ugreater:
      Sgtu(t9, rs, rt);
      LoadZeroIfConditionNotZero(rd, t9);
      // rs > rt
      break;

    case Ugreater_equal:
      Sgeu(t9, rs, rt);
      LoadZeroIfConditionNotZero(rd, t9);
      // rs >= rt
      break;
    case Uless:
      Sltu(t9, rs, rt);
      LoadZeroIfConditionNotZero(rd, t9);
      // rs < rt
      break;
    case Uless_equal:
      Sleu(t9, rs, rt);
      LoadZeroIfConditionNotZero(rd, t9);
      // rs <= rt
      break;
    default:
      UNREACHABLE();
  }
}

void TurboAssembler::LoadZeroIfConditionNotZero(Register dest,
                                                Register condition) {
  if (IsMipsArchVariant(kMips32r6)) {
    seleqz(dest, dest, condition);
  } else {
    Movn(dest, zero_reg, condition);
  }
}

void TurboAssembler::LoadZeroIfConditionZero(Register dest,
                                             Register condition) {
  if (IsMipsArchVariant(kMips32r6)) {
    selnez(dest, dest, condition);
  } else {
    Movz(dest, zero_reg, condition);
  }
}

2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
void TurboAssembler::LoadZeroIfFPUCondition(Register dest) {
  if (IsMipsArchVariant(kMips32r6)) {
    mfc1(kScratchReg, kDoubleCompareReg);
    LoadZeroIfConditionNotZero(dest, kScratchReg);
  } else {
    Movt(dest, zero_reg);
  }
}

void TurboAssembler::LoadZeroIfNotFPUCondition(Register dest) {
  if (IsMipsArchVariant(kMips32r6)) {
    mfc1(kScratchReg, kDoubleCompareReg);
    LoadZeroIfConditionZero(dest, kScratchReg);
  } else {
    Movf(dest, zero_reg);
  }
}

2491
void TurboAssembler::Movz(Register rd, Register rs, Register rt) {
2492
  if (IsMipsArchVariant(kLoongson) || IsMipsArchVariant(kMips32r6)) {
2493 2494 2495 2496 2497 2498 2499 2500 2501
    Label done;
    Branch(&done, ne, rt, Operand(zero_reg));
    mov(rd, rs);
    bind(&done);
  } else {
    movz(rd, rs, rt);
  }
}

2502
void TurboAssembler::Movn(Register rd, Register rs, Register rt) {
2503
  if (IsMipsArchVariant(kLoongson) || IsMipsArchVariant(kMips32r6)) {
2504 2505 2506 2507 2508 2509 2510 2511 2512
    Label done;
    Branch(&done, eq, rt, Operand(zero_reg));
    mov(rd, rs);
    bind(&done);
  } else {
    movn(rd, rs, rt);
  }
}

2513
void TurboAssembler::Movt(Register rd, Register rs, uint16_t cc) {
2514
  if (IsMipsArchVariant(kLoongson)) {
2515
    BlockTrampolinePoolScope block_trampoline_pool(this);
2516 2517
    // Tests an FP condition code and then conditionally move rs to rd.
    // We do not currently use any FPU cc bit other than bit 0.
2518
    DCHECK_EQ(cc, 0);
2519
    DCHECK(rs != t8 && rd != t8);
2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
    Label done;
    Register scratch = t8;
    // For testing purposes we need to fetch content of the FCSR register and
    // than test its cc (floating point condition code) bit (for cc = 0, it is
    // 24. bit of the FCSR).
    cfc1(scratch, FCSR);
    // For the MIPS I, II and III architectures, the contents of scratch is
    // UNPREDICTABLE for the instruction immediately following CFC1.
    nop();
    srl(scratch, scratch, 16);
    andi(scratch, scratch, 0x0080);
    Branch(&done, eq, scratch, Operand(zero_reg));
    mov(rd, rs);
    bind(&done);
  } else {
    movt(rd, rs, cc);
  }
}

2539
void TurboAssembler::Movf(Register rd, Register rs, uint16_t cc) {
2540
  if (IsMipsArchVariant(kLoongson)) {
2541
    BlockTrampolinePoolScope block_trampoline_pool(this);
2542 2543
    // Tests an FP condition code and then conditionally move rs to rd.
    // We do not currently use any FPU cc bit other than bit 0.
2544
    DCHECK_EQ(cc, 0);
2545
    DCHECK(rs != t8 && rd != t8);
2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
    Label done;
    Register scratch = t8;
    // For testing purposes we need to fetch content of the FCSR register and
    // than test its cc (floating point condition code) bit (for cc = 0, it is
    // 24. bit of the FCSR).
    cfc1(scratch, FCSR);
    // For the MIPS I, II and III architectures, the contents of scratch is
    // UNPREDICTABLE for the instruction immediately following CFC1.
    nop();
    srl(scratch, scratch, 16);
    andi(scratch, scratch, 0x0080);
    Branch(&done, ne, scratch, Operand(zero_reg));
    mov(rd, rs);
    bind(&done);
  } else {
    movf(rd, rs, cc);
  }
}

2565
void TurboAssembler::Clz(Register rd, Register rs) {
2566
  if (IsMipsArchVariant(kLoongson)) {
2567
    BlockTrampolinePoolScope block_trampoline_pool(this);
2568
    DCHECK(rd != t8 && rd != t9 && rs != t8 && rs != t9);
2569 2570 2571
    Register mask = t8;
    Register scratch = t9;
    Label loop, end;
2572 2573 2574 2575 2576 2577 2578 2579 2580
    {
      UseScratchRegisterScope temps(this);
      Register scratch1 = temps.Acquire();
      mov(scratch1, rs);
      mov(rd, zero_reg);
      lui(mask, 0x8000);
      bind(&loop);
      and_(scratch, scratch1, mask);
    }
2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
    Branch(&end, ne, scratch, Operand(zero_reg));
    addiu(rd, rd, 1);
    Branch(&loop, ne, mask, Operand(zero_reg), USE_DELAY_SLOT);
    srl(mask, mask, 1);
    bind(&end);
  } else {
    clz(rd, rs);
  }
}

2591 2592 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
void TurboAssembler::Ctz(Register rd, Register rs) {
  if (IsMipsArchVariant(kMips32r6)) {
    // We don't have an instruction to count the number of trailing zeroes.
    // Start by flipping the bits end-for-end so we can count the number of
    // leading zeroes instead.
    Ror(rd, rs, 16);
    wsbh(rd, rd);
    bitswap(rd, rd);
    Clz(rd, rd);
  } else {
    // Convert trailing zeroes to trailing ones, and bits to their left
    // to zeroes.
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
    Addu(scratch, rs, -1);
    Xor(rd, scratch, rs);
    And(rd, rd, scratch);
    // Count number of leading zeroes.
    Clz(rd, rd);
    // Subtract number of leading zeroes from 32 to get number of trailing
    // ones. Remember that the trailing ones were formerly trailing zeroes.
    li(scratch, 32);
    Subu(rd, scratch, rd);
  }
}

void TurboAssembler::Popcnt(Register rd, Register rs) {
2618
  ASM_CODE_COMMENT(this);
2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
  // https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
  //
  // A generalization of the best bit counting method to integers of
  // bit-widths up to 128 (parameterized by type T) is this:
  //
  // v = v - ((v >> 1) & (T)~(T)0/3);                           // temp
  // v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);      // temp
  // v = (v + (v >> 4)) & (T)~(T)0/255*15;                      // temp
  // c = (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * BITS_PER_BYTE; //count
  //
  // For comparison, for 32-bit quantities, this algorithm can be executed
  // using 20 MIPS instructions (the calls to LoadConst32() generate two
  // machine instructions each for the values being used in this algorithm).
  // A(n unrolled) loop-based algorithm requires 25 instructions.
  //
  // For 64-bit quantities, this algorithm gets executed twice, (once
  // for in_lo, and again for in_hi), but saves a few instructions
  // because the mask values only have to be loaded once. Using this
  // algorithm the count for a 64-bit operand can be performed in 29
  // instructions compared to a loop-based algorithm which requires 47
  // instructions.
  uint32_t B0 = 0x55555555;     // (T)~(T)0/3
  uint32_t B1 = 0x33333333;     // (T)~(T)0/15*3
  uint32_t B2 = 0x0F0F0F0F;     // (T)~(T)0/255*15
  uint32_t value = 0x01010101;  // (T)~(T)0/255
  uint32_t shift = 24;          // (sizeof(T) - 1) * BITS_PER_BYTE
2645
  BlockTrampolinePoolScope block_trampoline_pool(this);
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665
  UseScratchRegisterScope temps(this);
  Register scratch = temps.Acquire();
  Register scratch2 = t8;
  srl(scratch, rs, 1);
  li(scratch2, B0);
  And(scratch, scratch, scratch2);
  Subu(scratch, rs, scratch);
  li(scratch2, B1);
  And(rd, scratch, scratch2);
  srl(scratch, scratch, 2);
  And(scratch, scratch, scratch2);
  Addu(scratch, rd, scratch);
  srl(rd, scratch, 4);
  Addu(rd, rd, scratch);
  li(scratch2, B2);
  And(rd, rd, scratch2);
  li(scratch, value);
  Mul(rd, rd, scratch);
  srl(rd, rd, shift);
}
2666

2667
void TurboAssembler::TryInlineTruncateDoubleToI(Register result,
2668 2669
                                                DoubleRegister double_input,
                                                Label* done) {
2670
  BlockTrampolinePoolScope block_trampoline_pool(this);
2671
  DoubleRegister single_scratch = kScratchDoubleReg.low();
2672
  Register scratch = t9;
2673 2674 2675 2676

  // Try a conversion to a signed integer.
  trunc_w_d(single_scratch, double_input);
  mfc1(result, single_scratch);
2677
  // Retrieve the FCSR.
2678 2679
  cfc1(scratch, FCSR);
  // Check for overflow and NaNs.
2680
  And(scratch, scratch,
2681 2682
      kFCSROverflowCauseMask | kFCSRUnderflowCauseMask |
          kFCSRInvalidOpCauseMask);
2683
  // If we had no exceptions we are done.
2684 2685 2686
  Branch(done, eq, scratch, Operand(zero_reg));
}

2687 2688
void TurboAssembler::TruncateDoubleToI(Isolate* isolate, Zone* zone,
                                       Register result,
2689 2690
                                       DoubleRegister double_input,
                                       StubCallMode stub_mode) {
2691 2692 2693 2694 2695 2696 2697
  Label done;

  TryInlineTruncateDoubleToI(result, double_input, &done);

  // If we fell through then inline version didn't succeed - call stub instead.
  push(ra);
  Subu(sp, sp, Operand(kDoubleSize));  // Put input on stack.
2698
  Sdc1(double_input, MemOperand(sp, 0));
2699

2700
#if V8_ENABLE_WEBASSEMBLY
2701
  if (stub_mode == StubCallMode::kCallWasmRuntimeStub) {
2702
    Call(wasm::WasmCode::kDoubleToI, RelocInfo::WASM_STUB_CALL);
2703
#else
2704 2705
  // For balance.
  if (false) {
2706
#endif  // V8_ENABLE_WEBASSEMBLY
2707 2708 2709
  } else {
    Call(BUILTIN_CODE(isolate, DoubleToI), RelocInfo::CODE_TARGET);
  }
2710
  lw(result, MemOperand(sp, 0));
2711 2712 2713 2714 2715 2716 2717

  Addu(sp, sp, Operand(kDoubleSize));
  pop(ra);

  bind(&done);
}

2718 2719 2720
// Emulated condtional branches do not emit a nop in the branch delay slot.
//
// BRANCH_ARGS_CHECK checks that conditional jump arguments are correct.
2721 2722 2723
#define BRANCH_ARGS_CHECK(cond, rs, rt)                                  \
  DCHECK((cond == cc_always && rs == zero_reg && rt.rm() == zero_reg) || \
         (cond != cc_always && (rs != zero_reg || rt.rm() != zero_reg)))
2724

2725
void TurboAssembler::Branch(int32_t offset, BranchDelaySlot bdslot) {
2726
  DCHECK(IsMipsArchVariant(kMips32r6) ? is_int26(offset) : is_int16(offset));
2727 2728 2729
  BranchShort(offset, bdslot);
}

2730
void TurboAssembler::Branch(int32_t offset, Condition cond, Register rs,
2731 2732 2733 2734
                            const Operand& rt, BranchDelaySlot bdslot) {
  bool is_near = BranchShortCheck(offset, nullptr, cond, rs, rt, bdslot);
  DCHECK(is_near);
  USE(is_near);
2735 2736
}

2737
void TurboAssembler::Branch(Label* L, BranchDelaySlot bdslot) {
2738
  if (L->is_bound()) {
2739
    if (is_near_branch(L)) {
2740 2741
      BranchShort(L, bdslot);
    } else {
2742
      BranchLong(L, bdslot);
2743
    }
2744
  } else {
2745
    if (is_trampoline_emitted()) {
2746
      BranchLong(L, bdslot);
2747 2748 2749
    } else {
      BranchShort(L, bdslot);
    }
2750 2751 2752
  }
}

2753 2754
void TurboAssembler::Branch(Label* L, Condition cond, Register rs,
                            const Operand& rt, BranchDelaySlot bdslot) {
2755
  if (L->is_bound()) {
2756
    if (!BranchShortCheck(0, L, cond, rs, rt, bdslot)) {
2757 2758 2759 2760
      if (cond != cc_always) {
        Label skip;
        Condition neg_cond = NegateCondition(cond);
        BranchShort(&skip, neg_cond, rs, rt);
2761
        BranchLong(L, bdslot);
2762 2763
        bind(&skip);
      } else {
2764
        BranchLong(L, bdslot);
2765
      }
2766
    }
2767
  } else {
2768
    if (is_trampoline_emitted()) {
2769 2770 2771 2772
      if (cond != cc_always) {
        Label skip;
        Condition neg_cond = NegateCondition(cond);
        BranchShort(&skip, neg_cond, rs, rt);
2773
        BranchLong(L, bdslot);
2774 2775
        bind(&skip);
      } else {
2776
        BranchLong(L, bdslot);
2777
      }
2778 2779 2780
    } else {
      BranchShort(L, cond, rs, rt, bdslot);
    }
2781 2782 2783
  }
}

2784
void TurboAssembler::Branch(Label* L, Condition cond, Register rs,
2785
                            RootIndex index, BranchDelaySlot bdslot) {
2786 2787 2788 2789
  UseScratchRegisterScope temps(this);
  Register scratch = temps.Acquire();
  LoadRoot(scratch, index);
  Branch(L, cond, rs, Operand(scratch), bdslot);
2790 2791
}

2792
void TurboAssembler::BranchShortHelper(int16_t offset, Label* L,
2793
                                       BranchDelaySlot bdslot) {
2794
  DCHECK(L == nullptr || offset == 0);
2795
  offset = GetOffset(offset, L, OffsetSize::kOffset16);
2796 2797 2798
  b(offset);

  // Emit a nop in the branch delay slot if required.
2799
  if (bdslot == PROTECT) nop();
2800 2801
}

2802
void TurboAssembler::BranchShortHelperR6(int32_t offset, Label* L) {
2803
  DCHECK(L == nullptr || offset == 0);
2804 2805 2806 2807
  offset = GetOffset(offset, L, OffsetSize::kOffset26);
  bc(offset);
}

2808
void TurboAssembler::BranchShort(int32_t offset, BranchDelaySlot bdslot) {
2809 2810 2811 2812 2813 2814 2815 2816 2817
  if (IsMipsArchVariant(kMips32r6) && bdslot == PROTECT) {
    DCHECK(is_int26(offset));
    BranchShortHelperR6(offset, nullptr);
  } else {
    DCHECK(is_int16(offset));
    BranchShortHelper(offset, nullptr, bdslot);
  }
}

2818
void TurboAssembler::BranchShort(Label* L, BranchDelaySlot bdslot) {
2819 2820 2821 2822 2823 2824 2825
  if (IsMipsArchVariant(kMips32r6) && bdslot == PROTECT) {
    BranchShortHelperR6(0, L);
  } else {
    BranchShortHelper(0, L, bdslot);
  }
}

2826
int32_t TurboAssembler::GetOffset(int32_t offset, Label* L, OffsetSize bits) {
2827 2828 2829 2830 2831 2832 2833 2834
  if (L) {
    offset = branch_offset_helper(L, bits) >> 2;
  } else {
    DCHECK(is_intn(offset, bits));
  }
  return offset;
}

2835
Register TurboAssembler::GetRtAsRegisterHelper(const Operand& rt,
2836 2837
                                               Register scratch) {
  Register r2 = no_reg;
2838
  if (rt.is_reg()) {
2839
    r2 = rt.rm();
2840
  } else {
2841 2842
    r2 = scratch;
    li(r2, rt);
2843
  }
2844 2845

  return r2;
2846 2847
}

2848
bool TurboAssembler::CalculateOffset(Label* L, int32_t* offset,
2849 2850
                                     OffsetSize bits) {
  if (!is_near(L, bits)) return false;
2851
  *offset = GetOffset(*offset, L, bits);
2852 2853 2854
  return true;
}

2855 2856
bool TurboAssembler::CalculateOffset(Label* L, int32_t* offset, OffsetSize bits,
                                     Register* scratch, const Operand& rt) {
2857
  if (!is_near(L, bits)) return false;
2858 2859
  *scratch = GetRtAsRegisterHelper(rt, *scratch);
  *offset = GetOffset(*offset, L, bits);
2860 2861 2862
  return true;
}

2863
bool TurboAssembler::BranchShortHelperR6(int32_t offset, Label* L,
2864 2865
                                         Condition cond, Register rs,
                                         const Operand& rt) {
2866
  DCHECK(L == nullptr || offset == 0);
2867 2868
  UseScratchRegisterScope temps(this);
  Register scratch = temps.hasAvailable() ? temps.Acquire() : t8;
2869 2870 2871 2872

  // Be careful to always use shifted_branch_offset only just before the
  // branch instruction, as the location will be remember for patching the
  // target.
2873 2874 2875 2876
  {
    BlockTrampolinePoolScope block_trampoline_pool(this);
    switch (cond) {
      case cc_always:
2877
        if (!CalculateOffset(L, &offset, OffsetSize::kOffset26)) return false;
2878
        bc(offset);
2879 2880
        break;
      case eq:
2881
        if (rt.is_reg() && rs.code() == rt.rm().code()) {
2882 2883
          // Pre R6 beq is used here to make the code patchable. Otherwise bc
          // should be used which has no condition field so is not patchable.
2884
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
2885
            return false;
2886 2887 2888
          beq(rs, scratch, offset);
          nop();
        } else if (IsZero(rt)) {
2889
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset21)) return false;
2890 2891 2892
          beqzc(rs, offset);
        } else {
          // We don't want any other register but scratch clobbered.
2893
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
2894
            return false;
2895 2896 2897 2898
          beqc(rs, scratch, offset);
        }
        break;
      case ne:
2899
        if (rt.is_reg() && rs.code() == rt.rm().code()) {
2900 2901
          // Pre R6 bne is used here to make the code patchable. Otherwise we
          // should not generate any instruction.
2902
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
2903
            return false;
2904 2905 2906
          bne(rs, scratch, offset);
          nop();
        } else if (IsZero(rt)) {
2907
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset21)) return false;
2908 2909 2910
          bnezc(rs, offset);
        } else {
          // We don't want any other register but scratch clobbered.
2911
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
2912
            return false;
2913 2914 2915
          bnec(rs, scratch, offset);
        }
        break;
2916

2917 2918 2919
      // Signed comparison.
      case greater:
        // rs > rt
2920
        if (rt.is_reg() && rs.code() == rt.rm().code()) {
2921
          break;  // No code needs to be emitted.
2922
        } else if (rs == zero_reg) {
2923
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
2924
            return false;
2925 2926
          bltzc(scratch, offset);
        } else if (IsZero(rt)) {
2927
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16)) return false;
2928 2929
          bgtzc(rs, offset);
        } else {
2930
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
2931
            return false;
2932
          DCHECK(rs != scratch);
2933 2934 2935 2936 2937
          bltc(scratch, rs, offset);
        }
        break;
      case greater_equal:
        // rs >= rt
2938
        if (rt.is_reg() && rs.code() == rt.rm().code()) {
2939
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset26)) return false;
2940
          bc(offset);
2941
        } else if (rs == zero_reg) {
2942
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
2943
            return false;
2944 2945
          blezc(scratch, offset);
        } else if (IsZero(rt)) {
2946
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16)) return false;
2947 2948
          bgezc(rs, offset);
        } else {
2949
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
2950
            return false;
2951
          DCHECK(rs != scratch);
2952 2953 2954 2955 2956
          bgec(rs, scratch, offset);
        }
        break;
      case less:
        // rs < rt
2957
        if (rt.is_reg() && rs.code() == rt.rm().code()) {
2958
          break;  // No code needs to be emitted.
2959
        } else if (rs == zero_reg) {
2960
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
2961
            return false;
2962 2963
          bgtzc(scratch, offset);
        } else if (IsZero(rt)) {
2964
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16)) return false;
2965 2966
          bltzc(rs, offset);
        } else {
2967
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
2968
            return false;
2969
          DCHECK(rs != scratch);
2970 2971 2972 2973 2974
          bltc(rs, scratch, offset);
        }
        break;
      case less_equal:
        // rs <= rt
2975
        if (rt.is_reg() && rs.code() == rt.rm().code()) {
2976
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset26)) return false;
2977
          bc(offset);
2978
        } else if (rs == zero_reg) {
2979
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
2980
            return false;
2981 2982
          bgezc(scratch, offset);
        } else if (IsZero(rt)) {
2983
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16)) return false;
2984 2985
          blezc(rs, offset);
        } else {
2986
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
2987
            return false;
2988
          DCHECK(rs != scratch);
2989 2990 2991 2992 2993 2994 2995
          bgec(scratch, rs, offset);
        }
        break;

      // Unsigned comparison.
      case Ugreater:
        // rs > rt
2996
        if (rt.is_reg() && rs.code() == rt.rm().code()) {
2997
          break;  // No code needs to be emitted.
2998
        } else if (rs == zero_reg) {
2999
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset21, &scratch, rt))
3000
            return false;
3001 3002
          bnezc(scratch, offset);
        } else if (IsZero(rt)) {
3003
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset21)) return false;
3004 3005
          bnezc(rs, offset);
        } else {
3006
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
3007
            return false;
3008
          DCHECK(rs != scratch);
3009 3010 3011 3012 3013
          bltuc(scratch, rs, offset);
        }
        break;
      case Ugreater_equal:
        // rs >= rt
3014
        if (rt.is_reg() && rs.code() == rt.rm().code()) {
3015
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset26)) return false;
3016
          bc(offset);
3017
        } else if (rs == zero_reg) {
3018
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset21, &scratch, rt))
3019
            return false;
3020 3021
          beqzc(scratch, offset);
        } else if (IsZero(rt)) {
3022
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset26)) return false;
3023 3024
          bc(offset);
        } else {
3025
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
3026
            return false;
3027
          DCHECK(rs != scratch);
3028 3029 3030 3031 3032
          bgeuc(rs, scratch, offset);
        }
        break;
      case Uless:
        // rs < rt
3033
        if (rt.is_reg() && rs.code() == rt.rm().code()) {
3034
          break;  // No code needs to be emitted.
3035
        } else if (rs == zero_reg) {
3036
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset21, &scratch, rt))
3037
            return false;
3038 3039 3040 3041
          bnezc(scratch, offset);
        } else if (IsZero(rt)) {
          break;  // No code needs to be emitted.
        } else {
3042
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
3043
            return false;
3044
          DCHECK(rs != scratch);
3045 3046 3047 3048 3049
          bltuc(rs, scratch, offset);
        }
        break;
      case Uless_equal:
        // rs <= rt
3050
        if (rt.is_reg() && rs.code() == rt.rm().code()) {
3051
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset26)) return false;
3052
          bc(offset);
3053
        } else if (rs == zero_reg) {
3054
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset26, &scratch, rt))
3055
            return false;
3056 3057
          bc(offset);
        } else if (IsZero(rt)) {
3058
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset21)) return false;
3059 3060
          beqzc(rs, offset);
        } else {
3061
          if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
3062
            return false;
3063
          DCHECK(rs != scratch);
3064 3065 3066 3067 3068 3069
          bgeuc(scratch, rs, offset);
        }
        break;
      default:
        UNREACHABLE();
    }
3070
  }
3071
  CheckTrampolinePoolQuick(1);
3072 3073 3074
  return true;
}

3075
bool TurboAssembler::BranchShortHelper(int16_t offset, Label* L, Condition cond,
3076 3077
                                       Register rs, const Operand& rt,
                                       BranchDelaySlot bdslot) {
3078
  DCHECK(L == nullptr || offset == 0);
3079 3080
  if (!is_near(L, OffsetSize::kOffset16)) return false;

3081 3082
  UseScratchRegisterScope temps(this);
  Register scratch = temps.hasAvailable() ? temps.Acquire() : t8;
3083 3084 3085 3086 3087
  int32_t offset32;

  // Be careful to always use shifted_branch_offset only just before the
  // branch instruction, as the location will be remember for patching the
  // target.
3088 3089 3090 3091
  {
    BlockTrampolinePoolScope block_trampoline_pool(this);
    switch (cond) {
      case cc_always:
3092
        offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
        b(offset32);
        break;
      case eq:
        if (IsZero(rt)) {
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          beq(rs, zero_reg, offset32);
        } else {
          // We don't want any other register but scratch clobbered.
          scratch = GetRtAsRegisterHelper(rt, scratch);
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          beq(rs, scratch, offset32);
        }
        break;
      case ne:
        if (IsZero(rt)) {
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          bne(rs, zero_reg, offset32);
        } else {
          // We don't want any other register but scratch clobbered.
          scratch = GetRtAsRegisterHelper(rt, scratch);
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          bne(rs, scratch, offset32);
        }
        break;
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 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
      // Signed comparison.
      case greater:
        if (IsZero(rt)) {
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          bgtz(rs, offset32);
        } else {
          Slt(scratch, GetRtAsRegisterHelper(rt, scratch), rs);
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          bne(scratch, zero_reg, offset32);
        }
        break;
      case greater_equal:
        if (IsZero(rt)) {
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          bgez(rs, offset32);
        } else {
          Slt(scratch, rs, rt);
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          beq(scratch, zero_reg, offset32);
        }
        break;
      case less:
        if (IsZero(rt)) {
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          bltz(rs, offset32);
        } else {
          Slt(scratch, rs, rt);
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          bne(scratch, zero_reg, offset32);
        }
        break;
      case less_equal:
        if (IsZero(rt)) {
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          blez(rs, offset32);
        } else {
          Slt(scratch, GetRtAsRegisterHelper(rt, scratch), rs);
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          beq(scratch, zero_reg, offset32);
        }
        break;
3159

3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202
      // Unsigned comparison.
      case Ugreater:
        if (IsZero(rt)) {
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          bne(rs, zero_reg, offset32);
        } else {
          Sltu(scratch, GetRtAsRegisterHelper(rt, scratch), rs);
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          bne(scratch, zero_reg, offset32);
        }
        break;
      case Ugreater_equal:
        if (IsZero(rt)) {
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          b(offset32);
        } else {
          Sltu(scratch, rs, rt);
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          beq(scratch, zero_reg, offset32);
        }
        break;
      case Uless:
        if (IsZero(rt)) {
          return true;  // No code needs to be emitted.
        } else {
          Sltu(scratch, rs, rt);
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          bne(scratch, zero_reg, offset32);
        }
        break;
      case Uless_equal:
        if (IsZero(rt)) {
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          beq(rs, zero_reg, offset32);
        } else {
          Sltu(scratch, GetRtAsRegisterHelper(rt, scratch), rs);
          offset32 = GetOffset(offset, L, OffsetSize::kOffset16);
          beq(scratch, zero_reg, offset32);
        }
        break;
      default:
        UNREACHABLE();
    }
3203
  }
3204
  // Emit a nop in the branch delay slot if required.
3205
  if (bdslot == PROTECT) nop();
3206 3207

  return true;
3208
}
3209

3210
bool TurboAssembler::BranchShortCheck(int32_t offset, Label* L, Condition cond,
3211 3212
                                      Register rs, const Operand& rt,
                                      BranchDelaySlot bdslot) {
3213
  BRANCH_ARGS_CHECK(cond, rs, rt);
3214 3215 3216 3217 3218 3219 3220
  if (!L) {
    if (IsMipsArchVariant(kMips32r6) && bdslot == PROTECT) {
      DCHECK(is_int26(offset));
      return BranchShortHelperR6(offset, nullptr, cond, rs, rt);
    } else {
      DCHECK(is_int16(offset));
      return BranchShortHelper(offset, nullptr, cond, rs, rt, bdslot);
3221 3222
    }
  } else {
3223
    DCHECK_EQ(offset, 0);
3224 3225 3226 3227
    if (IsMipsArchVariant(kMips32r6) && bdslot == PROTECT) {
      return BranchShortHelperR6(0, L, cond, rs, rt);
    } else {
      return BranchShortHelper(0, L, cond, rs, rt, bdslot);
3228
    }
3229
  }
3230 3231
}

3232
void TurboAssembler::BranchShort(int32_t offset, Condition cond, Register rs,
3233 3234
                                 const Operand& rt, BranchDelaySlot bdslot) {
  BranchShortCheck(offset, nullptr, cond, rs, rt, bdslot);
3235 3236
}

3237
void TurboAssembler::BranchShort(Label* L, Condition cond, Register rs,
3238 3239 3240 3241
                                 const Operand& rt, BranchDelaySlot bdslot) {
  BranchShortCheck(0, L, cond, rs, rt, bdslot);
}

3242
void TurboAssembler::BranchAndLink(int32_t offset, BranchDelaySlot bdslot) {
3243 3244 3245
  BranchAndLinkShort(offset, bdslot);
}

3246
void TurboAssembler::BranchAndLink(int32_t offset, Condition cond, Register rs,
3247 3248 3249 3250
                                   const Operand& rt, BranchDelaySlot bdslot) {
  bool is_near = BranchAndLinkShortCheck(offset, nullptr, cond, rs, rt, bdslot);
  DCHECK(is_near);
  USE(is_near);
3251 3252
}

3253
void TurboAssembler::BranchAndLink(Label* L, BranchDelaySlot bdslot) {
3254
  if (L->is_bound()) {
3255
    if (is_near_branch(L)) {
3256 3257
      BranchAndLinkShort(L, bdslot);
    } else {
3258
      BranchAndLinkLong(L, bdslot);
3259
    }
3260
  } else {
3261
    if (is_trampoline_emitted()) {
3262
      BranchAndLinkLong(L, bdslot);
3263 3264 3265
    } else {
      BranchAndLinkShort(L, bdslot);
    }
3266 3267 3268
  }
}

3269 3270
void TurboAssembler::BranchAndLink(Label* L, Condition cond, Register rs,
                                   const Operand& rt, BranchDelaySlot bdslot) {
3271
  if (L->is_bound()) {
3272
    if (!BranchAndLinkShortCheck(0, L, cond, rs, rt, bdslot)) {
3273 3274 3275
      Label skip;
      Condition neg_cond = NegateCondition(cond);
      BranchShort(&skip, neg_cond, rs, rt);
3276
      BranchAndLinkLong(L, bdslot);
3277 3278
      bind(&skip);
    }
3279
  } else {
3280 3281 3282 3283
    if (is_trampoline_emitted()) {
      Label skip;
      Condition neg_cond = NegateCondition(cond);
      BranchShort(&skip, neg_cond, rs, rt);
3284
      BranchAndLinkLong(L, bdslot);
3285 3286
      bind(&skip);
    } else {
3287
      BranchAndLinkShortCheck(0, L, cond, rs, rt, bdslot);
3288
    }
3289 3290 3291
  }
}

3292
void TurboAssembler::BranchAndLinkShortHelper(int16_t offset, Label* L,
3293
                                              BranchDelaySlot bdslot) {
3294
  DCHECK(L == nullptr || offset == 0);
3295
  offset = GetOffset(offset, L, OffsetSize::kOffset16);
3296 3297 3298
  bal(offset);

  // Emit a nop in the branch delay slot if required.
3299
  if (bdslot == PROTECT) nop();
3300 3301
}

3302
void TurboAssembler::BranchAndLinkShortHelperR6(int32_t offset, Label* L) {
3303
  DCHECK(L == nullptr || offset == 0);
3304 3305 3306
  offset = GetOffset(offset, L, OffsetSize::kOffset26);
  balc(offset);
}
3307

3308
void TurboAssembler::BranchAndLinkShort(int32_t offset,
3309 3310 3311 3312
                                        BranchDelaySlot bdslot) {
  if (IsMipsArchVariant(kMips32r6) && bdslot == PROTECT) {
    DCHECK(is_int26(offset));
    BranchAndLinkShortHelperR6(offset, nullptr);
3313
  } else {
3314 3315 3316 3317
    DCHECK(is_int16(offset));
    BranchAndLinkShortHelper(offset, nullptr, bdslot);
  }
}
3318

3319
void TurboAssembler::BranchAndLinkShort(Label* L, BranchDelaySlot bdslot) {
3320 3321 3322 3323
  if (IsMipsArchVariant(kMips32r6) && bdslot == PROTECT) {
    BranchAndLinkShortHelperR6(0, L);
  } else {
    BranchAndLinkShortHelper(0, L, bdslot);
3324
  }
3325 3326
}

3327
bool TurboAssembler::BranchAndLinkShortHelperR6(int32_t offset, Label* L,
3328 3329
                                                Condition cond, Register rs,
                                                const Operand& rt) {
3330
  DCHECK(L == nullptr || offset == 0);
3331 3332
  UseScratchRegisterScope temps(this);
  Register scratch = temps.hasAvailable() ? temps.Acquire() : t8;
3333
  OffsetSize bits = OffsetSize::kOffset16;
3334

3335 3336 3337 3338
  BlockTrampolinePoolScope block_trampoline_pool(this);
  DCHECK((cond == cc_always && is_int26(offset)) || is_int16(offset));
  switch (cond) {
    case cc_always:
3339
      if (!CalculateOffset(L, &offset, OffsetSize::kOffset26)) return false;
3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353
      balc(offset);
      break;
    case eq:
      if (!is_near(L, bits)) return false;
      Subu(scratch, rs, rt);
      offset = GetOffset(offset, L, bits);
      beqzalc(scratch, offset);
      break;
    case ne:
      if (!is_near(L, bits)) return false;
      Subu(scratch, rs, rt);
      offset = GetOffset(offset, L, bits);
      bnezalc(scratch, offset);
      break;
3354

3355 3356 3357
    // Signed comparison.
    case greater:
      // rs > rt
3358
      if (rs.code() == rt.rm().code()) {
3359
        break;  // No code needs to be emitted.
3360
      } else if (rs == zero_reg) {
3361
        if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
3362
          return false;
3363 3364
        bltzalc(scratch, offset);
      } else if (IsZero(rt)) {
3365
        if (!CalculateOffset(L, &offset, OffsetSize::kOffset16)) return false;
3366 3367 3368 3369 3370 3371 3372 3373 3374 3375
        bgtzalc(rs, offset);
      } else {
        if (!is_near(L, bits)) return false;
        Slt(scratch, GetRtAsRegisterHelper(rt, scratch), rs);
        offset = GetOffset(offset, L, bits);
        bnezalc(scratch, offset);
      }
      break;
    case greater_equal:
      // rs >= rt
3376
      if (rs.code() == rt.rm().code()) {
3377
        if (!CalculateOffset(L, &offset, OffsetSize::kOffset26)) return false;
3378
        balc(offset);
3379
      } else if (rs == zero_reg) {
3380
        if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
3381
          return false;
3382 3383
        blezalc(scratch, offset);
      } else if (IsZero(rt)) {
3384
        if (!CalculateOffset(L, &offset, OffsetSize::kOffset16)) return false;
3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
        bgezalc(rs, offset);
      } else {
        if (!is_near(L, bits)) return false;
        Slt(scratch, rs, rt);
        offset = GetOffset(offset, L, bits);
        beqzalc(scratch, offset);
      }
      break;
    case less:
      // rs < rt
3395
      if (rs.code() == rt.rm().code()) {
3396
        break;  // No code needs to be emitted.
3397
      } else if (rs == zero_reg) {
3398
        if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
3399
          return false;
3400 3401
        bgtzalc(scratch, offset);
      } else if (IsZero(rt)) {
3402
        if (!CalculateOffset(L, &offset, OffsetSize::kOffset16)) return false;
3403 3404 3405 3406 3407 3408 3409 3410 3411 3412
        bltzalc(rs, offset);
      } else {
        if (!is_near(L, bits)) return false;
        Slt(scratch, rs, rt);
        offset = GetOffset(offset, L, bits);
        bnezalc(scratch, offset);
      }
      break;
    case less_equal:
      // rs <= r2
3413
      if (rs.code() == rt.rm().code()) {
3414
        if (!CalculateOffset(L, &offset, OffsetSize::kOffset26)) return false;
3415
        balc(offset);
3416
      } else if (rs == zero_reg) {
3417
        if (!CalculateOffset(L, &offset, OffsetSize::kOffset16, &scratch, rt))
3418
          return false;
3419 3420
        bgezalc(scratch, offset);
      } else if (IsZero(rt)) {
3421
        if (!CalculateOffset(L, &offset, OffsetSize::kOffset16)) return false;
3422 3423 3424 3425 3426 3427 3428 3429
        blezalc(rs, offset);
      } else {
        if (!is_near(L, bits)) return false;
        Slt(scratch, GetRtAsRegisterHelper(rt, scratch), rs);
        offset = GetOffset(offset, L, bits);
        beqzalc(scratch, offset);
      }
      break;
3430

3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461
    // Unsigned comparison.
    case Ugreater:
      // rs > r2
      if (!is_near(L, bits)) return false;
      Sltu(scratch, GetRtAsRegisterHelper(rt, scratch), rs);
      offset = GetOffset(offset, L, bits);
      bnezalc(scratch, offset);
      break;
    case Ugreater_equal:
      // rs >= r2
      if (!is_near(L, bits)) return false;
      Sltu(scratch, rs, rt);
      offset = GetOffset(offset, L, bits);
      beqzalc(scratch, offset);
      break;
    case Uless:
      // rs < r2
      if (!is_near(L, bits)) return false;
      Sltu(scratch, rs, rt);
      offset = GetOffset(offset, L, bits);
      bnezalc(scratch, offset);
      break;
    case Uless_equal:
      // rs <= r2
      if (!is_near(L, bits)) return false;
      Sltu(scratch, GetRtAsRegisterHelper(rt, scratch), rs);
      offset = GetOffset(offset, L, bits);
      beqzalc(scratch, offset);
      break;
    default:
      UNREACHABLE();
3462
  }
3463 3464
  return true;
}
3465

3466 3467 3468
// Pre r6 we need to use a bgezal or bltzal, but they can't be used directly
// with the slt instructions. We could use sub or add instead but we would miss
// overflow cases, so we keep slt and add an intermediate third instruction.
3469
bool TurboAssembler::BranchAndLinkShortHelper(int16_t offset, Label* L,
3470 3471 3472
                                              Condition cond, Register rs,
                                              const Operand& rt,
                                              BranchDelaySlot bdslot) {
3473
  DCHECK(L == nullptr || offset == 0);
3474
  if (!is_near(L, OffsetSize::kOffset16)) return false;
3475

3476 3477
  Register scratch = t8;
  BlockTrampolinePoolScope block_trampoline_pool(this);
3478

3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 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
  switch (cond) {
    case cc_always:
      offset = GetOffset(offset, L, OffsetSize::kOffset16);
      bal(offset);
      break;
    case eq:
      bne(rs, GetRtAsRegisterHelper(rt, scratch), 2);
      nop();
      offset = GetOffset(offset, L, OffsetSize::kOffset16);
      bal(offset);
      break;
    case ne:
      beq(rs, GetRtAsRegisterHelper(rt, scratch), 2);
      nop();
      offset = GetOffset(offset, L, OffsetSize::kOffset16);
      bal(offset);
      break;

    // Signed comparison.
    case greater:
      Slt(scratch, GetRtAsRegisterHelper(rt, scratch), rs);
      addiu(scratch, scratch, -1);
      offset = GetOffset(offset, L, OffsetSize::kOffset16);
      bgezal(scratch, offset);
      break;
    case greater_equal:
      Slt(scratch, rs, rt);
      addiu(scratch, scratch, -1);
      offset = GetOffset(offset, L, OffsetSize::kOffset16);
      bltzal(scratch, offset);
      break;
    case less:
      Slt(scratch, rs, rt);
      addiu(scratch, scratch, -1);
      offset = GetOffset(offset, L, OffsetSize::kOffset16);
      bgezal(scratch, offset);
      break;
    case less_equal:
      Slt(scratch, GetRtAsRegisterHelper(rt, scratch), rs);
      addiu(scratch, scratch, -1);
      offset = GetOffset(offset, L, OffsetSize::kOffset16);
      bltzal(scratch, offset);
      break;

    // Unsigned comparison.
    case Ugreater:
      Sltu(scratch, GetRtAsRegisterHelper(rt, scratch), rs);
      addiu(scratch, scratch, -1);
      offset = GetOffset(offset, L, OffsetSize::kOffset16);
      bgezal(scratch, offset);
      break;
    case Ugreater_equal:
      Sltu(scratch, rs, rt);
      addiu(scratch, scratch, -1);
      offset = GetOffset(offset, L, OffsetSize::kOffset16);
      bltzal(scratch, offset);
      break;
    case Uless:
      Sltu(scratch, rs, rt);
      addiu(scratch, scratch, -1);
      offset = GetOffset(offset, L, OffsetSize::kOffset16);
      bgezal(scratch, offset);
      break;
    case Uless_equal:
      Sltu(scratch, GetRtAsRegisterHelper(rt, scratch), rs);
      addiu(scratch, scratch, -1);
      offset = GetOffset(offset, L, OffsetSize::kOffset16);
      bltzal(scratch, offset);
      break;
3548

3549 3550 3551
    default:
      UNREACHABLE();
  }
3552 3553

  // Emit a nop in the branch delay slot if required.
3554
  if (bdslot == PROTECT) nop();
3555 3556 3557 3558

  return true;
}

3559
bool TurboAssembler::BranchAndLinkShortCheck(int32_t offset, Label* L,
3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573
                                             Condition cond, Register rs,
                                             const Operand& rt,
                                             BranchDelaySlot bdslot) {
  BRANCH_ARGS_CHECK(cond, rs, rt);

  if (!L) {
    if (IsMipsArchVariant(kMips32r6) && bdslot == PROTECT) {
      DCHECK(is_int26(offset));
      return BranchAndLinkShortHelperR6(offset, nullptr, cond, rs, rt);
    } else {
      DCHECK(is_int16(offset));
      return BranchAndLinkShortHelper(offset, nullptr, cond, rs, rt, bdslot);
    }
  } else {
3574
    DCHECK_EQ(offset, 0);
3575 3576 3577 3578 3579 3580
    if (IsMipsArchVariant(kMips32r6) && bdslot == PROTECT) {
      return BranchAndLinkShortHelperR6(0, L, cond, rs, rt);
    } else {
      return BranchAndLinkShortHelper(0, L, cond, rs, rt, bdslot);
    }
  }
3581 3582
}

3583 3584
void TurboAssembler::LoadFromConstantsTable(Register destination,
                                            int constant_index) {
3585
  ASM_CODE_COMMENT(this);
3586
  DCHECK(RootsTable::IsImmortalImmovable(RootIndex::kBuiltinsConstantsTable));
3587
  LoadRoot(destination, RootIndex::kBuiltinsConstantsTable);
3588 3589 3590
  lw(destination,
     FieldMemOperand(destination,
                     FixedArray::kHeaderSize + constant_index * kPointerSize));
3591 3592
}

3593 3594
void TurboAssembler::LoadRootRelative(Register destination, int32_t offset) {
  lw(destination, MemOperand(kRootRegister, offset));
3595
}
3596 3597 3598 3599 3600 3601 3602 3603 3604

void TurboAssembler::LoadRootRegisterOffset(Register destination,
                                            intptr_t offset) {
  if (offset == 0) {
    Move(destination, kRootRegister);
  } else {
    Addu(destination, kRootRegister, offset);
  }
}
3605

3606
void TurboAssembler::Jump(Register target, int16_t offset, Condition cond,
3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632
                          Register rs, const Operand& rt, BranchDelaySlot bd) {
  BlockTrampolinePoolScope block_trampoline_pool(this);
  DCHECK(is_int16(offset));
  if (IsMipsArchVariant(kMips32r6) && bd == PROTECT) {
    if (cond == cc_always) {
      jic(target, offset);
    } else {
      BRANCH_ARGS_CHECK(cond, rs, rt);
      Branch(2, NegateCondition(cond), rs, rt);
      jic(target, offset);
    }
  } else {
    if (offset != 0) {
      Addu(target, target, offset);
    }
    if (cond == cc_always) {
      jr(target);
    } else {
      BRANCH_ARGS_CHECK(cond, rs, rt);
      Branch(2, NegateCondition(cond), rs, rt);
      jr(target);
    }
    // Emit a nop in the branch delay slot if required.
    if (bd == PROTECT) nop();
  }
}
3633

3634
void TurboAssembler::Jump(Register target, Register base, int16_t offset,
3635
                          Condition cond, Register rs, const Operand& rt,
3636
                          BranchDelaySlot bd) {
3637
  DCHECK(is_int16(offset));
3638
  BlockTrampolinePoolScope block_trampoline_pool(this);
3639 3640
  if (IsMipsArchVariant(kMips32r6) && bd == PROTECT) {
    if (cond == cc_always) {
3641
      jic(base, offset);
3642 3643 3644
    } else {
      BRANCH_ARGS_CHECK(cond, rs, rt);
      Branch(2, NegateCondition(cond), rs, rt);
3645
      jic(base, offset);
3646
    }
3647
  } else {
3648 3649 3650
    if (offset != 0) {
      Addu(target, base, offset);
    } else {  // Call through target
3651
      if (target != base) mov(target, base);
3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
    }
    if (cond == cc_always) {
      jr(target);
    } else {
      BRANCH_ARGS_CHECK(cond, rs, rt);
      Branch(2, NegateCondition(cond), rs, rt);
      jr(target);
    }
    // Emit a nop in the branch delay slot if required.
    if (bd == PROTECT) nop();
  }
}

3665
void TurboAssembler::Jump(Register target, const Operand& offset,
3666 3667 3668 3669 3670 3671
                          Condition cond, Register rs, const Operand& rt,
                          BranchDelaySlot bd) {
  BlockTrampolinePoolScope block_trampoline_pool(this);
  if (IsMipsArchVariant(kMips32r6) && bd == PROTECT &&
      !is_int16(offset.immediate())) {
    uint32_t aui_offset, jic_offset;
3672 3673
    Assembler::UnpackTargetAddressUnsigned(offset.immediate(), &aui_offset,
                                           &jic_offset);
3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686
    RecordRelocInfo(RelocInfo::EXTERNAL_REFERENCE, offset.immediate());
    aui(target, target, aui_offset);
    if (cond == cc_always) {
      jic(target, jic_offset);
    } else {
      BRANCH_ARGS_CHECK(cond, rs, rt);
      Branch(2, NegateCondition(cond), rs, rt);
      jic(target, jic_offset);
    }
  } else {
    if (offset.immediate() != 0) {
      Addu(target, target, offset);
    }
3687 3688 3689 3690 3691 3692 3693 3694 3695
    if (cond == cc_always) {
      jr(target);
    } else {
      BRANCH_ARGS_CHECK(cond, rs, rt);
      Branch(2, NegateCondition(cond), rs, rt);
      jr(target);
    }
    // Emit a nop in the branch delay slot if required.
    if (bd == PROTECT) nop();
3696 3697 3698
  }
}

3699 3700
void TurboAssembler::Jump(intptr_t target, RelocInfo::Mode rmode,
                          Condition cond, Register rs, const Operand& rt,
3701
                          BranchDelaySlot bd) {
3702
  BlockTrampolinePoolScope block_trampoline_pool(this);
3703 3704 3705 3706 3707 3708
  Label skip;
  if (cond != cc_always) {
    Branch(USE_DELAY_SLOT, &skip, NegateCondition(cond), rs, rt);
  }
  // The first instruction of 'li' may be placed in the delay slot.
  // This is not an issue, t9 is expected to be clobbered anyway.
3709 3710
  if (IsMipsArchVariant(kMips32r6) && bd == PROTECT) {
    uint32_t lui_offset, jic_offset;
3711
    UnpackTargetAddressUnsigned(target, &lui_offset, &jic_offset);
3712 3713 3714
    if (MustUseReg(rmode)) {
      RecordRelocInfo(rmode, target);
    }
3715 3716 3717 3718 3719 3720
    lui(t9, lui_offset);
    Jump(t9, jic_offset, al, zero_reg, Operand(zero_reg), bd);
  } else {
    li(t9, Operand(target, rmode));
    Jump(t9, 0, al, zero_reg, Operand(zero_reg), bd);
  }
3721
  bind(&skip);
3722 3723
}

3724 3725
void TurboAssembler::Jump(Address target, RelocInfo::Mode rmode, Condition cond,
                          Register rs, const Operand& rt, BranchDelaySlot bd) {
3726
  DCHECK(!RelocInfo::IsCodeTarget(rmode));
3727
  Jump(static_cast<intptr_t>(target), rmode, cond, rs, rt, bd);
3728 3729
}

3730 3731
void TurboAssembler::Jump(Handle<Code> code, RelocInfo::Mode rmode,
                          Condition cond, Register rs, const Operand& rt,
3732
                          BranchDelaySlot bd) {
3733
  DCHECK(RelocInfo::IsCodeTarget(rmode));
3734
  BlockTrampolinePoolScope block_trampoline_pool(this);
3735

3736
  Builtin builtin = Builtin::kNoBuiltinId;
3737
  bool target_is_isolate_independent_builtin =
3738 3739
      isolate()->builtins()->IsBuiltinHandle(code, &builtin) &&
      Builtins::IsIsolateIndependent(builtin);
3740 3741 3742 3743 3744 3745 3746 3747 3748
  if (target_is_isolate_independent_builtin &&
      options().use_pc_relative_calls_and_jumps) {
    int32_t code_target_index = AddCodeTarget(code);
    Label skip;
    BlockTrampolinePoolScope block_trampoline_pool(this);
    if (cond != cc_always) {
      // By using delay slot, we always execute first instruction of
      // GenPcRelativeJump (which is or_(t8, ra, zero_reg)).
      Branch(USE_DELAY_SLOT, &skip, NegateCondition(cond), rs, rt);
3749
    }
3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760
    GenPCRelativeJump(t8, t9, code_target_index,
                      RelocInfo::RELATIVE_CODE_TARGET, bd);
    bind(&skip);
    return;
  } else if (root_array_available_ && options().isolate_independent_code) {
    IndirectLoadConstant(t9, code);
    Jump(t9, Code::kHeaderSize - kHeapObjectTag, cond, rs, rt, bd);
    return;
  } else if (target_is_isolate_independent_builtin &&
             options().inline_offheap_trampolines) {
    // Inline the trampoline.
Liu Yu's avatar
Liu Yu committed
3761
    RecordCommentForOffHeapTrampoline(builtin);
3762
    li(t9, Operand(BuiltinEntry(builtin), RelocInfo::OFF_HEAP_TARGET));
3763
    Jump(t9, 0, cond, rs, rt, bd);
3764
    RecordComment("]");
3765
    return;
3766
  }
3767

3768
  Jump(static_cast<intptr_t>(code.address()), rmode, cond, rs, rt, bd);
3769 3770
}

3771
void TurboAssembler::Jump(const ExternalReference& reference) {
3772 3773
  li(t9, reference);
  Jump(t9);
3774 3775
}

Yu Yin's avatar
Yu Yin committed
3776 3777 3778
void MacroAssembler::JumpIfIsInRange(Register value, unsigned lower_limit,
                                     unsigned higher_limit,
                                     Label* on_in_range) {
3779
  ASM_CODE_COMMENT(this);
Yu Yin's avatar
Yu Yin committed
3780 3781 3782 3783 3784 3785 3786 3787 3788 3789
  if (lower_limit != 0) {
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
    Subu(scratch, value, Operand(lower_limit));
    Branch(on_in_range, ls, scratch, Operand(higher_limit - lower_limit));
  } else {
    Branch(on_in_range, ls, value, Operand(higher_limit - lower_limit));
  }
}

3790
// Note: To call gcc-compiled C code on mips, you must call through t9.
3791
void TurboAssembler::Call(Register target, int16_t offset, Condition cond,
3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816
                          Register rs, const Operand& rt, BranchDelaySlot bd) {
  DCHECK(is_int16(offset));
  BlockTrampolinePoolScope block_trampoline_pool(this);
  if (IsMipsArchVariant(kMips32r6) && bd == PROTECT) {
    if (cond == cc_always) {
      jialc(target, offset);
    } else {
      BRANCH_ARGS_CHECK(cond, rs, rt);
      Branch(2, NegateCondition(cond), rs, rt);
      jialc(target, offset);
    }
  } else {
    if (offset != 0) {
      Addu(target, target, offset);
    }
    if (cond == cc_always) {
      jalr(target);
    } else {
      BRANCH_ARGS_CHECK(cond, rs, rt);
      Branch(2, NegateCondition(cond), rs, rt);
      jalr(target);
    }
    // Emit a nop in the branch delay slot if required.
    if (bd == PROTECT) nop();
  }
3817
  set_pc_for_safepoint();
3818 3819
}

3820
// Note: To call gcc-compiled C code on mips, you must call through t9.
3821
void TurboAssembler::Call(Register target, Register base, int16_t offset,
3822
                          Condition cond, Register rs, const Operand& rt,
3823
                          BranchDelaySlot bd) {
3824
  DCHECK(is_uint16(offset));
3825
  BlockTrampolinePoolScope block_trampoline_pool(this);
3826 3827
  if (IsMipsArchVariant(kMips32r6) && bd == PROTECT) {
    if (cond == cc_always) {
3828
      jialc(base, offset);
3829 3830 3831
    } else {
      BRANCH_ARGS_CHECK(cond, rs, rt);
      Branch(2, NegateCondition(cond), rs, rt);
3832
      jialc(base, offset);
3833
    }
3834
  } else {
3835 3836 3837
    if (offset != 0) {
      Addu(target, base, offset);
    } else {  // Call through target
3838
      if (target != base) mov(target, base);
3839
    }
3840 3841 3842 3843 3844 3845 3846 3847 3848
    if (cond == cc_always) {
      jalr(target);
    } else {
      BRANCH_ARGS_CHECK(cond, rs, rt);
      Branch(2, NegateCondition(cond), rs, rt);
      jalr(target);
    }
    // Emit a nop in the branch delay slot if required.
    if (bd == PROTECT) nop();
3849
  }
3850
  set_pc_for_safepoint();
3851 3852
}

3853 3854
void TurboAssembler::Call(Address target, RelocInfo::Mode rmode, Condition cond,
                          Register rs, const Operand& rt, BranchDelaySlot bd) {
3855
  CheckBuffer();
3856
  BlockTrampolinePoolScope block_trampoline_pool(this);
3857
  int32_t target_int = static_cast<int32_t>(target);
3858 3859
  if (IsMipsArchVariant(kMips32r6) && bd == PROTECT && cond == cc_always) {
    uint32_t lui_offset, jialc_offset;
3860
    UnpackTargetAddressUnsigned(target_int, &lui_offset, &jialc_offset);
3861 3862 3863 3864 3865 3866 3867 3868 3869
    if (MustUseReg(rmode)) {
      RecordRelocInfo(rmode, target_int);
    }
    lui(t9, lui_offset);
    Call(t9, jialc_offset, cond, rs, rt, bd);
  } else {
    li(t9, Operand(target_int, rmode), CONSTANT_SIZE);
    Call(t9, 0, cond, rs, rt, bd);
  }
3870 3871
}

3872 3873
void TurboAssembler::Call(Handle<Code> code, RelocInfo::Mode rmode,
                          Condition cond, Register rs, const Operand& rt,
3874 3875
                          BranchDelaySlot bd) {
  BlockTrampolinePoolScope block_trampoline_pool(this);
3876

3877
  Builtin builtin = Builtin::kNoBuiltinId;
3878
  bool target_is_isolate_independent_builtin =
3879 3880
      isolate()->builtins()->IsBuiltinHandle(code, &builtin) &&
      Builtins::IsIsolateIndependent(builtin);
3881 3882 3883 3884 3885 3886 3887
  if (target_is_isolate_independent_builtin &&
      options().use_pc_relative_calls_and_jumps) {
    int32_t code_target_index = AddCodeTarget(code);
    Label skip;
    BlockTrampolinePoolScope block_trampoline_pool(this);
    if (cond != cc_always) {
      Branch(PROTECT, &skip, NegateCondition(cond), rs, rt);
3888
    }
3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899
    GenPCRelativeJumpAndLink(t8, code_target_index,
                             RelocInfo::RELATIVE_CODE_TARGET, bd);
    bind(&skip);
    return;
  } else if (root_array_available_ && options().isolate_independent_code) {
    IndirectLoadConstant(t9, code);
    Call(t9, Code::kHeaderSize - kHeapObjectTag, cond, rs, rt, bd);
    return;
  } else if (target_is_isolate_independent_builtin &&
             options().inline_offheap_trampolines) {
    // Inline the trampoline.
3900
    RecordCommentForOffHeapTrampoline(builtin);
3901
    li(t9, Operand(BuiltinEntry(builtin), RelocInfo::OFF_HEAP_TARGET));
3902
    Call(t9, 0, cond, rs, rt, bd);
3903
    RecordComment("]");
3904
    return;
3905
  }
3906

3907
  DCHECK(RelocInfo::IsCodeTarget(rmode));
3908
  DCHECK(code->IsExecutable());
3909
  Call(code.address(), rmode, cond, rs, rt, bd);
3910 3911
}

3912
void TurboAssembler::LoadEntryFromBuiltinIndex(Register builtin_index) {
3913
  ASM_CODE_COMMENT(this);
3914 3915 3916 3917 3918
  STATIC_ASSERT(kSystemPointerSize == 4);
  STATIC_ASSERT(kSmiShiftSize == 0);
  STATIC_ASSERT(kSmiTagSize == 1);
  STATIC_ASSERT(kSmiTag == 0);

3919 3920 3921 3922 3923
  // The builtin_index register contains the builtin index as a Smi.
  SmiUntag(builtin_index, builtin_index);
  Lsa(builtin_index, kRootRegister, builtin_index, kSystemPointerSizeLog2);
  lw(builtin_index,
     MemOperand(builtin_index, IsolateData::builtin_entry_table_offset()));
3924
}
Liu Yu's avatar
Liu Yu committed
3925
void TurboAssembler::LoadEntryFromBuiltin(Builtin builtin,
3926
                                          Register destination) {
Liu Yu's avatar
Liu Yu committed
3927
  Lw(destination, EntryFromBuiltinAsOperand(builtin));
3928
}
Liu Yu's avatar
Liu Yu committed
3929
MemOperand TurboAssembler::EntryFromBuiltinAsOperand(Builtin builtin) {
3930 3931
  DCHECK(root_array_available());
  return MemOperand(kRootRegister,
3932
                    IsolateData::BuiltinEntrySlotOffset(builtin));
3933
}
3934 3935

void TurboAssembler::CallBuiltinByIndex(Register builtin_index) {
3936
  ASM_CODE_COMMENT(this);
3937
  LoadEntryFromBuiltinIndex(builtin_index);
3938
  Call(builtin_index);
3939
}
Liu Yu's avatar
Liu Yu committed
3940 3941
void TurboAssembler::CallBuiltin(Builtin builtin) {
  RecordCommentForOffHeapTrampoline(builtin);
3942
  Call(BuiltinEntry(builtin), RelocInfo::OFF_HEAP_TARGET);
3943
  RecordComment("]");
3944
}
3945

3946 3947
void TurboAssembler::PatchAndJump(Address target) {
  if (kArchVariant != kMips32r6) {
3948
    ASM_CODE_COMMENT(this);
3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
    mov(scratch, ra);
    bal(1);                                  // jump to lw
    nop();                                   // in the delay slot
    lw(t9, MemOperand(ra, kInstrSize * 3));  // ra == pc_
    jr(t9);
    mov(ra, scratch);  // in delay slot
    DCHECK_EQ(reinterpret_cast<uint32_t>(pc_) % 8, 0);
    *reinterpret_cast<uint32_t*>(pc_) = target;
    pc_ += sizeof(uint32_t);
  } else {
    // TODO(mips r6): Implement.
    UNIMPLEMENTED();
  }
}

3966
void TurboAssembler::StoreReturnAddressAndCall(Register target) {
3967
  ASM_CODE_COMMENT(this);
3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000
  // This generates the final instruction sequence for calls to C functions
  // once an exit frame has been constructed.
  //
  // Note that this assumes the caller code (i.e. the Code object currently
  // being generated) is immovable or that the callee function cannot trigger
  // GC, since the callee function will return to it.

  Assembler::BlockTrampolinePoolScope block_trampoline_pool(this);
  static constexpr int kNumInstructionsToJump = 4;
  Label find_ra;
  // Adjust the value in ra to point to the correct return location, 2nd
  // instruction past the real call into C code (the jalr(t9)), and push it.
  // This is the return address of the exit frame.
  if (kArchVariant >= kMips32r6) {
    addiupc(ra, kNumInstructionsToJump + 1);
  } else {
    // This no-op-and-link sequence saves PC + 8 in ra register on pre-r6 MIPS
    nal();  // nal has branch delay slot.
    Addu(ra, ra, kNumInstructionsToJump * kInstrSize);
  }
  bind(&find_ra);

  // This spot was reserved in EnterExitFrame.
  sw(ra, MemOperand(sp));
  // Stack space reservation moved to the branch delay slot below.
  // Stack is still aligned.

  // Call the C routine.
  mov(t9, target);  // Function pointer to t9 to conform to ABI for PIC.
  jalr(t9);
  // Set up sp in the delay slot.
  addiu(sp, sp, -kCArgsSlotsSize);
  // Make sure the stored 'ra' points to this position.
tzik's avatar
tzik committed
4001
  DCHECK_EQ(kNumInstructionsToJump, InstructionsGeneratedSince(&find_ra));
4002 4003
}

4004
void TurboAssembler::Ret(Condition cond, Register rs, const Operand& rt,
4005
                         BranchDelaySlot bd) {
4006
  Jump(ra, 0, cond, rs, rt, bd);
4007 4008
}

4009
void TurboAssembler::BranchLong(Label* L, BranchDelaySlot bdslot) {
4010 4011 4012 4013
  if (IsMipsArchVariant(kMips32r6) && bdslot == PROTECT &&
      (!L->is_bound() || is_near_r6(L))) {
    BranchShortHelperR6(0, L);
  } else {
4014
    // Generate position independent long branch.
4015
    BlockTrampolinePoolScope block_trampoline_pool(this);
4016 4017
    int32_t imm32;
    imm32 = branch_long_offset(L);
4018
    GenPCRelativeJump(t8, t9, imm32, RelocInfo::NO_INFO, bdslot);
4019 4020 4021
  }
}

4022 4023 4024 4025 4026 4027
void TurboAssembler::BranchLong(int32_t offset, BranchDelaySlot bdslot) {
  if (IsMipsArchVariant(kMips32r6) && bdslot == PROTECT && (is_int26(offset))) {
    BranchShortHelperR6(offset, nullptr);
  } else {
    // Generate position independent long branch.
    BlockTrampolinePoolScope block_trampoline_pool(this);
4028
    GenPCRelativeJump(t8, t9, offset, RelocInfo::NO_INFO, bdslot);
4029 4030 4031
  }
}

4032
void TurboAssembler::BranchAndLinkLong(Label* L, BranchDelaySlot bdslot) {
4033 4034 4035 4036
  if (IsMipsArchVariant(kMips32r6) && bdslot == PROTECT &&
      (!L->is_bound() || is_near_r6(L))) {
    BranchAndLinkShortHelperR6(0, L);
  } else {
4037
    // Generate position independent long branch and link.
4038
    BlockTrampolinePoolScope block_trampoline_pool(this);
4039 4040
    int32_t imm32;
    imm32 = branch_long_offset(L);
4041
    GenPCRelativeJumpAndLink(t8, imm32, RelocInfo::NO_INFO, bdslot);
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 4078 4079 4080 4081
void TurboAssembler::DropArguments(Register count, ArgumentsCountType type,
                                   ArgumentsCountMode mode) {
  switch (type) {
    case kCountIsInteger: {
      Lsa(sp, sp, count, kPointerSizeLog2);
      break;
    }
    case kCountIsSmi: {
      STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
      Lsa(sp, sp, count, kPointerSizeLog2 - kSmiTagSize, count);
      break;
    }
    case kCountIsBytes: {
      Addu(sp, sp, count);
      break;
    }
  }
  if (mode == kCountExcludesReceiver) {
    Addu(sp, sp, kSystemPointerSize);
  }
}

void TurboAssembler::DropArgumentsAndPushNewReceiver(Register argc,
                                                     Register receiver,
                                                     ArgumentsCountType type,
                                                     ArgumentsCountMode mode) {
  DCHECK(!AreAliased(argc, receiver));
  if (mode == kCountExcludesReceiver) {
    // Drop arguments without receiver and override old receiver.
    DropArguments(argc, type, kCountIncludesReceiver);
    sw(receiver, MemOperand(sp));
  } else {
    DropArguments(argc, type, mode);
    push(receiver);
  }
}

4082
void TurboAssembler::DropAndRet(int drop) {
4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095
  int32_t drop_size = drop * kSystemPointerSize;
  DCHECK(is_int31(drop_size));

  if (is_int16(drop_size)) {
    Ret(USE_DELAY_SLOT);
    addiu(sp, sp, drop_size);
  } else {
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
    li(scratch, drop_size);
    Ret(USE_DELAY_SLOT);
    addu(sp, sp, scratch);
  }
4096
}
4097

4098
void TurboAssembler::DropAndRet(int drop, Condition cond, Register r1,
4099
                                const Operand& r2) {
4100
  // Both Drop and Ret need to be conditional.
4101 4102 4103
  Label skip;
  if (cond != cc_always) {
    Branch(&skip, NegateCondition(cond), r1, r2);
4104 4105
  }

4106 4107
  Drop(drop);
  Ret();
4108

4109 4110
  if (cond != cc_always) {
    bind(&skip);
4111
  }
4112 4113
}

4114
void TurboAssembler::Drop(int count, Condition cond, Register reg,
4115 4116 4117 4118 4119 4120 4121 4122
                          const Operand& op) {
  if (count <= 0) {
    return;
  }

  Label skip;

  if (cond != al) {
4123
    Branch(&skip, NegateCondition(cond), reg, op);
4124 4125
  }

4126
  Addu(sp, sp, Operand(count * kPointerSize));
4127 4128 4129 4130

  if (cond != al) {
    bind(&skip);
  }
4131 4132
}

4133
void MacroAssembler::Swap(Register reg1, Register reg2, Register scratch) {
4134
  if (scratch == no_reg) {
4135 4136 4137 4138 4139 4140 4141 4142
    Xor(reg1, reg1, Operand(reg2));
    Xor(reg2, reg2, Operand(reg1));
    Xor(reg1, reg1, Operand(reg2));
  } else {
    mov(scratch, reg1);
    mov(reg1, reg2);
    mov(reg2, scratch);
  }
4143 4144
}

4145
void TurboAssembler::Call(Label* target) { BranchAndLink(target); }
4146

4147 4148 4149 4150 4151
void TurboAssembler::LoadAddress(Register dst, Label* target) {
  uint32_t address = jump_address(target);
  li(dst, address);
}

4152
void TurboAssembler::Push(Handle<HeapObject> handle) {
4153 4154 4155 4156
  UseScratchRegisterScope temps(this);
  Register scratch = temps.Acquire();
  li(scratch, Operand(handle));
  push(scratch);
4157 4158
}

4159
void TurboAssembler::Push(Smi smi) {
4160 4161 4162 4163
  UseScratchRegisterScope temps(this);
  Register scratch = temps.Acquire();
  li(scratch, Operand(smi));
  push(scratch);
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
void TurboAssembler::PushArray(Register array, Register size, Register scratch,
                               Register scratch2, PushArrayOrder order) {
  DCHECK(!AreAliased(array, size, scratch, scratch2));
  Label loop, entry;
  if (order == PushArrayOrder::kReverse) {
    mov(scratch, zero_reg);
    jmp(&entry);
    bind(&loop);
    Lsa(scratch2, array, scratch, kPointerSizeLog2);
    Lw(scratch2, MemOperand(scratch2));
    push(scratch2);
    Addu(scratch, scratch, Operand(1));
    bind(&entry);
    Branch(&loop, less, scratch, Operand(size));
  } else {
    mov(scratch, size);
    jmp(&entry);
    bind(&loop);
    Lsa(scratch2, array, scratch, kPointerSizeLog2);
    Lw(scratch2, MemOperand(scratch2));
    push(scratch2);
    bind(&entry);
    Addu(scratch, scratch, Operand(-1));
    Branch(&loop, greater_equal, scratch, Operand(zero_reg));
  }
}

4193
// ---------------------------------------------------------------------------
4194
// Exception handling.
4195

4196
void MacroAssembler::PushStackHandler() {
4197
  // Adjust this code if not the case.
4198
  STATIC_ASSERT(StackHandlerConstants::kSize == 2 * kPointerSize);
4199
  STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0 * kPointerSize);
4200

4201
  Push(Smi::zero());  // Padding.
4202

4203
  // Link the current handler as the next handler.
4204 4205
  li(t2,
     ExternalReference::Create(IsolateAddressId::kHandlerAddress, isolate()));
4206 4207
  lw(t1, MemOperand(t2));
  push(t1);
4208

4209 4210
  // Set this new handler as the current one.
  sw(sp, MemOperand(t2));
4211 4212
}

4213
void MacroAssembler::PopStackHandler() {
4214
  STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
4215 4216
  pop(a1);
  Addu(sp, sp, Operand(StackHandlerConstants::kSize - kPointerSize));
4217 4218
  UseScratchRegisterScope temps(this);
  Register scratch = temps.Acquire();
4219 4220
  li(scratch,
     ExternalReference::Create(IsolateAddressId::kHandlerAddress, isolate()));
4221
  sw(a1, MemOperand(scratch));
4222 4223
}

4224
void TurboAssembler::FPUCanonicalizeNaN(const DoubleRegister dst,
4225 4226 4227
                                        const DoubleRegister src) {
  sub_d(dst, src, kDoubleRegZero);
}
4228

4229
void TurboAssembler::MovFromFloatResult(DoubleRegister dst) {
4230
  if (IsMipsSoftFloatABI) {
4231 4232 4233 4234 4235
    if (kArchEndian == kLittle) {
      Move(dst, v0, v1);
    } else {
      Move(dst, v1, v0);
    }
4236
  } else {
4237
    Move(dst, f0);  // Reg f0 is o32 ABI FP return value.
4238 4239 4240
  }
}

4241
void TurboAssembler::MovFromFloatParameter(DoubleRegister dst) {
4242
  if (IsMipsSoftFloatABI) {
4243 4244 4245 4246 4247
    if (kArchEndian == kLittle) {
      Move(dst, a0, a1);
    } else {
      Move(dst, a1, a0);
    }
4248 4249 4250 4251 4252
  } else {
    Move(dst, f12);  // Reg f12 is o32 ABI FP first argument value.
  }
}

4253
void TurboAssembler::MovToFloatParameter(DoubleRegister src) {
4254
  if (!IsMipsSoftFloatABI) {
4255
    Move(f12, src);
4256
  } else {
4257 4258 4259 4260 4261
    if (kArchEndian == kLittle) {
      Move(a0, a1, src);
    } else {
      Move(a1, a0, src);
    }
4262 4263 4264
  }
}

4265
void TurboAssembler::MovToFloatResult(DoubleRegister src) {
4266
  if (!IsMipsSoftFloatABI) {
4267
    Move(f0, src);
4268
  } else {
4269 4270 4271 4272 4273
    if (kArchEndian == kLittle) {
      Move(v0, v1, src);
    } else {
      Move(v1, v0, src);
    }
4274 4275 4276
  }
}

4277
void TurboAssembler::MovToFloatParameters(DoubleRegister src1,
4278
                                          DoubleRegister src2) {
4279
  if (!IsMipsSoftFloatABI) {
4280 4281
    if (src2 == f12) {
      DCHECK(src1 != f14);
4282 4283
      Move(f14, src2);
      Move(f12, src1);
4284
    } else {
4285 4286
      Move(f12, src1);
      Move(f14, src2);
4287
    }
4288
  } else {
4289 4290 4291 4292 4293 4294 4295
    if (kArchEndian == kLittle) {
      Move(a0, a1, src1);
      Move(a2, a3, src2);
    } else {
      Move(a1, a0, src1);
      Move(a3, a2, src2);
    }
4296 4297 4298
  }
}

4299
// -----------------------------------------------------------------------------
4300
// JavaScript invokes.
4301

4302
void MacroAssembler::LoadStackLimit(Register destination, StackLimitKind kind) {
4303
  ASM_CODE_COMMENT(this);
4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320
  DCHECK(root_array_available());
  Isolate* isolate = this->isolate();
  ExternalReference limit =
      kind == StackLimitKind::kRealStackLimit
          ? ExternalReference::address_of_real_jslimit(isolate)
          : ExternalReference::address_of_jslimit(isolate);
  DCHECK(TurboAssembler::IsAddressableThroughRootRegister(isolate, limit));

  intptr_t offset =
      TurboAssembler::RootRegisterOffsetForExternalReference(isolate, limit);
  CHECK(is_int32(offset));
  Lw(destination, MemOperand(kRootRegister, static_cast<int32_t>(offset)));
}

void MacroAssembler::StackOverflowCheck(Register num_args, Register scratch1,
                                        Register scratch2,
                                        Label* stack_overflow) {
4321
  ASM_CODE_COMMENT(this);
4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335
  // Check the stack for overflow. We are not trying to catch
  // interruptions (e.g. debug break and preemption) here, so the "real stack
  // limit" is checked.

  LoadStackLimit(scratch1, StackLimitKind::kRealStackLimit);
  // Make scratch1 the space we have left. The stack might already be overflowed
  // here which will cause scratch1 to become negative.
  subu(scratch1, sp, scratch1);
  // Check if the arguments will overflow the stack.
  sll(scratch2, num_args, kPointerSizeLog2);
  // Signed comparison.
  Branch(stack_overflow, le, scratch1, Operand(scratch2));
}

4336 4337
void MacroAssembler::InvokePrologue(Register expected_parameter_count,
                                    Register actual_parameter_count,
4338
                                    Label* done, InvokeType type) {
4339
  ASM_CODE_COMMENT(this);
4340 4341 4342 4343 4344 4345
  Label regular_invoke;

  //  a0: actual arguments count
  //  a1: function (passed through to callee)
  //  a2: expected arguments count

4346 4347 4348
  DCHECK_EQ(actual_parameter_count, a0);
  DCHECK_EQ(expected_parameter_count, a2);

4349 4350
  // If the expected parameter count is equal to the adaptor sentinel, no need
  // to push undefined value as arguments.
4351 4352 4353 4354
  if (kDontAdaptArgumentsSentinel != 0) {
    Branch(&regular_invoke, eq, expected_parameter_count,
           Operand(kDontAdaptArgumentsSentinel));
  }
4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380

  // If overapplication or if the actual argument count is equal to the
  // formal parameter count, no need to push extra undefined values.
  Subu(expected_parameter_count, expected_parameter_count,
       actual_parameter_count);
  Branch(&regular_invoke, le, expected_parameter_count, Operand(zero_reg));

  Label stack_overflow;
  StackOverflowCheck(expected_parameter_count, t0, t1, &stack_overflow);
  // Underapplication. Move the arguments already in the stack, including the
  // receiver and the return address.
  {
    Label copy;
    Register src = t3, dest = t4;
    mov(src, sp);
    sll(t0, expected_parameter_count, kSystemPointerSizeLog2);
    Subu(sp, sp, Operand(t0));
    // Update stack pointer.
    mov(dest, sp);
    mov(t0, a0);
    bind(&copy);
    Lw(t1, MemOperand(src, 0));
    Sw(t1, MemOperand(dest, 0));
    Subu(t0, t0, Operand(1));
    Addu(src, src, Operand(kSystemPointerSize));
    Addu(dest, dest, Operand(kSystemPointerSize));
4381
    Branch(&copy, gt, t0, Operand(zero_reg));
4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398
  }

  // Fill remaining expected arguments with undefined values.
  LoadRoot(t0, RootIndex::kUndefinedValue);
  {
    Label loop;
    bind(&loop);
    Sw(t0, MemOperand(t4, 0));
    Subu(expected_parameter_count, expected_parameter_count, Operand(1));
    Addu(t4, t4, Operand(kSystemPointerSize));
    Branch(&loop, gt, expected_parameter_count, Operand(zero_reg));
  }
  b(&regular_invoke);
  nop();

  bind(&stack_overflow);
  {
4399 4400
    FrameScope frame(
        this, has_frame() ? StackFrame::NO_FRAME_TYPE : StackFrame::INTERNAL);
4401 4402 4403
    CallRuntime(Runtime::kThrowStackOverflow);
    break_(0xCC);
  }
4404 4405

  bind(&regular_invoke);
4406 4407
}

4408
void MacroAssembler::CheckDebugHook(Register fun, Register new_target,
4409 4410
                                    Register expected_parameter_count,
                                    Register actual_parameter_count) {
4411
  Label skip_hook;
4412
  li(t0, ExternalReference::debug_hook_on_function_call_address(isolate()));
4413
  lb(t0, MemOperand(t0));
4414
  Branch(&skip_hook, eq, t0, Operand(zero_reg));
4415

4416
  {
4417
    // Load receiver to pass it later to DebugOnFunctionCall hook.
4418 4419
    LoadReceiver(t0, actual_parameter_count);

4420 4421
    FrameScope frame(
        this, has_frame() ? StackFrame::NO_FRAME_TYPE : StackFrame::INTERNAL);
4422 4423 4424 4425 4426 4427
    SmiTag(expected_parameter_count);
    Push(expected_parameter_count);

    SmiTag(actual_parameter_count);
    Push(actual_parameter_count);

4428 4429 4430 4431 4432
    if (new_target.is_valid()) {
      Push(new_target);
    }
    Push(fun);
    Push(fun);
4433
    Push(t0);
4434
    CallRuntime(Runtime::kDebugOnFunctionCall);
4435 4436 4437 4438
    Pop(fun);
    if (new_target.is_valid()) {
      Pop(new_target);
    }
4439 4440 4441 4442 4443 4444

    Pop(actual_parameter_count);
    SmiUntag(actual_parameter_count);

    Pop(expected_parameter_count);
    SmiUntag(expected_parameter_count);
4445
  }
4446
  bind(&skip_hook);
4447 4448 4449
}

void MacroAssembler::InvokeFunctionCode(Register function, Register new_target,
4450 4451
                                        Register expected_parameter_count,
                                        Register actual_parameter_count,
4452
                                        InvokeType type) {
4453
  // You can't call a function without a valid frame.
4454
  DCHECK_IMPLIES(type == InvokeType::kCall, has_frame());
4455
  DCHECK_EQ(function, a1);
4456
  DCHECK_IMPLIES(new_target.is_valid(), new_target == a3);
4457

4458
  // On function call, call into the debugger if necessary.
4459 4460
  CheckDebugHook(function, new_target, expected_parameter_count,
                 actual_parameter_count);
4461 4462

  // Clear the new.target register if not given.
4463
  if (!new_target.is_valid()) {
4464
    LoadRoot(a3, RootIndex::kUndefinedValue);
4465
  }
4466

4467
  Label done;
4468
  InvokePrologue(expected_parameter_count, actual_parameter_count, &done, type);
4469 4470 4471 4472 4473
  // We call indirectly through the code field in the function to
  // allow recompilation to take effect without changing any of the
  // call sites.
  Register code = kJavaScriptCallCodeStartRegister;
  lw(code, FieldMemOperand(function, JSFunction::kCodeOffset));
4474 4475 4476 4477 4478 4479 4480 4481 4482
  switch (type) {
    case InvokeType::kCall:
      Addu(code, code, Code::kHeaderSize - kHeapObjectTag);
      Call(code);
      break;
    case InvokeType::kJump:
      Addu(code, code, Code::kHeaderSize - kHeapObjectTag);
      Jump(code);
      break;
4483
  }
4484 4485 4486 4487

  // Continue here if InvokePrologue does handle the invocation due to
  // mismatched parameter counts.
  bind(&done);
4488 4489
}

4490 4491
void MacroAssembler::InvokeFunctionWithNewTarget(
    Register function, Register new_target, Register actual_parameter_count,
4492
    InvokeType type) {
4493
  ASM_CODE_COMMENT(this);
4494
  // You can't call a function without a valid frame.
4495
  DCHECK_IMPLIES(type == InvokeType::kCall, has_frame());
4496

4497
  // Contract with called JS functions requires that function is passed in a1.
4498
  DCHECK_EQ(function, a1);
4499
  Register expected_reg = a2;
4500
  Register temp_reg = t0;
4501

4502
  lw(temp_reg, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset));
4503
  lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset));
4504 4505 4506
  lhu(expected_reg,
      FieldMemOperand(temp_reg,
                      SharedFunctionInfo::kFormalParameterCountOffset));
4507

4508
  InvokeFunctionCode(function, new_target, expected_reg, actual_parameter_count,
4509
                     type);
4510 4511
}

4512
void MacroAssembler::InvokeFunction(Register function,
4513 4514
                                    Register expected_parameter_count,
                                    Register actual_parameter_count,
4515
                                    InvokeType type) {
4516
  ASM_CODE_COMMENT(this);
4517
  // You can't call a function without a valid frame.
4518
  DCHECK_IMPLIES(type == InvokeType::kCall, has_frame());
4519

4520
  // Contract with called JS functions requires that function is passed in a1.
4521
  DCHECK_EQ(function, a1);
4522

4523 4524 4525
  // Get the function and setup the context.
  lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset));

4526
  InvokeFunctionCode(a1, no_reg, expected_parameter_count,
4527
                     actual_parameter_count, type);
4528 4529
}

4530 4531 4532
// ---------------------------------------------------------------------------
// Support functions.

4533
void MacroAssembler::GetObjectType(Register object, Register map,
4534
                                   Register type_reg) {
4535
  LoadMap(map, object);
4536
  lhu(type_reg, FieldMemOperand(map, Map::kInstanceTypeOffset));
4537
}
4538

4539 4540 4541 4542 4543 4544 4545
void MacroAssembler::GetInstanceTypeRange(Register map, Register type_reg,
                                          InstanceType lower_limit,
                                          Register range) {
  lhu(type_reg, FieldMemOperand(map, Map::kInstanceTypeOffset));
  Subu(range, type_reg, Operand(lower_limit));
}

4546
// -----------------------------------------------------------------------------
4547
// Runtime calls.
4548

4549 4550
void TurboAssembler::AddOverflow(Register dst, Register left,
                                 const Operand& right, Register overflow) {
4551
  ASM_CODE_COMMENT(this);
4552
  BlockTrampolinePoolScope block_trampoline_pool(this);
4553 4554 4555 4556 4557
  Register right_reg = no_reg;
  Register scratch = t8;
  if (!right.is_reg()) {
    li(at, Operand(right));
    right_reg = at;
4558
  } else {
4559
    right_reg = right.rm();
4560 4561
  }

4562 4563 4564
  DCHECK(left != scratch && right_reg != scratch && dst != scratch &&
         overflow != scratch);
  DCHECK(overflow != left && overflow != right_reg);
4565

4566 4567 4568 4569 4570 4571
  if (dst == left || dst == right_reg) {
    addu(scratch, left, right_reg);
    xor_(overflow, scratch, left);
    xor_(at, scratch, right_reg);
    and_(overflow, overflow, at);
    mov(dst, scratch);
4572
  } else {
4573 4574 4575 4576
    addu(dst, left, right_reg);
    xor_(overflow, dst, left);
    xor_(at, dst, right_reg);
    and_(overflow, overflow, at);
4577 4578 4579
  }
}

4580 4581
void TurboAssembler::SubOverflow(Register dst, Register left,
                                 const Operand& right, Register overflow) {
4582
  ASM_CODE_COMMENT(this);
4583
  BlockTrampolinePoolScope block_trampoline_pool(this);
4584 4585 4586 4587 4588
  Register right_reg = no_reg;
  Register scratch = t8;
  if (!right.is_reg()) {
    li(at, Operand(right));
    right_reg = at;
4589
  } else {
4590
    right_reg = right.rm();
4591 4592
  }

4593 4594 4595 4596 4597 4598 4599 4600 4601 4602
  DCHECK(left != scratch && right_reg != scratch && dst != scratch &&
         overflow != scratch);
  DCHECK(overflow != left && overflow != right_reg);

  if (dst == left || dst == right_reg) {
    subu(scratch, left, right_reg);
    xor_(overflow, left, scratch);
    xor_(at, left, right_reg);
    and_(overflow, overflow, at);
    mov(dst, scratch);
4603
  } else {
4604 4605 4606 4607
    subu(dst, left, right_reg);
    xor_(overflow, left, dst);
    xor_(at, left, right_reg);
    and_(overflow, overflow, at);
4608 4609 4610
  }
}

4611 4612
void TurboAssembler::MulOverflow(Register dst, Register left,
                                 const Operand& right, Register overflow) {
4613
  ASM_CODE_COMMENT(this);
4614
  BlockTrampolinePoolScope block_trampoline_pool(this);
4615 4616 4617 4618 4619 4620
  Register right_reg = no_reg;
  Register scratch = t8;
  Register scratch2 = t9;
  if (!right.is_reg()) {
    li(at, Operand(right));
    right_reg = at;
4621
  } else {
4622
    right_reg = right.rm();
4623 4624
  }

4625 4626 4627
  DCHECK(left != scratch && right_reg != scratch && dst != scratch &&
         overflow != scratch);
  DCHECK(overflow != left && overflow != right_reg);
4628

4629 4630 4631 4632 4633
  if (dst == left || dst == right_reg) {
    Mul(overflow, scratch2, left, right_reg);
    sra(scratch, scratch2, 31);
    xor_(overflow, overflow, scratch);
    mov(dst, scratch2);
4634
  } else {
4635
    Mul(overflow, dst, left, right_reg);
4636
    sra(scratch, dst, 31);
4637
    xor_(overflow, overflow, scratch);
4638
  }
4639
}
4640

4641
void MacroAssembler::CallRuntime(const Runtime::Function* f, int num_arguments,
4642
                                 SaveFPRegsMode save_doubles) {
4643
  ASM_CODE_COMMENT(this);
4644 4645 4646 4647 4648
  // All parameters are on the stack. v0 has the return value after call.

  // If the expected number of arguments of the runtime function is
  // constant, we check that the actual number of arguments match the
  // expectation.
4649
  CHECK(f->nargs < 0 || f->nargs == num_arguments);
4650 4651 4652 4653 4654

  // TODO(1236192): Most runtime routines don't need the number of
  // arguments passed in because it is constant. At some point we
  // should remove this need and make the runtime routine entry code
  // smarter.
4655
  PrepareCEntryArgs(num_arguments);
4656
  PrepareCEntryFunction(ExternalReference::Create(f));
4657 4658 4659
  Handle<Code> code =
      CodeFactory::CEntry(isolate(), f->result_size, save_doubles);
  Call(code, RelocInfo::CODE_TARGET);
4660 4661
}

4662
void MacroAssembler::TailCallRuntime(Runtime::FunctionId fid) {
4663
  ASM_CODE_COMMENT(this);
4664 4665 4666 4667 4668
  const Runtime::Function* function = Runtime::FunctionForId(fid);
  DCHECK_EQ(1, function->result_size);
  if (function->nargs >= 0) {
    PrepareCEntryArgs(function->nargs);
  }
4669
  JumpToExternalReference(ExternalReference::Create(fid));
4670 4671
}

4672
void MacroAssembler::JumpToExternalReference(const ExternalReference& builtin,
4673 4674
                                             BranchDelaySlot bd,
                                             bool builtin_exit_frame) {
4675
  PrepareCEntryFunction(builtin);
4676 4677
  Handle<Code> code = CodeFactory::CEntry(isolate(), 1, SaveFPRegsMode::kIgnore,
                                          ArgvMode::kStack, builtin_exit_frame);
4678
  Jump(code, RelocInfo::CODE_TARGET, al, zero_reg, Operand(zero_reg), bd);
4679 4680
}

4681
void MacroAssembler::JumpToOffHeapInstructionStream(Address entry) {
4682
  li(kOffHeapTrampolineRegister, Operand(entry, RelocInfo::OFF_HEAP_TARGET));
4683 4684 4685
  Jump(kOffHeapTrampolineRegister);
}

4686 4687
void MacroAssembler::LoadWeakValue(Register out, Register in,
                                   Label* target_if_cleared) {
4688
  Branch(target_if_cleared, eq, in, Operand(kClearedWeakHeapObjectLower32));
4689 4690 4691 4692

  And(out, in, Operand(~kWeakHeapObjectMask));
}

4693 4694 4695
void MacroAssembler::EmitIncrementCounter(StatsCounter* counter, int value,
                                          Register scratch1,
                                          Register scratch2) {
4696
  DCHECK_GT(value, 0);
4697
  if (FLAG_native_code_counters && counter->Enabled()) {
4698
    ASM_CODE_COMMENT(this);
4699
    li(scratch2, ExternalReference::Create(counter));
4700 4701 4702 4703
    lw(scratch1, MemOperand(scratch2));
    Addu(scratch1, scratch1, Operand(value));
    sw(scratch1, MemOperand(scratch2));
  }
4704 4705
}

4706 4707 4708
void MacroAssembler::EmitDecrementCounter(StatsCounter* counter, int value,
                                          Register scratch1,
                                          Register scratch2) {
4709
  DCHECK_GT(value, 0);
4710
  if (FLAG_native_code_counters && counter->Enabled()) {
4711
    ASM_CODE_COMMENT(this);
4712
    li(scratch2, ExternalReference::Create(counter));
4713 4714 4715 4716
    lw(scratch1, MemOperand(scratch2));
    Subu(scratch1, scratch1, Operand(value));
    sw(scratch1, MemOperand(scratch2));
  }
4717 4718
}

4719
// -----------------------------------------------------------------------------
4720
// Debugging.
4721

4722
void TurboAssembler::Trap() { stop(); }
4723
void TurboAssembler::DebugBreak() { stop(); }
4724

4725
void TurboAssembler::Assert(Condition cc, AbortReason reason, Register rs,
4726
                            Operand rt) {
4727
  if (FLAG_debug_code) Check(cc, reason, rs, rt);
4728 4729
}

4730
void TurboAssembler::Check(Condition cc, AbortReason reason, Register rs,
4731
                           Operand rt) {
4732 4733
  Label L;
  Branch(&L, cc, rs, rt);
4734
  Abort(reason);
4735
  // Will not return here.
4736
  bind(&L);
4737 4738
}

4739
void TurboAssembler::Abort(AbortReason reason) {
4740 4741
  Label abort_start;
  bind(&abort_start);
4742 4743 4744 4745 4746
  if (FLAG_code_comments) {
    const char* msg = GetAbortReason(reason);
    RecordComment("Abort message: ");
    RecordComment(msg);
  }
4747

4748 4749
  // Avoid emitting call to builtin if requested.
  if (trap_on_abort()) {
4750
    stop();
4751 4752
    return;
  }
4753

4754 4755
  if (should_abort_hard()) {
    // We don't care if we constructed a frame. Just pretend we did.
4756
    FrameScope assume_frame(this, StackFrame::NO_FRAME_TYPE);
4757 4758 4759 4760 4761 4762
    PrepareCallCFunction(0, a0);
    li(a0, Operand(static_cast<int>(reason)));
    CallCFunction(ExternalReference::abort_with_reason(), 1);
    return;
  }

4763 4764
  Move(a0, Smi::FromInt(static_cast<int>(reason)));

4765 4766 4767 4768
  // Disable stub call restrictions to always allow calls to abort.
  if (!has_frame_) {
    // We don't actually want to generate a pile of code for this, so just
    // claim there is a stack frame, without generating one.
4769
    FrameScope scope(this, StackFrame::NO_FRAME_TYPE);
4770
    Call(BUILTIN_CODE(isolate(), Abort), RelocInfo::CODE_TARGET);
4771
  } else {
4772
    Call(BUILTIN_CODE(isolate(), Abort), RelocInfo::CODE_TARGET);
4773
  }
4774
  // Will not return here.
4775 4776 4777 4778 4779
  if (is_trampoline_pool_blocked()) {
    // If the calling code cares about the exact number of
    // instructions generated, we insert padding here to keep the size
    // of the Abort macro constant.
    // Currently in debug mode with debug_code enabled the number of
4780 4781
    // generated instructions is 10, so we use this as a maximum value.
    static const int kExpectedAbortInstructions = 10;
4782
    int abort_instructions = InstructionsGeneratedSince(&abort_start);
4783
    DCHECK_LE(abort_instructions, kExpectedAbortInstructions);
4784 4785 4786 4787 4788 4789
    while (abort_instructions++ < kExpectedAbortInstructions) {
      nop();
    }
  }
}

4790
void TurboAssembler::LoadMap(Register destination, Register object) {
4791 4792 4793
  Lw(destination, FieldMemOperand(object, HeapObject::kMapOffset));
}

4794
void MacroAssembler::LoadNativeContextSlot(Register dst, int index) {
4795 4796 4797 4798
  LoadMap(dst, cp);
  Lw(dst,
     FieldMemOperand(dst, Map::kConstructorOrBackPointerOrNativeContextOffset));
  Lw(dst, MemOperand(dst, Context::SlotOffset(index)));
4799 4800
}

4801
void TurboAssembler::StubPrologue(StackFrame::Type type) {
4802 4803 4804 4805
  UseScratchRegisterScope temps(this);
  Register scratch = temps.Acquire();
  li(scratch, Operand(StackFrame::TypeToMarker(type)));
  PushCommonFrame(scratch);
4806 4807
}

4808
void TurboAssembler::Prologue() { PushStandardFrame(a1); }
4809

4810
void TurboAssembler::EnterFrame(StackFrame::Type type) {
4811
  ASM_CODE_COMMENT(this);
4812
  BlockTrampolinePoolScope block_trampoline_pool(this);
4813 4814 4815 4816 4817 4818
  Push(ra, fp);
  Move(fp, sp);
  if (!StackFrame::IsJavaScript(type)) {
    li(kScratchReg, Operand(StackFrame::TypeToMarker(type)));
    Push(kScratchReg);
  }
4819 4820 4821
#if V8_ENABLE_WEBASSEMBLY
  if (type == StackFrame::WASM) Push(kWasmInstanceRegister);
#endif  // V8_ENABLE_WEBASSEMBLY
4822 4823
}

4824
void TurboAssembler::LeaveFrame(StackFrame::Type type) {
4825
  ASM_CODE_COMMENT(this);
4826 4827 4828
  addiu(sp, fp, 2 * kPointerSize);
  lw(ra, MemOperand(fp, 1 * kPointerSize));
  lw(fp, MemOperand(fp, 0 * kPointerSize));
4829 4830
}

4831 4832
void MacroAssembler::EnterExitFrame(bool save_doubles, int stack_space,
                                    StackFrame::Type frame_type) {
4833
  ASM_CODE_COMMENT(this);
4834
  BlockTrampolinePoolScope block_trampoline_pool(this);
4835 4836 4837
  DCHECK(frame_type == StackFrame::EXIT ||
         frame_type == StackFrame::BUILTIN_EXIT);

4838
  // Set up the frame structure on the stack.
4839 4840 4841
  STATIC_ASSERT(2 * kPointerSize == ExitFrameConstants::kCallerSPDisplacement);
  STATIC_ASSERT(1 * kPointerSize == ExitFrameConstants::kCallerPCOffset);
  STATIC_ASSERT(0 * kPointerSize == ExitFrameConstants::kCallerFPOffset);
4842

4843 4844 4845 4846
  // This is how the stack will look:
  // fp + 2 (==kCallerSPDisplacement) - old stack's end
  // [fp + 1 (==kCallerPCOffset)] - saved old ra
  // [fp + 0 (==kCallerFPOffset)] - saved old fp
4847 4848
  // [fp - 1 StackFrame::EXIT Smi
  // [fp - 2 (==kSPOffset)] - sp of the called function
4849 4850
  // fp - (2 + stack_space + alignment) == sp == [fp - kSPOffset] - top of the
  //   new stack (will contain saved ra)
4851

4852
  // Save registers and reserve room for saved entry sp.
4853
  addiu(sp, sp, -2 * kPointerSize - ExitFrameConstants::kFixedFrameSizeFromFp);
4854 4855
  sw(ra, MemOperand(sp, 3 * kPointerSize));
  sw(fp, MemOperand(sp, 2 * kPointerSize));
4856 4857 4858 4859
  {
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
    li(scratch, Operand(StackFrame::TypeToMarker(frame_type)));
4860
    sw(scratch, MemOperand(sp, 1 * kPointerSize));
4861
  }
4862 4863
  // Set up new frame pointer.
  addiu(fp, sp, ExitFrameConstants::kFixedFrameSizeFromFp);
4864

4865
  if (FLAG_debug_code) {
4866 4867 4868
    sw(zero_reg, MemOperand(fp, ExitFrameConstants::kSPOffset));
  }

4869
  // Save the frame pointer and the context in top.
4870 4871
  li(t8,
     ExternalReference::Create(IsolateAddressId::kCEntryFPAddress, isolate()));
4872
  sw(fp, MemOperand(t8));
4873 4874
  li(t8,
     ExternalReference::Create(IsolateAddressId::kContextAddress, isolate()));
4875
  sw(cp, MemOperand(t8));
4876

4877 4878
  const int frame_alignment = MacroAssembler::ActivationFrameAlignment();
  if (save_doubles) {
4879
    // The stack  must be align to 0 modulo 8 for stores with sdc1.
4880
    DCHECK_EQ(kDoubleSize, frame_alignment);
4881
    if (frame_alignment > 0) {
4882
      DCHECK(base::bits::IsPowerOfTwo(frame_alignment));
4883 4884
      And(sp, sp, Operand(-frame_alignment));  // Align stack.
    }
4885
    int space = FPURegister::kNumRegisters * kDoubleSize;
4886 4887
    Subu(sp, sp, Operand(space));
    // Remember: we only need to save every 2nd double FPU value.
4888
    for (int i = 0; i < FPURegister::kNumRegisters; i += 2) {
4889
      FPURegister reg = FPURegister::from_code(i);
4890
      Sdc1(reg, MemOperand(sp, i * kDoubleSize));
4891 4892
    }
  }
4893

4894
  // Reserve place for the return address, stack space and an optional slot
4895
  // (used by DirectCEntry to hold the return value if a struct is
4896
  // returned) and align the frame preparing for calling the runtime function.
4897
  DCHECK_GE(stack_space, 0);
4898 4899
  Subu(sp, sp, Operand((stack_space + 2) * kPointerSize));
  if (frame_alignment > 0) {
4900
    DCHECK(base::bits::IsPowerOfTwo(frame_alignment));
4901
    And(sp, sp, Operand(-frame_alignment));  // Align stack.
4902
  }
4903 4904 4905

  // Set the exit frame sp value to point just before the return address
  // location.
4906 4907 4908 4909
  UseScratchRegisterScope temps(this);
  Register scratch = temps.Acquire();
  addiu(scratch, sp, kPointerSize);
  sw(scratch, MemOperand(fp, ExitFrameConstants::kSPOffset));
4910 4911
}

4912
void MacroAssembler::LeaveExitFrame(bool save_doubles, Register argument_count,
4913
                                    bool do_return,
4914
                                    bool argument_count_is_length) {
4915
  ASM_CODE_COMMENT(this);
4916
  BlockTrampolinePoolScope block_trampoline_pool(this);
4917 4918 4919 4920
  // Optionally restore all double registers.
  if (save_doubles) {
    // Remember: we only need to restore every 2nd double FPU value.
    lw(t8, MemOperand(fp, ExitFrameConstants::kSPOffset));
4921
    for (int i = 0; i < FPURegister::kNumRegisters; i += 2) {
4922
      FPURegister reg = FPURegister::from_code(i);
4923
      Ldc1(reg, MemOperand(t8, i * kDoubleSize + kPointerSize));
4924 4925
    }
  }
4926

4927
  // Clear top frame.
4928 4929
  li(t8,
     ExternalReference::Create(IsolateAddressId::kCEntryFPAddress, isolate()));
4930
  sw(zero_reg, MemOperand(t8));
4931 4932

  // Restore current context from top and clear it in debug mode.
4933 4934
  li(t8,
     ExternalReference::Create(IsolateAddressId::kContextAddress, isolate()));
4935 4936
  lw(cp, MemOperand(t8));

4937
#ifdef DEBUG
4938 4939
  li(t8,
     ExternalReference::Create(IsolateAddressId::kContextAddress, isolate()));
4940
  sw(a3, MemOperand(t8));
4941 4942 4943 4944
#endif

  // Pop the arguments, restore registers, and return.
  mov(sp, fp);  // Respect ABI stack constraint.
4945 4946
  lw(fp, MemOperand(sp, ExitFrameConstants::kCallerFPOffset));
  lw(ra, MemOperand(sp, ExitFrameConstants::kCallerPCOffset));
4947

4948
  if (argument_count.is_valid()) {
4949 4950 4951
    if (argument_count_is_length) {
      addu(sp, sp, argument_count);
    } else {
4952
      Lsa(sp, sp, argument_count, kPointerSizeLog2, t8);
4953
    }
4954
  }
4955 4956 4957 4958 4959 4960

  if (do_return) {
    Ret(USE_DELAY_SLOT);
    // If returning, the instruction in the delay slot will be the addiu below.
  }
  addiu(sp, sp, 8);
4961 4962
}

4963
int TurboAssembler::ActivationFrameAlignment() {
4964
#if V8_HOST_ARCH_MIPS
4965 4966 4967 4968
  // Running on the real platform. Use the alignment as mandated by the local
  // environment.
  // Note: This will break if we ever start generating snapshots on one Mips
  // platform for another Mips platform with a different alignment.
4969
  return base::OS::ActivationFrameAlignment();
4970
#else   // V8_HOST_ARCH_MIPS
4971 4972 4973 4974 4975
  // If we are using the simulator then we should always align to the expected
  // alignment. As the simulator is used to generate snapshots we do not know
  // if the target platform will need alignment, so this is controlled from a
  // flag.
  return FLAG_sim_stack_alignment;
4976
#endif  // V8_HOST_ARCH_MIPS
4977 4978
}

4979
void MacroAssembler::AssertStackIsAligned() {
4980
  if (FLAG_debug_code) {
4981
    ASM_CODE_COMMENT(this);
4982 4983
    const int frame_alignment = ActivationFrameAlignment();
    const int frame_alignment_mask = frame_alignment - 1;
4984

4985 4986 4987 4988 4989 4990 4991 4992
    if (frame_alignment > kPointerSize) {
      Label alignment_as_expected;
      DCHECK(base::bits::IsPowerOfTwo(frame_alignment));
      UseScratchRegisterScope temps(this);
      Register scratch = temps.Acquire();
      andi(scratch, sp, frame_alignment_mask);
      Branch(&alignment_as_expected, eq, scratch, Operand(zero_reg));
      // Don't use Check here, as it will call Runtime_Abort re-entering here.
4993
      stop();
4994
      bind(&alignment_as_expected);
4995
    }
4996
  }
4997 4998
}

4999
void TurboAssembler::JumpIfSmi(Register value, Label* smi_label,
5000
                               BranchDelaySlot bd) {
5001
  DCHECK_EQ(0, kSmiTag);
5002 5003
  UseScratchRegisterScope temps(this);
  Register scratch = temps.Acquire();
5004 5005 5006 5007
  andi(scratch, value, kSmiTagMask);
  Branch(bd, smi_label, eq, scratch, Operand(zero_reg));
}

5008
void MacroAssembler::JumpIfNotSmi(Register value, Label* not_smi_label,
5009
                                  BranchDelaySlot bd) {
5010
  DCHECK_EQ(0, kSmiTag);
5011 5012
  UseScratchRegisterScope temps(this);
  Register scratch = temps.Acquire();
5013 5014 5015 5016
  andi(scratch, value, kSmiTagMask);
  Branch(bd, not_smi_label, ne, scratch, Operand(zero_reg));
}

5017
void MacroAssembler::AssertNotSmi(Register object) {
5018
  if (FLAG_debug_code) {
5019
    ASM_CODE_COMMENT(this);
5020
    STATIC_ASSERT(kSmiTag == 0);
5021 5022 5023
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
    andi(scratch, object, kSmiTagMask);
5024
    Check(ne, AbortReason::kOperandIsASmi, scratch, Operand(zero_reg));
5025
  }
5026 5027
}

5028
void MacroAssembler::AssertSmi(Register object) {
5029
  if (FLAG_debug_code) {
5030
    ASM_CODE_COMMENT(this);
5031
    STATIC_ASSERT(kSmiTag == 0);
5032 5033 5034
    UseScratchRegisterScope temps(this);
    Register scratch = temps.Acquire();
    andi(scratch, object, kSmiTagMask);
5035
    Check(eq, AbortReason::kOperandIsASmi, scratch, Operand(zero_reg));
5036
  }
5037 5038
}

5039
void MacroAssembler::AssertConstructor(Register object) {
5040
  if (FLAG_debug_code) {
5041
    ASM_CODE_COMMENT(this);
5042
    BlockTrampolinePoolScope block_trampoline_pool(this);
5043 5044 5045 5046 5047
    STATIC_ASSERT(kSmiTag == 0);
    SmiTst(object, t8);
    Check(ne, AbortReason::kOperandIsASmiAndNotAConstructor, t8,
          Operand(zero_reg));

5048
    LoadMap(t8, object);
5049
    lbu(t8, FieldMemOperand(t8, Map::kBitFieldOffset));
5050
    And(t8, t8, Operand(Map::Bits1::IsConstructorBit::kMask));
5051 5052 5053 5054
    Check(ne, AbortReason::kOperandIsNotAConstructor, t8, Operand(zero_reg));
  }
}

5055
void MacroAssembler::AssertFunction(Register object) {
5056
  if (FLAG_debug_code) {
5057
    ASM_CODE_COMMENT(this);
5058
    BlockTrampolinePoolScope block_trampoline_pool(this);
5059
    STATIC_ASSERT(kSmiTag == 0);
5060
    SmiTst(object, t8);
5061 5062
    Check(ne, AbortReason::kOperandIsASmiAndNotAFunction, t8,
          Operand(zero_reg));
5063 5064 5065 5066 5067 5068
    push(object);
    LoadMap(object, object);
    GetInstanceTypeRange(object, object, FIRST_JS_FUNCTION_TYPE, t8);
    Check(ls, AbortReason::kOperandIsNotAFunction, t8,
          Operand(LAST_JS_FUNCTION_TYPE - FIRST_JS_FUNCTION_TYPE));
    pop(object);
5069 5070 5071
  }
}

5072 5073
void MacroAssembler::AssertCallableFunction(Register object) {
  if (FLAG_debug_code) {
5074
    ASM_CODE_COMMENT(this);
5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089
    BlockTrampolinePoolScope block_trampoline_pool(this);
    STATIC_ASSERT(kSmiTag == 0);
    SmiTst(object, t8);
    Check(ne, AbortReason::kOperandIsASmiAndNotAFunction, t8,
          Operand(zero_reg));
    push(object);
    LoadMap(object, object);
    GetInstanceTypeRange(object, object, FIRST_CALLABLE_JS_FUNCTION_TYPE, t8);
    Check(ls, AbortReason::kOperandIsNotACallableFunction, t8,
          Operand(LAST_CALLABLE_JS_FUNCTION_TYPE -
                  FIRST_CALLABLE_JS_FUNCTION_TYPE));
    pop(object);
  }
}

5090
void MacroAssembler::AssertBoundFunction(Register object) {
5091
  if (FLAG_debug_code) {
5092
    ASM_CODE_COMMENT(this);
5093
    BlockTrampolinePoolScope block_trampoline_pool(this);
5094 5095
    STATIC_ASSERT(kSmiTag == 0);
    SmiTst(object, t8);
5096 5097
    Check(ne, AbortReason::kOperandIsASmiAndNotABoundFunction, t8,
          Operand(zero_reg));
5098
    GetObjectType(object, t8, t8);
5099 5100
    Check(eq, AbortReason::kOperandIsNotABoundFunction, t8,
          Operand(JS_BOUND_FUNCTION_TYPE));
5101 5102 5103
  }
}

5104
void MacroAssembler::AssertGeneratorObject(Register object) {
5105
  if (!FLAG_debug_code) return;
5106
  ASM_CODE_COMMENT(this);
5107
  BlockTrampolinePoolScope block_trampoline_pool(this);
5108 5109
  STATIC_ASSERT(kSmiTag == 0);
  SmiTst(object, t8);
5110 5111
  Check(ne, AbortReason::kOperandIsASmiAndNotAGeneratorObject, t8,
        Operand(zero_reg));
5112

5113 5114
  GetObjectType(object, t8, t8);

5115
  Label done;
5116 5117 5118 5119

  // Check if JSGeneratorObject
  Branch(&done, eq, t8, Operand(JS_GENERATOR_OBJECT_TYPE));

5120 5121 5122
  // Check if JSAsyncFunctionObject (See MacroAssembler::CompareInstanceType)
  Branch(&done, eq, t8, Operand(JS_ASYNC_FUNCTION_OBJECT_TYPE));

5123 5124 5125
  // Check if JSAsyncGeneratorObject
  Branch(&done, eq, t8, Operand(JS_ASYNC_GENERATOR_OBJECT_TYPE));

5126
  Abort(AbortReason::kOperandIsNotAGeneratorObject);
5127 5128

  bind(&done);
5129
}
5130

5131 5132
void MacroAssembler::AssertUndefinedOrAllocationSite(Register object,
                                                     Register scratch) {
5133
  if (FLAG_debug_code) {
5134
    ASM_CODE_COMMENT(this);
5135 5136
    Label done_checking;
    AssertNotSmi(object);
5137
    LoadRoot(scratch, RootIndex::kUndefinedValue);
5138
    Branch(&done_checking, eq, object, Operand(scratch));
5139 5140 5141
    GetObjectType(object, scratch, scratch);
    Assert(eq, AbortReason::kExpectedUndefinedOrCell, scratch,
           Operand(ALLOCATION_SITE_TYPE));
5142 5143 5144 5145
    bind(&done_checking);
  }
}

5146
void TurboAssembler::Float32Max(FPURegister dst, FPURegister src1,
5147
                                FPURegister src2, Label* out_of_line) {
5148
  ASM_CODE_COMMENT(this);
5149
  if (src1 == src2) {
5150 5151 5152
    Move_s(dst, src1);
    return;
  }
5153 5154

  // Check if one of operands is NaN.
5155 5156
  CompareIsNanF32(src1, src2);
  BranchTrueF(out_of_line);
5157 5158 5159 5160 5161 5162

  if (IsMipsArchVariant(kMips32r6)) {
    max_s(dst, src1, src2);
  } else {
    Label return_left, return_right, done;

5163 5164 5165 5166
    CompareF32(OLT, src1, src2);
    BranchTrueShortF(&return_right);
    CompareF32(OLT, src2, src1);
    BranchTrueShortF(&return_left);
5167 5168

    // Operands are equal, but check for +/-0.
5169 5170 5171 5172 5173 5174
    {
      BlockTrampolinePoolScope block_trampoline_pool(this);
      mfc1(t8, src1);
      Branch(&return_left, eq, t8, Operand(zero_reg));
      Branch(&return_right);
    }
5175 5176

    bind(&return_right);
5177
    if (src2 != dst) {
5178 5179
      Move_s(dst, src2);
    }
5180
    Branch(&done);
5181 5182

    bind(&return_left);
5183
    if (src1 != dst) {
5184 5185 5186 5187 5188 5189 5190
      Move_s(dst, src1);
    }

    bind(&done);
  }
}

5191
void TurboAssembler::Float32MaxOutOfLine(FPURegister dst, FPURegister src1,
5192 5193 5194 5195
                                         FPURegister src2) {
  add_s(dst, src1, src2);
}

5196
void TurboAssembler::Float32Min(FPURegister dst, FPURegister src1,
5197
                                FPURegister src2, Label* out_of_line) {
5198
  ASM_CODE_COMMENT(this);
5199
  if (src1 == src2) {
5200 5201 5202
    Move_s(dst, src1);
    return;
  }
5203 5204

  // Check if one of operands is NaN.
5205 5206
  CompareIsNanF32(src1, src2);
  BranchTrueF(out_of_line);
5207 5208 5209 5210 5211 5212

  if (IsMipsArchVariant(kMips32r6)) {
    min_s(dst, src1, src2);
  } else {
    Label return_left, return_right, done;

5213 5214 5215 5216
    CompareF32(OLT, src1, src2);
    BranchTrueShortF(&return_left);
    CompareF32(OLT, src2, src1);
    BranchTrueShortF(&return_right);
5217 5218

    // Left equals right => check for -0.
5219 5220 5221 5222 5223 5224
    {
      BlockTrampolinePoolScope block_trampoline_pool(this);
      mfc1(t8, src1);
      Branch(&return_right, eq, t8, Operand(zero_reg));
      Branch(&return_left);
    }
5225 5226

    bind(&return_right);
5227
    if (src2 != dst) {
5228 5229
      Move_s(dst, src2);
    }
5230
    Branch(&done);
5231 5232

    bind(&return_left);
5233
    if (src1 != dst) {
5234 5235 5236 5237 5238 5239 5240
      Move_s(dst, src1);
    }

    bind(&done);
  }
}

5241
void TurboAssembler::Float32MinOutOfLine(FPURegister dst, FPURegister src1,
5242 5243 5244 5245
                                         FPURegister src2) {
  add_s(dst, src1, src2);
}

5246
void TurboAssembler::Float64Max(DoubleRegister dst, DoubleRegister src1,
5247
                                DoubleRegister src2, Label* out_of_line) {
5248
  ASM_CODE_COMMENT(this);
5249
  if (src1 == src2) {
5250 5251 5252
    Move_d(dst, src1);
    return;
  }
5253 5254

  // Check if one of operands is NaN.
5255 5256
  CompareIsNanF64(src1, src2);
  BranchTrueF(out_of_line);
5257 5258 5259 5260 5261 5262

  if (IsMipsArchVariant(kMips32r6)) {
    max_d(dst, src1, src2);
  } else {
    Label return_left, return_right, done;

5263 5264 5265 5266
    CompareF64(OLT, src1, src2);
    BranchTrueShortF(&return_right);
    CompareF64(OLT, src2, src1);
    BranchTrueShortF(&return_left);
5267 5268

    // Left equals right => check for -0.
5269 5270 5271 5272 5273 5274
    {
      BlockTrampolinePoolScope block_trampoline_pool(this);
      Mfhc1(t8, src1);
      Branch(&return_left, eq, t8, Operand(zero_reg));
      Branch(&return_right);
    }
5275 5276

    bind(&return_right);
5277
    if (src2 != dst) {
5278 5279
      Move_d(dst, src2);
    }
5280
    Branch(&done);
5281 5282

    bind(&return_left);
5283
    if (src1 != dst) {
5284 5285 5286 5287 5288 5289 5290
      Move_d(dst, src1);
    }

    bind(&done);
  }
}

5291
void TurboAssembler::Float64MaxOutOfLine(DoubleRegister dst,
5292 5293 5294 5295 5296
                                         DoubleRegister src1,
                                         DoubleRegister src2) {
  add_d(dst, src1, src2);
}

5297
void TurboAssembler::Float64Min(DoubleRegister dst, DoubleRegister src1,
5298
                                DoubleRegister src2, Label* out_of_line) {
5299
  ASM_CODE_COMMENT(this);
5300
  if (src1 == src2) {
5301 5302 5303
    Move_d(dst, src1);
    return;
  }
5304 5305

  // Check if one of operands is NaN.
5306 5307
  CompareIsNanF64(src1, src2);
  BranchTrueF(out_of_line);
5308 5309 5310 5311 5312 5313

  if (IsMipsArchVariant(kMips32r6)) {
    min_d(dst, src1, src2);
  } else {
    Label return_left, return_right, done;

5314 5315 5316 5317
    CompareF64(OLT, src1, src2);
    BranchTrueShortF(&return_left);
    CompareF64(OLT, src2, src1);
    BranchTrueShortF(&return_right);
5318 5319

    // Left equals right => check for -0.
5320 5321 5322 5323 5324 5325
    {
      BlockTrampolinePoolScope block_trampoline_pool(this);
      Mfhc1(t8, src1);
      Branch(&return_right, eq, t8, Operand(zero_reg));
      Branch(&return_left);
    }
5326 5327

    bind(&return_right);
5328
    if (src2 != dst) {
5329 5330
      Move_d(dst, src2);
    }
5331
    Branch(&done);
5332 5333

    bind(&return_left);
5334
    if (src1 != dst) {
5335 5336 5337 5338 5339 5340 5341
      Move_d(dst, src1);
    }

    bind(&done);
  }
}

5342
void TurboAssembler::Float64MinOutOfLine(DoubleRegister dst,
5343 5344 5345 5346
                                         DoubleRegister src1,
                                         DoubleRegister src2) {
  add_d(dst, src1, src2);
}
5347 5348 5349

static const int kRegisterPassedArguments = 4;

5350
int TurboAssembler::CalculateStackPassedWords(int num_reg_arguments,
5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362
                                              int num_double_arguments) {
  int stack_passed_words = 0;
  num_reg_arguments += 2 * num_double_arguments;

  // Up to four simple arguments are passed in registers a0..a3.
  if (num_reg_arguments > kRegisterPassedArguments) {
    stack_passed_words += num_reg_arguments - kRegisterPassedArguments;
  }
  stack_passed_words += kCArgSlotCount;
  return stack_passed_words;
}

5363
void TurboAssembler::PrepareCallCFunction(int num_reg_arguments,
5364 5365
                                          int num_double_arguments,
                                          Register scratch) {
5366
  ASM_CODE_COMMENT(this);
5367 5368 5369 5370 5371 5372 5373
  int frame_alignment = ActivationFrameAlignment();

  // Up to four simple arguments are passed in registers a0..a3.
  // Those four arguments must have reserved argument slots on the stack for
  // mips, even though those argument slots are not normally used.
  // Remaining arguments are pushed on the stack, above (higher address than)
  // the argument slots.
5374 5375
  int stack_passed_arguments =
      CalculateStackPassedWords(num_reg_arguments, num_double_arguments);
5376 5377 5378 5379 5380
  if (frame_alignment > kPointerSize) {
    // Make stack end at alignment and make room for num_arguments - 4 words
    // and the original value of sp.
    mov(scratch, sp);
    Subu(sp, sp, Operand((stack_passed_arguments + 1) * kPointerSize));
5381
    DCHECK(base::bits::IsPowerOfTwo(frame_alignment));
5382 5383 5384 5385 5386 5387 5388
    And(sp, sp, Operand(-frame_alignment));
    sw(scratch, MemOperand(sp, stack_passed_arguments * kPointerSize));
  } else {
    Subu(sp, sp, Operand(stack_passed_arguments * kPointerSize));
  }
}

5389
void TurboAssembler::PrepareCallCFunction(int num_reg_arguments,
5390 5391 5392 5393
                                          Register scratch) {
  PrepareCallCFunction(num_reg_arguments, 0, scratch);
}

5394
void TurboAssembler::CallCFunction(ExternalReference function,
5395 5396
                                   int num_reg_arguments,
                                   int num_double_arguments) {
5397
  ASM_CODE_COMMENT(this);
5398 5399 5400
  // Linux/MIPS convention demands that register t9 contains
  // the address of the function being call in case of
  // Position independent code
5401
  BlockTrampolinePoolScope block_trampoline_pool(this);
5402
  li(t9, function);
5403
  CallCFunctionHelper(t9, 0, num_reg_arguments, num_double_arguments);
5404 5405
}

5406
void TurboAssembler::CallCFunction(Register function, int num_reg_arguments,
5407
                                   int num_double_arguments) {
5408
  ASM_CODE_COMMENT(this);
5409
  CallCFunctionHelper(function, 0, num_reg_arguments, num_double_arguments);
5410 5411
}

5412
void TurboAssembler::CallCFunction(ExternalReference function,
5413 5414 5415 5416
                                   int num_arguments) {
  CallCFunction(function, num_arguments, 0);
}

5417
void TurboAssembler::CallCFunction(Register function, int num_arguments) {
5418
  CallCFunction(function, num_arguments, 0);
5419 5420
}

5421
void TurboAssembler::CallCFunctionHelper(Register function_base,
5422
                                         int16_t function_offset,
5423 5424
                                         int num_reg_arguments,
                                         int num_double_arguments) {
5425
  DCHECK_LE(num_reg_arguments + num_double_arguments, kMaxCParameters);
5426
  DCHECK(has_frame());
5427 5428 5429 5430 5431 5432
  // Make sure that the stack is aligned before calling a C function unless
  // running in the simulator. The simulator has its own alignment check which
  // provides more information.
  // The argument stots are presumed to have been set up by
  // PrepareCallCFunction. The C function must be called via t9, for mips ABI.

5433
#if V8_HOST_ARCH_MIPS
5434
  if (FLAG_debug_code) {
5435
    int frame_alignment = base::OS::ActivationFrameAlignment();
5436 5437
    int frame_alignment_mask = frame_alignment - 1;
    if (frame_alignment > kPointerSize) {
5438
      DCHECK(base::bits::IsPowerOfTwo(frame_alignment));
5439
      Label alignment_as_expected;
5440 5441 5442 5443
      UseScratchRegisterScope temps(this);
      Register scratch = temps.Acquire();
      And(scratch, sp, Operand(frame_alignment_mask));
      Branch(&alignment_as_expected, eq, scratch, Operand(zero_reg));
5444 5445
      // Don't use Check here, as it will call Runtime_Abort possibly
      // re-entering here.
5446
      stop();
5447
      bind(&alignment_as_expected);
5448 5449
    }
  }
5450 5451 5452 5453 5454 5455
#endif  // V8_HOST_ARCH_MIPS

  // Just call directly. The function called cannot cause a GC, or
  // allow preemption, so the return address in the link register
  // stays correct.

5456 5457 5458 5459 5460 5461
  {
    BlockTrampolinePoolScope block_trampoline_pool(this);
    if (function_base != t9) {
      mov(t9, function_base);
      function_base = t9;
    }
5462

5463 5464 5465 5466
    if (function_offset != 0) {
      addiu(t9, t9, function_offset);
      function_offset = 0;
    }
5467

5468 5469
    // Save the frame pointer and PC so that the stack layout remains iterable,
    // even without an ExitFrame which normally exists between JS and C frames.
5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491
    // 't' registers are caller-saved so this is safe as a scratch register.
    Register pc_scratch = t4;
    Register scratch = t5;
    DCHECK(!AreAliased(pc_scratch, scratch, function_base));

    mov(scratch, ra);
    nal();
    mov(pc_scratch, ra);
    mov(ra, scratch);

    // See x64 code for reasoning about how to address the isolate data fields.
    if (root_array_available()) {
      sw(pc_scratch, MemOperand(kRootRegister,
                                IsolateData::fast_c_call_caller_pc_offset()));
      sw(fp, MemOperand(kRootRegister,
                        IsolateData::fast_c_call_caller_fp_offset()));
    } else {
      DCHECK_NOT_NULL(isolate());
      li(scratch, ExternalReference::fast_c_call_caller_pc_address(isolate()));
      sw(pc_scratch, MemOperand(scratch));
      li(scratch, ExternalReference::fast_c_call_caller_fp_address(isolate()));
      sw(fp, MemOperand(scratch));
5492 5493
    }

5494
    Call(function_base, function_offset);
5495

5496 5497 5498 5499 5500 5501
    // We don't unset the PC; the FP is the source of truth.
    if (root_array_available()) {
      sw(zero_reg, MemOperand(kRootRegister,
                              IsolateData::fast_c_call_caller_fp_offset()));
    } else {
      DCHECK_NOT_NULL(isolate());
5502 5503 5504
      li(scratch, ExternalReference::fast_c_call_caller_fp_address(isolate()));
      sw(zero_reg, MemOperand(scratch));
    }
5505

5506 5507
    int stack_passed_arguments =
        CalculateStackPassedWords(num_reg_arguments, num_double_arguments);
5508

5509 5510 5511 5512 5513 5514 5515
    if (base::OS::ActivationFrameAlignment() > kPointerSize) {
      lw(sp, MemOperand(sp, stack_passed_arguments * kPointerSize));
    } else {
      Addu(sp, sp, Operand(stack_passed_arguments * kPointerSize));
    }

    set_pc_for_safepoint();
5516
  }
5517 5518
}

5519 5520
#undef BRANCH_ARGS_CHECK

5521 5522
void TurboAssembler::CheckPageFlag(Register object, Register scratch, int mask,
                                   Condition cc, Label* condition_met) {
5523
  ASM_CODE_COMMENT(this);
5524
  And(scratch, object, Operand(~kPageAlignmentMask));
5525
  lw(scratch, MemOperand(scratch, BasicMemoryChunk::kFlagsOffset));
5526 5527 5528 5529
  And(scratch, scratch, Operand(mask));
  Branch(condition_met, cc, scratch, Operand(zero_reg));
}

5530 5531
Register GetRegisterThatIsNotOneOf(Register reg1, Register reg2, Register reg3,
                                   Register reg4, Register reg5,
5532
                                   Register reg6) {
5533
  RegList regs = {reg1, reg2, reg3, reg4, reg5, reg6};
5534

5535
  const RegisterConfiguration* config = RegisterConfiguration::Default();
5536 5537 5538
  for (int i = 0; i < config->num_allocatable_general_registers(); ++i) {
    int code = config->GetAllocatableGeneralCode(i);
    Register candidate = Register::from_code(code);
5539
    if (regs.has(candidate)) continue;
5540 5541 5542 5543 5544
    return candidate;
  }
  UNREACHABLE();
}

5545 5546 5547 5548 5549
void TurboAssembler::ComputeCodeStartAddress(Register dst) {
  // This push on ra and the pop below together ensure that we restore the
  // register ra, which is needed while computing the code start address.
  push(ra);

5550
  // The nal instruction puts the address of the current instruction into
5551
  // the return address (ra) register, which we can use later on.
5552 5553 5554 5555 5556 5557
  if (IsMipsArchVariant(kMips32r6)) {
    addiupc(ra, 1);
  } else {
    nal();
    nop();
  }
5558 5559 5560 5561 5562 5563 5564
  int pc = pc_offset();
  li(dst, pc);
  subu(dst, ra, dst);

  pop(ra);  // Restore ra
}

5565 5566 5567
void TurboAssembler::CallForDeoptimization(Builtin target, int, Label* exit,
                                           DeoptimizeKind kind, Label* ret,
                                           Label*) {
5568
  ASM_CODE_COMMENT(this);
5569 5570
  BlockTrampolinePoolScope block_trampoline_pool(this);
  Lw(t9,
5571
     MemOperand(kRootRegister, IsolateData::BuiltinEntrySlotOffset(target)));
5572 5573
  Call(t9);
  DCHECK_EQ(SizeOfCodeGeneratedSince(exit),
5574 5575
            (kind == DeoptimizeKind::kLazy) ? Deoptimizer::kLazyDeoptExitSize
                                            : Deoptimizer::kEagerDeoptExitSize);
5576 5577
}

5578 5579
void TurboAssembler::LoadCodeObjectEntry(Register destination,
                                         Register code_object) {
5580
  ASM_CODE_COMMENT(this);
5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592
  // Code objects are called differently depending on whether we are generating
  // builtin code (which will later be embedded into the binary) or compiling
  // user JS code at runtime.
  // * Builtin code runs in --jitless mode and thus must not call into on-heap
  //   Code targets. Instead, we dispatch through the builtins entry table.
  // * Codegen at runtime does not have this restriction and we can use the
  //   shorter, branchless instruction sequence. The assumption here is that
  //   targets are usually generated code and not builtin Code objects.
  if (options().isolate_independent_code) {
    DCHECK(root_array_available());
    Label if_code_is_off_heap, out;

5593
    Register scratch = kScratchReg;
5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623
    DCHECK(!AreAliased(destination, scratch));
    DCHECK(!AreAliased(code_object, scratch));

    // Check whether the Code object is an off-heap trampoline. If so, call its
    // (off-heap) entry point directly without going through the (on-heap)
    // trampoline.  Otherwise, just call the Code object as always.
    Lw(scratch, FieldMemOperand(code_object, Code::kFlagsOffset));
    And(scratch, scratch, Operand(Code::IsOffHeapTrampoline::kMask));
    Branch(&if_code_is_off_heap, ne, scratch, Operand(zero_reg));

    // Not an off-heap trampoline object, the entry point is at
    // Code::raw_instruction_start().
    Addu(destination, code_object, Code::kHeaderSize - kHeapObjectTag);
    Branch(&out);

    // An off-heap trampoline, the entry point is loaded from the builtin entry
    // table.
    bind(&if_code_is_off_heap);
    Lw(scratch, FieldMemOperand(code_object, Code::kBuiltinIndexOffset));
    Lsa(destination, kRootRegister, scratch, kSystemPointerSizeLog2);
    Lw(destination,
       MemOperand(destination, IsolateData::builtin_entry_table_offset()));

    bind(&out);
  } else {
    Addu(destination, code_object, Code::kHeaderSize - kHeapObjectTag);
  }
}

void TurboAssembler::CallCodeObject(Register code_object) {
5624
  ASM_CODE_COMMENT(this);
5625 5626 5627 5628
  LoadCodeObjectEntry(code_object, code_object);
  Call(code_object);
}
void TurboAssembler::JumpCodeObject(Register code_object, JumpMode jump_mode) {
5629
  ASM_CODE_COMMENT(this);
5630 5631 5632 5633 5634
  DCHECK_EQ(JumpMode::kJump, jump_mode);
  LoadCodeObjectEntry(code_object, code_object);
  Jump(code_object);
}

5635 5636
}  // namespace internal
}  // namespace v8
5637

5638
#endif  // V8_TARGET_ARCH_MIPS