simulator-mips64.cc 240 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// Copyright 2011 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <limits.h>
#include <stdarg.h>
#include <stdlib.h>
#include <cmath>

#if V8_TARGET_ARCH_MIPS64

12
#include "src/assembler-inl.h"
13
#include "src/base/bits.h"
14
#include "src/codegen.h"
15
#include "src/disasm.h"
16
#include "src/macro-assembler.h"
17 18
#include "src/mips64/constants-mips64.h"
#include "src/mips64/simulator-mips64.h"
19
#include "src/ostreams.h"
20
#include "src/runtime/runtime-utils.h"
21 22 23 24 25 26 27

// Only build the simulator if not compiling for real MIPS hardware.
#if defined(USE_SIMULATOR)

namespace v8 {
namespace internal {

28 29
// Util functions.
inline bool HaveSameSign(int64_t a, int64_t b) { return ((a ^ b) >= 0); }
30 31 32 33 34 35 36 37 38 39 40 41 42 43

uint32_t get_fcsr_condition_bit(uint32_t cc) {
  if (cc == 0) {
    return 23;
  } else {
    return 24 + cc;
  }
}


static int64_t MultiplyHighSigned(int64_t u, int64_t v) {
  uint64_t u0, v0, w0;
  int64_t u1, v1, w1, w2, t;

44
  u0 = u & 0xFFFFFFFFL;
45
  u1 = u >> 32;
46
  v0 = v & 0xFFFFFFFFL;
47 48 49 50
  v1 = v >> 32;

  w0 = u0 * v0;
  t = u1 * v0 + (w0 >> 32);
51
  w1 = t & 0xFFFFFFFFL;
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
  w2 = t >> 32;
  w1 = u0 * v1 + w1;

  return u1 * v1 + w2 + (w1 >> 32);
}


// This macro provides a platform independent use of sscanf. The reason for
// SScanF not being implemented in a platform independent was through
// ::v8::internal::OS in the same way as SNPrintF is that the Windows C Run-Time
// Library does not provide vsscanf.
#define SScanF sscanf  // NOLINT

// The MipsDebugger class is used by the simulator while debugging simulated
// code.
class MipsDebugger {
 public:
  explicit MipsDebugger(Simulator* sim) : sim_(sim) { }

  void Stop(Instruction* instr);
  void Debug();
  // Print all registers with a nice formatting.
  void PrintAllRegs();
  void PrintAllRegsIncludingFPU();

 private:
78 79
  // We set the breakpoint code to 0xFFFFF to easily recognize it.
  static const Instr kBreakpointInstr = SPECIAL | BREAK | 0xFFFFF << 6;
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  static const Instr kNopInstr =  0x0;

  Simulator* sim_;

  int64_t GetRegisterValue(int regnum);
  int64_t GetFPURegisterValue(int regnum);
  float GetFPURegisterValueFloat(int regnum);
  double GetFPURegisterValueDouble(int regnum);
  bool GetValue(const char* desc, int64_t* value);

  // Set or delete a breakpoint. Returns true if successful.
  bool SetBreakpoint(Instruction* breakpc);
  bool DeleteBreakpoint(Instruction* breakpc);

  // Undo and redo all breakpoints. This is needed to bracket disassembly and
  // execution to skip past breakpoints when run from the debugger.
  void UndoBreakpoints();
  void RedoBreakpoints();
};

100
inline void UNSUPPORTED() { printf("Sim: Unsupported instruction.\n"); }
101 102 103 104

void MipsDebugger::Stop(Instruction* instr) {
  // Get the stop code.
  uint32_t code = instr->Bits(25, 6);
105
  PrintF("Simulator hit (%u)\n", code);
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  Debug();
}

int64_t MipsDebugger::GetRegisterValue(int regnum) {
  if (regnum == kNumSimuRegisters) {
    return sim_->get_pc();
  } else {
    return sim_->get_register(regnum);
  }
}


int64_t MipsDebugger::GetFPURegisterValue(int regnum) {
  if (regnum == kNumFPURegisters) {
    return sim_->get_pc();
  } else {
    return sim_->get_fpu_register(regnum);
  }
}


float MipsDebugger::GetFPURegisterValueFloat(int regnum) {
  if (regnum == kNumFPURegisters) {
    return sim_->get_pc();
  } else {
    return sim_->get_fpu_register_float(regnum);
  }
}


double MipsDebugger::GetFPURegisterValueDouble(int regnum) {
  if (regnum == kNumFPURegisters) {
    return sim_->get_pc();
  } else {
    return sim_->get_fpu_register_double(regnum);
  }
}


bool MipsDebugger::GetValue(const char* desc, int64_t* value) {
  int regnum = Registers::Number(desc);
  int fpuregnum = FPURegisters::Number(desc);

  if (regnum != kInvalidRegister) {
    *value = GetRegisterValue(regnum);
    return true;
  } else if (fpuregnum != kInvalidFPURegister) {
    *value = GetFPURegisterValue(fpuregnum);
    return true;
  } else if (strncmp(desc, "0x", 2) == 0) {
    return SScanF(desc + 2, "%" SCNx64,
                  reinterpret_cast<uint64_t*>(value)) == 1;
  } else {
    return SScanF(desc, "%" SCNu64, reinterpret_cast<uint64_t*>(value)) == 1;
  }
  return false;
}


bool MipsDebugger::SetBreakpoint(Instruction* breakpc) {
  // Check if a breakpoint can be set. If not return without any side-effects.
167
  if (sim_->break_pc_ != nullptr) {
168 169 170 171 172 173 174 175 176 177 178 179 180
    return false;
  }

  // Set the breakpoint.
  sim_->break_pc_ = breakpc;
  sim_->break_instr_ = breakpc->InstructionBits();
  // Not setting the breakpoint instruction in the code itself. It will be set
  // when the debugger shell continues.
  return true;
}


bool MipsDebugger::DeleteBreakpoint(Instruction* breakpc) {
181
  if (sim_->break_pc_ != nullptr) {
182 183 184
    sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
  }

185
  sim_->break_pc_ = nullptr;
186 187 188 189 190 191
  sim_->break_instr_ = 0;
  return true;
}


void MipsDebugger::UndoBreakpoints() {
192
  if (sim_->break_pc_ != nullptr) {
193 194 195 196 197 198
    sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
  }
}


void MipsDebugger::RedoBreakpoints() {
199
  if (sim_->break_pc_ != nullptr) {
200 201 202 203 204 205 206 207 208 209
    sim_->break_pc_->SetInstructionBits(kBreakpointInstr);
  }
}


void MipsDebugger::PrintAllRegs() {
#define REG_INFO(n) Registers::Name(n), GetRegisterValue(n), GetRegisterValue(n)

  PrintF("\n");
  // at, v0, a0.
210 211
  PrintF("%3s: 0x%016" PRIx64 " %14" PRId64 "\t%3s: 0x%016" PRIx64 " %14" PRId64
         "\t%3s: 0x%016" PRIx64 " %14" PRId64 "\n",
212 213
         REG_INFO(1), REG_INFO(2), REG_INFO(4));
  // v1, a1.
214 215
  PrintF("%34s\t%3s: 0x%016" PRIx64 "  %14" PRId64 " \t%3s: 0x%016" PRIx64
         "  %14" PRId64 " \n",
216 217
         "", REG_INFO(3), REG_INFO(5));
  // a2.
218 219
  PrintF("%34s\t%34s\t%3s: 0x%016" PRIx64 "  %14" PRId64 " \n", "", "",
         REG_INFO(6));
220
  // a3.
221 222
  PrintF("%34s\t%34s\t%3s: 0x%016" PRIx64 "  %14" PRId64 " \n", "", "",
         REG_INFO(7));
223 224 225
  PrintF("\n");
  // a4-t3, s0-s7
  for (int i = 0; i < 8; i++) {
226 227 228
    PrintF("%3s: 0x%016" PRIx64 "  %14" PRId64 " \t%3s: 0x%016" PRIx64
           "  %14" PRId64 " \n",
           REG_INFO(8 + i), REG_INFO(16 + i));
229 230 231
  }
  PrintF("\n");
  // t8, k0, LO.
232 233
  PrintF("%3s: 0x%016" PRIx64 "  %14" PRId64 " \t%3s: 0x%016" PRIx64
         "  %14" PRId64 " \t%3s: 0x%016" PRIx64 "  %14" PRId64 " \n",
234 235
         REG_INFO(24), REG_INFO(26), REG_INFO(32));
  // t9, k1, HI.
236 237
  PrintF("%3s: 0x%016" PRIx64 "  %14" PRId64 " \t%3s: 0x%016" PRIx64
         "  %14" PRId64 " \t%3s: 0x%016" PRIx64 "  %14" PRId64 " \n",
238 239
         REG_INFO(25), REG_INFO(27), REG_INFO(33));
  // sp, fp, gp.
240 241
  PrintF("%3s: 0x%016" PRIx64 "  %14" PRId64 " \t%3s: 0x%016" PRIx64
         "  %14" PRId64 " \t%3s: 0x%016" PRIx64 "  %14" PRId64 " \n",
242 243
         REG_INFO(29), REG_INFO(30), REG_INFO(28));
  // pc.
244 245
  PrintF("%3s: 0x%016" PRIx64 "  %14" PRId64 " \t%3s: 0x%016" PRIx64
         "  %14" PRId64 " \n",
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
         REG_INFO(31), REG_INFO(34));

#undef REG_INFO
#undef FPU_REG_INFO
}


void MipsDebugger::PrintAllRegsIncludingFPU() {
#define FPU_REG_INFO(n) FPURegisters::Name(n), \
        GetFPURegisterValue(n), \
        GetFPURegisterValueDouble(n)

  PrintAllRegs();

  PrintF("\n\n");
  // f0, f1, f2, ... f31.
  // TODO(plind): consider printing 2 columns for space efficiency.
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(0));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(1));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(2));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(3));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(4));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(5));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(6));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(7));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(8));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(9));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(10));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(11));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(12));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(13));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(14));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(15));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(16));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(17));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(18));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(19));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(20));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(21));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(22));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(23));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(24));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(25));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(26));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(27));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(28));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(29));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(30));
  PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n", FPU_REG_INFO(31));
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332

#undef REG_INFO
#undef FPU_REG_INFO
}


void MipsDebugger::Debug() {
  intptr_t last_pc = -1;
  bool done = false;

#define COMMAND_SIZE 63
#define ARG_SIZE 255

#define STR(a) #a
#define XSTR(a) STR(a)

  char cmd[COMMAND_SIZE + 1];
  char arg1[ARG_SIZE + 1];
  char arg2[ARG_SIZE + 1];
  char* argv[3] = { cmd, arg1, arg2 };

  // Make sure to have a proper terminating character if reaching the limit.
  cmd[COMMAND_SIZE] = 0;
  arg1[ARG_SIZE] = 0;
  arg2[ARG_SIZE] = 0;

  // Undo all set breakpoints while running in the debugger shell. This will
  // make them invisible to all commands.
  UndoBreakpoints();

  while (!done && (sim_->get_pc() != Simulator::end_sim_pc)) {
    if (last_pc != sim_->get_pc()) {
      disasm::NameConverter converter;
      disasm::Disassembler dasm(converter);
      // Use a reasonably large buffer.
      v8::internal::EmbeddedVector<char, 256> buffer;
      dasm.InstructionDecode(buffer,
                             reinterpret_cast<byte*>(sim_->get_pc()));
333
      PrintF("  0x%016" PRIx64 "   %s\n", sim_->get_pc(), buffer.start());
334 335 336
      last_pc = sim_->get_pc();
    }
    char* line = ReadLine("sim> ");
337
    if (line == nullptr) {
338 339 340
      break;
    } else {
      char* last_input = sim_->last_debugger_input();
341
      if (strcmp(line, "\n") == 0 && last_input != nullptr) {
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
        line = last_input;
      } else {
        // Ownership is transferred to sim_;
        sim_->set_last_debugger_input(line);
      }
      // Use sscanf to parse the individual parts of the command line. At the
      // moment no command expects more than two parameters.
      int argc = SScanF(line,
                        "%" XSTR(COMMAND_SIZE) "s "
                        "%" XSTR(ARG_SIZE) "s "
                        "%" XSTR(ARG_SIZE) "s",
                        cmd, arg1, arg2);
      if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) {
        Instruction* instr = reinterpret_cast<Instruction*>(sim_->get_pc());
        if (!(instr->IsTrap()) ||
            instr->InstructionBits() == rtCallRedirInstr) {
          sim_->InstructionDecode(
              reinterpret_cast<Instruction*>(sim_->get_pc()));
        } else {
          // Allow si to jump over generated breakpoints.
          PrintF("/!\\ Jumping over generated breakpoint.\n");
363
          sim_->set_pc(sim_->get_pc() + kInstrSize);
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
        }
      } else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) {
        // Execute the one instruction we broke at with breakpoints disabled.
        sim_->InstructionDecode(reinterpret_cast<Instruction*>(sim_->get_pc()));
        // Leave the debugger shell.
        done = true;
      } else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) {
        if (argc == 2) {
          int64_t value;
          double dvalue;
          if (strcmp(arg1, "all") == 0) {
            PrintAllRegs();
          } else if (strcmp(arg1, "allf") == 0) {
            PrintAllRegsIncludingFPU();
          } else {
            int regnum = Registers::Number(arg1);
            int fpuregnum = FPURegisters::Number(arg1);

            if (regnum != kInvalidRegister) {
              value = GetRegisterValue(regnum);
384 385
              PrintF("%s: 0x%08" PRIx64 "  %" PRId64 "  \n", arg1, value,
                     value);
386 387 388
            } else if (fpuregnum != kInvalidFPURegister) {
              value = GetFPURegisterValue(fpuregnum);
              dvalue = GetFPURegisterValueDouble(fpuregnum);
389
              PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n",
390 391 392 393 394 395 396 397 398 399 400 401 402 403
                     FPURegisters::Name(fpuregnum), value, dvalue);
            } else {
              PrintF("%s unrecognized\n", arg1);
            }
          }
        } else {
          if (argc == 3) {
            if (strcmp(arg2, "single") == 0) {
              int64_t value;
              float fvalue;
              int fpuregnum = FPURegisters::Number(arg1);

              if (fpuregnum != kInvalidFPURegister) {
                value = GetFPURegisterValue(fpuregnum);
404
                value &= 0xFFFFFFFFUL;
405
                fvalue = GetFPURegisterValueFloat(fpuregnum);
406
                PrintF("%s: 0x%08" PRIx64 "  %11.4e\n", arg1, value, fvalue);
407 408 409 410 411 412 413 414 415 416 417 418 419 420
              } else {
                PrintF("%s unrecognized\n", arg1);
              }
            } else {
              PrintF("print <fpu register> single\n");
            }
          } else {
            PrintF("print <register> or print <fpu register> single\n");
          }
        }
      } else if ((strcmp(cmd, "po") == 0)
                 || (strcmp(cmd, "printobject") == 0)) {
        if (argc == 2) {
          int64_t value;
421
          StdoutStream os;
422 423 424 425
          if (GetValue(arg1, &value)) {
            Object* obj = reinterpret_cast<Object*>(value);
            os << arg1 << ": \n";
#ifdef DEBUG
426
            obj->Print(os);
427 428 429 430 431 432 433 434 435 436 437
            os << "\n";
#else
            os << Brief(obj) << "\n";
#endif
          } else {
            os << arg1 << " unrecognized\n";
          }
        } else {
          PrintF("printobject <value>\n");
        }
      } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) {
438 439
        int64_t* cur = nullptr;
        int64_t* end = nullptr;
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
        int next_arg = 1;

        if (strcmp(cmd, "stack") == 0) {
          cur = reinterpret_cast<int64_t*>(sim_->get_register(Simulator::sp));
        } else {  // Command "mem".
          int64_t value;
          if (!GetValue(arg1, &value)) {
            PrintF("%s unrecognized\n", arg1);
            continue;
          }
          cur = reinterpret_cast<int64_t*>(value);
          next_arg++;
        }

        int64_t words;
        if (argc == next_arg) {
          words = 10;
        } else {
          if (!GetValue(argv[next_arg], &words)) {
            words = 10;
          }
        }
        end = cur + words;

        while (cur < end) {
465
          PrintF("  0x%012" PRIxPTR " :  0x%016" PRIx64 "  %14" PRId64 " ",
466 467 468
                 reinterpret_cast<intptr_t>(cur), *cur, *cur);
          HeapObject* obj = reinterpret_cast<HeapObject*>(*cur);
          int64_t value = *cur;
469
          Heap* current_heap = sim_->isolate_->heap();
470 471
          if (((value & 1) == 0) ||
              current_heap->ContainsSlow(obj->address())) {
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
            PrintF(" (");
            if ((value & 1) == 0) {
              PrintF("smi %d", static_cast<int>(value >> 32));
            } else {
              obj->ShortPrint();
            }
            PrintF(")");
          }
          PrintF("\n");
          cur++;
        }

      } else if ((strcmp(cmd, "disasm") == 0) ||
                 (strcmp(cmd, "dpc") == 0) ||
                 (strcmp(cmd, "di") == 0)) {
        disasm::NameConverter converter;
        disasm::Disassembler dasm(converter);
        // Use a reasonably large buffer.
        v8::internal::EmbeddedVector<char, 256> buffer;

492 493
        byte* cur = nullptr;
        byte* end = nullptr;
494 495 496

        if (argc == 1) {
          cur = reinterpret_cast<byte*>(sim_->get_pc());
497
          end = cur + (10 * kInstrSize);
498 499 500 501 502 503 504 505
        } else if (argc == 2) {
          int regnum = Registers::Number(arg1);
          if (regnum != kInvalidRegister || strncmp(arg1, "0x", 2) == 0) {
            // The argument is an address or a register name.
            int64_t value;
            if (GetValue(arg1, &value)) {
              cur = reinterpret_cast<byte*>(value);
              // Disassemble 10 instructions at <arg1>.
506
              end = cur + (10 * kInstrSize);
507 508 509 510 511 512 513
            }
          } else {
            // The argument is the number of instructions.
            int64_t value;
            if (GetValue(arg1, &value)) {
              cur = reinterpret_cast<byte*>(sim_->get_pc());
              // Disassemble <arg1> instructions.
514
              end = cur + (value * kInstrSize);
515 516 517 518 519 520 521
            }
          }
        } else {
          int64_t value1;
          int64_t value2;
          if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
            cur = reinterpret_cast<byte*>(value1);
522
            end = cur + (value2 * kInstrSize);
523 524 525 526 527
          }
        }

        while (cur < end) {
          dasm.InstructionDecode(buffer, cur);
528 529
          PrintF("  0x%08" PRIxPTR "   %s\n", reinterpret_cast<intptr_t>(cur),
                 buffer.start());
530
          cur += kInstrSize;
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
        }
      } else if (strcmp(cmd, "gdb") == 0) {
        PrintF("relinquishing control to gdb\n");
        v8::base::OS::DebugBreak();
        PrintF("regaining control from gdb\n");
      } else if (strcmp(cmd, "break") == 0) {
        if (argc == 2) {
          int64_t value;
          if (GetValue(arg1, &value)) {
            if (!SetBreakpoint(reinterpret_cast<Instruction*>(value))) {
              PrintF("setting breakpoint failed\n");
            }
          } else {
            PrintF("%s unrecognized\n", arg1);
          }
        } else {
          PrintF("break <address>\n");
        }
      } else if (strcmp(cmd, "del") == 0) {
550
        if (!DeleteBreakpoint(nullptr)) {
551 552 553 554 555 556
          PrintF("deleting breakpoint failed\n");
        }
      } else if (strcmp(cmd, "flags") == 0) {
        PrintF("No flags on MIPS !\n");
      } else if (strcmp(cmd, "stop") == 0) {
        int64_t value;
557
        intptr_t stop_pc = sim_->get_pc() - 2 * kInstrSize;
558 559
        Instruction* stop_instr = reinterpret_cast<Instruction*>(stop_pc);
        Instruction* msg_address =
560
            reinterpret_cast<Instruction*>(stop_pc + kInstrSize);
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
        if ((argc == 2) && (strcmp(arg1, "unstop") == 0)) {
          // Remove the current stop.
          if (sim_->IsStopInstruction(stop_instr)) {
            stop_instr->SetInstructionBits(kNopInstr);
            msg_address->SetInstructionBits(kNopInstr);
          } else {
            PrintF("Not at debugger stop.\n");
          }
        } else if (argc == 3) {
          // Print information about all/the specified breakpoint(s).
          if (strcmp(arg1, "info") == 0) {
            if (strcmp(arg2, "all") == 0) {
              PrintF("Stop information:\n");
              for (uint32_t i = kMaxWatchpointCode + 1;
                   i <= kMaxStopCode;
                   i++) {
                sim_->PrintStopInfo(i);
              }
            } else if (GetValue(arg2, &value)) {
              sim_->PrintStopInfo(value);
            } else {
              PrintF("Unrecognized argument.\n");
            }
          } else if (strcmp(arg1, "enable") == 0) {
            // Enable all/the specified breakpoint(s).
            if (strcmp(arg2, "all") == 0) {
              for (uint32_t i = kMaxWatchpointCode + 1;
                   i <= kMaxStopCode;
                   i++) {
                sim_->EnableStop(i);
              }
            } else if (GetValue(arg2, &value)) {
              sim_->EnableStop(value);
            } else {
              PrintF("Unrecognized argument.\n");
            }
          } else if (strcmp(arg1, "disable") == 0) {
            // Disable all/the specified breakpoint(s).
            if (strcmp(arg2, "all") == 0) {
              for (uint32_t i = kMaxWatchpointCode + 1;
                   i <= kMaxStopCode;
                   i++) {
                sim_->DisableStop(i);
              }
            } else if (GetValue(arg2, &value)) {
              sim_->DisableStop(value);
            } else {
              PrintF("Unrecognized argument.\n");
            }
          }
        } else {
          PrintF("Wrong usage. Use help command for more information.\n");
        }
      } else if ((strcmp(cmd, "stat") == 0) || (strcmp(cmd, "st") == 0)) {
        // Print registers and disassemble.
        PrintAllRegs();
        PrintF("\n");

        disasm::NameConverter converter;
        disasm::Disassembler dasm(converter);
        // Use a reasonably large buffer.
        v8::internal::EmbeddedVector<char, 256> buffer;

624 625
        byte* cur = nullptr;
        byte* end = nullptr;
626 627 628

        if (argc == 1) {
          cur = reinterpret_cast<byte*>(sim_->get_pc());
629
          end = cur + (10 * kInstrSize);
630 631 632 633 634
        } else if (argc == 2) {
          int64_t value;
          if (GetValue(arg1, &value)) {
            cur = reinterpret_cast<byte*>(value);
            // no length parameter passed, assume 10 instructions
635
            end = cur + (10 * kInstrSize);
636 637 638 639 640 641
          }
        } else {
          int64_t value1;
          int64_t value2;
          if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
            cur = reinterpret_cast<byte*>(value1);
642
            end = cur + (value2 * kInstrSize);
643 644 645 646 647
          }
        }

        while (cur < end) {
          dasm.InstructionDecode(buffer, cur);
648 649
          PrintF("  0x%08" PRIxPTR "   %s\n", reinterpret_cast<intptr_t>(cur),
                 buffer.start());
650
          cur += kInstrSize;
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
        }
      } else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) {
        PrintF("cont\n");
        PrintF("  continue execution (alias 'c')\n");
        PrintF("stepi\n");
        PrintF("  step one instruction (alias 'si')\n");
        PrintF("print <register>\n");
        PrintF("  print register content (alias 'p')\n");
        PrintF("  use register name 'all' to print all registers\n");
        PrintF("printobject <register>\n");
        PrintF("  print an object from a register (alias 'po')\n");
        PrintF("stack [<words>]\n");
        PrintF("  dump stack content, default dump 10 words)\n");
        PrintF("mem <address> [<words>]\n");
        PrintF("  dump memory content, default dump 10 words)\n");
        PrintF("flags\n");
        PrintF("  print flags\n");
        PrintF("disasm [<instructions>]\n");
        PrintF("disasm [<address/register>]\n");
        PrintF("disasm [[<address/register>] <instructions>]\n");
        PrintF("  disassemble code, default is 10 instructions\n");
        PrintF("  from pc (alias 'di')\n");
        PrintF("gdb\n");
        PrintF("  enter gdb\n");
        PrintF("break <address>\n");
        PrintF("  set a break point on the address\n");
        PrintF("del\n");
        PrintF("  delete the breakpoint\n");
        PrintF("stop feature:\n");
        PrintF("  Description:\n");
        PrintF("    Stops are debug instructions inserted by\n");
        PrintF("    the Assembler::stop() function.\n");
        PrintF("    When hitting a stop, the Simulator will\n");
684
        PrintF("    stop and give control to the Debugger.\n");
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
        PrintF("    All stop codes are watched:\n");
        PrintF("    - They can be enabled / disabled: the Simulator\n");
        PrintF("       will / won't stop when hitting them.\n");
        PrintF("    - The Simulator keeps track of how many times they \n");
        PrintF("      are met. (See the info command.) Going over a\n");
        PrintF("      disabled stop still increases its counter. \n");
        PrintF("  Commands:\n");
        PrintF("    stop info all/<code> : print infos about number <code>\n");
        PrintF("      or all stop(s).\n");
        PrintF("    stop enable/disable all/<code> : enables / disables\n");
        PrintF("      all or number <code> stop(s)\n");
        PrintF("    stop unstop\n");
        PrintF("      ignore the stop instruction at the current location\n");
        PrintF("      from now on\n");
      } else {
        PrintF("Unknown command: %s\n", cmd);
      }
    }
  }

  // Add all the breakpoints back to stop execution and enter the debugger
  // shell when hit.
  RedoBreakpoints();

#undef COMMAND_SIZE
#undef ARG_SIZE

#undef STR
#undef XSTR
}

716
bool Simulator::ICacheMatch(void* one, void* two) {
717 718
  DCHECK_EQ(reinterpret_cast<intptr_t>(one) & CachePage::kPageMask, 0);
  DCHECK_EQ(reinterpret_cast<intptr_t>(two) & CachePage::kPageMask, 0);
719 720 721 722 723 724 725 726 727
  return one == two;
}


static uint32_t ICacheHash(void* key) {
  return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(key)) >> 2;
}


728
static bool AllOnOnePage(uintptr_t start, size_t size) {
729 730 731 732 733 734 735 736 737 738 739
  intptr_t start_page = (start & ~CachePage::kPageMask);
  intptr_t end_page = ((start + size) & ~CachePage::kPageMask);
  return start_page == end_page;
}


void Simulator::set_last_debugger_input(char* input) {
  DeleteArray(last_debugger_input_);
  last_debugger_input_ = input;
}

740 741 742 743
void Simulator::SetRedirectInstruction(Instruction* instruction) {
  instruction->SetInstructionBits(rtCallRedirInstr);
}

744 745
void Simulator::FlushICache(base::CustomMatcherHashMap* i_cache,
                            void* start_addr, size_t size) {
746 747 748 749 750 751 752 753 754 755 756
  int64_t start = reinterpret_cast<int64_t>(start_addr);
  int64_t intra_line = (start & CachePage::kLineMask);
  start -= intra_line;
  size += intra_line;
  size = ((size - 1) | CachePage::kLineMask) + 1;
  int offset = (start & CachePage::kPageMask);
  while (!AllOnOnePage(start, size - 1)) {
    int bytes_to_flush = CachePage::kPageSize - offset;
    FlushOnePage(i_cache, start, bytes_to_flush);
    start += bytes_to_flush;
    size -= bytes_to_flush;
757
    DCHECK_EQ((int64_t)0, start & CachePage::kPageMask);
758 759 760 761 762 763 764
    offset = 0;
  }
  if (size != 0) {
    FlushOnePage(i_cache, start, size);
  }
}

765 766
CachePage* Simulator::GetCachePage(base::CustomMatcherHashMap* i_cache,
                                   void* page) {
lpy's avatar
lpy committed
767
  base::HashMap::Entry* entry = i_cache->LookupOrInsert(page, ICacheHash(page));
768
  if (entry->value == nullptr) {
769 770 771 772 773 774 775 776
    CachePage* new_page = new CachePage();
    entry->value = new_page;
  }
  return reinterpret_cast<CachePage*>(entry->value);
}


// Flush from start up to and not including start + size.
777 778
void Simulator::FlushOnePage(base::CustomMatcherHashMap* i_cache,
                             intptr_t start, size_t size) {
779
  DCHECK_LE(size, CachePage::kPageSize);
780
  DCHECK(AllOnOnePage(start, size - 1));
781 782
  DCHECK_EQ(start & CachePage::kLineMask, 0);
  DCHECK_EQ(size & CachePage::kLineMask, 0);
783 784 785 786 787 788 789
  void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask));
  int offset = (start & CachePage::kPageMask);
  CachePage* cache_page = GetCachePage(i_cache, page);
  char* valid_bytemap = cache_page->ValidityByte(offset);
  memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift);
}

790 791
void Simulator::CheckICache(base::CustomMatcherHashMap* i_cache,
                            Instruction* instr) {
792 793 794 795 796 797 798 799 800 801 802
  int64_t address = reinterpret_cast<int64_t>(instr);
  void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask));
  void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask));
  int offset = (address & CachePage::kPageMask);
  CachePage* cache_page = GetCachePage(i_cache, page);
  char* cache_valid_byte = cache_page->ValidityByte(offset);
  bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID);
  char* cached_line = cache_page->CachedData(offset & ~CachePage::kLineMask);
  if (cache_hit) {
    // Check that the data in memory matches the contents of the I-cache.
    CHECK_EQ(0, memcmp(reinterpret_cast<void*>(instr),
803
                       cache_page->CachedData(offset), kInstrSize));
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
  } else {
    // Cache miss.  Load memory into the cache.
    memcpy(cached_line, line, CachePage::kLineLength);
    *cache_valid_byte = CachePage::LINE_VALID;
  }
}


Simulator::Simulator(Isolate* isolate) : isolate_(isolate) {
  // Set up simulator support first. Some of this information is needed to
  // setup the architecture state.
  stack_size_ = FLAG_sim_stack_size * KB;
  stack_ = reinterpret_cast<char*>(malloc(stack_size_));
  pc_modified_ = false;
  icount_ = 0;
  break_count_ = 0;
820
  break_pc_ = nullptr;
821 822 823 824 825 826 827 828
  break_instr_ = 0;

  // Set up architecture state.
  // All registers are initialized to zero to start with.
  for (int i = 0; i < kNumSimuRegisters; i++) {
    registers_[i] = 0;
  }
  for (int i = 0; i < kNumFPURegisters; i++) {
829 830
    FPUregisters_[2 * i] = 0;
    FPUregisters_[2 * i + 1] = 0;  // upper part for MSA ASE
831
  }
832 833 834

  if (kArchVariant == kMips64r6) {
    FCSR_ = kFCSRNaN2008FlagMask;
835
    MSACSR_ = 0;
836 837 838
  } else {
    FCSR_ = 0;
  }
839 840 841 842 843 844 845 846 847 848

  // The sp is initialized to point to the bottom (high address) of the
  // allocated stack area. To be safe in potential stack underflows we leave
  // some buffer below.
  registers_[sp] = reinterpret_cast<int64_t>(stack_) + stack_size_ - 64;
  // The ra and pc are initialized to a known bad value that will cause an
  // access violation if the simulator ever tries to execute it.
  registers_[pc] = bad_ra;
  registers_[ra] = bad_ra;

849
  last_debugger_input_ = nullptr;
850 851 852
}


853
Simulator::~Simulator() { free(stack_); }
854 855 856 857 858 859


// Get the active Simulator for the current thread.
Simulator* Simulator::current(Isolate* isolate) {
  v8::internal::Isolate::PerIsolateThreadData* isolate_data =
       isolate->FindOrAllocatePerThreadDataForThisThread();
860
  DCHECK_NOT_NULL(isolate_data);
861 862

  Simulator* sim = isolate_data->simulator();
863
  if (sim == nullptr) {
864 865 866 867 868 869 870 871 872 873 874
    // TODO(146): delete the simulator object when a thread/isolate goes away.
    sim = new Simulator(isolate);
    isolate_data->set_simulator(sim);
  }
  return sim;
}


// Sets the register in the architecture state. It will also deal with updating
// Simulator internal state for special registers such as PC.
void Simulator::set_register(int reg, int64_t value) {
875
  DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
876 877 878 879 880 881 882 883 884 885
  if (reg == pc) {
    pc_modified_ = true;
  }

  // Zero register always holds 0.
  registers_[reg] = (reg == 0) ? 0 : value;
}


void Simulator::set_dw_register(int reg, const int* dbl) {
886
  DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
887 888 889 890 891 892 893
  registers_[reg] = dbl[1];
  registers_[reg] = registers_[reg] << 32;
  registers_[reg] += dbl[0];
}


void Simulator::set_fpu_register(int fpureg, int64_t value) {
894
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
895
  FPUregisters_[fpureg * 2] = value;
896 897 898 899 900
}


void Simulator::set_fpu_register_word(int fpureg, int32_t value) {
  // Set ONLY lower 32-bits, leaving upper bits untouched.
901
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
902 903
  int32_t* pword;
  if (kArchEndian == kLittle) {
904
    pword = reinterpret_cast<int32_t*>(&FPUregisters_[fpureg * 2]);
905
  } else {
906
    pword = reinterpret_cast<int32_t*>(&FPUregisters_[fpureg * 2]) + 1;
907
  }
908 909 910 911 912 913
  *pword = value;
}


void Simulator::set_fpu_register_hi_word(int fpureg, int32_t value) {
  // Set ONLY upper 32-bits, leaving lower bits untouched.
914
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
915 916
  int32_t* phiword;
  if (kArchEndian == kLittle) {
917
    phiword = (reinterpret_cast<int32_t*>(&FPUregisters_[fpureg * 2])) + 1;
918
  } else {
919
    phiword = reinterpret_cast<int32_t*>(&FPUregisters_[fpureg * 2]);
920
  }
921 922 923 924 925
  *phiword = value;
}


void Simulator::set_fpu_register_float(int fpureg, float value) {
926
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
927
  *bit_cast<float*>(&FPUregisters_[fpureg * 2]) = value;
928 929 930 931
}


void Simulator::set_fpu_register_double(int fpureg, double value) {
932
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
933
  *bit_cast<double*>(&FPUregisters_[fpureg * 2]) = value;
934 935 936 937 938 939
}


// Get the register from the architecture state. This function does handle
// the special case of accessing the PC register.
int64_t Simulator::get_register(int reg) const {
940
  DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
941 942 943 944 945 946 947 948 949
  if (reg == 0)
    return 0;
  else
    return registers_[reg] + ((reg == pc) ? Instruction::kPCReadOffset : 0);
}


double Simulator::get_double_from_register_pair(int reg) {
  // TODO(plind): bad ABI stuff, refactor or remove.
950
  DCHECK((reg >= 0) && (reg < kNumSimuRegisters) && ((reg % 2) == 0));
951 952 953 954 955 956 957 958 959 960 961 962

  double dm_val = 0.0;
  // Read the bits from the unsigned integer register_[] array
  // into the double precision floating point value and return it.
  char buffer[sizeof(registers_[0])];
  memcpy(buffer, &registers_[reg], sizeof(registers_[0]));
  memcpy(&dm_val, buffer, sizeof(registers_[0]));
  return(dm_val);
}


int64_t Simulator::get_fpu_register(int fpureg) const {
963
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
964
  return FPUregisters_[fpureg * 2];
965 966 967 968
}


int32_t Simulator::get_fpu_register_word(int fpureg) const {
969
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
970
  return static_cast<int32_t>(FPUregisters_[fpureg * 2] & 0xFFFFFFFF);
971 972 973 974
}


int32_t Simulator::get_fpu_register_signed_word(int fpureg) const {
975
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
976
  return static_cast<int32_t>(FPUregisters_[fpureg * 2] & 0xFFFFFFFF);
977 978 979
}


980
int32_t Simulator::get_fpu_register_hi_word(int fpureg) const {
981
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
982
  return static_cast<int32_t>((FPUregisters_[fpureg * 2] >> 32) & 0xFFFFFFFF);
983 984 985 986
}


float Simulator::get_fpu_register_float(int fpureg) const {
987
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
988
  return *bit_cast<float*>(const_cast<int64_t*>(&FPUregisters_[fpureg * 2]));
989 990 991 992
}


double Simulator::get_fpu_register_double(int fpureg) const {
993
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
994
  return *bit_cast<double*>(&FPUregisters_[fpureg * 2]);
995 996
}

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
template <typename T>
void Simulator::get_msa_register(int wreg, T* value) {
  DCHECK((wreg >= 0) && (wreg < kNumMSARegisters));
  memcpy(value, FPUregisters_ + wreg * 2, kSimd128Size);
}

template <typename T>
void Simulator::set_msa_register(int wreg, const T* value) {
  DCHECK((wreg >= 0) && (wreg < kNumMSARegisters));
  memcpy(FPUregisters_ + wreg * 2, value, kSimd128Size);
}
1008 1009 1010 1011 1012 1013

// Runtime FP routines take up to two double arguments and zero
// or one integer arguments. All are constructed here,
// from a0-a3 or f12 and f13 (n64), or f14 (O32).
void Simulator::GetFpArgs(double* x, double* y, int32_t* z) {
  if (!IsMipsSoftFloatABI) {
1014
    const int fparg2 = 13;
1015 1016
    *x = get_fpu_register_double(12);
    *y = get_fpu_register_double(fparg2);
1017
    *z = static_cast<int32_t>(get_register(a2));
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
  } else {
  // TODO(plind): bad ABI stuff, refactor or remove.
    // We use a char buffer to get around the strict-aliasing rules which
    // otherwise allow the compiler to optimize away the copy.
    char buffer[sizeof(*x)];
    int32_t* reg_buffer = reinterpret_cast<int32_t*>(buffer);

    // Registers a0 and a1 -> x.
    reg_buffer[0] = get_register(a0);
    reg_buffer[1] = get_register(a1);
    memcpy(x, buffer, sizeof(buffer));
    // Registers a2 and a3 -> y.
    reg_buffer[0] = get_register(a2);
    reg_buffer[1] = get_register(a3);
    memcpy(y, buffer, sizeof(buffer));
    // Register 2 -> z.
    reg_buffer[0] = get_register(a2);
    memcpy(z, buffer, sizeof(*z));
  }
}


// The return value is either in v0/v1 or f0.
void Simulator::SetFpResult(const double& result) {
  if (!IsMipsSoftFloatABI) {
    set_fpu_register_double(0, result);
  } else {
    char buffer[2 * sizeof(registers_[0])];
    int64_t* reg_buffer = reinterpret_cast<int64_t*>(buffer);
    memcpy(buffer, &result, sizeof(buffer));
    // Copy result to v0 and v1.
    set_register(v0, reg_buffer[0]);
    set_register(v1, reg_buffer[1]);
  }
}


// Helper functions for setting and testing the FCSR register's bits.
void Simulator::set_fcsr_bit(uint32_t cc, bool value) {
  if (value) {
    FCSR_ |= (1 << cc);
  } else {
    FCSR_ &= ~(1 << cc);
  }
}


bool Simulator::test_fcsr_bit(uint32_t cc) {
  return FCSR_ & (1 << cc);
}


1070 1071 1072 1073
void Simulator::set_fcsr_rounding_mode(FPURoundingMode mode) {
  FCSR_ |= mode & kFPURoundingModeMask;
}

1074 1075 1076
void Simulator::set_msacsr_rounding_mode(FPURoundingMode mode) {
  MSACSR_ |= mode & kFPURoundingModeMask;
}
1077 1078 1079 1080 1081

unsigned int Simulator::get_fcsr_rounding_mode() {
  return FCSR_ & kFPURoundingModeMask;
}

1082 1083 1084
unsigned int Simulator::get_msacsr_rounding_mode() {
  return MSACSR_ & kFPURoundingModeMask;
}
1085

1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
// Sets the rounding error codes in FCSR based on the result of the rounding.
// Returns true if the operation was invalid.
bool Simulator::set_fcsr_round_error(double original, double rounded) {
  bool ret = false;
  double max_int32 = std::numeric_limits<int32_t>::max();
  double min_int32 = std::numeric_limits<int32_t>::min();

  if (!std::isfinite(original) || !std::isfinite(rounded)) {
    set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
    ret = true;
  }

  if (original != rounded) {
    set_fcsr_bit(kFCSRInexactFlagBit, true);
  }

1102
  if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) {
1103 1104 1105 1106
    set_fcsr_bit(kFCSRUnderflowFlagBit, true);
    ret = true;
  }

1107
  if (rounded > max_int32 || rounded < min_int32) {
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    set_fcsr_bit(kFCSROverflowFlagBit, true);
    // The reference is not really clear but it seems this is required:
    set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
    ret = true;
  }

  return ret;
}


// Sets the rounding error codes in FCSR based on the result of the rounding.
// Returns true if the operation was invalid.
bool Simulator::set_fcsr_round64_error(double original, double rounded) {
  bool ret = false;
1122 1123
  // The value of INT64_MAX (2^63-1) can't be represented as double exactly,
  // loading the most accurate representation into max_int64, which is 2^63.
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
  double max_int64 = std::numeric_limits<int64_t>::max();
  double min_int64 = std::numeric_limits<int64_t>::min();

  if (!std::isfinite(original) || !std::isfinite(rounded)) {
    set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
    ret = true;
  }

  if (original != rounded) {
    set_fcsr_bit(kFCSRInexactFlagBit, true);
  }

1136
  if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) {
1137 1138 1139 1140
    set_fcsr_bit(kFCSRUnderflowFlagBit, true);
    ret = true;
  }

1141
  if (rounded >= max_int64 || rounded < min_int64) {
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
    set_fcsr_bit(kFCSROverflowFlagBit, true);
    // The reference is not really clear but it seems this is required:
    set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
    ret = true;
  }

  return ret;
}


1152 1153
// Sets the rounding error codes in FCSR based on the result of the rounding.
// Returns true if the operation was invalid.
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
bool Simulator::set_fcsr_round_error(float original, float rounded) {
  bool ret = false;
  double max_int32 = std::numeric_limits<int32_t>::max();
  double min_int32 = std::numeric_limits<int32_t>::min();

  if (!std::isfinite(original) || !std::isfinite(rounded)) {
    set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
    ret = true;
  }

  if (original != rounded) {
    set_fcsr_bit(kFCSRInexactFlagBit, true);
  }

  if (rounded < FLT_MIN && rounded > -FLT_MIN && rounded != 0) {
    set_fcsr_bit(kFCSRUnderflowFlagBit, true);
    ret = true;
  }

1173
  if (rounded > max_int32 || rounded < min_int32) {
1174 1175 1176 1177 1178 1179 1180 1181 1182
    set_fcsr_bit(kFCSROverflowFlagBit, true);
    // The reference is not really clear but it seems this is required:
    set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
    ret = true;
  }

  return ret;
}

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
void Simulator::set_fpu_register_word_invalid_result(float original,
                                                     float rounded) {
  if (FCSR_ & kFCSRNaN2008FlagMask) {
    double max_int32 = std::numeric_limits<int32_t>::max();
    double min_int32 = std::numeric_limits<int32_t>::min();
    if (std::isnan(original)) {
      set_fpu_register_word(fd_reg(), 0);
    } else if (rounded > max_int32) {
      set_fpu_register_word(fd_reg(), kFPUInvalidResult);
    } else if (rounded < min_int32) {
      set_fpu_register_word(fd_reg(), kFPUInvalidResultNegative);
    } else {
      UNREACHABLE();
    }
  } else {
    set_fpu_register_word(fd_reg(), kFPUInvalidResult);
  }
}


void Simulator::set_fpu_register_invalid_result(float original, float rounded) {
  if (FCSR_ & kFCSRNaN2008FlagMask) {
    double max_int32 = std::numeric_limits<int32_t>::max();
    double min_int32 = std::numeric_limits<int32_t>::min();
    if (std::isnan(original)) {
      set_fpu_register(fd_reg(), 0);
    } else if (rounded > max_int32) {
      set_fpu_register(fd_reg(), kFPUInvalidResult);
    } else if (rounded < min_int32) {
      set_fpu_register(fd_reg(), kFPUInvalidResultNegative);
    } else {
      UNREACHABLE();
    }
  } else {
    set_fpu_register(fd_reg(), kFPUInvalidResult);
  }
}


void Simulator::set_fpu_register_invalid_result64(float original,
                                                  float rounded) {
  if (FCSR_ & kFCSRNaN2008FlagMask) {
1225 1226
    // The value of INT64_MAX (2^63-1) can't be represented as double exactly,
    // loading the most accurate representation into max_int64, which is 2^63.
1227 1228 1229 1230
    double max_int64 = std::numeric_limits<int64_t>::max();
    double min_int64 = std::numeric_limits<int64_t>::min();
    if (std::isnan(original)) {
      set_fpu_register(fd_reg(), 0);
1231
    } else if (rounded >= max_int64) {
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
      set_fpu_register(fd_reg(), kFPU64InvalidResult);
    } else if (rounded < min_int64) {
      set_fpu_register(fd_reg(), kFPU64InvalidResultNegative);
    } else {
      UNREACHABLE();
    }
  } else {
    set_fpu_register(fd_reg(), kFPU64InvalidResult);
  }
}


void Simulator::set_fpu_register_word_invalid_result(double original,
                                                     double rounded) {
  if (FCSR_ & kFCSRNaN2008FlagMask) {
    double max_int32 = std::numeric_limits<int32_t>::max();
    double min_int32 = std::numeric_limits<int32_t>::min();
    if (std::isnan(original)) {
      set_fpu_register_word(fd_reg(), 0);
    } else if (rounded > max_int32) {
      set_fpu_register_word(fd_reg(), kFPUInvalidResult);
    } else if (rounded < min_int32) {
      set_fpu_register_word(fd_reg(), kFPUInvalidResultNegative);
    } else {
      UNREACHABLE();
    }
  } else {
    set_fpu_register_word(fd_reg(), kFPUInvalidResult);
  }
}


void Simulator::set_fpu_register_invalid_result(double original,
                                                double rounded) {
  if (FCSR_ & kFCSRNaN2008FlagMask) {
    double max_int32 = std::numeric_limits<int32_t>::max();
    double min_int32 = std::numeric_limits<int32_t>::min();
    if (std::isnan(original)) {
      set_fpu_register(fd_reg(), 0);
    } else if (rounded > max_int32) {
      set_fpu_register(fd_reg(), kFPUInvalidResult);
    } else if (rounded < min_int32) {
      set_fpu_register(fd_reg(), kFPUInvalidResultNegative);
    } else {
      UNREACHABLE();
    }
  } else {
    set_fpu_register(fd_reg(), kFPUInvalidResult);
  }
}


void Simulator::set_fpu_register_invalid_result64(double original,
                                                  double rounded) {
  if (FCSR_ & kFCSRNaN2008FlagMask) {
1287 1288
    // The value of INT64_MAX (2^63-1) can't be represented as double exactly,
    // loading the most accurate representation into max_int64, which is 2^63.
1289 1290 1291 1292
    double max_int64 = std::numeric_limits<int64_t>::max();
    double min_int64 = std::numeric_limits<int64_t>::min();
    if (std::isnan(original)) {
      set_fpu_register(fd_reg(), 0);
1293
    } else if (rounded >= max_int64) {
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
      set_fpu_register(fd_reg(), kFPU64InvalidResult);
    } else if (rounded < min_int64) {
      set_fpu_register(fd_reg(), kFPU64InvalidResultNegative);
    } else {
      UNREACHABLE();
    }
  } else {
    set_fpu_register(fd_reg(), kFPU64InvalidResult);
  }
}

1305 1306 1307 1308 1309

// Sets the rounding error codes in FCSR based on the result of the rounding.
// Returns true if the operation was invalid.
bool Simulator::set_fcsr_round64_error(float original, float rounded) {
  bool ret = false;
1310 1311
  // The value of INT64_MAX (2^63-1) can't be represented as double exactly,
  // loading the most accurate representation into max_int64, which is 2^63.
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
  double max_int64 = std::numeric_limits<int64_t>::max();
  double min_int64 = std::numeric_limits<int64_t>::min();

  if (!std::isfinite(original) || !std::isfinite(rounded)) {
    set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
    ret = true;
  }

  if (original != rounded) {
    set_fcsr_bit(kFCSRInexactFlagBit, true);
  }

  if (rounded < FLT_MIN && rounded > -FLT_MIN && rounded != 0) {
    set_fcsr_bit(kFCSRUnderflowFlagBit, true);
    ret = true;
  }

1329
  if (rounded >= max_int64 || rounded < min_int64) {
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
    set_fcsr_bit(kFCSROverflowFlagBit, true);
    // The reference is not really clear but it seems this is required:
    set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
    ret = true;
  }

  return ret;
}


1340
// For cvt instructions only
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
void Simulator::round_according_to_fcsr(double toRound, double& rounded,
                                        int32_t& rounded_int, double fs) {
  // 0 RN (round to nearest): Round a result to the nearest
  // representable value; if the result is exactly halfway between
  // two representable values, round to zero. Behave like round_w_d.

  // 1 RZ (round toward zero): Round a result to the closest
  // representable value whose absolute value is less than or
  // equal to the infinitely accurate result. Behave like trunc_w_d.

  // 2 RP (round up, or toward +infinity): Round a result to the
  // next representable value up. Behave like ceil_w_d.

  // 3 RN (round down, or toward −infinity): Round a result to
  // the next representable value down. Behave like floor_w_d.
  switch (FCSR_ & 3) {
    case kRoundToNearest:
      rounded = std::floor(fs + 0.5);
      rounded_int = static_cast<int32_t>(rounded);
      if ((rounded_int & 1) != 0 && rounded_int - fs == 0.5) {
        // If the number is halfway between two integers,
        // round to the even one.
        rounded_int--;
1364
        rounded -= 1.;
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
      }
      break;
    case kRoundToZero:
      rounded = trunc(fs);
      rounded_int = static_cast<int32_t>(rounded);
      break;
    case kRoundToPlusInf:
      rounded = std::ceil(fs);
      rounded_int = static_cast<int32_t>(rounded);
      break;
    case kRoundToMinusInf:
      rounded = std::floor(fs);
      rounded_int = static_cast<int32_t>(rounded);
      break;
  }
}


void Simulator::round64_according_to_fcsr(double toRound, double& rounded,
                                          int64_t& rounded_int, double fs) {
  // 0 RN (round to nearest): Round a result to the nearest
  // representable value; if the result is exactly halfway between
  // two representable values, round to zero. Behave like round_w_d.

  // 1 RZ (round toward zero): Round a result to the closest
  // representable value whose absolute value is less than or.
  // equal to the infinitely accurate result. Behave like trunc_w_d.

  // 2 RP (round up, or toward +infinity): Round a result to the
  // next representable value up. Behave like ceil_w_d.

  // 3 RN (round down, or toward −infinity): Round a result to
  // the next representable value down. Behave like floor_w_d.
  switch (FCSR_ & 3) {
    case kRoundToNearest:
      rounded = std::floor(fs + 0.5);
      rounded_int = static_cast<int64_t>(rounded);
      if ((rounded_int & 1) != 0 && rounded_int - fs == 0.5) {
        // If the number is halfway between two integers,
        // round to the even one.
        rounded_int--;
1406
        rounded -= 1.;
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
      }
      break;
    case kRoundToZero:
      rounded = trunc(fs);
      rounded_int = static_cast<int64_t>(rounded);
      break;
    case kRoundToPlusInf:
      rounded = std::ceil(fs);
      rounded_int = static_cast<int64_t>(rounded);
      break;
    case kRoundToMinusInf:
      rounded = std::floor(fs);
      rounded_int = static_cast<int64_t>(rounded);
      break;
  }
}


1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
// for cvt instructions only
void Simulator::round_according_to_fcsr(float toRound, float& rounded,
                                        int32_t& rounded_int, float fs) {
  // 0 RN (round to nearest): Round a result to the nearest
  // representable value; if the result is exactly halfway between
  // two representable values, round to zero. Behave like round_w_d.

  // 1 RZ (round toward zero): Round a result to the closest
  // representable value whose absolute value is less than or
  // equal to the infinitely accurate result. Behave like trunc_w_d.

  // 2 RP (round up, or toward +infinity): Round a result to the
  // next representable value up. Behave like ceil_w_d.

  // 3 RN (round down, or toward −infinity): Round a result to
  // the next representable value down. Behave like floor_w_d.
  switch (FCSR_ & 3) {
    case kRoundToNearest:
      rounded = std::floor(fs + 0.5);
      rounded_int = static_cast<int32_t>(rounded);
      if ((rounded_int & 1) != 0 && rounded_int - fs == 0.5) {
        // If the number is halfway between two integers,
        // round to the even one.
        rounded_int--;
1449
        rounded -= 1.f;
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
      }
      break;
    case kRoundToZero:
      rounded = trunc(fs);
      rounded_int = static_cast<int32_t>(rounded);
      break;
    case kRoundToPlusInf:
      rounded = std::ceil(fs);
      rounded_int = static_cast<int32_t>(rounded);
      break;
    case kRoundToMinusInf:
      rounded = std::floor(fs);
      rounded_int = static_cast<int32_t>(rounded);
      break;
  }
}


void Simulator::round64_according_to_fcsr(float toRound, float& rounded,
                                          int64_t& rounded_int, float fs) {
  // 0 RN (round to nearest): Round a result to the nearest
  // representable value; if the result is exactly halfway between
  // two representable values, round to zero. Behave like round_w_d.

  // 1 RZ (round toward zero): Round a result to the closest
  // representable value whose absolute value is less than or.
  // equal to the infinitely accurate result. Behave like trunc_w_d.

  // 2 RP (round up, or toward +infinity): Round a result to the
  // next representable value up. Behave like ceil_w_d.

  // 3 RN (round down, or toward −infinity): Round a result to
  // the next representable value down. Behave like floor_w_d.
  switch (FCSR_ & 3) {
    case kRoundToNearest:
      rounded = std::floor(fs + 0.5);
      rounded_int = static_cast<int64_t>(rounded);
      if ((rounded_int & 1) != 0 && rounded_int - fs == 0.5) {
        // If the number is halfway between two integers,
        // round to the even one.
        rounded_int--;
1491
        rounded -= 1.f;
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
      }
      break;
    case kRoundToZero:
      rounded = trunc(fs);
      rounded_int = static_cast<int64_t>(rounded);
      break;
    case kRoundToPlusInf:
      rounded = std::ceil(fs);
      rounded_int = static_cast<int64_t>(rounded);
      break;
    case kRoundToMinusInf:
      rounded = std::floor(fs);
      rounded_int = static_cast<int64_t>(rounded);
      break;
  }
}

1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
template <typename T_fp, typename T_int>
void Simulator::round_according_to_msacsr(T_fp toRound, T_fp& rounded,
                                          T_int& rounded_int) {
  // 0 RN (round to nearest): Round a result to the nearest
  // representable value; if the result is exactly halfway between
  // two representable values, round to zero. Behave like round_w_d.

  // 1 RZ (round toward zero): Round a result to the closest
  // representable value whose absolute value is less than or
  // equal to the infinitely accurate result. Behave like trunc_w_d.

  // 2 RP (round up, or toward +infinity): Round a result to the
  // next representable value up. Behave like ceil_w_d.

  // 3 RN (round down, or toward −infinity): Round a result to
  // the next representable value down. Behave like floor_w_d.
  switch (get_msacsr_rounding_mode()) {
    case kRoundToNearest:
      rounded = std::floor(toRound + 0.5);
      rounded_int = static_cast<T_int>(rounded);
      if ((rounded_int & 1) != 0 && rounded_int - toRound == 0.5) {
        // If the number is halfway between two integers,
        // round to the even one.
        rounded_int--;
        rounded -= 1.;
      }
      break;
    case kRoundToZero:
      rounded = trunc(toRound);
      rounded_int = static_cast<T_int>(rounded);
      break;
    case kRoundToPlusInf:
      rounded = std::ceil(toRound);
      rounded_int = static_cast<T_int>(rounded);
      break;
    case kRoundToMinusInf:
      rounded = std::floor(toRound);
      rounded_int = static_cast<T_int>(rounded);
      break;
  }
}
1550

1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
// Raw access to the PC register.
void Simulator::set_pc(int64_t value) {
  pc_modified_ = true;
  registers_[pc] = value;
}


bool Simulator::has_bad_pc() const {
  return ((registers_[pc] == bad_ra) || (registers_[pc] == end_sim_pc));
}


// Raw access to the PC register without the special adjustment when reading.
int64_t Simulator::get_pc() const {
  return registers_[pc];
}


// The MIPS cannot do unaligned reads and writes.  On some MIPS platforms an
// interrupt is caused.  On others it does a funky rotation thing.  For now we
// simply disallow unaligned reads, but at some point we may want to move to
// emulating the rotate behaviour.  Note that simulator runs have the runtime
// system running directly on the host system and only generated code is
// executed in the simulator.  Since the host is typically IA32 we will not
// get the correct MIPS-like behaviour on unaligned accesses.

// TODO(plind): refactor this messy debug code when we do unaligned access.
void Simulator::DieOrDebug() {
1579
  if ((1)) {  // Flag for this was removed.
1580 1581 1582 1583 1584 1585 1586
    MipsDebugger dbg(this);
    dbg.Debug();
  } else {
    base::OS::Abort();
  }
}

1587
void Simulator::TraceRegWr(int64_t value, TraceType t) {
1588
  if (::v8::internal::FLAG_trace_sim) {
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
    union {
      int64_t fmt_int64;
      int32_t fmt_int32[2];
      float fmt_float[2];
      double fmt_double;
    } v;
    v.fmt_int64 = value;

    switch (t) {
      case WORD:
        SNPrintF(trace_buf_, "%016" PRIx64 "    (%" PRId64 ")    int32:%" PRId32
                             " uint32:%" PRIu32,
                 v.fmt_int64, icount_, v.fmt_int32[0], v.fmt_int32[0]);
        break;
      case DWORD:
        SNPrintF(trace_buf_, "%016" PRIx64 "    (%" PRId64 ")    int64:%" PRId64
                             " uint64:%" PRIu64,
                 value, icount_, value, value);
        break;
      case FLOAT:
        SNPrintF(trace_buf_, "%016" PRIx64 "    (%" PRId64 ")    flt:%e",
                 v.fmt_int64, icount_, v.fmt_float[0]);
        break;
      case DOUBLE:
        SNPrintF(trace_buf_, "%016" PRIx64 "    (%" PRId64 ")    dbl:%e",
                 v.fmt_int64, icount_, v.fmt_double);
        break;
      case FLOAT_DOUBLE:
        SNPrintF(trace_buf_, "%016" PRIx64 "    (%" PRId64 ")    flt:%e dbl:%e",
                 v.fmt_int64, icount_, v.fmt_float[0], v.fmt_double);
        break;
      case WORD_DWORD:
        SNPrintF(trace_buf_,
                 "%016" PRIx64 "    (%" PRId64 ")    int32:%" PRId32
                 " uint32:%" PRIu32 " int64:%" PRId64 " uint64:%" PRIu64,
                 v.fmt_int64, icount_, v.fmt_int32[0], v.fmt_int32[0],
                 v.fmt_int64, v.fmt_int64);
        break;
      default:
        UNREACHABLE();
    }
1630 1631 1632
  }
}

1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
template <typename T>
void Simulator::TraceMSARegWr(T* value, TraceType t) {
  if (::v8::internal::FLAG_trace_sim) {
    union {
      uint8_t b[16];
      uint16_t h[8];
      uint32_t w[4];
      uint64_t d[2];
      float f[4];
      double df[2];
    } v;
    memcpy(v.b, value, kSimd128Size);
    switch (t) {
      case BYTE:
        SNPrintF(trace_buf_,
                 "LO: %016" PRIx64 "  HI: %016" PRIx64 "    (%" PRIu64 ")",
                 v.d[0], v.d[1], icount_);
        break;
      case HALF:
        SNPrintF(trace_buf_,
                 "LO: %016" PRIx64 "  HI: %016" PRIx64 "    (%" PRIu64 ")",
                 v.d[0], v.d[1], icount_);
        break;
      case WORD:
        SNPrintF(trace_buf_,
                 "LO: %016" PRIx64 "  HI: %016" PRIx64 "    (%" PRIu64
                 ")    int32[0..3]:%" PRId32 "  %" PRId32 "  %" PRId32
                 "  %" PRId32,
                 v.d[0], v.d[1], icount_, v.w[0], v.w[1], v.w[2], v.w[3]);
        break;
      case DWORD:
        SNPrintF(trace_buf_,
                 "LO: %016" PRIx64 "  HI: %016" PRIx64 "    (%" PRIu64 ")",
                 v.d[0], v.d[1], icount_);
        break;
      case FLOAT:
        SNPrintF(trace_buf_,
                 "LO: %016" PRIx64 "  HI: %016" PRIx64 "    (%" PRIu64
                 ")    flt[0..3]:%e  %e  %e  %e",
                 v.d[0], v.d[1], icount_, v.f[0], v.f[1], v.f[2], v.f[3]);
        break;
      case DOUBLE:
        SNPrintF(trace_buf_,
                 "LO: %016" PRIx64 "  HI: %016" PRIx64 "    (%" PRIu64
                 ")    dbl[0..1]:%e  %e",
                 v.d[0], v.d[1], icount_, v.df[0], v.df[1]);
        break;
      default:
        UNREACHABLE();
    }
  }
}

1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
template <typename T>
void Simulator::TraceMSARegWr(T* value) {
  if (::v8::internal::FLAG_trace_sim) {
    union {
      uint8_t b[kMSALanesByte];
      uint16_t h[kMSALanesHalf];
      uint32_t w[kMSALanesWord];
      uint64_t d[kMSALanesDword];
      float f[kMSALanesWord];
      double df[kMSALanesDword];
    } v;
    memcpy(v.b, value, kMSALanesByte);

    if (std::is_same<T, int32_t>::value) {
      SNPrintF(trace_buf_,
               "LO: %016" PRIx64 "  HI: %016" PRIx64 "    (%" PRIu64
               ")    int32[0..3]:%" PRId32 "  %" PRId32 "  %" PRId32
               "  %" PRId32,
               v.d[0], v.d[1], icount_, v.w[0], v.w[1], v.w[2], v.w[3]);
    } else if (std::is_same<T, float>::value) {
      SNPrintF(trace_buf_,
               "LO: %016" PRIx64 "  HI: %016" PRIx64 "    (%" PRIu64
               ")    flt[0..3]:%e  %e  %e  %e",
               v.d[0], v.d[1], icount_, v.f[0], v.f[1], v.f[2], v.f[3]);
    } else if (std::is_same<T, double>::value) {
      SNPrintF(trace_buf_,
               "LO: %016" PRIx64 "  HI: %016" PRIx64 "    (%" PRIu64
               ")    dbl[0..1]:%e  %e",
               v.d[0], v.d[1], icount_, v.df[0], v.df[1]);
    } else {
      SNPrintF(trace_buf_,
               "LO: %016" PRIx64 "  HI: %016" PRIx64 "    (%" PRIu64 ")",
               v.d[0], v.d[1], icount_);
    }
  }
}

1723
// TODO(plind): consider making icount_ printing a flag option.
1724
void Simulator::TraceMemRd(int64_t addr, int64_t value, TraceType t) {
1725
  if (::v8::internal::FLAG_trace_sim) {
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
    union {
      int64_t fmt_int64;
      int32_t fmt_int32[2];
      float fmt_float[2];
      double fmt_double;
    } v;
    v.fmt_int64 = value;

    switch (t) {
      case WORD:
        SNPrintF(trace_buf_, "%016" PRIx64 "  <-- [%016" PRIx64 "]    (%" PRId64
                             ")    int32:%" PRId32 " uint32:%" PRIu32,
                 v.fmt_int64, addr, icount_, v.fmt_int32[0], v.fmt_int32[0]);
        break;
      case DWORD:
        SNPrintF(trace_buf_, "%016" PRIx64 "  <-- [%016" PRIx64 "]    (%" PRId64
                             ")    int64:%" PRId64 " uint64:%" PRIu64,
                 value, addr, icount_, value, value);
        break;
      case FLOAT:
        SNPrintF(trace_buf_, "%016" PRIx64 "  <-- [%016" PRIx64 "]    (%" PRId64
                             ")    flt:%e",
                 v.fmt_int64, addr, icount_, v.fmt_float[0]);
        break;
      case DOUBLE:
        SNPrintF(trace_buf_, "%016" PRIx64 "  <-- [%016" PRIx64 "]    (%" PRId64
                             ")    dbl:%e",
                 v.fmt_int64, addr, icount_, v.fmt_double);
        break;
      case FLOAT_DOUBLE:
        SNPrintF(trace_buf_, "%016" PRIx64 "  <-- [%016" PRIx64 "]    (%" PRId64
                             ")    flt:%e dbl:%e",
                 v.fmt_int64, addr, icount_, v.fmt_float[0], v.fmt_double);
        break;
      default:
        UNREACHABLE();
    }
1763 1764 1765 1766 1767 1768 1769 1770
  }
}


void Simulator::TraceMemWr(int64_t addr, int64_t value, TraceType t) {
  if (::v8::internal::FLAG_trace_sim) {
    switch (t) {
      case BYTE:
1771 1772 1773
        SNPrintF(trace_buf_, "               %02" PRIx8 " --> [%016" PRIx64
                             "]    (%" PRId64 ")",
                 static_cast<uint8_t>(value), addr, icount_);
1774 1775
        break;
      case HALF:
1776 1777 1778
        SNPrintF(trace_buf_, "            %04" PRIx16 " --> [%016" PRIx64
                             "]    (%" PRId64 ")",
                 static_cast<uint16_t>(value), addr, icount_);
1779 1780
        break;
      case WORD:
1781 1782 1783
        SNPrintF(trace_buf_,
                 "        %08" PRIx32 " --> [%016" PRIx64 "]    (%" PRId64 ")",
                 static_cast<uint32_t>(value), addr, icount_);
1784 1785
        break;
      case DWORD:
1786
        SNPrintF(trace_buf_,
1787
                 "%016" PRIx64 "  --> [%016" PRIx64 "]    (%" PRId64 " )",
1788 1789
                 value, addr, icount_);
        break;
1790 1791
      default:
        UNREACHABLE();
1792 1793 1794 1795
    }
  }
}

1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
template <typename T>
void Simulator::TraceMemRd(int64_t addr, T value) {
  if (::v8::internal::FLAG_trace_sim) {
    switch (sizeof(T)) {
      case 1:
        SNPrintF(trace_buf_,
                 "%08" PRIx8 " <-- [%08" PRIx64 "]    (%" PRIu64
                 ")    int8:%" PRId8 " uint8:%" PRIu8,
                 static_cast<uint8_t>(value), addr, icount_,
                 static_cast<int8_t>(value), static_cast<uint8_t>(value));
        break;
      case 2:
        SNPrintF(trace_buf_,
                 "%08" PRIx16 " <-- [%08" PRIx64 "]    (%" PRIu64
                 ")    int16:%" PRId16 " uint16:%" PRIu16,
                 static_cast<uint16_t>(value), addr, icount_,
                 static_cast<int16_t>(value), static_cast<uint16_t>(value));
        break;
      case 4:
        SNPrintF(trace_buf_,
                 "%08" PRIx32 " <-- [%08" PRIx64 "]    (%" PRIu64
                 ")    int32:%" PRId32 " uint32:%" PRIu32,
                 static_cast<uint32_t>(value), addr, icount_,
                 static_cast<int32_t>(value), static_cast<uint32_t>(value));
        break;
      case 8:
        SNPrintF(trace_buf_,
                 "%08" PRIx64 " <-- [%08" PRIx64 "]    (%" PRIu64
                 ")    int64:%" PRId64 " uint64:%" PRIu64,
                 static_cast<uint64_t>(value), addr, icount_,
                 static_cast<int64_t>(value), static_cast<uint64_t>(value));
        break;
      default:
        UNREACHABLE();
    }
  }
}

template <typename T>
void Simulator::TraceMemWr(int64_t addr, T value) {
  if (::v8::internal::FLAG_trace_sim) {
    switch (sizeof(T)) {
      case 1:
        SNPrintF(trace_buf_,
                 "      %02" PRIx8 " --> [%08" PRIx64 "]    (%" PRIu64 ")",
                 static_cast<uint8_t>(value), addr, icount_);
        break;
      case 2:
        SNPrintF(trace_buf_,
                 "    %04" PRIx16 " --> [%08" PRIx64 "]    (%" PRIu64 ")",
                 static_cast<uint16_t>(value), addr, icount_);
        break;
      case 4:
        SNPrintF(trace_buf_,
                 "%08" PRIx32 " --> [%08" PRIx64 "]    (%" PRIu64 ")",
                 static_cast<uint32_t>(value), addr, icount_);
        break;
      case 8:
        SNPrintF(trace_buf_,
                 "%16" PRIx64 " --> [%08" PRIx64 "]    (%" PRIu64 ")",
                 static_cast<uint64_t>(value), addr, icount_);
        break;
      default:
        UNREACHABLE();
    }
  }
}
1863 1864 1865

// TODO(plind): sign-extend and zero-extend not implmented properly
// on all the ReadXX functions, I don't think re-interpret cast does it.
1866
int32_t Simulator::ReadW(int64_t addr, Instruction* instr, TraceType t) {
1867
  if (addr >=0 && addr < 0x400) {
1868
    // This has to be a nullptr-dereference, drop into debugger.
1869 1870
    PrintF("Memory read from bad address: 0x%08" PRIx64 " , pc=0x%08" PRIxPTR
           " \n",
1871 1872 1873
           addr, reinterpret_cast<intptr_t>(instr));
    DieOrDebug();
  }
1874
  if ((addr & 0x3) == 0 || kArchVariant == kMips64r6) {
1875
    int32_t* ptr = reinterpret_cast<int32_t*>(addr);
1876
    TraceMemRd(addr, static_cast<int64_t>(*ptr), t);
1877 1878
    return *ptr;
  }
1879
  PrintF("Unaligned read at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR "\n", addr,
1880 1881 1882 1883 1884 1885 1886 1887
         reinterpret_cast<intptr_t>(instr));
  DieOrDebug();
  return 0;
}


uint32_t Simulator::ReadWU(int64_t addr, Instruction* instr) {
  if (addr >=0 && addr < 0x400) {
1888
    // This has to be a nullptr-dereference, drop into debugger.
1889 1890
    PrintF("Memory read from bad address: 0x%08" PRIx64 " , pc=0x%08" PRIxPTR
           " \n",
1891 1892 1893
           addr, reinterpret_cast<intptr_t>(instr));
    DieOrDebug();
  }
1894
  if ((addr & 0x3) == 0 || kArchVariant == kMips64r6) {
1895
    uint32_t* ptr = reinterpret_cast<uint32_t*>(addr);
1896
    TraceMemRd(addr, static_cast<int64_t>(*ptr), WORD);
1897 1898
    return *ptr;
  }
1899
  PrintF("Unaligned read at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR "\n", addr,
1900 1901 1902 1903 1904 1905
         reinterpret_cast<intptr_t>(instr));
  DieOrDebug();
  return 0;
}


1906
void Simulator::WriteW(int64_t addr, int32_t value, Instruction* instr) {
1907
  if (addr >= 0 && addr < 0x400) {
1908
    // This has to be a nullptr-dereference, drop into debugger.
1909 1910
    PrintF("Memory write to bad address: 0x%08" PRIx64 " , pc=0x%08" PRIxPTR
           " \n",
1911 1912 1913
           addr, reinterpret_cast<intptr_t>(instr));
    DieOrDebug();
  }
1914
  if ((addr & 0x3) == 0 || kArchVariant == kMips64r6) {
1915 1916 1917 1918 1919
    TraceMemWr(addr, value, WORD);
    int* ptr = reinterpret_cast<int*>(addr);
    *ptr = value;
    return;
  }
1920
  PrintF("Unaligned write at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR "\n", addr,
1921 1922 1923 1924 1925 1926 1927
         reinterpret_cast<intptr_t>(instr));
  DieOrDebug();
}


int64_t Simulator::Read2W(int64_t addr, Instruction* instr) {
  if (addr >=0 && addr < 0x400) {
1928
    // This has to be a nullptr-dereference, drop into debugger.
1929 1930
    PrintF("Memory read from bad address: 0x%08" PRIx64 " , pc=0x%08" PRIxPTR
           " \n",
1931 1932 1933
           addr, reinterpret_cast<intptr_t>(instr));
    DieOrDebug();
  }
1934
  if ((addr & kPointerAlignmentMask) == 0 || kArchVariant == kMips64r6) {
1935 1936 1937 1938
    int64_t* ptr = reinterpret_cast<int64_t*>(addr);
    TraceMemRd(addr, *ptr);
    return *ptr;
  }
1939
  PrintF("Unaligned read at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR "\n", addr,
1940 1941 1942 1943 1944 1945 1946 1947
         reinterpret_cast<intptr_t>(instr));
  DieOrDebug();
  return 0;
}


void Simulator::Write2W(int64_t addr, int64_t value, Instruction* instr) {
  if (addr >= 0 && addr < 0x400) {
1948
    // This has to be a nullptr-dereference, drop into debugger.
1949 1950
    PrintF("Memory write to bad address: 0x%08" PRIx64 " , pc=0x%08" PRIxPTR
           "\n",
1951 1952 1953
           addr, reinterpret_cast<intptr_t>(instr));
    DieOrDebug();
  }
1954
  if ((addr & kPointerAlignmentMask) == 0 || kArchVariant == kMips64r6) {
1955 1956 1957 1958 1959
    TraceMemWr(addr, value, DWORD);
    int64_t* ptr = reinterpret_cast<int64_t*>(addr);
    *ptr = value;
    return;
  }
1960
  PrintF("Unaligned write at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR "\n", addr,
1961 1962 1963 1964 1965 1966
         reinterpret_cast<intptr_t>(instr));
  DieOrDebug();
}


double Simulator::ReadD(int64_t addr, Instruction* instr) {
1967
  if ((addr & kDoubleAlignmentMask) == 0 || kArchVariant == kMips64r6) {
1968 1969 1970
    double* ptr = reinterpret_cast<double*>(addr);
    return *ptr;
  }
1971 1972
  PrintF("Unaligned (double) read at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR "\n",
         addr, reinterpret_cast<intptr_t>(instr));
1973 1974 1975 1976 1977 1978
  base::OS::Abort();
  return 0;
}


void Simulator::WriteD(int64_t addr, double value, Instruction* instr) {
1979
  if ((addr & kDoubleAlignmentMask) == 0 || kArchVariant == kMips64r6) {
1980 1981 1982 1983
    double* ptr = reinterpret_cast<double*>(addr);
    *ptr = value;
    return;
  }
1984 1985 1986
  PrintF("Unaligned (double) write at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR
         "\n",
         addr, reinterpret_cast<intptr_t>(instr));
1987 1988 1989 1990 1991
  DieOrDebug();
}


uint16_t Simulator::ReadHU(int64_t addr, Instruction* instr) {
1992
  if ((addr & 1) == 0 || kArchVariant == kMips64r6) {
1993 1994 1995 1996
    uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
    TraceMemRd(addr, static_cast<int64_t>(*ptr));
    return *ptr;
  }
1997 1998 1999
  PrintF("Unaligned unsigned halfword read at 0x%08" PRIx64
         " , pc=0x%08" V8PRIxPTR "\n",
         addr, reinterpret_cast<intptr_t>(instr));
2000 2001 2002 2003 2004 2005
  DieOrDebug();
  return 0;
}


int16_t Simulator::ReadH(int64_t addr, Instruction* instr) {
2006
  if ((addr & 1) == 0 || kArchVariant == kMips64r6) {
2007 2008 2009 2010
    int16_t* ptr = reinterpret_cast<int16_t*>(addr);
    TraceMemRd(addr, static_cast<int64_t>(*ptr));
    return *ptr;
  }
2011 2012 2013
  PrintF("Unaligned signed halfword read at 0x%08" PRIx64
         " , pc=0x%08" V8PRIxPTR "\n",
         addr, reinterpret_cast<intptr_t>(instr));
2014 2015 2016 2017 2018 2019
  DieOrDebug();
  return 0;
}


void Simulator::WriteH(int64_t addr, uint16_t value, Instruction* instr) {
2020
  if ((addr & 1) == 0 || kArchVariant == kMips64r6) {
2021 2022 2023 2024 2025
    TraceMemWr(addr, value, HALF);
    uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
    *ptr = value;
    return;
  }
2026 2027 2028
  PrintF("Unaligned unsigned halfword write at 0x%08" PRIx64
         " , pc=0x%08" V8PRIxPTR "\n",
         addr, reinterpret_cast<intptr_t>(instr));
2029 2030 2031 2032 2033
  DieOrDebug();
}


void Simulator::WriteH(int64_t addr, int16_t value, Instruction* instr) {
2034
  if ((addr & 1) == 0 || kArchVariant == kMips64r6) {
2035 2036 2037 2038 2039
    TraceMemWr(addr, value, HALF);
    int16_t* ptr = reinterpret_cast<int16_t*>(addr);
    *ptr = value;
    return;
  }
2040 2041 2042
  PrintF("Unaligned halfword write at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR
         "\n",
         addr, reinterpret_cast<intptr_t>(instr));
2043 2044 2045 2046 2047 2048 2049
  DieOrDebug();
}


uint32_t Simulator::ReadBU(int64_t addr) {
  uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
  TraceMemRd(addr, static_cast<int64_t>(*ptr));
2050
  return *ptr & 0xFF;
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
}


int32_t Simulator::ReadB(int64_t addr) {
  int8_t* ptr = reinterpret_cast<int8_t*>(addr);
  TraceMemRd(addr, static_cast<int64_t>(*ptr));
  return *ptr;
}


void Simulator::WriteB(int64_t addr, uint8_t value) {
  TraceMemWr(addr, value, BYTE);
  uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
  *ptr = value;
}


void Simulator::WriteB(int64_t addr, int8_t value) {
  TraceMemWr(addr, value, BYTE);
  int8_t* ptr = reinterpret_cast<int8_t*>(addr);
  *ptr = value;
}

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
template <typename T>
T Simulator::ReadMem(int64_t addr, Instruction* instr) {
  int alignment_mask = (1 << sizeof(T)) - 1;
  if ((addr & alignment_mask) == 0 || kArchVariant == kMips64r6) {
    T* ptr = reinterpret_cast<T*>(addr);
    TraceMemRd(addr, *ptr);
    return *ptr;
  }
  PrintF("Unaligned read of type sizeof(%ld) at 0x%08lx, pc=0x%08" V8PRIxPTR
         "\n",
         sizeof(T), addr, reinterpret_cast<intptr_t>(instr));
  base::OS::Abort();
  return 0;
}

template <typename T>
void Simulator::WriteMem(int64_t addr, T value, Instruction* instr) {
  int alignment_mask = (1 << sizeof(T)) - 1;
  if ((addr & alignment_mask) == 0 || kArchVariant == kMips64r6) {
    T* ptr = reinterpret_cast<T*>(addr);
    *ptr = value;
    TraceMemWr(addr, value);
    return;
  }
  PrintF("Unaligned write of type sizeof(%ld) at 0x%08lx, pc=0x%08" V8PRIxPTR
         "\n",
         sizeof(T), addr, reinterpret_cast<intptr_t>(instr));
  base::OS::Abort();
}
2103 2104

// Returns the limit of the stack area to enable checking for stack overflows.
2105 2106 2107 2108 2109 2110 2111 2112 2113
uintptr_t Simulator::StackLimit(uintptr_t c_limit) const {
  // The simulator uses a separate JS stack. If we have exhausted the C stack,
  // we also drop down the JS limit to reflect the exhaustion on the JS stack.
  if (GetCurrentStackPosition() < c_limit) {
    return reinterpret_cast<uintptr_t>(get_sp());
  }

  // Otherwise the limit is the JS stack. Leave a safety margin of 1024 bytes
  // to prevent overrunning the stack when pushing values.
2114 2115 2116 2117 2118 2119
  return reinterpret_cast<uintptr_t>(stack_) + 1024;
}


// Unsupported instructions use Format to print an error and stop execution.
void Simulator::Format(Instruction* instr, const char* format) {
2120
  PrintF("Simulator found unsupported instruction:\n 0x%08" PRIxPTR " : %s\n",
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
         reinterpret_cast<intptr_t>(instr), format);
  UNIMPLEMENTED_MIPS();
}


// Calls into the V8 runtime are based on this very simple interface.
// Note: To be able to return two values from some calls the code in runtime.cc
// uses the ObjectPair which is essentially two 32-bit values stuffed into a
// 64-bit value. With the code below we assume that all runtime calls return
// 64 bits of result. If they don't, the v1 result register contains a bogus
// value, which is fine because it is caller-saved.

2133 2134 2135 2136 2137
typedef ObjectPair (*SimulatorRuntimeCall)(int64_t arg0, int64_t arg1,
                                           int64_t arg2, int64_t arg3,
                                           int64_t arg4, int64_t arg5,
                                           int64_t arg6, int64_t arg7,
                                           int64_t arg8);
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156

// These prototypes handle the four types of FP calls.
typedef int64_t (*SimulatorRuntimeCompareCall)(double darg0, double darg1);
typedef double (*SimulatorRuntimeFPFPCall)(double darg0, double darg1);
typedef double (*SimulatorRuntimeFPCall)(double darg0);
typedef double (*SimulatorRuntimeFPIntCall)(double darg0, int32_t arg0);

// This signature supports direct call in to API function native callback
// (refer to InvocationCallback in v8.h).
typedef void (*SimulatorRuntimeDirectApiCall)(int64_t arg0);
typedef void (*SimulatorRuntimeProfilingApiCall)(int64_t arg0, void* arg1);

// This signature supports direct call to accessor getter callback.
typedef void (*SimulatorRuntimeDirectGetterCall)(int64_t arg0, int64_t arg1);
typedef void (*SimulatorRuntimeProfilingGetterCall)(
    int64_t arg0, int64_t arg1, void* arg2);

// Software interrupt instructions are used by the simulator to call into the
// C-based V8 runtime. They are also used for debugging with simulator.
2157
void Simulator::SoftwareInterrupt() {
2158 2159 2160
  // There are several instructions that could get us here,
  // the break_ instruction, or several variants of traps. All
  // Are "SPECIAL" class opcode, and are distinuished by function.
2161 2162
  int32_t func = instr_.FunctionFieldRaw();
  uint32_t code = (func == BREAK) ? instr_.Bits(25, 6) : -1;
2163
  // We first check if we met a call_rt_redirected.
2164
  if (instr_.InstructionBits() == rtCallRedirInstr) {
2165
    Redirection* redirection = Redirection::FromInstruction(instr_.instr());
2166 2167 2168

    int64_t* stack_pointer = reinterpret_cast<int64_t*>(get_register(sp));

2169 2170 2171 2172
    int64_t arg0 = get_register(a0);
    int64_t arg1 = get_register(a1);
    int64_t arg2 = get_register(a2);
    int64_t arg3 = get_register(a3);
2173 2174 2175 2176 2177 2178
    int64_t arg4 = get_register(a4);
    int64_t arg5 = get_register(a5);
    int64_t arg6 = get_register(a6);
    int64_t arg7 = get_register(a7);
    int64_t arg8 = stack_pointer[0];
    STATIC_ASSERT(kMaxCParameters == 9);
2179

2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
    bool fp_call =
         (redirection->type() == ExternalReference::BUILTIN_FP_FP_CALL) ||
         (redirection->type() == ExternalReference::BUILTIN_COMPARE_CALL) ||
         (redirection->type() == ExternalReference::BUILTIN_FP_CALL) ||
         (redirection->type() == ExternalReference::BUILTIN_FP_INT_CALL);

    if (!IsMipsSoftFloatABI) {
      // With the hard floating point calling convention, double
      // arguments are passed in FPU registers. Fetch the arguments
      // from there and call the builtin using soft floating point
      // convention.
      switch (redirection->type()) {
      case ExternalReference::BUILTIN_FP_FP_CALL:
      case ExternalReference::BUILTIN_COMPARE_CALL:
        arg0 = get_fpu_register(f12);
        arg1 = get_fpu_register(f13);
        arg2 = get_fpu_register(f14);
        arg3 = get_fpu_register(f15);
        break;
      case ExternalReference::BUILTIN_FP_CALL:
        arg0 = get_fpu_register(f12);
        arg1 = get_fpu_register(f13);
        break;
      case ExternalReference::BUILTIN_FP_INT_CALL:
        arg0 = get_fpu_register(f12);
        arg1 = get_fpu_register(f13);
        arg2 = get_register(a2);
        break;
      default:
        break;
      }
    }

    // This is dodgy but it works because the C entry stubs are never moved.
    // See comment in codegen-arm.cc and bug 1242173.
    int64_t saved_ra = get_register(ra);

    intptr_t external =
          reinterpret_cast<intptr_t>(redirection->external_function());

    // Based on CpuFeatures::IsSupported(FPU), Mips will use either hardware
    // FPU, or gcc soft-float routines. Hardware FPU is simulated in this
    // simulator. Soft-float has additional abstraction of ExternalReference,
    // to support serialization.
    if (fp_call) {
      double dval0, dval1;  // one or two double parameters
      int32_t ival;         // zero or one integer parameters
      int64_t iresult = 0;  // integer return value
      double dresult = 0;   // double return value
      GetFpArgs(&dval0, &dval1, &ival);
      SimulatorRuntimeCall generic_target =
          reinterpret_cast<SimulatorRuntimeCall>(external);
      if (::v8::internal::FLAG_trace_sim) {
        switch (redirection->type()) {
          case ExternalReference::BUILTIN_FP_FP_CALL:
          case ExternalReference::BUILTIN_COMPARE_CALL:
            PrintF("Call to host function at %p with args %f, %f",
2237 2238
                   reinterpret_cast<void*>(FUNCTION_ADDR(generic_target)),
                   dval0, dval1);
2239 2240 2241
            break;
          case ExternalReference::BUILTIN_FP_CALL:
            PrintF("Call to host function at %p with arg %f",
2242 2243
                   reinterpret_cast<void*>(FUNCTION_ADDR(generic_target)),
                   dval0);
2244 2245 2246
            break;
          case ExternalReference::BUILTIN_FP_INT_CALL:
            PrintF("Call to host function at %p with args %f, %d",
2247 2248
                   reinterpret_cast<void*>(FUNCTION_ADDR(generic_target)),
                   dval0, ival);
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
            break;
          default:
            UNREACHABLE();
            break;
        }
      }
      switch (redirection->type()) {
      case ExternalReference::BUILTIN_COMPARE_CALL: {
        SimulatorRuntimeCompareCall target =
          reinterpret_cast<SimulatorRuntimeCompareCall>(external);
        iresult = target(dval0, dval1);
        set_register(v0, static_cast<int64_t>(iresult));
      //  set_register(v1, static_cast<int64_t>(iresult >> 32));
        break;
      }
      case ExternalReference::BUILTIN_FP_FP_CALL: {
        SimulatorRuntimeFPFPCall target =
          reinterpret_cast<SimulatorRuntimeFPFPCall>(external);
        dresult = target(dval0, dval1);
        SetFpResult(dresult);
        break;
      }
      case ExternalReference::BUILTIN_FP_CALL: {
        SimulatorRuntimeFPCall target =
          reinterpret_cast<SimulatorRuntimeFPCall>(external);
        dresult = target(dval0);
        SetFpResult(dresult);
        break;
      }
      case ExternalReference::BUILTIN_FP_INT_CALL: {
        SimulatorRuntimeFPIntCall target =
          reinterpret_cast<SimulatorRuntimeFPIntCall>(external);
        dresult = target(dval0, ival);
        SetFpResult(dresult);
        break;
      }
      default:
        UNREACHABLE();
        break;
      }
      if (::v8::internal::FLAG_trace_sim) {
        switch (redirection->type()) {
        case ExternalReference::BUILTIN_COMPARE_CALL:
          PrintF("Returned %08x\n", static_cast<int32_t>(iresult));
          break;
        case ExternalReference::BUILTIN_FP_FP_CALL:
        case ExternalReference::BUILTIN_FP_CALL:
        case ExternalReference::BUILTIN_FP_INT_CALL:
          PrintF("Returned %f\n", dresult);
          break;
        default:
          UNREACHABLE();
          break;
        }
      }
    } else if (redirection->type() == ExternalReference::DIRECT_API_CALL) {
      if (::v8::internal::FLAG_trace_sim) {
2306 2307
        PrintF("Call to host function at %p args %08" PRIx64 " \n",
               reinterpret_cast<void*>(external), arg0);
2308 2309 2310 2311 2312 2313 2314
      }
      SimulatorRuntimeDirectApiCall target =
          reinterpret_cast<SimulatorRuntimeDirectApiCall>(external);
      target(arg0);
    } else if (
        redirection->type() == ExternalReference::PROFILING_API_CALL) {
      if (::v8::internal::FLAG_trace_sim) {
2315 2316 2317
        PrintF("Call to host function at %p args %08" PRIx64 "  %08" PRIx64
               " \n",
               reinterpret_cast<void*>(external), arg0, arg1);
2318 2319 2320 2321 2322 2323 2324
      }
      SimulatorRuntimeProfilingApiCall target =
          reinterpret_cast<SimulatorRuntimeProfilingApiCall>(external);
      target(arg0, Redirection::ReverseRedirection(arg1));
    } else if (
        redirection->type() == ExternalReference::DIRECT_GETTER_CALL) {
      if (::v8::internal::FLAG_trace_sim) {
2325 2326 2327
        PrintF("Call to host function at %p args %08" PRIx64 "  %08" PRIx64
               " \n",
               reinterpret_cast<void*>(external), arg0, arg1);
2328 2329 2330 2331 2332 2333 2334
      }
      SimulatorRuntimeDirectGetterCall target =
          reinterpret_cast<SimulatorRuntimeDirectGetterCall>(external);
      target(arg0, arg1);
    } else if (
        redirection->type() == ExternalReference::PROFILING_GETTER_CALL) {
      if (::v8::internal::FLAG_trace_sim) {
2335 2336 2337
        PrintF("Call to host function at %p args %08" PRIx64 "  %08" PRIx64
               "  %08" PRIx64 " \n",
               reinterpret_cast<void*>(external), arg0, arg1, arg2);
2338 2339 2340 2341 2342
      }
      SimulatorRuntimeProfilingGetterCall target =
          reinterpret_cast<SimulatorRuntimeProfilingGetterCall>(external);
      target(arg0, arg1, Redirection::ReverseRedirection(arg2));
    } else {
2343 2344
      DCHECK(redirection->type() == ExternalReference::BUILTIN_CALL ||
             redirection->type() == ExternalReference::BUILTIN_CALL_PAIR);
2345 2346 2347 2348 2349
      SimulatorRuntimeCall target =
                  reinterpret_cast<SimulatorRuntimeCall>(external);
      if (::v8::internal::FLAG_trace_sim) {
        PrintF(
            "Call to host function at %p "
2350
            "args %08" PRIx64 " , %08" PRIx64 " , %08" PRIx64 " , %08" PRIx64
2351 2352
            " , %08" PRIx64 " , %08" PRIx64 " , %08" PRIx64 " , %08" PRIx64
            " , %08" PRIx64 " \n",
2353 2354
            reinterpret_cast<void*>(FUNCTION_ADDR(target)), arg0, arg1, arg2,
            arg3, arg4, arg5, arg6, arg7, arg8);
2355
      }
2356 2357
      ObjectPair result =
          target(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
2358 2359 2360 2361
      set_register(v0, (int64_t)(result.x));
      set_register(v1, (int64_t)(result.y));
    }
     if (::v8::internal::FLAG_trace_sim) {
2362 2363
       PrintF("Returned %08" PRIx64 "  : %08" PRIx64 " \n", get_register(v1),
              get_register(v0));
2364 2365 2366 2367 2368 2369 2370 2371 2372
    }
    set_register(ra, saved_ra);
    set_pc(get_register(ra));

  } else if (func == BREAK && code <= kMaxStopCode) {
    if (IsWatchpoint(code)) {
      PrintWatchpoint(code);
    } else {
      IncreaseStopCounter(code);
2373
      HandleStop(code, instr_.instr());
2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391
    }
  } else {
    // All remaining break_ codes, and all traps are handled here.
    MipsDebugger dbg(this);
    dbg.Debug();
  }
}


// Stop helper functions.
bool Simulator::IsWatchpoint(uint64_t code) {
  return (code <= kMaxWatchpointCode);
}


void Simulator::PrintWatchpoint(uint64_t code) {
  MipsDebugger dbg(this);
  ++break_count_;
2392 2393
  PrintF("\n---- break %" PRId64 "  marker: %3d  (instr count: %8" PRId64
         " ) ----------"
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417
         "----------------------------------",
         code, break_count_, icount_);
  dbg.PrintAllRegs();  // Print registers and continue running.
}


void Simulator::HandleStop(uint64_t code, Instruction* instr) {
  // Stop if it is enabled, otherwise go on jumping over the stop
  // and the message address.
  if (IsEnabledStop(code)) {
    MipsDebugger dbg(this);
    dbg.Stop(instr);
  }
}


bool Simulator::IsStopInstruction(Instruction* instr) {
  int32_t func = instr->FunctionFieldRaw();
  uint32_t code = static_cast<uint32_t>(instr->Bits(25, 6));
  return (func == BREAK) && code > kMaxWatchpointCode && code <= kMaxStopCode;
}


bool Simulator::IsEnabledStop(uint64_t code) {
2418 2419
  DCHECK_LE(code, kMaxStopCode);
  DCHECK_GT(code, kMaxWatchpointCode);
2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438
  return !(watched_stops_[code].count & kStopDisabledBit);
}


void Simulator::EnableStop(uint64_t code) {
  if (!IsEnabledStop(code)) {
    watched_stops_[code].count &= ~kStopDisabledBit;
  }
}


void Simulator::DisableStop(uint64_t code) {
  if (IsEnabledStop(code)) {
    watched_stops_[code].count |= kStopDisabledBit;
  }
}


void Simulator::IncreaseStopCounter(uint64_t code) {
2439
  DCHECK_LE(code, kMaxStopCode);
2440
  if ((watched_stops_[code].count & ~(1 << 31)) == 0x7FFFFFFF) {
2441 2442 2443 2444
    PrintF("Stop counter for code %" PRId64
           "  has overflowed.\n"
           "Enabling this code and reseting the counter to 0.\n",
           code);
2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
    watched_stops_[code].count = 0;
    EnableStop(code);
  } else {
    watched_stops_[code].count++;
  }
}


// Print a stop status.
void Simulator::PrintStopInfo(uint64_t code) {
  if (code <= kMaxWatchpointCode) {
    PrintF("That is a watchpoint, not a stop.\n");
    return;
  } else if (code > kMaxStopCode) {
    PrintF("Code too large, only %u stops can be used\n", kMaxStopCode + 1);
    return;
  }
  const char* state = IsEnabledStop(code) ? "Enabled" : "Disabled";
  int32_t count = watched_stops_[code].count & ~kStopDisabledBit;
  // Don't print the state of unused breakpoints.
  if (count != 0) {
    if (watched_stops_[code].desc) {
2467
      PrintF("stop %" PRId64 "  - 0x%" PRIx64 " : \t%s, \tcounter = %i, \t%s\n",
2468 2469
             code, code, state, count, watched_stops_[code].desc);
    } else {
2470 2471
      PrintF("stop %" PRId64 "  - 0x%" PRIx64 " : \t%s, \tcounter = %i\n", code,
             code, state, count);
2472 2473 2474 2475 2476
    }
  }
}


2477
void Simulator::SignalException(Exception e) {
2478
  FATAL("Error: Exception %i raised.", static_cast<int>(e));
2479 2480
}

2481 2482
// Min/Max template functions for Double and Single arguments.

2483
template <typename T>
2484
static T FPAbs(T a);
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496

template <>
double FPAbs<double>(double a) {
  return fabs(a);
}

template <>
float FPAbs<float>(float a) {
  return fabsf(a);
}

template <typename T>
2497
static bool FPUProcessNaNsAndZeros(T a, T b, MaxMinKind kind, T& result) {
2498 2499 2500 2501 2502 2503 2504 2505
  if (std::isnan(a) && std::isnan(b)) {
    result = a;
  } else if (std::isnan(a)) {
    result = b;
  } else if (std::isnan(b)) {
    result = a;
  } else if (b == a) {
    // Handle -0.0 == 0.0 case.
2506
    // std::signbit() returns int 0 or 1 so subtracting MaxMinKind::kMax
2507 2508
    // negates the result.
    result = std::signbit(b) - static_cast<int>(kind) ? b : a;
2509 2510 2511 2512 2513 2514 2515
  } else {
    return false;
  }
  return true;
}

template <typename T>
2516
static T FPUMin(T a, T b) {
2517
  T result;
2518
  if (FPUProcessNaNsAndZeros(a, b, MaxMinKind::kMin, result)) {
2519 2520 2521 2522 2523 2524 2525
    return result;
  } else {
    return b < a ? b : a;
  }
}

template <typename T>
2526
static T FPUMax(T a, T b) {
2527
  T result;
2528
  if (FPUProcessNaNsAndZeros(a, b, MaxMinKind::kMax, result)) {
2529 2530 2531 2532 2533 2534 2535
    return result;
  } else {
    return b > a ? b : a;
  }
}

template <typename T>
2536
static T FPUMinA(T a, T b) {
2537
  T result;
2538
  if (!FPUProcessNaNsAndZeros(a, b, MaxMinKind::kMin, result)) {
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
    if (FPAbs(a) < FPAbs(b)) {
      result = a;
    } else if (FPAbs(b) < FPAbs(a)) {
      result = b;
    } else {
      result = a < b ? a : b;
    }
  }
  return result;
}

template <typename T>
2551
static T FPUMaxA(T a, T b) {
2552
  T result;
2553
  if (!FPUProcessNaNsAndZeros(a, b, MaxMinKind::kMin, result)) {
2554 2555 2556 2557 2558 2559 2560 2561 2562 2563
    if (FPAbs(a) > FPAbs(b)) {
      result = a;
    } else if (FPAbs(b) > FPAbs(a)) {
      result = b;
    } else {
      result = a > b ? a : b;
    }
  }
  return result;
}
2564

2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607
enum class KeepSign : bool { no = false, yes };

template <typename T, typename std::enable_if<std::is_floating_point<T>::value,
                                              int>::type = 0>
T FPUCanonalizeNaNArg(T result, T arg, KeepSign keepSign = KeepSign::no) {
  DCHECK(std::isnan(arg));
  T qNaN = std::numeric_limits<T>::quiet_NaN();
  if (keepSign == KeepSign::yes) {
    return std::copysign(qNaN, result);
  }
  return qNaN;
}

template <typename T>
T FPUCanonalizeNaNArgs(T result, KeepSign keepSign, T first) {
  if (std::isnan(first)) {
    return FPUCanonalizeNaNArg(result, first, keepSign);
  }
  return result;
}

template <typename T, typename... Args>
T FPUCanonalizeNaNArgs(T result, KeepSign keepSign, T first, Args... args) {
  if (std::isnan(first)) {
    return FPUCanonalizeNaNArg(result, first, keepSign);
  }
  return FPUCanonalizeNaNArgs(result, keepSign, args...);
}

template <typename Func, typename T, typename... Args>
T FPUCanonalizeOperation(Func f, T first, Args... args) {
  return FPUCanonalizeOperation(f, KeepSign::no, first, args...);
}

template <typename Func, typename T, typename... Args>
T FPUCanonalizeOperation(Func f, KeepSign keepSign, T first, Args... args) {
  T result = f(first, args...);
  if (std::isnan(result)) {
    result = FPUCanonalizeNaNArgs(result, keepSign, first, args...);
  }
  return result;
}

2608 2609
// Handle execution based on instruction types.

2610
void Simulator::DecodeTypeRegisterSRsType() {
2611
  float fs, ft, fd;
2612 2613 2614
  fs = get_fpu_register_float(fs_reg());
  ft = get_fpu_register_float(ft_reg());
  fd = get_fpu_register_float(fd_reg());
2615 2616
  int32_t ft_int = bit_cast<int32_t>(ft);
  int32_t fd_int = bit_cast<int32_t>(fd);
2617
  uint32_t cc, fcsr_cc;
2618
  cc = instr_.FCccValue();
2619
  fcsr_cc = get_fcsr_condition_bit(cc);
2620
  switch (instr_.FunctionFieldRaw()) {
2621
    case RINT: {
2622
      DCHECK_EQ(kArchVariant, kMips64r6);
2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
      float result, temp_result;
      double temp;
      float upper = std::ceil(fs);
      float lower = std::floor(fs);
      switch (get_fcsr_rounding_mode()) {
        case kRoundToNearest:
          if (upper - fs < fs - lower) {
            result = upper;
          } else if (upper - fs > fs - lower) {
            result = lower;
          } else {
            temp_result = upper / 2;
            float reminder = modf(temp_result, &temp);
            if (reminder == 0) {
              result = upper;
            } else {
              result = lower;
            }
          }
          break;
        case kRoundToZero:
          result = (fs > 0 ? lower : upper);
          break;
        case kRoundToPlusInf:
          result = upper;
          break;
        case kRoundToMinusInf:
          result = lower;
          break;
      }
2653
      SetFPUFloatResult(fd_reg(), result);
2654 2655 2656 2657 2658 2659
      if (result != fs) {
        set_fcsr_bit(kFCSRInexactFlagBit, true);
      }
      break;
    }
    case ADD_S:
2660
      SetFPUFloatResult(
2661 2662 2663
          fd_reg(),
          FPUCanonalizeOperation([](float lhs, float rhs) { return lhs + rhs; },
                                 fs, ft));
2664
      break;
2665
    case SUB_S:
2666
      SetFPUFloatResult(
2667 2668 2669
          fd_reg(),
          FPUCanonalizeOperation([](float lhs, float rhs) { return lhs - rhs; },
                                 fs, ft));
2670
      break;
2671
    case MADDF_S:
2672
      DCHECK_EQ(kArchVariant, kMips64r6);
2673
      SetFPUFloatResult(fd_reg(), std::fma(fs, ft, fd));
2674 2675
      break;
    case MSUBF_S:
2676
      DCHECK_EQ(kArchVariant, kMips64r6);
2677
      SetFPUFloatResult(fd_reg(), std::fma(-fs, ft, fd));
2678
      break;
2679
    case MUL_S:
2680
      SetFPUFloatResult(
2681 2682 2683
          fd_reg(),
          FPUCanonalizeOperation([](float lhs, float rhs) { return lhs * rhs; },
                                 fs, ft));
2684
      break;
2685
    case DIV_S:
2686
      SetFPUFloatResult(
2687 2688 2689
          fd_reg(),
          FPUCanonalizeOperation([](float lhs, float rhs) { return lhs / rhs; },
                                 fs, ft));
2690
      break;
2691
    case ABS_S:
2692 2693
      SetFPUFloatResult(fd_reg(), FPUCanonalizeOperation(
                                      [](float fs) { return FPAbs(fs); }, fs));
2694
      break;
2695
    case MOV_S:
2696
      SetFPUFloatResult(fd_reg(), fs);
2697
      break;
2698
    case NEG_S:
2699 2700 2701
      SetFPUFloatResult(fd_reg(),
                        FPUCanonalizeOperation([](float src) { return -src; },
                                               KeepSign::yes, fs));
2702
      break;
2703
    case SQRT_S:
2704
      SetFPUFloatResult(
2705 2706
          fd_reg(),
          FPUCanonalizeOperation([](float src) { return std::sqrt(src); }, fs));
2707
      break;
2708
    case RSQRT_S:
2709
      SetFPUFloatResult(
2710 2711
          fd_reg(), FPUCanonalizeOperation(
                        [](float src) { return 1.0 / std::sqrt(src); }, fs));
2712
      break;
2713
    case RECIP_S:
2714 2715
      SetFPUFloatResult(fd_reg(), FPUCanonalizeOperation(
                                      [](float src) { return 1.0 / src; }, fs));
2716
      break;
2717 2718
    case C_F_D:
      set_fcsr_bit(fcsr_cc, false);
2719
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2720
      break;
2721 2722
    case C_UN_D:
      set_fcsr_bit(fcsr_cc, std::isnan(fs) || std::isnan(ft));
2723
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2724 2725 2726
      break;
    case C_EQ_D:
      set_fcsr_bit(fcsr_cc, (fs == ft));
2727
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2728 2729 2730
      break;
    case C_UEQ_D:
      set_fcsr_bit(fcsr_cc, (fs == ft) || (std::isnan(fs) || std::isnan(ft)));
2731
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2732 2733 2734
      break;
    case C_OLT_D:
      set_fcsr_bit(fcsr_cc, (fs < ft));
2735
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2736 2737 2738
      break;
    case C_ULT_D:
      set_fcsr_bit(fcsr_cc, (fs < ft) || (std::isnan(fs) || std::isnan(ft)));
2739
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2740 2741 2742
      break;
    case C_OLE_D:
      set_fcsr_bit(fcsr_cc, (fs <= ft));
2743
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2744 2745 2746
      break;
    case C_ULE_D:
      set_fcsr_bit(fcsr_cc, (fs <= ft) || (std::isnan(fs) || std::isnan(ft)));
2747
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2748
      break;
2749
    case CVT_D_S:
2750
      SetFPUDoubleResult(fd_reg(), static_cast<double>(fs));
2751
      break;
2752 2753 2754 2755 2756 2757
    case CLASS_S: {  // Mips64r6 instruction
      // Convert float input to uint32_t for easier bit manipulation
      uint32_t classed = bit_cast<uint32_t>(fs);

      // Extracting sign, exponent and mantissa from the input float
      uint32_t sign = (classed >> 31) & 1;
2758 2759
      uint32_t exponent = (classed >> 23) & 0x000000FF;
      uint32_t mantissa = classed & 0x007FFFFF;
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
      uint32_t result;
      float fResult;

      // Setting flags if input float is negative infinity,
      // positive infinity, negative zero or positive zero
      bool negInf = (classed == 0xFF800000);
      bool posInf = (classed == 0x7F800000);
      bool negZero = (classed == 0x80000000);
      bool posZero = (classed == 0x00000000);

      bool signalingNan;
      bool quietNan;
      bool negSubnorm;
      bool posSubnorm;
      bool negNorm;
      bool posNorm;

      // Setting flags if float is NaN
      signalingNan = false;
      quietNan = false;
2780
      if (!negInf && !posInf && (exponent == 0xFF)) {
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809
        quietNan = ((mantissa & 0x00200000) == 0) &&
                   ((mantissa & (0x00200000 - 1)) == 0);
        signalingNan = !quietNan;
      }

      // Setting flags if float is subnormal number
      posSubnorm = false;
      negSubnorm = false;
      if ((exponent == 0) && (mantissa != 0)) {
        DCHECK(sign == 0 || sign == 1);
        posSubnorm = (sign == 0);
        negSubnorm = (sign == 1);
      }

      // Setting flags if float is normal number
      posNorm = false;
      negNorm = false;
      if (!posSubnorm && !negSubnorm && !posInf && !negInf && !signalingNan &&
          !quietNan && !negZero && !posZero) {
        DCHECK(sign == 0 || sign == 1);
        posNorm = (sign == 0);
        negNorm = (sign == 1);
      }

      // Calculating result according to description of CLASS.S instruction
      result = (posZero << 9) | (posSubnorm << 8) | (posNorm << 7) |
               (posInf << 6) | (negZero << 5) | (negSubnorm << 4) |
               (negNorm << 3) | (negInf << 2) | (quietNan << 1) | signalingNan;

2810
      DCHECK_NE(result, 0);
2811 2812

      fResult = bit_cast<float>(result);
2813
      SetFPUFloatResult(fd_reg(), fResult);
2814 2815 2816 2817 2818 2819
      break;
    }
    case CVT_L_S: {
      float rounded;
      int64_t result;
      round64_according_to_fcsr(fs, rounded, result, fs);
2820
      SetFPUResult(fd_reg(), result);
2821
      if (set_fcsr_round64_error(fs, rounded)) {
2822
        set_fpu_register_invalid_result64(fs, rounded);
2823 2824 2825 2826 2827 2828 2829
      }
      break;
    }
    case CVT_W_S: {
      float rounded;
      int32_t result;
      round_according_to_fcsr(fs, rounded, result, fs);
2830
      SetFPUWordResult(fd_reg(), result);
2831
      if (set_fcsr_round_error(fs, rounded)) {
2832
        set_fpu_register_word_invalid_result(fs, rounded);
2833 2834 2835
      }
      break;
    }
2836 2837 2838
    case TRUNC_W_S: {  // Truncate single to word (round towards 0).
      float rounded = trunc(fs);
      int32_t result = static_cast<int32_t>(rounded);
2839
      SetFPUWordResult(fd_reg(), result);
2840
      if (set_fcsr_round_error(fs, rounded)) {
2841
        set_fpu_register_word_invalid_result(fs, rounded);
2842 2843 2844 2845 2846
      }
    } break;
    case TRUNC_L_S: {  // Mips64r2 instruction.
      float rounded = trunc(fs);
      int64_t result = static_cast<int64_t>(rounded);
2847
      SetFPUResult(fd_reg(), result);
2848
      if (set_fcsr_round64_error(fs, rounded)) {
2849
        set_fpu_register_invalid_result64(fs, rounded);
2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
      }
      break;
    }
    case ROUND_W_S: {
      float rounded = std::floor(fs + 0.5);
      int32_t result = static_cast<int32_t>(rounded);
      if ((result & 1) != 0 && result - fs == 0.5) {
        // If the number is halfway between two integers,
        // round to the even one.
        result--;
      }
2861
      SetFPUWordResult(fd_reg(), result);
2862
      if (set_fcsr_round_error(fs, rounded)) {
2863
        set_fpu_register_word_invalid_result(fs, rounded);
2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875
      }
      break;
    }
    case ROUND_L_S: {  // Mips64r2 instruction.
      float rounded = std::floor(fs + 0.5);
      int64_t result = static_cast<int64_t>(rounded);
      if ((result & 1) != 0 && result - fs == 0.5) {
        // If the number is halfway between two integers,
        // round to the even one.
        result--;
      }
      int64_t i64 = static_cast<int64_t>(result);
2876
      SetFPUResult(fd_reg(), i64);
2877
      if (set_fcsr_round64_error(fs, rounded)) {
2878
        set_fpu_register_invalid_result64(fs, rounded);
2879 2880 2881 2882 2883 2884
      }
      break;
    }
    case FLOOR_L_S: {  // Mips64r2 instruction.
      float rounded = floor(fs);
      int64_t result = static_cast<int64_t>(rounded);
2885
      SetFPUResult(fd_reg(), result);
2886
      if (set_fcsr_round64_error(fs, rounded)) {
2887
        set_fpu_register_invalid_result64(fs, rounded);
2888 2889 2890 2891 2892 2893 2894
      }
      break;
    }
    case FLOOR_W_S:  // Round double to word towards negative infinity.
    {
      float rounded = std::floor(fs);
      int32_t result = static_cast<int32_t>(rounded);
2895
      SetFPUWordResult(fd_reg(), result);
2896
      if (set_fcsr_round_error(fs, rounded)) {
2897
        set_fpu_register_word_invalid_result(fs, rounded);
2898 2899 2900 2901 2902 2903
      }
    } break;
    case CEIL_W_S:  // Round double to word towards positive infinity.
    {
      float rounded = std::ceil(fs);
      int32_t result = static_cast<int32_t>(rounded);
2904
      SetFPUWordResult(fd_reg(), result);
2905
      if (set_fcsr_round_error(fs, rounded)) {
2906
        set_fpu_register_invalid_result(fs, rounded);
2907 2908 2909 2910 2911
      }
    } break;
    case CEIL_L_S: {  // Mips64r2 instruction.
      float rounded = ceil(fs);
      int64_t result = static_cast<int64_t>(rounded);
2912
      SetFPUResult(fd_reg(), result);
2913
      if (set_fcsr_round64_error(fs, rounded)) {
2914
        set_fpu_register_invalid_result64(fs, rounded);
2915 2916 2917 2918
      }
      break;
    }
    case MINA:
2919
      DCHECK_EQ(kArchVariant, kMips64r6);
2920
      SetFPUFloatResult(fd_reg(), FPUMinA(ft, fs));
2921 2922
      break;
    case MAXA:
2923
      DCHECK_EQ(kArchVariant, kMips64r6);
2924
      SetFPUFloatResult(fd_reg(), FPUMaxA(ft, fs));
2925 2926
      break;
    case MIN:
2927
      DCHECK_EQ(kArchVariant, kMips64r6);
2928
      SetFPUFloatResult(fd_reg(), FPUMin(ft, fs));
2929 2930
      break;
    case MAX:
2931
      DCHECK_EQ(kArchVariant, kMips64r6);
2932
      SetFPUFloatResult(fd_reg(), FPUMax(ft, fs));
2933 2934
      break;
    case SEL:
2935
      DCHECK_EQ(kArchVariant, kMips64r6);
2936
      SetFPUFloatResult(fd_reg(), (fd_int & 0x1) == 0 ? fs : ft);
2937 2938
      break;
    case SELEQZ_C:
2939
      DCHECK_EQ(kArchVariant, kMips64r6);
2940 2941 2942
      SetFPUFloatResult(
          fd_reg(),
          (ft_int & 0x1) == 0 ? get_fpu_register_float(fs_reg()) : 0.0);
2943 2944
      break;
    case SELNEZ_C:
2945
      DCHECK_EQ(kArchVariant, kMips64r6);
2946 2947 2948
      SetFPUFloatResult(
          fd_reg(),
          (ft_int & 0x1) != 0 ? get_fpu_register_float(fs_reg()) : 0.0);
2949 2950
      break;
    case MOVZ_C: {
2951
      DCHECK_EQ(kArchVariant, kMips64r2);
2952
      if (rt() == 0) {
2953
        SetFPUFloatResult(fd_reg(), fs);
2954 2955 2956 2957
      }
      break;
    }
    case MOVN_C: {
2958
      DCHECK_EQ(kArchVariant, kMips64r2);
2959
      if (rt() != 0) {
2960
        SetFPUFloatResult(fd_reg(), fs);
2961 2962 2963 2964 2965
      }
      break;
    }
    case MOVF: {
      // Same function field for MOVT.D and MOVF.D
2966
      uint32_t ft_cc = (ft_reg() >> 2) & 0x7;
2967 2968
      ft_cc = get_fcsr_condition_bit(ft_cc);

2969
      if (instr_.Bit(16)) {  // Read Tf bit.
2970
        // MOVT.D
2971
        if (test_fcsr_bit(ft_cc)) SetFPUFloatResult(fd_reg(), fs);
2972 2973
      } else {
        // MOVF.D
2974
        if (!test_fcsr_bit(ft_cc)) SetFPUFloatResult(fd_reg(), fs);
2975 2976 2977
      }
      break;
    }
2978
    default:
2979
      // TRUNC_W_S ROUND_W_S ROUND_L_S FLOOR_W_S FLOOR_L_S
2980 2981 2982 2983 2984 2985
      // CEIL_W_S CEIL_L_S CVT_PS_S are unimplemented.
      UNREACHABLE();
  }
}


2986
void Simulator::DecodeTypeRegisterDRsType() {
2987
  double ft, fs, fd;
2988
  uint32_t cc, fcsr_cc;
2989
  fs = get_fpu_register_double(fs_reg());
2990 2991
  ft = (instr_.FunctionFieldRaw() != MOVF) ? get_fpu_register_double(ft_reg())
                                           : 0.0;
2992
  fd = get_fpu_register_double(fd_reg());
2993
  cc = instr_.FCccValue();
2994
  fcsr_cc = get_fcsr_condition_bit(cc);
2995 2996
  int64_t ft_int = bit_cast<int64_t>(ft);
  int64_t fd_int = bit_cast<int64_t>(fd);
2997
  switch (instr_.FunctionFieldRaw()) {
2998
    case RINT: {
2999
      DCHECK_EQ(kArchVariant, kMips64r6);
3000 3001 3002
      double result, temp, temp_result;
      double upper = std::ceil(fs);
      double lower = std::floor(fs);
3003
      switch (get_fcsr_rounding_mode()) {
3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
        case kRoundToNearest:
          if (upper - fs < fs - lower) {
            result = upper;
          } else if (upper - fs > fs - lower) {
            result = lower;
          } else {
            temp_result = upper / 2;
            double reminder = modf(temp_result, &temp);
            if (reminder == 0) {
              result = upper;
            } else {
              result = lower;
            }
          }
          break;
        case kRoundToZero:
          result = (fs > 0 ? lower : upper);
          break;
        case kRoundToPlusInf:
          result = upper;
          break;
        case kRoundToMinusInf:
          result = lower;
          break;
      }
3029
      SetFPUDoubleResult(fd_reg(), result);
3030 3031 3032 3033 3034
      if (result != fs) {
        set_fcsr_bit(kFCSRInexactFlagBit, true);
      }
      break;
    }
3035
    case SEL:
3036
      DCHECK_EQ(kArchVariant, kMips64r6);
3037
      SetFPUDoubleResult(fd_reg(), (fd_int & 0x1) == 0 ? fs : ft);
3038
      break;
3039
    case SELEQZ_C:
3040
      DCHECK_EQ(kArchVariant, kMips64r6);
3041
      SetFPUDoubleResult(fd_reg(), (ft_int & 0x1) == 0 ? fs : 0.0);
3042 3043
      break;
    case SELNEZ_C:
3044
      DCHECK_EQ(kArchVariant, kMips64r6);
3045
      SetFPUDoubleResult(fd_reg(), (ft_int & 0x1) != 0 ? fs : 0.0);
3046
      break;
3047
    case MOVZ_C: {
3048
      DCHECK_EQ(kArchVariant, kMips64r2);
3049
      if (rt() == 0) {
3050
        SetFPUDoubleResult(fd_reg(), fs);
3051 3052 3053 3054
      }
      break;
    }
    case MOVN_C: {
3055
      DCHECK_EQ(kArchVariant, kMips64r2);
3056
      if (rt() != 0) {
3057
        SetFPUDoubleResult(fd_reg(), fs);
3058 3059 3060 3061 3062
      }
      break;
    }
    case MOVF: {
      // Same function field for MOVT.D and MOVF.D
3063
      uint32_t ft_cc = (ft_reg() >> 2) & 0x7;
3064
      ft_cc = get_fcsr_condition_bit(ft_cc);
3065
      if (instr_.Bit(16)) {  // Read Tf bit.
3066
        // MOVT.D
3067
        if (test_fcsr_bit(ft_cc)) SetFPUDoubleResult(fd_reg(), fs);
3068 3069
      } else {
        // MOVF.D
3070
        if (!test_fcsr_bit(ft_cc)) SetFPUDoubleResult(fd_reg(), fs);
3071 3072 3073 3074
      }
      break;
    }
    case MINA:
3075
      DCHECK_EQ(kArchVariant, kMips64r6);
3076
      SetFPUDoubleResult(fd_reg(), FPUMinA(ft, fs));
3077 3078
      break;
    case MAXA:
3079
      DCHECK_EQ(kArchVariant, kMips64r6);
3080
      SetFPUDoubleResult(fd_reg(), FPUMaxA(ft, fs));
3081
      break;
3082
    case MIN:
3083
      DCHECK_EQ(kArchVariant, kMips64r6);
3084
      SetFPUDoubleResult(fd_reg(), FPUMin(ft, fs));
3085 3086
      break;
    case MAX:
3087
      DCHECK_EQ(kArchVariant, kMips64r6);
3088
      SetFPUDoubleResult(fd_reg(), FPUMax(ft, fs));
3089
      break;
3090
    case ADD_D:
3091
      SetFPUDoubleResult(
3092 3093 3094
          fd_reg(),
          FPUCanonalizeOperation(
              [](double lhs, double rhs) { return lhs + rhs; }, fs, ft));
3095 3096
      break;
    case SUB_D:
3097
      SetFPUDoubleResult(
3098 3099 3100
          fd_reg(),
          FPUCanonalizeOperation(
              [](double lhs, double rhs) { return lhs - rhs; }, fs, ft));
3101
      break;
3102
    case MADDF_D:
3103
      DCHECK_EQ(kArchVariant, kMips64r6);
3104
      SetFPUDoubleResult(fd_reg(), std::fma(fs, ft, fd));
3105 3106
      break;
    case MSUBF_D:
3107
      DCHECK_EQ(kArchVariant, kMips64r6);
3108
      SetFPUDoubleResult(fd_reg(), std::fma(-fs, ft, fd));
3109
      break;
3110
    case MUL_D:
3111
      SetFPUDoubleResult(
3112 3113 3114
          fd_reg(),
          FPUCanonalizeOperation(
              [](double lhs, double rhs) { return lhs * rhs; }, fs, ft));
3115 3116
      break;
    case DIV_D:
3117
      SetFPUDoubleResult(
3118 3119 3120
          fd_reg(),
          FPUCanonalizeOperation(
              [](double lhs, double rhs) { return lhs / rhs; }, fs, ft));
3121 3122
      break;
    case ABS_D:
3123
      SetFPUDoubleResult(
3124 3125
          fd_reg(),
          FPUCanonalizeOperation([](double fs) { return FPAbs(fs); }, fs));
3126 3127
      break;
    case MOV_D:
3128
      SetFPUDoubleResult(fd_reg(), fs);
3129 3130
      break;
    case NEG_D:
3131 3132 3133
      SetFPUDoubleResult(fd_reg(),
                         FPUCanonalizeOperation([](double src) { return -src; },
                                                KeepSign::yes, fs));
3134 3135
      break;
    case SQRT_D:
3136
      SetFPUDoubleResult(
3137 3138
          fd_reg(),
          FPUCanonalizeOperation([](double fs) { return std::sqrt(fs); }, fs));
3139
      break;
3140
    case RSQRT_D:
3141
      SetFPUDoubleResult(
3142 3143
          fd_reg(), FPUCanonalizeOperation(
                        [](double fs) { return 1.0 / std::sqrt(fs); }, fs));
3144
      break;
3145
    case RECIP_D:
3146 3147
      SetFPUDoubleResult(fd_reg(), FPUCanonalizeOperation(
                                       [](double fs) { return 1.0 / fs; }, fs));
3148
      break;
3149 3150
    case C_UN_D:
      set_fcsr_bit(fcsr_cc, std::isnan(fs) || std::isnan(ft));
3151
      TraceRegWr(test_fcsr_bit(fcsr_cc));
3152 3153 3154
      break;
    case C_EQ_D:
      set_fcsr_bit(fcsr_cc, (fs == ft));
3155
      TraceRegWr(test_fcsr_bit(fcsr_cc));
3156 3157 3158
      break;
    case C_UEQ_D:
      set_fcsr_bit(fcsr_cc, (fs == ft) || (std::isnan(fs) || std::isnan(ft)));
3159
      TraceRegWr(test_fcsr_bit(fcsr_cc));
3160 3161 3162
      break;
    case C_OLT_D:
      set_fcsr_bit(fcsr_cc, (fs < ft));
3163
      TraceRegWr(test_fcsr_bit(fcsr_cc));
3164 3165 3166
      break;
    case C_ULT_D:
      set_fcsr_bit(fcsr_cc, (fs < ft) || (std::isnan(fs) || std::isnan(ft)));
3167
      TraceRegWr(test_fcsr_bit(fcsr_cc));
3168 3169 3170
      break;
    case C_OLE_D:
      set_fcsr_bit(fcsr_cc, (fs <= ft));
3171
      TraceRegWr(test_fcsr_bit(fcsr_cc));
3172 3173 3174
      break;
    case C_ULE_D:
      set_fcsr_bit(fcsr_cc, (fs <= ft) || (std::isnan(fs) || std::isnan(ft)));
3175
      TraceRegWr(test_fcsr_bit(fcsr_cc));
3176
      break;
3177 3178 3179 3180
    case CVT_W_D: {  // Convert double to word.
      double rounded;
      int32_t result;
      round_according_to_fcsr(fs, rounded, result, fs);
3181
      SetFPUWordResult(fd_reg(), result);
3182
      if (set_fcsr_round_error(fs, rounded)) {
3183
        set_fpu_register_word_invalid_result(fs, rounded);
3184 3185 3186
      }
      break;
    }
3187 3188 3189 3190 3191 3192 3193 3194 3195
    case ROUND_W_D:  // Round double to word (round half to even).
    {
      double rounded = std::floor(fs + 0.5);
      int32_t result = static_cast<int32_t>(rounded);
      if ((result & 1) != 0 && result - fs == 0.5) {
        // If the number is halfway between two integers,
        // round to the even one.
        result--;
      }
3196
      SetFPUWordResult(fd_reg(), result);
3197
      if (set_fcsr_round_error(fs, rounded)) {
3198
        set_fpu_register_invalid_result(fs, rounded);
3199 3200 3201 3202 3203 3204
      }
    } break;
    case TRUNC_W_D:  // Truncate double to word (round towards 0).
    {
      double rounded = trunc(fs);
      int32_t result = static_cast<int32_t>(rounded);
3205
      SetFPUWordResult(fd_reg(), result);
3206
      if (set_fcsr_round_error(fs, rounded)) {
3207
        set_fpu_register_invalid_result(fs, rounded);
3208 3209 3210 3211 3212 3213
      }
    } break;
    case FLOOR_W_D:  // Round double to word towards negative infinity.
    {
      double rounded = std::floor(fs);
      int32_t result = static_cast<int32_t>(rounded);
3214
      SetFPUWordResult(fd_reg(), result);
3215
      if (set_fcsr_round_error(fs, rounded)) {
3216
        set_fpu_register_invalid_result(fs, rounded);
3217 3218 3219 3220 3221 3222
      }
    } break;
    case CEIL_W_D:  // Round double to word towards positive infinity.
    {
      double rounded = std::ceil(fs);
      int32_t result = static_cast<int32_t>(rounded);
3223
      SetFPUWordResult2(fd_reg(), result);
3224
      if (set_fcsr_round_error(fs, rounded)) {
3225
        set_fpu_register_invalid_result(fs, rounded);
3226 3227 3228
      }
    } break;
    case CVT_S_D:  // Convert double to float (single).
3229
      SetFPUFloatResult(fd_reg(), static_cast<float>(fs));
3230
      break;
3231 3232 3233 3234
    case CVT_L_D: {  // Mips64r2: Truncate double to 64-bit long-word.
      double rounded;
      int64_t result;
      round64_according_to_fcsr(fs, rounded, result, fs);
3235
      SetFPUResult(fd_reg(), result);
3236
      if (set_fcsr_round64_error(fs, rounded)) {
3237
        set_fpu_register_invalid_result64(fs, rounded);
3238 3239 3240
      }
      break;
    }
3241
    case ROUND_L_D: {  // Mips64r2 instruction.
3242
      double rounded = std::floor(fs + 0.5);
3243
      int64_t result = static_cast<int64_t>(rounded);
3244 3245 3246 3247 3248 3249
      if ((result & 1) != 0 && result - fs == 0.5) {
        // If the number is halfway between two integers,
        // round to the even one.
        result--;
      }
      int64_t i64 = static_cast<int64_t>(result);
3250
      SetFPUResult(fd_reg(), i64);
3251
      if (set_fcsr_round64_error(fs, rounded)) {
3252
        set_fpu_register_invalid_result64(fs, rounded);
3253 3254 3255 3256 3257 3258
      }
      break;
    }
    case TRUNC_L_D: {  // Mips64r2 instruction.
      double rounded = trunc(fs);
      int64_t result = static_cast<int64_t>(rounded);
3259
      SetFPUResult(fd_reg(), result);
3260
      if (set_fcsr_round64_error(fs, rounded)) {
3261
        set_fpu_register_invalid_result64(fs, rounded);
3262 3263 3264 3265 3266 3267
      }
      break;
    }
    case FLOOR_L_D: {  // Mips64r2 instruction.
      double rounded = floor(fs);
      int64_t result = static_cast<int64_t>(rounded);
3268
      SetFPUResult(fd_reg(), result);
3269
      if (set_fcsr_round64_error(fs, rounded)) {
3270
        set_fpu_register_invalid_result64(fs, rounded);
3271 3272 3273 3274 3275 3276
      }
      break;
    }
    case CEIL_L_D: {  // Mips64r2 instruction.
      double rounded = ceil(fs);
      int64_t result = static_cast<int64_t>(rounded);
3277
      SetFPUResult(fd_reg(), result);
3278
      if (set_fcsr_round64_error(fs, rounded)) {
3279
        set_fpu_register_invalid_result64(fs, rounded);
3280 3281 3282
      }
      break;
    }
3283 3284 3285 3286 3287 3288
    case CLASS_D: {  // Mips64r6 instruction
      // Convert double input to uint64_t for easier bit manipulation
      uint64_t classed = bit_cast<uint64_t>(fs);

      // Extracting sign, exponent and mantissa from the input double
      uint32_t sign = (classed >> 63) & 1;
3289 3290
      uint32_t exponent = (classed >> 52) & 0x00000000000007FF;
      uint64_t mantissa = classed & 0x000FFFFFFFFFFFFF;
3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310
      uint64_t result;
      double dResult;

      // Setting flags if input double is negative infinity,
      // positive infinity, negative zero or positive zero
      bool negInf = (classed == 0xFFF0000000000000);
      bool posInf = (classed == 0x7FF0000000000000);
      bool negZero = (classed == 0x8000000000000000);
      bool posZero = (classed == 0x0000000000000000);

      bool signalingNan;
      bool quietNan;
      bool negSubnorm;
      bool posSubnorm;
      bool negNorm;
      bool posNorm;

      // Setting flags if double is NaN
      signalingNan = false;
      quietNan = false;
3311
      if (!negInf && !posInf && exponent == 0x7FF) {
3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340
        quietNan = ((mantissa & 0x0008000000000000) != 0) &&
                   ((mantissa & (0x0008000000000000 - 1)) == 0);
        signalingNan = !quietNan;
      }

      // Setting flags if double is subnormal number
      posSubnorm = false;
      negSubnorm = false;
      if ((exponent == 0) && (mantissa != 0)) {
        DCHECK(sign == 0 || sign == 1);
        posSubnorm = (sign == 0);
        negSubnorm = (sign == 1);
      }

      // Setting flags if double is normal number
      posNorm = false;
      negNorm = false;
      if (!posSubnorm && !negSubnorm && !posInf && !negInf && !signalingNan &&
          !quietNan && !negZero && !posZero) {
        DCHECK(sign == 0 || sign == 1);
        posNorm = (sign == 0);
        negNorm = (sign == 1);
      }

      // Calculating result according to description of CLASS.D instruction
      result = (posZero << 9) | (posSubnorm << 8) | (posNorm << 7) |
               (posInf << 6) | (negZero << 5) | (negSubnorm << 4) |
               (negNorm << 3) | (negInf << 2) | (quietNan << 1) | signalingNan;

3341
      DCHECK_NE(result, 0);
3342 3343

      dResult = bit_cast<double>(result);
3344
      SetFPUDoubleResult(fd_reg(), dResult);
3345 3346 3347 3348
      break;
    }
    case C_F_D: {
      set_fcsr_bit(fcsr_cc, false);
3349
      TraceRegWr(test_fcsr_bit(fcsr_cc));
3350
      break;
3351
    }
3352 3353 3354 3355 3356 3357
    default:
      UNREACHABLE();
  }
}


3358 3359 3360 3361
void Simulator::DecodeTypeRegisterWRsType() {
  float fs = get_fpu_register_float(fs_reg());
  float ft = get_fpu_register_float(ft_reg());
  int64_t alu_out = 0x12345678;
3362
  switch (instr_.FunctionFieldRaw()) {
3363
    case CVT_S_W:  // Convert word to float (single).
3364
      alu_out = get_fpu_register_signed_word(fs_reg());
3365
      SetFPUFloatResult(fd_reg(), static_cast<float>(alu_out));
3366 3367
      break;
    case CVT_D_W:  // Convert word to double.
3368
      alu_out = get_fpu_register_signed_word(fs_reg());
3369
      SetFPUDoubleResult(fd_reg(), static_cast<double>(alu_out));
3370
      break;
3371
    case CMP_AF:
3372
      SetFPUWordResult2(fd_reg(), 0);
3373 3374 3375
      break;
    case CMP_UN:
      if (std::isnan(fs) || std::isnan(ft)) {
3376
        SetFPUWordResult2(fd_reg(), -1);
3377
      } else {
3378
        SetFPUWordResult2(fd_reg(), 0);
3379 3380 3381 3382
      }
      break;
    case CMP_EQ:
      if (fs == ft) {
3383
        SetFPUWordResult2(fd_reg(), -1);
3384
      } else {
3385
        SetFPUWordResult2(fd_reg(), 0);
3386 3387 3388 3389
      }
      break;
    case CMP_UEQ:
      if ((fs == ft) || (std::isnan(fs) || std::isnan(ft))) {
3390
        SetFPUWordResult2(fd_reg(), -1);
3391
      } else {
3392
        SetFPUWordResult2(fd_reg(), 0);
3393 3394 3395 3396
      }
      break;
    case CMP_LT:
      if (fs < ft) {
3397
        SetFPUWordResult2(fd_reg(), -1);
3398
      } else {
3399
        SetFPUWordResult2(fd_reg(), 0);
3400 3401 3402 3403
      }
      break;
    case CMP_ULT:
      if ((fs < ft) || (std::isnan(fs) || std::isnan(ft))) {
3404
        SetFPUWordResult2(fd_reg(), -1);
3405
      } else {
3406
        SetFPUWordResult2(fd_reg(), 0);
3407 3408 3409 3410
      }
      break;
    case CMP_LE:
      if (fs <= ft) {
3411
        SetFPUWordResult2(fd_reg(), -1);
3412
      } else {
3413
        SetFPUWordResult2(fd_reg(), 0);
3414 3415 3416 3417
      }
      break;
    case CMP_ULE:
      if ((fs <= ft) || (std::isnan(fs) || std::isnan(ft))) {
3418
        SetFPUWordResult2(fd_reg(), -1);
3419
      } else {
3420
        SetFPUWordResult2(fd_reg(), 0);
3421 3422 3423 3424
      }
      break;
    case CMP_OR:
      if (!std::isnan(fs) && !std::isnan(ft)) {
3425
        SetFPUWordResult2(fd_reg(), -1);
3426
      } else {
3427
        SetFPUWordResult2(fd_reg(), 0);
3428 3429 3430 3431
      }
      break;
    case CMP_UNE:
      if ((fs != ft) || (std::isnan(fs) || std::isnan(ft))) {
3432
        SetFPUWordResult2(fd_reg(), -1);
3433
      } else {
3434
        SetFPUWordResult2(fd_reg(), 0);
3435 3436 3437 3438
      }
      break;
    case CMP_NE:
      if (fs != ft) {
3439
        SetFPUWordResult2(fd_reg(), -1);
3440
      } else {
3441
        SetFPUWordResult2(fd_reg(), 0);
3442 3443 3444
      }
      break;
    default:
3445 3446 3447 3448 3449
      UNREACHABLE();
  }
}


3450 3451 3452
void Simulator::DecodeTypeRegisterLRsType() {
  double fs = get_fpu_register_double(fs_reg());
  double ft = get_fpu_register_double(ft_reg());
3453
  int64_t i64;
3454
  switch (instr_.FunctionFieldRaw()) {
3455
    case CVT_D_L:  // Mips32r2 instruction.
3456
      i64 = get_fpu_register(fs_reg());
3457
      SetFPUDoubleResult(fd_reg(), static_cast<double>(i64));
3458 3459
      break;
    case CVT_S_L:
3460
      i64 = get_fpu_register(fs_reg());
3461
      SetFPUFloatResult(fd_reg(), static_cast<float>(i64));
3462
      break;
3463
    case CMP_AF:
3464
      SetFPUResult(fd_reg(), 0);
3465 3466 3467
      break;
    case CMP_UN:
      if (std::isnan(fs) || std::isnan(ft)) {
3468
        SetFPUResult(fd_reg(), -1);
3469
      } else {
3470
        SetFPUResult(fd_reg(), 0);
3471 3472 3473 3474
      }
      break;
    case CMP_EQ:
      if (fs == ft) {
3475
        SetFPUResult(fd_reg(), -1);
3476
      } else {
3477
        SetFPUResult(fd_reg(), 0);
3478 3479 3480 3481
      }
      break;
    case CMP_UEQ:
      if ((fs == ft) || (std::isnan(fs) || std::isnan(ft))) {
3482
        SetFPUResult(fd_reg(), -1);
3483
      } else {
3484
        SetFPUResult(fd_reg(), 0);
3485 3486 3487 3488
      }
      break;
    case CMP_LT:
      if (fs < ft) {
3489
        SetFPUResult(fd_reg(), -1);
3490
      } else {
3491
        SetFPUResult(fd_reg(), 0);
3492 3493 3494 3495
      }
      break;
    case CMP_ULT:
      if ((fs < ft) || (std::isnan(fs) || std::isnan(ft))) {
3496
        SetFPUResult(fd_reg(), -1);
3497
      } else {
3498
        SetFPUResult(fd_reg(), 0);
3499 3500 3501 3502
      }
      break;
    case CMP_LE:
      if (fs <= ft) {
3503
        SetFPUResult(fd_reg(), -1);
3504
      } else {
3505
        SetFPUResult(fd_reg(), 0);
3506 3507 3508 3509
      }
      break;
    case CMP_ULE:
      if ((fs <= ft) || (std::isnan(fs) || std::isnan(ft))) {
3510
        SetFPUResult(fd_reg(), -1);
3511
      } else {
3512
        SetFPUResult(fd_reg(), 0);
3513 3514
      }
      break;
3515 3516
    case CMP_OR:
      if (!std::isnan(fs) && !std::isnan(ft)) {
3517
        SetFPUResult(fd_reg(), -1);
3518
      } else {
3519
        SetFPUResult(fd_reg(), 0);
3520 3521 3522 3523
      }
      break;
    case CMP_UNE:
      if ((fs != ft) || (std::isnan(fs) || std::isnan(ft))) {
3524
        SetFPUResult(fd_reg(), -1);
3525
      } else {
3526
        SetFPUResult(fd_reg(), 0);
3527 3528 3529 3530
      }
      break;
    case CMP_NE:
      if (fs != ft && (!std::isnan(fs) && !std::isnan(ft))) {
3531
        SetFPUResult(fd_reg(), -1);
3532
      } else {
3533
        SetFPUResult(fd_reg(), 0);
3534 3535 3536
      }
      break;
    default:
3537 3538 3539 3540
      UNREACHABLE();
  }
}

3541 3542

void Simulator::DecodeTypeRegisterCOP1() {
3543
  switch (instr_.RsFieldRaw()) {
3544 3545 3546 3547 3548 3549
    case BC1:  // Branch on coprocessor condition.
    case BC1EQZ:
    case BC1NEZ:
      UNREACHABLE();
      break;
    case CFC1:
3550
      // At the moment only FCSR is supported.
3551
      DCHECK_EQ(fs_reg(), kFCSRRegister);
3552
      SetResult(rt_reg(), FCSR_);
3553 3554
      break;
    case MFC1:
3555 3556
      set_register(rt_reg(),
                   static_cast<int64_t>(get_fpu_register_word(fs_reg())));
3557
      TraceRegWr(get_register(rt_reg()), WORD_DWORD);
3558
      break;
3559
    case DMFC1:
3560
      SetResult(rt_reg(), get_fpu_register(fs_reg()));
3561
      break;
3562
    case MFHC1:
3563
      SetResult(rt_reg(), get_fpu_register_hi_word(fs_reg()));
3564
      break;
3565
    case CTC1: {
3566
      // At the moment only FCSR is supported.
3567
      DCHECK_EQ(fs_reg(), kFCSRRegister);
3568 3569 3570 3571
      uint32_t reg = static_cast<uint32_t>(rt());
      if (kArchVariant == kMips64r6) {
        FCSR_ = reg | kFCSRNaN2008FlagMask;
      } else {
3572
        DCHECK_EQ(kArchVariant, kMips64r2);
3573 3574
        FCSR_ = reg & ~kFCSRNaN2008FlagMask;
      }
3575
      TraceRegWr(FCSR_);
3576
      break;
3577
    }
3578 3579
    case MTC1:
      // Hardware writes upper 32-bits to zero on mtc1.
3580 3581
      set_fpu_register_hi_word(fs_reg(), 0);
      set_fpu_register_word(fs_reg(), static_cast<int32_t>(rt()));
3582
      TraceRegWr(get_fpu_register(fs_reg()), FLOAT_DOUBLE);
3583 3584
      break;
    case DMTC1:
3585
      SetFPUResult2(fs_reg(), rt());
3586 3587
      break;
    case MTHC1:
3588
      set_fpu_register_hi_word(fs_reg(), static_cast<int32_t>(rt()));
3589
      TraceRegWr(get_fpu_register(fs_reg()), DOUBLE);
3590 3591
      break;
    case S:
3592
      DecodeTypeRegisterSRsType();
3593 3594
      break;
    case D:
3595
      DecodeTypeRegisterDRsType();
3596 3597
      break;
    case W:
3598
      DecodeTypeRegisterWRsType();
3599 3600
      break;
    case L:
3601
      DecodeTypeRegisterLRsType();
3602 3603 3604 3605 3606 3607 3608
      break;
    default:
      UNREACHABLE();
  }
}


3609
void Simulator::DecodeTypeRegisterCOP1X() {
3610
  switch (instr_.FunctionFieldRaw()) {
3611
    case MADD_S: {
3612
      DCHECK_EQ(kArchVariant, kMips64r2);
3613 3614 3615 3616
      float fr, ft, fs;
      fr = get_fpu_register_float(fr_reg());
      fs = get_fpu_register_float(fs_reg());
      ft = get_fpu_register_float(ft_reg());
3617
      SetFPUFloatResult(fd_reg(), fs * ft + fr);
3618 3619 3620
      break;
    }
    case MSUB_S: {
3621
      DCHECK_EQ(kArchVariant, kMips64r2);
3622 3623 3624 3625
      float fr, ft, fs;
      fr = get_fpu_register_float(fr_reg());
      fs = get_fpu_register_float(fs_reg());
      ft = get_fpu_register_float(ft_reg());
3626
      SetFPUFloatResult(fd_reg(), fs * ft - fr);
3627 3628 3629
      break;
    }
    case MADD_D: {
3630
      DCHECK_EQ(kArchVariant, kMips64r2);
3631
      double fr, ft, fs;
3632 3633 3634
      fr = get_fpu_register_double(fr_reg());
      fs = get_fpu_register_double(fs_reg());
      ft = get_fpu_register_double(ft_reg());
3635
      SetFPUDoubleResult(fd_reg(), fs * ft + fr);
3636
      break;
3637 3638
    }
    case MSUB_D: {
3639
      DCHECK_EQ(kArchVariant, kMips64r2);
3640 3641 3642 3643
      double fr, ft, fs;
      fr = get_fpu_register_double(fr_reg());
      fs = get_fpu_register_double(fs_reg());
      ft = get_fpu_register_double(ft_reg());
3644
      SetFPUDoubleResult(fd_reg(), fs * ft - fr);
3645 3646
      break;
    }
3647 3648 3649 3650 3651 3652
    default:
      UNREACHABLE();
  }
}


3653 3654 3655 3656 3657 3658
void Simulator::DecodeTypeRegisterSPECIAL() {
  int64_t i64hilo;
  uint64_t u64hilo;
  int64_t alu_out;
  bool do_interrupt = false;

3659
  switch (instr_.FunctionFieldRaw()) {
3660
    case SELEQZ_S:
3661
      DCHECK_EQ(kArchVariant, kMips64r6);
3662
      SetResult(rd_reg(), rt() == 0 ? rs() : 0);
3663 3664
      break;
    case SELNEZ_S:
3665
      DCHECK_EQ(kArchVariant, kMips64r6);
3666
      SetResult(rd_reg(), rt() != 0 ? rs() : 0);
3667 3668
      break;
    case JR: {
3669 3670
      int64_t next_pc = rs();
      int64_t current_pc = get_pc();
3671
      Instruction* branch_delay_instr =
3672
          reinterpret_cast<Instruction*>(current_pc + kInstrSize);
3673 3674 3675 3676 3677 3678
      BranchDelayInstructionDecode(branch_delay_instr);
      set_pc(next_pc);
      pc_modified_ = true;
      break;
    }
    case JALR: {
3679 3680 3681
      int64_t next_pc = rs();
      int64_t current_pc = get_pc();
      int32_t return_addr_reg = rd_reg();
3682
      Instruction* branch_delay_instr =
3683
          reinterpret_cast<Instruction*>(current_pc + kInstrSize);
3684
      BranchDelayInstructionDecode(branch_delay_instr);
3685
      set_register(return_addr_reg, current_pc + 2 * kInstrSize);
3686 3687 3688 3689
      set_pc(next_pc);
      pc_modified_ = true;
      break;
    }
3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704
    case SLL:
      SetResult(rd_reg(), static_cast<int32_t>(rt()) << sa());
      break;
    case DSLL:
      SetResult(rd_reg(), rt() << sa());
      break;
    case DSLL32:
      SetResult(rd_reg(), rt() << sa() << 32);
      break;
    case SRL:
      if (rs_reg() == 0) {
        // Regular logical right shift of a word by a fixed number of
        // bits instruction. RS field is always equal to 0.
        // Sign-extend the 32-bit result.
        alu_out = static_cast<int32_t>(static_cast<uint32_t>(rt_u()) >> sa());
3705
      } else if (rs_reg() == 1) {
3706 3707 3708 3709 3710 3711
        // Logical right-rotate of a word by a fixed number of bits. This
        // is special case of SRL instruction, added in MIPS32 Release 2.
        // RS field is equal to 00001.
        alu_out = static_cast<int32_t>(
            base::bits::RotateRight32(static_cast<const uint32_t>(rt_u()),
                                      static_cast<const uint32_t>(sa())));
3712 3713
      } else {
        UNREACHABLE();
3714 3715 3716 3717
      }
      SetResult(rd_reg(), alu_out);
      break;
    case DSRL:
3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731
      if (rs_reg() == 0) {
        // Regular logical right shift of a word by a fixed number of
        // bits instruction. RS field is always equal to 0.
        // Sign-extend the 64-bit result.
        alu_out = static_cast<int64_t>(rt_u() >> sa());
      } else if (rs_reg() == 1) {
        // Logical right-rotate of a word by a fixed number of bits. This
        // is special case of SRL instruction, added in MIPS32 Release 2.
        // RS field is equal to 00001.
        alu_out = static_cast<int64_t>(base::bits::RotateRight64(rt_u(), sa()));
      } else {
        UNREACHABLE();
      }
      SetResult(rd_reg(), alu_out);
3732 3733
      break;
    case DSRL32:
3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748
      if (rs_reg() == 0) {
        // Regular logical right shift of a word by a fixed number of
        // bits instruction. RS field is always equal to 0.
        // Sign-extend the 64-bit result.
        alu_out = static_cast<int64_t>(rt_u() >> sa() >> 32);
      } else if (rs_reg() == 1) {
        // Logical right-rotate of a word by a fixed number of bits. This
        // is special case of SRL instruction, added in MIPS32 Release 2.
        // RS field is equal to 00001.
        alu_out =
            static_cast<int64_t>(base::bits::RotateRight64(rt_u(), sa() + 32));
      } else {
        UNREACHABLE();
      }
      SetResult(rd_reg(), alu_out);
3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783
      break;
    case SRA:
      SetResult(rd_reg(), (int32_t)rt() >> sa());
      break;
    case DSRA:
      SetResult(rd_reg(), rt() >> sa());
      break;
    case DSRA32:
      SetResult(rd_reg(), rt() >> sa() >> 32);
      break;
    case SLLV:
      SetResult(rd_reg(), (int32_t)rt() << rs());
      break;
    case DSLLV:
      SetResult(rd_reg(), rt() << rs());
      break;
    case SRLV:
      if (sa() == 0) {
        // Regular logical right-shift of a word by a variable number of
        // bits instruction. SA field is always equal to 0.
        alu_out = static_cast<int32_t>((uint32_t)rt_u() >> rs());
      } else {
        // Logical right-rotate of a word by a variable number of bits.
        // This is special case od SRLV instruction, added in MIPS32
        // Release 2. SA field is equal to 00001.
        alu_out = static_cast<int32_t>(
            base::bits::RotateRight32(static_cast<const uint32_t>(rt_u()),
                                      static_cast<const uint32_t>(rs_u())));
      }
      SetResult(rd_reg(), alu_out);
      break;
    case DSRLV:
      if (sa() == 0) {
        // Regular logical right-shift of a word by a variable number of
        // bits instruction. SA field is always equal to 0.
3784
        alu_out = static_cast<int64_t>(rt_u() >> rs());
3785 3786 3787 3788
      } else {
        // Logical right-rotate of a word by a variable number of bits.
        // This is special case od SRLV instruction, added in MIPS32
        // Release 2. SA field is equal to 00001.
3789 3790
        alu_out =
            static_cast<int64_t>(base::bits::RotateRight64(rt_u(), rs_u()));
3791 3792 3793 3794 3795 3796 3797 3798 3799
      }
      SetResult(rd_reg(), alu_out);
      break;
    case SRAV:
      SetResult(rd_reg(), (int32_t)rt() >> rs());
      break;
    case DSRAV:
      SetResult(rd_reg(), rt() >> rs());
      break;
3800
    case LSA: {
3801
      DCHECK_EQ(kArchVariant, kMips64r6);
3802 3803 3804 3805 3806 3807 3808 3809 3810
      int8_t sa = lsa_sa() + 1;
      int32_t _rt = static_cast<int32_t>(rt());
      int32_t _rs = static_cast<int32_t>(rs());
      int32_t res = _rs << sa;
      res += _rt;
      SetResult(rd_reg(), static_cast<int64_t>(res));
      break;
    }
    case DLSA:
3811
      DCHECK_EQ(kArchVariant, kMips64r6);
3812 3813
      SetResult(rd_reg(), (rs() << (lsa_sa() + 1)) + rt());
      break;
3814 3815
    case MFHI:  // MFHI == CLZ on R6.
      if (kArchVariant != kMips64r6) {
3816
        DCHECK_EQ(sa(), 0);
3817 3818 3819 3820
        alu_out = get_register(HI);
      } else {
        // MIPS spec: If no bits were set in GPR rs(), the result written to
        // GPR rd() is 32.
3821
        DCHECK_EQ(sa(), 1);
3822 3823 3824 3825
        alu_out = base::bits::CountLeadingZeros32(static_cast<int32_t>(rs_u()));
      }
      SetResult(rd_reg(), alu_out);
      break;
3826 3827
    case MFLO:  // MFLO == DCLZ on R6.
      if (kArchVariant != kMips64r6) {
3828
        DCHECK_EQ(sa(), 0);
3829 3830 3831 3832
        alu_out = get_register(LO);
      } else {
        // MIPS spec: If no bits were set in GPR rs(), the result written to
        // GPR rd() is 64.
3833
        DCHECK_EQ(sa(), 1);
3834 3835 3836
        alu_out = base::bits::CountLeadingZeros64(static_cast<int64_t>(rs_u()));
      }
      SetResult(rd_reg(), alu_out);
3837
      break;
3838
    // Instructions using HI and LO registers.
3839 3840 3841 3842
    case MULT: {  // MULT == D_MUL_MUH.
      int32_t rs_lo = static_cast<int32_t>(rs());
      int32_t rt_lo = static_cast<int32_t>(rt());
      i64hilo = static_cast<int64_t>(rs_lo) * static_cast<int64_t>(rt_lo);
3843
      if (kArchVariant != kMips64r6) {
3844
        set_register(LO, static_cast<int32_t>(i64hilo & 0xFFFFFFFF));
3845 3846
        set_register(HI, static_cast<int32_t>(i64hilo >> 32));
      } else {
3847
        switch (sa()) {
3848
          case MUL_OP:
3849
            SetResult(rd_reg(), static_cast<int32_t>(i64hilo & 0xFFFFFFFF));
3850 3851
            break;
          case MUH_OP:
3852
            SetResult(rd_reg(), static_cast<int32_t>(i64hilo >> 32));
3853 3854 3855 3856 3857 3858 3859
            break;
          default:
            UNIMPLEMENTED_MIPS();
            break;
        }
      }
      break;
3860
    }
3861
    case MULTU:
3862 3863
      u64hilo = static_cast<uint64_t>(rs_u() & 0xFFFFFFFF) *
                static_cast<uint64_t>(rt_u() & 0xFFFFFFFF);
3864
      if (kArchVariant != kMips64r6) {
3865
        set_register(LO, static_cast<int32_t>(u64hilo & 0xFFFFFFFF));
3866 3867 3868 3869
        set_register(HI, static_cast<int32_t>(u64hilo >> 32));
      } else {
        switch (sa()) {
          case MUL_OP:
3870
            SetResult(rd_reg(), static_cast<int32_t>(u64hilo & 0xFFFFFFFF));
3871 3872
            break;
          case MUH_OP:
3873
            SetResult(rd_reg(), static_cast<int32_t>(u64hilo >> 32));
3874 3875 3876 3877 3878 3879
            break;
          default:
            UNIMPLEMENTED_MIPS();
            break;
        }
      }
3880 3881 3882
      break;
    case DMULT:  // DMULT == D_MUL_MUH.
      if (kArchVariant != kMips64r6) {
3883 3884
        set_register(LO, rs() * rt());
        set_register(HI, MultiplyHighSigned(rs(), rt()));
3885
      } else {
3886
        switch (sa()) {
3887
          case MUL_OP:
3888
            SetResult(rd_reg(), rs() * rt());
3889 3890
            break;
          case MUH_OP:
3891
            SetResult(rd_reg(), MultiplyHighSigned(rs(), rt()));
3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902
            break;
          default:
            UNIMPLEMENTED_MIPS();
            break;
        }
      }
      break;
    case DMULTU:
      UNIMPLEMENTED_MIPS();
      break;
    case DIV:
3903 3904
    case DDIV: {
      const int64_t int_min_value =
3905
          instr_.FunctionFieldRaw() == DIV ? INT_MIN : LONG_MIN;
3906 3907 3908 3909 3910 3911
      switch (kArchVariant) {
        case kMips64r2:
          // Divide by zero and overflow was not checked in the
          // configuration step - div and divu do not raise exceptions. On
          // division by 0 the result will be UNPREDICTABLE. On overflow
          // (INT_MIN/-1), return INT_MIN which is what the hardware does.
3912
          if (rs() == int_min_value && rt() == -1) {
3913
            set_register(LO, int_min_value);
3914
            set_register(HI, 0);
3915 3916 3917
          } else if (rt() != 0) {
            set_register(LO, rs() / rt());
            set_register(HI, rs() % rt());
3918 3919 3920
          }
          break;
        case kMips64r6:
3921
          switch (sa()) {
3922
            case DIV_OP:
3923
              if (rs() == int_min_value && rt() == -1) {
3924
                SetResult(rd_reg(), int_min_value);
3925
              } else if (rt() != 0) {
3926
                SetResult(rd_reg(), rs() / rt());
3927 3928 3929
              }
              break;
            case MOD_OP:
3930
              if (rs() == int_min_value && rt() == -1) {
3931
                SetResult(rd_reg(), 0);
3932
              } else if (rt() != 0) {
3933
                SetResult(rd_reg(), rs() % rt());
3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944
              }
              break;
            default:
              UNIMPLEMENTED_MIPS();
              break;
          }
          break;
        default:
          break;
      }
      break;
3945
    }
3946
    case DIVU:
3947 3948 3949 3950
      switch (kArchVariant) {
        case kMips64r6: {
          uint32_t rt_u_32 = static_cast<uint32_t>(rt_u());
          uint32_t rs_u_32 = static_cast<uint32_t>(rs_u());
3951
          switch (sa()) {
3952 3953
            case DIV_OP:
              if (rt_u_32 != 0) {
3954
                SetResult(rd_reg(), rs_u_32 / rt_u_32);
3955 3956 3957 3958
              }
              break;
            case MOD_OP:
              if (rt_u() != 0) {
3959
                SetResult(rd_reg(), rs_u_32 % rt_u_32);
3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974
              }
              break;
            default:
              UNIMPLEMENTED_MIPS();
              break;
          }
        } break;
        default: {
          if (rt_u() != 0) {
            uint32_t rt_u_32 = static_cast<uint32_t>(rt_u());
            uint32_t rs_u_32 = static_cast<uint32_t>(rs_u());
            set_register(LO, rs_u_32 / rt_u_32);
            set_register(HI, rs_u_32 % rt_u_32);
          }
        }
3975 3976
      }
      break;
3977
    case DDIVU:
3978 3979
      switch (kArchVariant) {
        case kMips64r6: {
3980
          switch (instr_.SaValue()) {
3981 3982
            case DIV_OP:
              if (rt_u() != 0) {
3983
                SetResult(rd_reg(), rs_u() / rt_u());
3984 3985 3986 3987
              }
              break;
            case MOD_OP:
              if (rt_u() != 0) {
3988
                SetResult(rd_reg(), rs_u() % rt_u());
3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001
              }
              break;
            default:
              UNIMPLEMENTED_MIPS();
              break;
          }
        } break;
        default: {
          if (rt_u() != 0) {
            set_register(LO, rs_u() / rt_u());
            set_register(HI, rs_u() % rt_u());
          }
        }
4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069
      }
      break;
    case ADD:
    case DADD:
      if (HaveSameSign(rs(), rt())) {
        if (rs() > 0) {
          if (rs() > (Registers::kMaxValue - rt())) {
            SignalException(kIntegerOverflow);
          }
        } else if (rs() < 0) {
          if (rs() < (Registers::kMinValue - rt())) {
            SignalException(kIntegerUnderflow);
          }
        }
      }
      SetResult(rd_reg(), rs() + rt());
      break;
    case ADDU: {
      int32_t alu32_out = static_cast<int32_t>(rs() + rt());
      // Sign-extend result of 32bit operation into 64bit register.
      SetResult(rd_reg(), static_cast<int64_t>(alu32_out));
      break;
    }
    case DADDU:
      SetResult(rd_reg(), rs() + rt());
      break;
    case SUB:
    case DSUB:
      if (!HaveSameSign(rs(), rt())) {
        if (rs() > 0) {
          if (rs() > (Registers::kMaxValue + rt())) {
            SignalException(kIntegerOverflow);
          }
        } else if (rs() < 0) {
          if (rs() < (Registers::kMinValue + rt())) {
            SignalException(kIntegerUnderflow);
          }
        }
      }
      SetResult(rd_reg(), rs() - rt());
      break;
    case SUBU: {
      int32_t alu32_out = static_cast<int32_t>(rs() - rt());
      // Sign-extend result of 32bit operation into 64bit register.
      SetResult(rd_reg(), static_cast<int64_t>(alu32_out));
      break;
    }
    case DSUBU:
      SetResult(rd_reg(), rs() - rt());
      break;
    case AND:
      SetResult(rd_reg(), rs() & rt());
      break;
    case OR:
      SetResult(rd_reg(), rs() | rt());
      break;
    case XOR:
      SetResult(rd_reg(), rs() ^ rt());
      break;
    case NOR:
      SetResult(rd_reg(), ~(rs() | rt()));
      break;
    case SLT:
      SetResult(rd_reg(), rs() < rt() ? 1 : 0);
      break;
    case SLTU:
      SetResult(rd_reg(), rs_u() < rt_u() ? 1 : 0);
      break;
4070 4071
    // Break and trap instructions.
    case BREAK:
4072 4073
      do_interrupt = true;
      break;
4074
    case TGE:
4075 4076
      do_interrupt = rs() >= rt();
      break;
4077
    case TGEU:
4078 4079
      do_interrupt = rs_u() >= rt_u();
      break;
4080
    case TLT:
4081 4082
      do_interrupt = rs() < rt();
      break;
4083
    case TLTU:
4084 4085
      do_interrupt = rs_u() < rt_u();
      break;
4086
    case TEQ:
4087 4088
      do_interrupt = rs() == rt();
      break;
4089
    case TNE:
4090
      do_interrupt = rs() != rt();
4091
      break;
4092 4093 4094
    case SYNC:
      // TODO(palfia): Ignore sync instruction for now.
      break;
4095 4096
    // Conditional moves.
    case MOVN:
4097 4098
      if (rt()) {
        SetResult(rd_reg(), rs());
4099 4100 4101
      }
      break;
    case MOVCI: {
4102
      uint32_t cc = instr_.FBccValue();
4103
      uint32_t fcsr_cc = get_fcsr_condition_bit(cc);
4104
      if (instr_.Bit(16)) {  // Read Tf bit.
4105
        if (test_fcsr_bit(fcsr_cc)) SetResult(rd_reg(), rs());
4106
      } else {
4107
        if (!test_fcsr_bit(fcsr_cc)) SetResult(rd_reg(), rs());
4108 4109 4110 4111
      }
      break;
    }
    case MOVZ:
4112 4113
      if (!rt()) {
        SetResult(rd_reg(), rs());
4114 4115
      }
      break;
4116 4117 4118 4119
    default:
      UNREACHABLE();
  }
  if (do_interrupt) {
4120
    SoftwareInterrupt();
4121 4122 4123 4124
  }
}


4125 4126
void Simulator::DecodeTypeRegisterSPECIAL2() {
  int64_t alu_out;
4127
  switch (instr_.FunctionFieldRaw()) {
4128
    case MUL:
4129 4130
      alu_out = static_cast<int32_t>(rs_u()) * static_cast<int32_t>(rt_u());
      SetResult(rd_reg(), alu_out);
4131 4132 4133 4134
      // HI and LO are UNPREDICTABLE after the operation.
      set_register(LO, Unpredictable);
      set_register(HI, Unpredictable);
      break;
4135 4136 4137 4138
    case CLZ:
      // MIPS32 spec: If no bits were set in GPR rs(), the result written to
      // GPR rd is 32.
      alu_out = base::bits::CountLeadingZeros32(static_cast<uint32_t>(rs_u()));
4139 4140 4141 4142 4143 4144 4145
      SetResult(rd_reg(), alu_out);
      break;
    case DCLZ:
      // MIPS64 spec: If no bits were set in GPR rs(), the result written to
      // GPR rd is 64.
      alu_out = base::bits::CountLeadingZeros64(static_cast<uint64_t>(rs_u()));
      SetResult(rd_reg(), alu_out);
4146 4147 4148 4149
      break;
    default:
      alu_out = 0x12345678;
      UNREACHABLE();
4150 4151 4152 4153
  }
}


4154 4155
void Simulator::DecodeTypeRegisterSPECIAL3() {
  int64_t alu_out;
4156
  switch (instr_.FunctionFieldRaw()) {
4157 4158 4159
    case EXT: {  // Mips32r2 instruction.
      // Interpret rd field as 5-bit msbd of extract.
      uint16_t msbd = rd_reg();
4160 4161
      // Interpret sa field as 5-bit lsb of extract.
      uint16_t lsb = sa();
4162
      uint16_t size = msbd + 1;
4163 4164 4165 4166 4167
      uint64_t mask = (1ULL << size) - 1;
      alu_out = static_cast<int32_t>((rs_u() & (mask << lsb)) >> lsb);
      SetResult(rt_reg(), alu_out);
      break;
    }
4168
    case DEXT: {  // Mips64r2 instruction.
4169 4170
      // Interpret rd field as 5-bit msbd of extract.
      uint16_t msbd = rd_reg();
4171 4172
      // Interpret sa field as 5-bit lsb of extract.
      uint16_t lsb = sa();
4173
      uint16_t size = msbd + 1;
4174
      uint64_t mask = (size == 64) ? UINT64_MAX : (1ULL << size) - 1;
4175 4176 4177 4178
      alu_out = static_cast<int64_t>((rs_u() & (mask << lsb)) >> lsb);
      SetResult(rt_reg(), alu_out);
      break;
    }
4179
    case DEXTM: {
4180 4181
      // Interpret rd field as 5-bit msbdminus32 of extract.
      uint16_t msbdminus32 = rd_reg();
4182 4183
      // Interpret sa field as 5-bit lsb of extract.
      uint16_t lsb = sa();
4184
      uint16_t size = msbdminus32 + 1 + 32;
4185
      uint64_t mask = (size == 64) ? UINT64_MAX : (1ULL << size) - 1;
4186 4187 4188 4189 4190
      alu_out = static_cast<int64_t>((rs_u() & (mask << lsb)) >> lsb);
      SetResult(rt_reg(), alu_out);
      break;
    }
    case DEXTU: {
4191 4192 4193 4194
      // Interpret rd field as 5-bit msbd of extract.
      uint16_t msbd = rd_reg();
      // Interpret sa field as 5-bit lsbminus32 of extract and add 32 to get
      // lsb.
4195
      uint16_t lsb = sa() + 32;
4196
      uint16_t size = msbd + 1;
4197
      uint64_t mask = (size == 64) ? UINT64_MAX : (1ULL << size) - 1;
4198 4199 4200 4201
      alu_out = static_cast<int64_t>((rs_u() & (mask << lsb)) >> lsb);
      SetResult(rt_reg(), alu_out);
      break;
    }
4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251
    case INS: {  // Mips32r2 instruction.
      // Interpret rd field as 5-bit msb of insert.
      uint16_t msb = rd_reg();
      // Interpret sa field as 5-bit lsb of insert.
      uint16_t lsb = sa();
      uint16_t size = msb - lsb + 1;
      uint64_t mask = (1ULL << size) - 1;
      alu_out = static_cast<int32_t>((rt_u() & ~(mask << lsb)) |
                                     ((rs_u() & mask) << lsb));
      SetResult(rt_reg(), alu_out);
      break;
    }
    case DINS: {  // Mips64r2 instruction.
      // Interpret rd field as 5-bit msb of insert.
      uint16_t msb = rd_reg();
      // Interpret sa field as 5-bit lsb of insert.
      uint16_t lsb = sa();
      uint16_t size = msb - lsb + 1;
      uint64_t mask = (1ULL << size) - 1;
      alu_out = (rt_u() & ~(mask << lsb)) | ((rs_u() & mask) << lsb);
      SetResult(rt_reg(), alu_out);
      break;
    }
    case DINSM: {  // Mips64r2 instruction.
      // Interpret rd field as 5-bit msbminus32 of insert.
      uint16_t msbminus32 = rd_reg();
      // Interpret sa field as 5-bit lsb of insert.
      uint16_t lsb = sa();
      uint16_t size = msbminus32 + 32 - lsb + 1;
      uint64_t mask;
      if (size < 64)
        mask = (1ULL << size) - 1;
      else
        mask = std::numeric_limits<uint64_t>::max();
      alu_out = (rt_u() & ~(mask << lsb)) | ((rs_u() & mask) << lsb);
      SetResult(rt_reg(), alu_out);
      break;
    }
    case DINSU: {  // Mips64r2 instruction.
      // Interpret rd field as 5-bit msbminus32 of insert.
      uint16_t msbminus32 = rd_reg();
      // Interpret rd field as 5-bit lsbminus32 of insert.
      uint16_t lsbminus32 = sa();
      uint16_t lsb = lsbminus32 + 32;
      uint16_t size = msbminus32 + 32 - lsb + 1;
      uint64_t mask = (1ULL << size) - 1;
      alu_out = (rt_u() & ~(mask << lsb)) | ((rs_u() & mask) << lsb);
      SetResult(rt_reg(), alu_out);
      break;
    }
4252
    case BSHFL: {
4253
      int32_t sa = instr_.SaFieldRaw() >> kSaShift;
4254 4255 4256 4257 4258 4259 4260 4261 4262
      switch (sa) {
        case BITSWAP: {
          uint32_t input = static_cast<uint32_t>(rt());
          uint32_t output = 0;
          uint8_t i_byte, o_byte;

          // Reverse the bit in byte for each individual byte
          for (int i = 0; i < 4; i++) {
            output = output >> 8;
4263
            i_byte = input & 0xFF;
4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278

            // Fast way to reverse bits in byte
            // Devised by Sean Anderson, July 13, 2001
            o_byte = static_cast<uint8_t>(((i_byte * 0x0802LU & 0x22110LU) |
                                           (i_byte * 0x8020LU & 0x88440LU)) *
                                              0x10101LU >>
                                          16);

            output = output | (static_cast<uint32_t>(o_byte << 24));
            input = input >> 8;
          }

          alu_out = static_cast<int64_t>(static_cast<int32_t>(output));
          break;
        }
4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289
        case SEB: {
          uint8_t input = static_cast<uint8_t>(rt());
          uint32_t output = input;
          uint32_t mask = 0x00000080;

          // Extending sign
          if (mask & input) {
            output |= 0xFFFFFF00;
          }

          alu_out = static_cast<int32_t>(output);
4290
          break;
4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329
        }
        case SEH: {
          uint16_t input = static_cast<uint16_t>(rt());
          uint32_t output = input;
          uint32_t mask = 0x00008000;

          // Extending sign
          if (mask & input) {
            output |= 0xFFFF0000;
          }

          alu_out = static_cast<int32_t>(output);
          break;
        }
        case WSBH: {
          uint32_t input = static_cast<uint32_t>(rt());
          uint64_t output = 0;

          uint32_t mask = 0xFF000000;
          for (int i = 0; i < 4; i++) {
            uint32_t tmp = mask & input;
            if (i % 2 == 0) {
              tmp = tmp >> 8;
            } else {
              tmp = tmp << 8;
            }
            output = output | tmp;
            mask = mask >> 8;
          }
          mask = 0x80000000;

          // Extending sign
          if (mask & output) {
            output |= 0xFFFFFFFF00000000;
          }

          alu_out = static_cast<int64_t>(output);
          break;
        }
4330
        default: {
4331
          const uint8_t bp2 = instr_.Bp2Value();
4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352
          sa >>= kBp2Bits;
          switch (sa) {
            case ALIGN: {
              if (bp2 == 0) {
                alu_out = static_cast<int32_t>(rt());
              } else {
                uint64_t rt_hi = rt() << (8 * bp2);
                uint64_t rs_lo = rs() >> (8 * (4 - bp2));
                alu_out = static_cast<int32_t>(rt_hi | rs_lo);
              }
              break;
            }
            default:
              alu_out = 0x12345678;
              UNREACHABLE();
              break;
          }
          break;
        }
      }
      SetResult(rd_reg(), alu_out);
4353
      break;
4354 4355
    }
    case DBSHFL: {
4356
      int32_t sa = instr_.SaFieldRaw() >> kSaShift;
4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367
      switch (sa) {
        case DBITSWAP: {
          switch (sa) {
            case DBITSWAP_SA: {  // Mips64r6
              uint64_t input = static_cast<uint64_t>(rt());
              uint64_t output = 0;
              uint8_t i_byte, o_byte;

              // Reverse the bit in byte for each individual byte
              for (int i = 0; i < 8; i++) {
                output = output >> 8;
4368
                i_byte = input & 0xFF;
4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387

                // Fast way to reverse bits in byte
                // Devised by Sean Anderson, July 13, 2001
                o_byte =
                    static_cast<uint8_t>(((i_byte * 0x0802LU & 0x22110LU) |
                                          (i_byte * 0x8020LU & 0x88440LU)) *
                                             0x10101LU >>
                                         16);

                output = output | ((static_cast<uint64_t>(o_byte) << 56));
                input = input >> 8;
              }

              alu_out = static_cast<int64_t>(output);
              break;
            }
          }
          break;
        }
4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404
        case DSBH: {
          uint64_t input = static_cast<uint64_t>(rt());
          uint64_t output = 0;

          uint64_t mask = 0xFF00000000000000;
          for (int i = 0; i < 8; i++) {
            uint64_t tmp = mask & input;
            if (i % 2 == 0)
              tmp = tmp >> 8;
            else
              tmp = tmp << 8;

            output = output | tmp;
            mask = mask >> 8;
          }

          alu_out = static_cast<int64_t>(output);
4405
          break;
4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428
        }
        case DSHD: {
          uint64_t input = static_cast<uint64_t>(rt());
          uint64_t output = 0;

          uint64_t mask = 0xFFFF000000000000;
          for (int i = 0; i < 4; i++) {
            uint64_t tmp = mask & input;
            if (i == 0)
              tmp = tmp >> 48;
            else if (i == 1)
              tmp = tmp >> 16;
            else if (i == 2)
              tmp = tmp << 16;
            else
              tmp = tmp << 48;
            output = output | tmp;
            mask = mask >> 16;
          }

          alu_out = static_cast<int64_t>(output);
          break;
        }
4429
        default: {
4430
          const uint8_t bp3 = instr_.Bp3Value();
4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451
          sa >>= kBp3Bits;
          switch (sa) {
            case DALIGN: {
              if (bp3 == 0) {
                alu_out = static_cast<int64_t>(rt());
              } else {
                uint64_t rt_hi = rt() << (8 * bp3);
                uint64_t rs_lo = rs() >> (8 * (8 - bp3));
                alu_out = static_cast<int64_t>(rt_hi | rs_lo);
              }
              break;
            }
            default:
              alu_out = 0x12345678;
              UNREACHABLE();
              break;
          }
          break;
        }
      }
      SetResult(rd_reg(), alu_out);
4452
      break;
4453
    }
4454 4455 4456 4457 4458
    default:
      UNREACHABLE();
  }
}

4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536
int Simulator::DecodeMsaDataFormat() {
  int df = -1;
  if (instr_.IsMSABranchInstr()) {
    switch (instr_.RsFieldRaw()) {
      case BZ_V:
      case BNZ_V:
        df = MSA_VECT;
        break;
      case BZ_B:
      case BNZ_B:
        df = MSA_BYTE;
        break;
      case BZ_H:
      case BNZ_H:
        df = MSA_HALF;
        break;
      case BZ_W:
      case BNZ_W:
        df = MSA_WORD;
        break;
      case BZ_D:
      case BNZ_D:
        df = MSA_DWORD;
        break;
      default:
        UNREACHABLE();
        break;
    }
  } else {
    int DF[] = {MSA_BYTE, MSA_HALF, MSA_WORD, MSA_DWORD};
    switch (instr_.MSAMinorOpcodeField()) {
      case kMsaMinorI5:
      case kMsaMinorI10:
      case kMsaMinor3R:
        df = DF[instr_.Bits(22, 21)];
        break;
      case kMsaMinorMI10:
        df = DF[instr_.Bits(1, 0)];
        break;
      case kMsaMinorBIT:
        df = DF[instr_.MsaBitDf()];
        break;
      case kMsaMinorELM:
        df = DF[instr_.MsaElmDf()];
        break;
      case kMsaMinor3RF: {
        uint32_t opcode = instr_.InstructionBits() & kMsa3RFMask;
        switch (opcode) {
          case FEXDO:
          case FTQ:
          case MUL_Q:
          case MADD_Q:
          case MSUB_Q:
          case MULR_Q:
          case MADDR_Q:
          case MSUBR_Q:
            df = DF[1 + instr_.Bit(21)];
            break;
          default:
            df = DF[2 + instr_.Bit(21)];
            break;
        }
      } break;
      case kMsaMinor2R:
        df = DF[instr_.Bits(17, 16)];
        break;
      case kMsaMinor2RF:
        df = DF[2 + instr_.Bit(16)];
        break;
      default:
        UNREACHABLE();
        break;
    }
  }
  return df;
}

void Simulator::DecodeTypeMsaI8() {
4537
  DCHECK_EQ(kArchVariant, kMips64r6);
4538 4539
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaI8Mask;
4540 4541
  int8_t i8 = instr_.MsaImm8Value();
  msa_reg_t ws, wd;
4542 4543 4544

  switch (opcode) {
    case ANDI_B:
4545 4546 4547 4548 4549 4550 4551
      get_msa_register(instr_.WsValue(), ws.b);
      for (int i = 0; i < kMSALanesByte; i++) {
        wd.b[i] = ws.b[i] & i8;
      }
      set_msa_register(instr_.WdValue(), wd.b);
      TraceMSARegWr(wd.b);
      break;
4552
    case ORI_B:
4553 4554 4555 4556 4557 4558 4559
      get_msa_register(instr_.WsValue(), ws.b);
      for (int i = 0; i < kMSALanesByte; i++) {
        wd.b[i] = ws.b[i] | i8;
      }
      set_msa_register(instr_.WdValue(), wd.b);
      TraceMSARegWr(wd.b);
      break;
4560
    case NORI_B:
4561 4562 4563 4564 4565 4566 4567
      get_msa_register(instr_.WsValue(), ws.b);
      for (int i = 0; i < kMSALanesByte; i++) {
        wd.b[i] = ~(ws.b[i] | i8);
      }
      set_msa_register(instr_.WdValue(), wd.b);
      TraceMSARegWr(wd.b);
      break;
4568
    case XORI_B:
4569 4570 4571 4572 4573 4574 4575
      get_msa_register(instr_.WsValue(), ws.b);
      for (int i = 0; i < kMSALanesByte; i++) {
        wd.b[i] = ws.b[i] ^ i8;
      }
      set_msa_register(instr_.WdValue(), wd.b);
      TraceMSARegWr(wd.b);
      break;
4576
    case BMNZI_B:
4577 4578 4579 4580 4581 4582 4583 4584
      get_msa_register(instr_.WsValue(), ws.b);
      get_msa_register(instr_.WdValue(), wd.b);
      for (int i = 0; i < kMSALanesByte; i++) {
        wd.b[i] = (ws.b[i] & i8) | (wd.b[i] & ~i8);
      }
      set_msa_register(instr_.WdValue(), wd.b);
      TraceMSARegWr(wd.b);
      break;
4585
    case BMZI_B:
4586 4587 4588 4589 4590 4591 4592 4593
      get_msa_register(instr_.WsValue(), ws.b);
      get_msa_register(instr_.WdValue(), wd.b);
      for (int i = 0; i < kMSALanesByte; i++) {
        wd.b[i] = (ws.b[i] & ~i8) | (wd.b[i] & i8);
      }
      set_msa_register(instr_.WdValue(), wd.b);
      TraceMSARegWr(wd.b);
      break;
4594
    case BSELI_B:
4595 4596 4597 4598 4599 4600 4601 4602
      get_msa_register(instr_.WsValue(), ws.b);
      get_msa_register(instr_.WdValue(), wd.b);
      for (int i = 0; i < kMSALanesByte; i++) {
        wd.b[i] = (ws.b[i] & ~wd.b[i]) | (wd.b[i] & i8);
      }
      set_msa_register(instr_.WdValue(), wd.b);
      TraceMSARegWr(wd.b);
      break;
4603
    case SHF_B:
4604 4605 4606 4607 4608 4609 4610 4611 4612
      get_msa_register(instr_.WsValue(), ws.b);
      for (int i = 0; i < kMSALanesByte; i++) {
        int j = i % 4;
        int k = (i8 >> (2 * j)) & 0x3;
        wd.b[i] = ws.b[i - j + k];
      }
      set_msa_register(instr_.WdValue(), wd.b);
      TraceMSARegWr(wd.b);
      break;
4613
    case SHF_H:
4614 4615 4616 4617 4618 4619 4620 4621 4622
      get_msa_register(instr_.WsValue(), ws.h);
      for (int i = 0; i < kMSALanesHalf; i++) {
        int j = i % 4;
        int k = (i8 >> (2 * j)) & 0x3;
        wd.h[i] = ws.h[i - j + k];
      }
      set_msa_register(instr_.WdValue(), wd.h);
      TraceMSARegWr(wd.h);
      break;
4623
    case SHF_W:
4624 4625 4626 4627 4628 4629 4630
      get_msa_register(instr_.WsValue(), ws.w);
      for (int i = 0; i < kMSALanesWord; i++) {
        int j = (i8 >> (2 * i)) & 0x3;
        wd.w[i] = ws.w[j];
      }
      set_msa_register(instr_.WdValue(), wd.w);
      TraceMSARegWr(wd.w);
4631 4632 4633 4634 4635 4636
      break;
    default:
      UNREACHABLE();
  }
}

4637 4638 4639 4640 4641 4642
template <typename T>
T Simulator::MsaI5InstrHelper(uint32_t opcode, T ws, int32_t i5) {
  T res;
  uint32_t ui5 = i5 & 0x1Fu;
  uint64_t ws_u64 = static_cast<uint64_t>(ws);
  uint64_t ui5_u64 = static_cast<uint64_t>(ui5);
4643 4644 4645

  switch (opcode) {
    case ADDVI:
4646 4647
      res = static_cast<T>(ws + ui5);
      break;
4648
    case SUBVI:
4649 4650
      res = static_cast<T>(ws - ui5);
      break;
4651
    case MAXI_S:
4652 4653
      res = static_cast<T>(Max(ws, static_cast<T>(i5)));
      break;
4654
    case MINI_S:
4655 4656 4657 4658 4659
      res = static_cast<T>(Min(ws, static_cast<T>(i5)));
      break;
    case MAXI_U:
      res = static_cast<T>(Max(ws_u64, ui5_u64));
      break;
4660
    case MINI_U:
4661 4662
      res = static_cast<T>(Min(ws_u64, ui5_u64));
      break;
4663
    case CEQI:
4664 4665
      res = static_cast<T>(!Compare(ws, static_cast<T>(i5)) ? -1ull : 0ull);
      break;
4666
    case CLTI_S:
4667 4668 4669
      res = static_cast<T>((Compare(ws, static_cast<T>(i5)) == -1) ? -1ull
                                                                   : 0ull);
      break;
4670
    case CLTI_U:
4671 4672
      res = static_cast<T>((Compare(ws_u64, ui5_u64) == -1) ? -1ull : 0ull);
      break;
4673
    case CLEI_S:
4674 4675 4676
      res =
          static_cast<T>((Compare(ws, static_cast<T>(i5)) != 1) ? -1ull : 0ull);
      break;
4677
    case CLEI_U:
4678 4679 4680 4681 4682 4683 4684 4685 4686
      res = static_cast<T>((Compare(ws_u64, ui5_u64) != 1) ? -1ull : 0ull);
      break;
    default:
      UNREACHABLE();
  }
  return res;
}

void Simulator::DecodeTypeMsaI5() {
4687
  DCHECK_EQ(kArchVariant, kMips64r6);
4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaI5Mask;
  msa_reg_t ws, wd;

  // sign extend 5bit value to int32_t
  int32_t i5 = static_cast<int32_t>(instr_.MsaImm5Value() << 27) >> 27;

#define MSA_I5_DF(elem, num_of_lanes)                      \
  get_msa_register(instr_.WsValue(), ws.elem);             \
  for (int i = 0; i < num_of_lanes; i++) {                 \
    wd.elem[i] = MsaI5InstrHelper(opcode, ws.elem[i], i5); \
  }                                                        \
  set_msa_register(instr_.WdValue(), wd.elem);             \
  TraceMSARegWr(wd.elem)

  switch (DecodeMsaDataFormat()) {
    case MSA_BYTE:
      MSA_I5_DF(b, kMSALanesByte);
      break;
    case MSA_HALF:
      MSA_I5_DF(h, kMSALanesHalf);
      break;
    case MSA_WORD:
      MSA_I5_DF(w, kMSALanesWord);
      break;
    case MSA_DWORD:
      MSA_I5_DF(d, kMSALanesDword);
4715 4716 4717 4718
      break;
    default:
      UNREACHABLE();
  }
4719
#undef MSA_I5_DF
4720 4721 4722
}

void Simulator::DecodeTypeMsaI10() {
4723
  DCHECK_EQ(kArchVariant, kMips64r6);
4724 4725
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaI5Mask;
4726 4727 4728 4729 4730 4731 4732 4733 4734 4735
  int64_t s10 = (static_cast<int64_t>(instr_.MsaImm10Value()) << 54) >> 54;
  msa_reg_t wd;

#define MSA_I10_DF(elem, num_of_lanes, T)      \
  for (int i = 0; i < num_of_lanes; ++i) {     \
    wd.elem[i] = static_cast<T>(s10);          \
  }                                            \
  set_msa_register(instr_.WdValue(), wd.elem); \
  TraceMSARegWr(wd.elem)

4736
  if (opcode == LDI) {
4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752
    switch (DecodeMsaDataFormat()) {
      case MSA_BYTE:
        MSA_I10_DF(b, kMSALanesByte, int8_t);
        break;
      case MSA_HALF:
        MSA_I10_DF(h, kMSALanesHalf, int16_t);
        break;
      case MSA_WORD:
        MSA_I10_DF(w, kMSALanesWord, int32_t);
        break;
      case MSA_DWORD:
        MSA_I10_DF(d, kMSALanesDword, int64_t);
        break;
      default:
        UNREACHABLE();
    }
4753 4754 4755
  } else {
    UNREACHABLE();
  }
4756
#undef MSA_I10_DF
4757 4758 4759
}

void Simulator::DecodeTypeMsaELM() {
4760
  DCHECK_EQ(kArchVariant, kMips64r6);
4761
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
4762
  uint32_t opcode = instr_.InstructionBits() & kMsaLongerELMMask;
4763 4764 4765
  int32_t n = instr_.MsaElmNValue();
  int64_t alu_out;
  switch (opcode) {
4766
    case CTCMSA:
4767
      DCHECK_EQ(sa(), kMSACSRRegister);
4768 4769 4770 4771 4772
      MSACSR_ = bit_cast<uint32_t>(
          static_cast<int32_t>(registers_[rd_reg()] & kMaxUInt32));
      TraceRegWr(static_cast<int32_t>(MSACSR_));
      break;
    case CFCMSA:
4773
      DCHECK_EQ(rd_reg(), kMSACSRRegister);
4774 4775
      SetResult(sa(), static_cast<int64_t>(bit_cast<int32_t>(MSACSR_)));
      break;
4776 4777 4778 4779 4780 4781
    case MOVE_V: {
      msa_reg_t ws;
      get_msa_register(ws_reg(), &ws);
      set_msa_register(wd_reg(), &ws);
      TraceMSARegWr(&ws);
    } break;
4782 4783 4784 4785 4786 4787 4788 4789
    default:
      opcode &= kMsaELMMask;
      switch (opcode) {
        case COPY_S:
        case COPY_U: {
          msa_reg_t ws;
          switch (DecodeMsaDataFormat()) {
            case MSA_BYTE:
4790
              DCHECK_LT(n, kMSALanesByte);
4791 4792 4793 4794 4795 4796
              get_msa_register(instr_.WsValue(), ws.b);
              alu_out = static_cast<int32_t>(ws.b[n]);
              SetResult(wd_reg(),
                        (opcode == COPY_U) ? alu_out & 0xFFu : alu_out);
              break;
            case MSA_HALF:
4797
              DCHECK_LT(n, kMSALanesHalf);
4798 4799 4800 4801 4802 4803
              get_msa_register(instr_.WsValue(), ws.h);
              alu_out = static_cast<int32_t>(ws.h[n]);
              SetResult(wd_reg(),
                        (opcode == COPY_U) ? alu_out & 0xFFFFu : alu_out);
              break;
            case MSA_WORD:
4804
              DCHECK_LT(n, kMSALanesWord);
4805 4806 4807 4808 4809 4810
              get_msa_register(instr_.WsValue(), ws.w);
              alu_out = static_cast<int32_t>(ws.w[n]);
              SetResult(wd_reg(),
                        (opcode == COPY_U) ? alu_out & 0xFFFFFFFFu : alu_out);
              break;
            case MSA_DWORD:
4811
              DCHECK_LT(n, kMSALanesDword);
4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823
              get_msa_register(instr_.WsValue(), ws.d);
              alu_out = static_cast<int64_t>(ws.d[n]);
              SetResult(wd_reg(), alu_out);
              break;
            default:
              UNREACHABLE();
          }
        } break;
        case INSERT: {
          msa_reg_t wd;
          switch (DecodeMsaDataFormat()) {
            case MSA_BYTE: {
4824
              DCHECK_LT(n, kMSALanesByte);
4825 4826 4827 4828 4829 4830 4831 4832
              int64_t rs = get_register(instr_.WsValue());
              get_msa_register(instr_.WdValue(), wd.b);
              wd.b[n] = rs & 0xFFu;
              set_msa_register(instr_.WdValue(), wd.b);
              TraceMSARegWr(wd.b);
              break;
            }
            case MSA_HALF: {
4833
              DCHECK_LT(n, kMSALanesHalf);
4834 4835 4836 4837 4838 4839 4840 4841
              int64_t rs = get_register(instr_.WsValue());
              get_msa_register(instr_.WdValue(), wd.h);
              wd.h[n] = rs & 0xFFFFu;
              set_msa_register(instr_.WdValue(), wd.h);
              TraceMSARegWr(wd.h);
              break;
            }
            case MSA_WORD: {
4842
              DCHECK_LT(n, kMSALanesWord);
4843 4844 4845 4846 4847 4848 4849 4850
              int64_t rs = get_register(instr_.WsValue());
              get_msa_register(instr_.WdValue(), wd.w);
              wd.w[n] = rs & 0xFFFFFFFFu;
              set_msa_register(instr_.WdValue(), wd.w);
              TraceMSARegWr(wd.w);
              break;
            }
            case MSA_DWORD: {
4851
              DCHECK_LT(n, kMSALanesDword);
4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862
              int64_t rs = get_register(instr_.WsValue());
              get_msa_register(instr_.WdValue(), wd.d);
              wd.d[n] = rs;
              set_msa_register(instr_.WdValue(), wd.d);
              TraceMSARegWr(wd.d);
              break;
            }
            default:
              UNREACHABLE();
          }
        } break;
4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906
        case SLDI: {
          uint8_t v[32];
          msa_reg_t ws;
          msa_reg_t wd;
          get_msa_register(ws_reg(), &ws);
          get_msa_register(wd_reg(), &wd);
#define SLDI_DF(s, k)                \
  for (unsigned i = 0; i < s; i++) { \
    v[i] = ws.b[s * k + i];          \
    v[i + s] = wd.b[s * k + i];      \
  }                                  \
  for (unsigned i = 0; i < s; i++) { \
    wd.b[s * k + i] = v[i + n];      \
  }
          switch (DecodeMsaDataFormat()) {
            case MSA_BYTE:
              DCHECK(n < kMSALanesByte);
              SLDI_DF(kMSARegSize / sizeof(int8_t) / kBitsPerByte, 0)
              break;
            case MSA_HALF:
              DCHECK(n < kMSALanesHalf);
              for (int k = 0; k < 2; ++k) {
                SLDI_DF(kMSARegSize / sizeof(int16_t) / kBitsPerByte, k)
              }
              break;
            case MSA_WORD:
              DCHECK(n < kMSALanesWord);
              for (int k = 0; k < 4; ++k) {
                SLDI_DF(kMSARegSize / sizeof(int32_t) / kBitsPerByte, k)
              }
              break;
            case MSA_DWORD:
              DCHECK(n < kMSALanesDword);
              for (int k = 0; k < 8; ++k) {
                SLDI_DF(kMSARegSize / sizeof(int64_t) / kBitsPerByte, k)
              }
              break;
            default:
              UNREACHABLE();
          }
          set_msa_register(wd_reg(), &wd);
          TraceMSARegWr(&wd);
        } break;
#undef SLDI_DF
4907 4908 4909
        case SPLATI:
        case INSVE:
          UNIMPLEMENTED();
4910 4911 4912 4913 4914 4915 4916 4917
          break;
        default:
          UNREACHABLE();
      }
      break;
  }
}

4918 4919 4920 4921
template <typename T>
T Simulator::MsaBitInstrHelper(uint32_t opcode, T wd, T ws, int32_t m) {
  typedef typename std::make_unsigned<T>::type uT;
  T res;
4922 4923
  switch (opcode) {
    case SLLI:
4924 4925
      res = static_cast<T>(ws << m);
      break;
4926
    case SRAI:
4927 4928
      res = static_cast<T>(ArithmeticShiftRight(ws, m));
      break;
4929
    case SRLI:
4930 4931
      res = static_cast<T>(static_cast<uT>(ws) >> m);
      break;
4932
    case BCLRI:
4933 4934
      res = static_cast<T>(static_cast<T>(~(1ull << m)) & ws);
      break;
4935
    case BSETI:
4936 4937
      res = static_cast<T>(static_cast<T>(1ull << m) | ws);
      break;
4938
    case BNEGI:
4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982
      res = static_cast<T>(static_cast<T>(1ull << m) ^ ws);
      break;
    case BINSLI: {
      int elem_size = 8 * sizeof(T);
      int bits = m + 1;
      if (bits == elem_size) {
        res = static_cast<T>(ws);
      } else {
        uint64_t mask = ((1ull << bits) - 1) << (elem_size - bits);
        res = static_cast<T>((static_cast<T>(mask) & ws) |
                             (static_cast<T>(~mask) & wd));
      }
    } break;
    case BINSRI: {
      int elem_size = 8 * sizeof(T);
      int bits = m + 1;
      if (bits == elem_size) {
        res = static_cast<T>(ws);
      } else {
        uint64_t mask = (1ull << bits) - 1;
        res = static_cast<T>((static_cast<T>(mask) & ws) |
                             (static_cast<T>(~mask) & wd));
      }
    } break;
    case SAT_S: {
#define M_MAX_INT(x) static_cast<int64_t>((1LL << ((x)-1)) - 1)
#define M_MIN_INT(x) static_cast<int64_t>(-(1LL << ((x)-1)))
      int shift = 64 - 8 * sizeof(T);
      int64_t ws_i64 = (static_cast<int64_t>(ws) << shift) >> shift;
      res = static_cast<T>(ws_i64 < M_MIN_INT(m + 1)
                               ? M_MIN_INT(m + 1)
                               : ws_i64 > M_MAX_INT(m + 1) ? M_MAX_INT(m + 1)
                                                           : ws_i64);
#undef M_MAX_INT
#undef M_MIN_INT
    } break;
    case SAT_U: {
#define M_MAX_UINT(x) static_cast<uint64_t>(-1ULL >> (64 - (x)))
      uint64_t mask = static_cast<uint64_t>(-1ULL >> (64 - 8 * sizeof(T)));
      uint64_t ws_u64 = static_cast<uint64_t>(ws) & mask;
      res = static_cast<T>(ws_u64 < M_MAX_UINT(m + 1) ? ws_u64
                                                      : M_MAX_UINT(m + 1));
#undef M_MAX_UINT
    } break;
4983
    case SRARI:
4984 4985 4986 4987 4988 4989 4990
      if (!m) {
        res = static_cast<T>(ws);
      } else {
        res = static_cast<T>(ArithmeticShiftRight(ws, m)) +
              static_cast<T>((ws >> (m - 1)) & 0x1);
      }
      break;
4991
    case SRLRI:
4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005
      if (!m) {
        res = static_cast<T>(ws);
      } else {
        res = static_cast<T>(static_cast<uT>(ws) >> m) +
              static_cast<T>((ws >> (m - 1)) & 0x1);
      }
      break;
    default:
      UNREACHABLE();
  }
  return res;
}

void Simulator::DecodeTypeMsaBIT() {
5006
  DCHECK_EQ(kArchVariant, kMips64r6);
5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaBITMask;
  int32_t m = instr_.MsaBitMValue();
  msa_reg_t wd, ws;

#define MSA_BIT_DF(elem, num_of_lanes)                                 \
  get_msa_register(instr_.WsValue(), ws.elem);                         \
  if (opcode == BINSLI || opcode == BINSRI) {                          \
    get_msa_register(instr_.WdValue(), wd.elem);                       \
  }                                                                    \
  for (int i = 0; i < num_of_lanes; i++) {                             \
    wd.elem[i] = MsaBitInstrHelper(opcode, wd.elem[i], ws.elem[i], m); \
  }                                                                    \
  set_msa_register(instr_.WdValue(), wd.elem);                         \
  TraceMSARegWr(wd.elem)

  switch (DecodeMsaDataFormat()) {
    case MSA_BYTE:
      DCHECK(m < kMSARegSize / kMSALanesByte);
      MSA_BIT_DF(b, kMSALanesByte);
      break;
    case MSA_HALF:
      DCHECK(m < kMSARegSize / kMSALanesHalf);
      MSA_BIT_DF(h, kMSALanesHalf);
      break;
    case MSA_WORD:
      DCHECK(m < kMSARegSize / kMSALanesWord);
      MSA_BIT_DF(w, kMSALanesWord);
      break;
    case MSA_DWORD:
      DCHECK(m < kMSARegSize / kMSALanesDword);
      MSA_BIT_DF(d, kMSALanesDword);
5039 5040 5041 5042
      break;
    default:
      UNREACHABLE();
  }
5043
#undef MSA_BIT_DF
5044 5045 5046
}

void Simulator::DecodeTypeMsaMI10() {
5047
  DCHECK_EQ(kArchVariant, kMips64r6);
5048 5049
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaMI10Mask;
5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068
  int64_t s10 = (static_cast<int64_t>(instr_.MsaImmMI10Value()) << 54) >> 54;
  int64_t rs = get_register(instr_.WsValue());
  int64_t addr;
  msa_reg_t wd;

#define MSA_MI10_LOAD(elem, num_of_lanes, T)       \
  for (int i = 0; i < num_of_lanes; ++i) {         \
    addr = rs + (s10 + i) * sizeof(T);             \
    wd.elem[i] = ReadMem<T>(addr, instr_.instr()); \
  }                                                \
  set_msa_register(instr_.WdValue(), wd.elem);

#define MSA_MI10_STORE(elem, num_of_lanes, T)      \
  get_msa_register(instr_.WdValue(), wd.elem);     \
  for (int i = 0; i < num_of_lanes; ++i) {         \
    addr = rs + (s10 + i) * sizeof(T);             \
    WriteMem<T>(addr, wd.elem[i], instr_.instr()); \
  }

5069
  if (opcode == MSA_LD) {
5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085
    switch (DecodeMsaDataFormat()) {
      case MSA_BYTE:
        MSA_MI10_LOAD(b, kMSALanesByte, int8_t);
        break;
      case MSA_HALF:
        MSA_MI10_LOAD(h, kMSALanesHalf, int16_t);
        break;
      case MSA_WORD:
        MSA_MI10_LOAD(w, kMSALanesWord, int32_t);
        break;
      case MSA_DWORD:
        MSA_MI10_LOAD(d, kMSALanesDword, int64_t);
        break;
      default:
        UNREACHABLE();
    }
5086
  } else if (opcode == MSA_ST) {
5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102
    switch (DecodeMsaDataFormat()) {
      case MSA_BYTE:
        MSA_MI10_STORE(b, kMSALanesByte, int8_t);
        break;
      case MSA_HALF:
        MSA_MI10_STORE(h, kMSALanesHalf, int16_t);
        break;
      case MSA_WORD:
        MSA_MI10_STORE(w, kMSALanesWord, int32_t);
        break;
      case MSA_DWORD:
        MSA_MI10_STORE(d, kMSALanesDword, int64_t);
        break;
      default:
        UNREACHABLE();
    }
5103 5104 5105
  } else {
    UNREACHABLE();
  }
5106 5107 5108

#undef MSA_MI10_LOAD
#undef MSA_MI10_STORE
5109 5110
}

5111 5112 5113 5114 5115
template <typename T>
T Simulator::Msa3RInstrHelper(uint32_t opcode, T wd, T ws, T wt) {
  typedef typename std::make_unsigned<T>::type uT;
  T res;
  int wt_modulo = wt % (sizeof(T) * 8);
5116 5117
  switch (opcode) {
    case SLL_MSA:
5118 5119
      res = static_cast<T>(ws << wt_modulo);
      break;
5120
    case SRA_MSA:
5121 5122
      res = static_cast<T>(ArithmeticShiftRight(ws, wt_modulo));
      break;
5123
    case SRL_MSA:
5124 5125
      res = static_cast<T>(static_cast<uT>(ws) >> wt_modulo);
      break;
5126
    case BCLR:
5127 5128
      res = static_cast<T>(static_cast<T>(~(1ull << wt_modulo)) & ws);
      break;
5129
    case BSET:
5130 5131
      res = static_cast<T>(static_cast<T>(1ull << wt_modulo) | ws);
      break;
5132
    case BNEG:
5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156
      res = static_cast<T>(static_cast<T>(1ull << wt_modulo) ^ ws);
      break;
    case BINSL: {
      int elem_size = 8 * sizeof(T);
      int bits = wt_modulo + 1;
      if (bits == elem_size) {
        res = static_cast<T>(ws);
      } else {
        uint64_t mask = ((1ull << bits) - 1) << (elem_size - bits);
        res = static_cast<T>((static_cast<T>(mask) & ws) |
                             (static_cast<T>(~mask) & wd));
      }
    } break;
    case BINSR: {
      int elem_size = 8 * sizeof(T);
      int bits = wt_modulo + 1;
      if (bits == elem_size) {
        res = static_cast<T>(ws);
      } else {
        uint64_t mask = (1ull << bits) - 1;
        res = static_cast<T>((static_cast<T>(mask) & ws) |
                             (static_cast<T>(~mask) & wd));
      }
    } break;
5157
    case ADDV:
5158 5159
      res = ws + wt;
      break;
5160
    case SUBV:
5161 5162
      res = ws - wt;
      break;
5163
    case MAX_S:
5164 5165
      res = Max(ws, wt);
      break;
5166
    case MAX_U:
5167 5168
      res = static_cast<T>(Max(static_cast<uT>(ws), static_cast<uT>(wt)));
      break;
5169
    case MIN_S:
5170 5171
      res = Min(ws, wt);
      break;
5172
    case MIN_U:
5173 5174
      res = static_cast<T>(Min(static_cast<uT>(ws), static_cast<uT>(wt)));
      break;
5175
    case MAX_A:
5176 5177 5178 5179
      // We use negative abs in order to avoid problems
      // with corner case for MIN_INT
      res = Nabs(ws) < Nabs(wt) ? ws : wt;
      break;
5180
    case MIN_A:
5181 5182 5183 5184
      // We use negative abs in order to avoid problems
      // with corner case for MIN_INT
      res = Nabs(ws) > Nabs(wt) ? ws : wt;
      break;
5185
    case CEQ:
5186 5187
      res = static_cast<T>(!Compare(ws, wt) ? -1ull : 0ull);
      break;
5188
    case CLT_S:
5189 5190
      res = static_cast<T>((Compare(ws, wt) == -1) ? -1ull : 0ull);
      break;
5191
    case CLT_U:
5192 5193 5194 5195
      res = static_cast<T>(
          (Compare(static_cast<uT>(ws), static_cast<uT>(wt)) == -1) ? -1ull
                                                                    : 0ull);
      break;
5196
    case CLE_S:
5197 5198
      res = static_cast<T>((Compare(ws, wt) != 1) ? -1ull : 0ull);
      break;
5199
    case CLE_U:
5200 5201 5202 5203
      res = static_cast<T>(
          (Compare(static_cast<uT>(ws), static_cast<uT>(wt)) != 1) ? -1ull
                                                                   : 0ull);
      break;
5204
    case ADD_A:
5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215
      res = static_cast<T>(Abs(ws) + Abs(wt));
      break;
    case ADDS_A: {
      T ws_nabs = Nabs(ws);
      T wt_nabs = Nabs(wt);
      if (ws_nabs < -std::numeric_limits<T>::max() - wt_nabs) {
        res = std::numeric_limits<T>::max();
      } else {
        res = -(ws_nabs + wt_nabs);
      }
    } break;
5216
    case ADDS_S:
5217 5218 5219 5220 5221 5222 5223
      res = SaturateAdd(ws, wt);
      break;
    case ADDS_U: {
      uT ws_u = static_cast<uT>(ws);
      uT wt_u = static_cast<uT>(wt);
      res = static_cast<T>(SaturateAdd(ws_u, wt_u));
    } break;
5224
    case AVE_S:
5225 5226 5227 5228 5229 5230 5231
      res = static_cast<T>((wt & ws) + ((wt ^ ws) >> 1));
      break;
    case AVE_U: {
      uT ws_u = static_cast<uT>(ws);
      uT wt_u = static_cast<uT>(wt);
      res = static_cast<T>((wt_u & ws_u) + ((wt_u ^ ws_u) >> 1));
    } break;
5232
    case AVER_S:
5233 5234 5235 5236 5237 5238 5239
      res = static_cast<T>((wt | ws) - ((wt ^ ws) >> 1));
      break;
    case AVER_U: {
      uT ws_u = static_cast<uT>(ws);
      uT wt_u = static_cast<uT>(wt);
      res = static_cast<T>((wt_u | ws_u) - ((wt_u ^ ws_u) >> 1));
    } break;
5240
    case SUBS_S:
5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286
      res = SaturateSub(ws, wt);
      break;
    case SUBS_U: {
      uT ws_u = static_cast<uT>(ws);
      uT wt_u = static_cast<uT>(wt);
      res = static_cast<T>(SaturateSub(ws_u, wt_u));
    } break;
    case SUBSUS_U: {
      uT wsu = static_cast<uT>(ws);
      if (wt > 0) {
        uT wtu = static_cast<uT>(wt);
        if (wtu > wsu) {
          res = 0;
        } else {
          res = static_cast<T>(wsu - wtu);
        }
      } else {
        if (wsu > std::numeric_limits<uT>::max() + wt) {
          res = static_cast<T>(std::numeric_limits<uT>::max());
        } else {
          res = static_cast<T>(wsu - wt);
        }
      }
    } break;
    case SUBSUU_S: {
      uT wsu = static_cast<uT>(ws);
      uT wtu = static_cast<uT>(wt);
      uT wdu;
      if (wsu > wtu) {
        wdu = wsu - wtu;
        if (wdu > std::numeric_limits<T>::max()) {
          res = std::numeric_limits<T>::max();
        } else {
          res = static_cast<T>(wdu);
        }
      } else {
        wdu = wtu - wsu;
        CHECK(-std::numeric_limits<T>::max() ==
              std::numeric_limits<T>::min() + 1);
        if (wdu <= std::numeric_limits<T>::max()) {
          res = -static_cast<T>(wdu);
        } else {
          res = std::numeric_limits<T>::min();
        }
      }
    } break;
5287
    case ASUB_S:
5288 5289 5290 5291 5292 5293 5294
      res = static_cast<T>(Abs(ws - wt));
      break;
    case ASUB_U: {
      uT wsu = static_cast<uT>(ws);
      uT wtu = static_cast<uT>(wt);
      res = static_cast<T>(wsu > wtu ? wsu - wtu : wtu - wsu);
    } break;
5295
    case MULV:
5296 5297
      res = ws * wt;
      break;
5298
    case MADDV:
5299 5300
      res = wd + ws * wt;
      break;
5301
    case MSUBV:
5302 5303
      res = wd - ws * wt;
      break;
5304
    case DIV_S_MSA:
5305 5306
      res = wt != 0 ? ws / wt : static_cast<T>(Unpredictable);
      break;
5307
    case DIV_U:
5308 5309 5310
      res = wt != 0 ? static_cast<T>(static_cast<uT>(ws) / static_cast<uT>(wt))
                    : static_cast<T>(Unpredictable);
      break;
5311
    case MOD_S:
5312 5313
      res = wt != 0 ? ws % wt : static_cast<T>(Unpredictable);
      break;
5314
    case MOD_U:
5315 5316 5317
      res = wt != 0 ? static_cast<T>(static_cast<uT>(ws) % static_cast<uT>(wt))
                    : static_cast<T>(Unpredictable);
      break;
5318 5319 5320 5321 5322 5323 5324 5325
    case DOTP_S:
    case DOTP_U:
    case DPADD_S:
    case DPADD_U:
    case DPSUB_S:
    case DPSUB_U:
    case SLD:
    case SPLAT:
5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336
      UNIMPLEMENTED();
      break;
    case SRAR: {
      int bit = wt_modulo == 0 ? 0 : (ws >> (wt_modulo - 1)) & 1;
      res = static_cast<T>(ArithmeticShiftRight(ws, wt_modulo) + bit);
    } break;
    case SRLR: {
      uT wsu = static_cast<uT>(ws);
      int bit = wt_modulo == 0 ? 0 : (wsu >> (wt_modulo - 1)) & 1;
      res = static_cast<T>((wsu >> wt_modulo) + bit);
    } break;
5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374
    default:
      UNREACHABLE();
  }
  return res;
}
template <typename T_int, typename T_reg>
void Msa3RInstrHelper_shuffle(const uint32_t opcode, T_reg ws, T_reg wt,
                              T_reg wd, const int i, const int num_of_lanes) {
  T_int *ws_p, *wt_p, *wd_p;
  ws_p = reinterpret_cast<T_int*>(ws);
  wt_p = reinterpret_cast<T_int*>(wt);
  wd_p = reinterpret_cast<T_int*>(wd);
  switch (opcode) {
    case PCKEV:
      wd_p[i] = wt_p[2 * i];
      wd_p[i + num_of_lanes / 2] = ws_p[2 * i];
      break;
    case PCKOD:
      wd_p[i] = wt_p[2 * i + 1];
      wd_p[i + num_of_lanes / 2] = ws_p[2 * i + 1];
      break;
    case ILVL:
      wd_p[2 * i] = wt_p[i + num_of_lanes / 2];
      wd_p[2 * i + 1] = ws_p[i + num_of_lanes / 2];
      break;
    case ILVR:
      wd_p[2 * i] = wt_p[i];
      wd_p[2 * i + 1] = ws_p[i];
      break;
    case ILVEV:
      wd_p[2 * i] = wt_p[2 * i];
      wd_p[2 * i + 1] = ws_p[2 * i];
      break;
    case ILVOD:
      wd_p[2 * i] = wt_p[2 * i + 1];
      wd_p[2 * i + 1] = ws_p[2 * i + 1];
      break;
    case VSHF: {
5375 5376
      const int mask_not_valid = 0xC0;
      const int mask_6_bits = 0x3F;
5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405
      if ((wd_p[i] & mask_not_valid)) {
        wd_p[i] = 0;
      } else {
        int k = (wd_p[i] & mask_6_bits) % (num_of_lanes * 2);
        wd_p[i] = k >= num_of_lanes ? ws_p[k - num_of_lanes] : wt_p[k];
      }
    } break;
    default:
      UNREACHABLE();
  }
}

template <typename T_int, typename T_smaller_int, typename T_reg>
void Msa3RInstrHelper_horizontal(const uint32_t opcode, T_reg ws, T_reg wt,
                                 T_reg wd, const int i,
                                 const int num_of_lanes) {
  typedef typename std::make_unsigned<T_int>::type T_uint;
  typedef typename std::make_unsigned<T_smaller_int>::type T_smaller_uint;
  T_int* wd_p;
  T_smaller_int *ws_p, *wt_p;
  ws_p = reinterpret_cast<T_smaller_int*>(ws);
  wt_p = reinterpret_cast<T_smaller_int*>(wt);
  wd_p = reinterpret_cast<T_int*>(wd);
  T_uint* wd_pu;
  T_smaller_uint *ws_pu, *wt_pu;
  ws_pu = reinterpret_cast<T_smaller_uint*>(ws);
  wt_pu = reinterpret_cast<T_smaller_uint*>(wt);
  wd_pu = reinterpret_cast<T_uint*>(wd);
  switch (opcode) {
5406
    case HADD_S:
5407 5408 5409
      wd_p[i] =
          static_cast<T_int>(ws_p[2 * i + 1]) + static_cast<T_int>(wt_p[2 * i]);
      break;
5410
    case HADD_U:
5411 5412 5413
      wd_pu[i] = static_cast<T_uint>(ws_pu[2 * i + 1]) +
                 static_cast<T_uint>(wt_pu[2 * i]);
      break;
5414
    case HSUB_S:
5415 5416 5417
      wd_p[i] =
          static_cast<T_int>(ws_p[2 * i + 1]) - static_cast<T_int>(wt_p[2 * i]);
      break;
5418
    case HSUB_U:
5419 5420
      wd_pu[i] = static_cast<T_uint>(ws_pu[2 * i + 1]) -
                 static_cast<T_uint>(wt_pu[2 * i]);
5421 5422 5423 5424
      break;
    default:
      UNREACHABLE();
  }
5425 5426 5427
}

void Simulator::DecodeTypeMsa3R() {
5428
  DCHECK_EQ(kArchVariant, kMips64r6);
5429 5430 5431
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsa3RMask;
  msa_reg_t ws, wd, wt;
5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457
  get_msa_register(ws_reg(), &ws);
  get_msa_register(wt_reg(), &wt);
  get_msa_register(wd_reg(), &wd);
  switch (opcode) {
    case HADD_S:
    case HADD_U:
    case HSUB_S:
    case HSUB_U:
#define HORIZONTAL_ARITHMETIC_DF(num_of_lanes, int_type, lesser_int_type) \
  for (int i = 0; i < num_of_lanes; ++i) {                                \
    Msa3RInstrHelper_horizontal<int_type, lesser_int_type>(               \
        opcode, &ws, &wt, &wd, i, num_of_lanes);                          \
  }
      switch (DecodeMsaDataFormat()) {
        case MSA_HALF:
          HORIZONTAL_ARITHMETIC_DF(kMSALanesHalf, int16_t, int8_t);
          break;
        case MSA_WORD:
          HORIZONTAL_ARITHMETIC_DF(kMSALanesWord, int32_t, int16_t);
          break;
        case MSA_DWORD:
          HORIZONTAL_ARITHMETIC_DF(kMSALanesDword, int64_t, int32_t);
          break;
        default:
          UNREACHABLE();
      }
5458
      break;
5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482
#undef HORIZONTAL_ARITHMETIC_DF
    case VSHF:
#define VSHF_DF(num_of_lanes, int_type)                          \
  for (int i = 0; i < num_of_lanes; ++i) {                       \
    Msa3RInstrHelper_shuffle<int_type>(opcode, &ws, &wt, &wd, i, \
                                       num_of_lanes);            \
  }
      switch (DecodeMsaDataFormat()) {
        case MSA_BYTE:
          VSHF_DF(kMSALanesByte, int8_t);
          break;
        case MSA_HALF:
          VSHF_DF(kMSALanesHalf, int16_t);
          break;
        case MSA_WORD:
          VSHF_DF(kMSALanesWord, int32_t);
          break;
        case MSA_DWORD:
          VSHF_DF(kMSALanesDword, int64_t);
          break;
        default:
          UNREACHABLE();
      }
#undef VSHF_DF
5483
      break;
5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510
    case PCKEV:
    case PCKOD:
    case ILVL:
    case ILVR:
    case ILVEV:
    case ILVOD:
#define INTERLEAVE_PACK_DF(num_of_lanes, int_type)               \
  for (int i = 0; i < num_of_lanes / 2; ++i) {                   \
    Msa3RInstrHelper_shuffle<int_type>(opcode, &ws, &wt, &wd, i, \
                                       num_of_lanes);            \
  }
      switch (DecodeMsaDataFormat()) {
        case MSA_BYTE:
          INTERLEAVE_PACK_DF(kMSALanesByte, int8_t);
          break;
        case MSA_HALF:
          INTERLEAVE_PACK_DF(kMSALanesHalf, int16_t);
          break;
        case MSA_WORD:
          INTERLEAVE_PACK_DF(kMSALanesWord, int32_t);
          break;
        case MSA_DWORD:
          INTERLEAVE_PACK_DF(kMSALanesDword, int64_t);
          break;
        default:
          UNREACHABLE();
      }
5511
      break;
5512
#undef INTERLEAVE_PACK_DF
5513
    default:
5514 5515 5516
#define MSA_3R_DF(elem, num_of_lanes)                                          \
  for (int i = 0; i < num_of_lanes; i++) {                                     \
    wd.elem[i] = Msa3RInstrHelper(opcode, wd.elem[i], ws.elem[i], wt.elem[i]); \
5517
  }
5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534

      switch (DecodeMsaDataFormat()) {
        case MSA_BYTE:
          MSA_3R_DF(b, kMSALanesByte);
          break;
        case MSA_HALF:
          MSA_3R_DF(h, kMSALanesHalf);
          break;
        case MSA_WORD:
          MSA_3R_DF(w, kMSALanesWord);
          break;
        case MSA_DWORD:
          MSA_3R_DF(d, kMSALanesDword);
          break;
        default:
          UNREACHABLE();
      }
5535
#undef MSA_3R_DF
5536 5537 5538 5539
      break;
  }
  set_msa_register(wd_reg(), &wd);
  TraceMSARegWr(&wd);
5540 5541
}

5542 5543 5544 5545 5546
template <typename T_int, typename T_fp, typename T_reg>
void Msa3RFInstrHelper(uint32_t opcode, T_reg ws, T_reg wt, T_reg& wd) {
  const T_int all_ones = static_cast<T_int>(-1);
  const T_fp s_element = *reinterpret_cast<T_fp*>(&ws);
  const T_fp t_element = *reinterpret_cast<T_fp*>(&wt);
5547
  switch (opcode) {
5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636
    case FCUN: {
      if (std::isnan(s_element) || std::isnan(t_element)) {
        wd = all_ones;
      } else {
        wd = 0;
      }
    } break;
    case FCEQ: {
      if (s_element != t_element || std::isnan(s_element) ||
          std::isnan(t_element)) {
        wd = 0;
      } else {
        wd = all_ones;
      }
    } break;
    case FCUEQ: {
      if (s_element == t_element || std::isnan(s_element) ||
          std::isnan(t_element)) {
        wd = all_ones;
      } else {
        wd = 0;
      }
    } break;
    case FCLT: {
      if (s_element >= t_element || std::isnan(s_element) ||
          std::isnan(t_element)) {
        wd = 0;
      } else {
        wd = all_ones;
      }
    } break;
    case FCULT: {
      if (s_element < t_element || std::isnan(s_element) ||
          std::isnan(t_element)) {
        wd = all_ones;
      } else {
        wd = 0;
      }
    } break;
    case FCLE: {
      if (s_element > t_element || std::isnan(s_element) ||
          std::isnan(t_element)) {
        wd = 0;
      } else {
        wd = all_ones;
      }
    } break;
    case FCULE: {
      if (s_element <= t_element || std::isnan(s_element) ||
          std::isnan(t_element)) {
        wd = all_ones;
      } else {
        wd = 0;
      }
    } break;
    case FCOR: {
      if (std::isnan(s_element) || std::isnan(t_element)) {
        wd = 0;
      } else {
        wd = all_ones;
      }
    } break;
    case FCUNE: {
      if (s_element != t_element || std::isnan(s_element) ||
          std::isnan(t_element)) {
        wd = all_ones;
      } else {
        wd = 0;
      }
    } break;
    case FCNE: {
      if (s_element == t_element || std::isnan(s_element) ||
          std::isnan(t_element)) {
        wd = 0;
      } else {
        wd = all_ones;
      }
    } break;
    case FADD:
      wd = bit_cast<T_int>(s_element + t_element);
      break;
    case FSUB:
      wd = bit_cast<T_int>(s_element - t_element);
      break;
    case FMUL:
      wd = bit_cast<T_int>(s_element * t_element);
      break;
    case FDIV: {
      if (t_element == 0) {
5637
        wd = bit_cast<T_int>(std::numeric_limits<T_fp>::quiet_NaN());
5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669
      } else {
        wd = bit_cast<T_int>(s_element / t_element);
      }
    } break;
    case FMADD:
      wd = bit_cast<T_int>(
          std::fma(s_element, t_element, *reinterpret_cast<T_fp*>(&wd)));
      break;
    case FMSUB:
      wd = bit_cast<T_int>(
          std::fma(-s_element, t_element, *reinterpret_cast<T_fp*>(&wd)));
      break;
    case FEXP2:
      wd = bit_cast<T_int>(std::ldexp(s_element, static_cast<int>(wt)));
      break;
    case FMIN:
      wd = bit_cast<T_int>(std::min(s_element, t_element));
      break;
    case FMAX:
      wd = bit_cast<T_int>(std::max(s_element, t_element));
      break;
    case FMIN_A: {
      wd = bit_cast<T_int>(
          std::fabs(s_element) < std::fabs(t_element) ? s_element : t_element);
    } break;
    case FMAX_A: {
      wd = bit_cast<T_int>(
          std::fabs(s_element) > std::fabs(t_element) ? s_element : t_element);
    } break;
    case FSOR:
    case FSUNE:
    case FSNE:
5670 5671 5672 5673 5674 5675 5676 5677
    case FSAF:
    case FSUN:
    case FSEQ:
    case FSUEQ:
    case FSLT:
    case FSULT:
    case FSLE:
    case FSULE:
5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745
      UNIMPLEMENTED();
      break;
    default:
      UNREACHABLE();
  }
}

template <typename T_int, typename T_int_dbl, typename T_reg>
void Msa3RFInstrHelper2(uint32_t opcode, T_reg ws, T_reg wt, T_reg& wd) {
  // typedef typename std::make_unsigned<T_int>::type T_uint;
  typedef typename std::make_unsigned<T_int_dbl>::type T_uint_dbl;
  const T_int max_int = std::numeric_limits<T_int>::max();
  const T_int min_int = std::numeric_limits<T_int>::min();
  const int shift = kBitsPerByte * sizeof(T_int) - 1;
  const T_int_dbl reg_s = ws;
  const T_int_dbl reg_t = wt;
  T_int_dbl product, result;
  product = reg_s * reg_t;
  switch (opcode) {
    case MUL_Q: {
      const T_int_dbl min_fix_dbl =
          bit_cast<T_uint_dbl>(std::numeric_limits<T_int_dbl>::min()) >> 1U;
      const T_int_dbl max_fix_dbl = std::numeric_limits<T_int_dbl>::max() >> 1U;
      if (product == min_fix_dbl) {
        product = max_fix_dbl;
      }
      wd = static_cast<T_int>(product >> shift);
    } break;
    case MADD_Q: {
      result = (product + (static_cast<T_int_dbl>(wd) << shift)) >> shift;
      wd = static_cast<T_int>(
          result > max_int ? max_int : result < min_int ? min_int : result);
    } break;
    case MSUB_Q: {
      result = (-product + (static_cast<T_int_dbl>(wd) << shift)) >> shift;
      wd = static_cast<T_int>(
          result > max_int ? max_int : result < min_int ? min_int : result);
    } break;
    case MULR_Q: {
      const T_int_dbl min_fix_dbl =
          bit_cast<T_uint_dbl>(std::numeric_limits<T_int_dbl>::min()) >> 1U;
      const T_int_dbl max_fix_dbl = std::numeric_limits<T_int_dbl>::max() >> 1U;
      if (product == min_fix_dbl) {
        wd = static_cast<T_int>(max_fix_dbl >> shift);
        break;
      }
      wd = static_cast<T_int>((product + (1 << (shift - 1))) >> shift);
    } break;
    case MADDR_Q: {
      result = (product + (static_cast<T_int_dbl>(wd) << shift) +
                (1 << (shift - 1))) >>
               shift;
      wd = static_cast<T_int>(
          result > max_int ? max_int : result < min_int ? min_int : result);
    } break;
    case MSUBR_Q: {
      result = (-product + (static_cast<T_int_dbl>(wd) << shift) +
                (1 << (shift - 1))) >>
               shift;
      wd = static_cast<T_int>(
          result > max_int ? max_int : result < min_int ? min_int : result);
    } break;
    default:
      UNREACHABLE();
  }
}

void Simulator::DecodeTypeMsa3RF() {
5746
  DCHECK_EQ(kArchVariant, kMips64r6);
5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsa3RFMask;
  msa_reg_t wd, ws, wt;
  if (opcode != FCAF) {
    get_msa_register(ws_reg(), &ws);
    get_msa_register(wt_reg(), &wt);
  }
  switch (opcode) {
    case FCAF:
      wd.d[0] = 0;
      wd.d[1] = 0;
      break;
5759
    case FEXDO:
5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774
#define PACK_FLOAT16(sign, exp, frac) \
  static_cast<uint16_t>(((sign) << 15) + ((exp) << 10) + (frac))
#define FEXDO_DF(source, dst)                                        \
  do {                                                               \
    element = source;                                                \
    aSign = element >> 31;                                           \
    aExp = element >> 23 & 0xFF;                                     \
    aFrac = element & 0x007FFFFF;                                    \
    if (aExp == 0xFF) {                                              \
      if (aFrac) {                                                   \
        /* Input is a NaN */                                         \
        dst = 0x7DFFU;                                               \
        break;                                                       \
      }                                                              \
      /* Infinity */                                                 \
5775
      dst = PACK_FLOAT16(aSign, 0x1F, 0);                            \
5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788
      break;                                                         \
    } else if (aExp == 0 && aFrac == 0) {                            \
      dst = PACK_FLOAT16(aSign, 0, 0);                               \
      break;                                                         \
    } else {                                                         \
      int maxexp = 29;                                               \
      uint32_t mask;                                                 \
      uint32_t increment;                                            \
      bool rounding_bumps_exp;                                       \
      aFrac |= 0x00800000;                                           \
      aExp -= 0x71;                                                  \
      if (aExp < 1) {                                                \
        /* Will be denormal in halfprec */                           \
5789
        mask = 0x00FFFFFF;                                           \
5790 5791 5792 5793 5794
        if (aExp >= -11) {                                           \
          mask >>= 11 + aExp;                                        \
        }                                                            \
      } else {                                                       \
        /* Normal number in halfprec */                              \
5795
        mask = 0x00001FFF;                                           \
5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815
      }                                                              \
      switch (MSACSR_ & 3) {                                         \
        case kRoundToNearest:                                        \
          increment = (mask + 1) >> 1;                               \
          if ((aFrac & mask) == increment) {                         \
            increment = aFrac & (increment << 1);                    \
          }                                                          \
          break;                                                     \
        case kRoundToPlusInf:                                        \
          increment = aSign ? 0 : mask;                              \
          break;                                                     \
        case kRoundToMinusInf:                                       \
          increment = aSign ? mask : 0;                              \
          break;                                                     \
        case kRoundToZero:                                           \
          increment = 0;                                             \
          break;                                                     \
      }                                                              \
      rounding_bumps_exp = (aFrac + increment >= 0x01000000);        \
      if (aExp > maxexp || (aExp == maxexp && rounding_bumps_exp)) { \
5816
        dst = PACK_FLOAT16(aSign, 0x1F, 0);                          \
5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856
        break;                                                       \
      }                                                              \
      aFrac += increment;                                            \
      if (rounding_bumps_exp) {                                      \
        aFrac >>= 1;                                                 \
        aExp++;                                                      \
      }                                                              \
      if (aExp < -10) {                                              \
        dst = PACK_FLOAT16(aSign, 0, 0);                             \
        break;                                                       \
      }                                                              \
      if (aExp < 0) {                                                \
        aFrac >>= -aExp;                                             \
        aExp = 0;                                                    \
      }                                                              \
      dst = PACK_FLOAT16(aSign, aExp, aFrac >> 13);                  \
    }                                                                \
  } while (0);
      switch (DecodeMsaDataFormat()) {
        case MSA_HALF:
          for (int i = 0; i < kMSALanesWord; i++) {
            uint_fast32_t element;
            uint_fast32_t aSign, aFrac;
            int_fast32_t aExp;
            FEXDO_DF(ws.uw[i], wd.uh[i + kMSALanesHalf / 2])
            FEXDO_DF(wt.uw[i], wd.uh[i])
          }
          break;
        case MSA_WORD:
          for (int i = 0; i < kMSALanesDword; i++) {
            wd.w[i + kMSALanesWord / 2] = bit_cast<int32_t>(
                static_cast<float>(bit_cast<double>(ws.d[i])));
            wd.w[i] = bit_cast<int32_t>(
                static_cast<float>(bit_cast<double>(wt.d[i])));
          }
          break;
        default:
          UNREACHABLE();
      }
      break;
5857
#undef PACK_FLOAT16
5858
#undef FEXDO_DF
5859
    case FTQ:
5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902
#define FTQ_DF(source, dst, fp_type, int_type)                 \
  element = bit_cast<fp_type>(source) *                        \
            (1U << (sizeof(int_type) * kBitsPerByte - 1));     \
  if (element > std::numeric_limits<int_type>::max()) {        \
    dst = std::numeric_limits<int_type>::max();                \
  } else if (element < std::numeric_limits<int_type>::min()) { \
    dst = std::numeric_limits<int_type>::min();                \
  } else if (std::isnan(element)) {                            \
    dst = 0;                                                   \
  } else {                                                     \
    int_type fixed_point;                                      \
    round_according_to_msacsr(element, element, fixed_point);  \
    dst = fixed_point;                                         \
  }

      switch (DecodeMsaDataFormat()) {
        case MSA_HALF:
          for (int i = 0; i < kMSALanesWord; i++) {
            float element;
            FTQ_DF(ws.w[i], wd.h[i + kMSALanesHalf / 2], float, int16_t)
            FTQ_DF(wt.w[i], wd.h[i], float, int16_t)
          }
          break;
        case MSA_WORD:
          double element;
          for (int i = 0; i < kMSALanesDword; i++) {
            FTQ_DF(ws.d[i], wd.w[i + kMSALanesWord / 2], double, int32_t)
            FTQ_DF(wt.d[i], wd.w[i], double, int32_t)
          }
          break;
        default:
          UNREACHABLE();
      }
      break;
#undef FTQ_DF
#define MSA_3RF_DF(T1, T2, Lanes, ws, wt, wd)      \
  for (int i = 0; i < Lanes; i++) {                \
    Msa3RFInstrHelper<T1, T2>(opcode, ws, wt, wd); \
  }
#define MSA_3RF_DF2(T1, T2, Lanes, ws, wt, wd)      \
  for (int i = 0; i < Lanes; i++) {                 \
    Msa3RFInstrHelper2<T1, T2>(opcode, ws, wt, wd); \
  }
5903 5904 5905 5906
    case MADD_Q:
    case MSUB_Q:
    case MADDR_Q:
    case MSUBR_Q:
5907 5908
      get_msa_register(wd_reg(), &wd);
      V8_FALLTHROUGH;
5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922
    case MUL_Q:
    case MULR_Q:
      switch (DecodeMsaDataFormat()) {
        case MSA_HALF:
          MSA_3RF_DF2(int16_t, int32_t, kMSALanesHalf, ws.h[i], wt.h[i],
                      wd.h[i])
          break;
        case MSA_WORD:
          MSA_3RF_DF2(int32_t, int64_t, kMSALanesWord, ws.w[i], wt.w[i],
                      wd.w[i])
          break;
        default:
          UNREACHABLE();
      }
5923 5924
      break;
    default:
5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940
      if (opcode == FMADD || opcode == FMSUB) {
        get_msa_register(wd_reg(), &wd);
      }
      switch (DecodeMsaDataFormat()) {
        case MSA_WORD:
          MSA_3RF_DF(int32_t, float, kMSALanesWord, ws.w[i], wt.w[i], wd.w[i])
          break;
        case MSA_DWORD:
          MSA_3RF_DF(int64_t, double, kMSALanesDword, ws.d[i], wt.d[i], wd.d[i])
          break;
        default:
          UNREACHABLE();
      }
      break;
#undef MSA_3RF_DF
#undef MSA_3RF_DF2
5941
  }
5942 5943
  set_msa_register(wd_reg(), &wd);
  TraceMSARegWr(&wd);
5944 5945 5946
}

void Simulator::DecodeTypeMsaVec() {
5947
  DCHECK_EQ(kArchVariant, kMips64r6);
5948 5949
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaVECMask;
5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983
  msa_reg_t wd, ws, wt;

  get_msa_register(instr_.WsValue(), ws.d);
  get_msa_register(instr_.WtValue(), wt.d);
  if (opcode == BMNZ_V || opcode == BMZ_V || opcode == BSEL_V) {
    get_msa_register(instr_.WdValue(), wd.d);
  }

  for (int i = 0; i < kMSALanesDword; i++) {
    switch (opcode) {
      case AND_V:
        wd.d[i] = ws.d[i] & wt.d[i];
        break;
      case OR_V:
        wd.d[i] = ws.d[i] | wt.d[i];
        break;
      case NOR_V:
        wd.d[i] = ~(ws.d[i] | wt.d[i]);
        break;
      case XOR_V:
        wd.d[i] = ws.d[i] ^ wt.d[i];
        break;
      case BMNZ_V:
        wd.d[i] = (wt.d[i] & ws.d[i]) | (~wt.d[i] & wd.d[i]);
        break;
      case BMZ_V:
        wd.d[i] = (~wt.d[i] & ws.d[i]) | (wt.d[i] & wd.d[i]);
        break;
      case BSEL_V:
        wd.d[i] = (~wd.d[i] & ws.d[i]) | (wd.d[i] & wt.d[i]);
        break;
      default:
        UNREACHABLE();
    }
5984
  }
5985 5986
  set_msa_register(instr_.WdValue(), wd.d);
  TraceMSARegWr(wd.d);
5987 5988 5989
}

void Simulator::DecodeTypeMsa2R() {
5990
  DCHECK_EQ(kArchVariant, kMips64r6);
5991 5992
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsa2RMask;
5993
  msa_reg_t wd, ws;
5994 5995 5996 5997 5998
  switch (opcode) {
    case FILL:
      switch (DecodeMsaDataFormat()) {
        case MSA_BYTE: {
          int64_t rs = get_register(instr_.WsValue());
5999 6000
          for (int i = 0; i < kMSALanesByte; i++) {
            wd.b[i] = rs & 0xFFu;
6001
          }
6002 6003
          set_msa_register(instr_.WdValue(), wd.b);
          TraceMSARegWr(wd.b);
6004 6005 6006 6007
          break;
        }
        case MSA_HALF: {
          int64_t rs = get_register(instr_.WsValue());
6008 6009
          for (int i = 0; i < kMSALanesHalf; i++) {
            wd.h[i] = rs & 0xFFFFu;
6010
          }
6011 6012
          set_msa_register(instr_.WdValue(), wd.h);
          TraceMSARegWr(wd.h);
6013 6014 6015 6016
          break;
        }
        case MSA_WORD: {
          int64_t rs = get_register(instr_.WsValue());
6017 6018
          for (int i = 0; i < kMSALanesWord; i++) {
            wd.w[i] = rs & 0xFFFFFFFFu;
6019
          }
6020 6021
          set_msa_register(instr_.WdValue(), wd.w);
          TraceMSARegWr(wd.w);
6022 6023 6024 6025
          break;
        }
        case MSA_DWORD: {
          int64_t rs = get_register(instr_.WsValue());
6026 6027 6028
          wd.d[0] = wd.d[1] = rs;
          set_msa_register(instr_.WdValue(), wd.d);
          TraceMSARegWr(wd.d);
6029 6030 6031 6032 6033 6034 6035
          break;
        }
        default:
          UNREACHABLE();
      }
      break;
    case PCNT:
6036 6037 6038 6039
#define PCNT_DF(elem, num_of_lanes)                       \
  get_msa_register(instr_.WsValue(), ws.elem);            \
  for (int i = 0; i < num_of_lanes; i++) {                \
    uint64_t u64elem = static_cast<uint64_t>(ws.elem[i]); \
6040
    wd.elem[i] = base::bits::CountPopulation(u64elem);    \
6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062
  }                                                       \
  set_msa_register(instr_.WdValue(), wd.elem);            \
  TraceMSARegWr(wd.elem)

      switch (DecodeMsaDataFormat()) {
        case MSA_BYTE:
          PCNT_DF(ub, kMSALanesByte);
          break;
        case MSA_HALF:
          PCNT_DF(uh, kMSALanesHalf);
          break;
        case MSA_WORD:
          PCNT_DF(uw, kMSALanesWord);
          break;
        case MSA_DWORD:
          PCNT_DF(ud, kMSALanesDword);
          break;
        default:
          UNREACHABLE();
      }
#undef PCNT_DF
      break;
6063
    case NLOC:
6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094
#define NLOC_DF(elem, num_of_lanes)                                         \
  get_msa_register(instr_.WsValue(), ws.elem);                              \
  for (int i = 0; i < num_of_lanes; i++) {                                  \
    const uint64_t mask = (num_of_lanes == kMSALanesDword)                  \
                              ? UINT64_MAX                                  \
                              : (1ULL << (kMSARegSize / num_of_lanes)) - 1; \
    uint64_t u64elem = static_cast<uint64_t>(~ws.elem[i]) & mask;           \
    wd.elem[i] = base::bits::CountLeadingZeros64(u64elem) -                 \
                 (64 - kMSARegSize / num_of_lanes);                         \
  }                                                                         \
  set_msa_register(instr_.WdValue(), wd.elem);                              \
  TraceMSARegWr(wd.elem)

      switch (DecodeMsaDataFormat()) {
        case MSA_BYTE:
          NLOC_DF(ub, kMSALanesByte);
          break;
        case MSA_HALF:
          NLOC_DF(uh, kMSALanesHalf);
          break;
        case MSA_WORD:
          NLOC_DF(uw, kMSALanesWord);
          break;
        case MSA_DWORD:
          NLOC_DF(ud, kMSALanesDword);
          break;
        default:
          UNREACHABLE();
      }
#undef NLOC_DF
      break;
6095
    case NLZC:
6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122
#define NLZC_DF(elem, num_of_lanes)                         \
  get_msa_register(instr_.WsValue(), ws.elem);              \
  for (int i = 0; i < num_of_lanes; i++) {                  \
    uint64_t u64elem = static_cast<uint64_t>(ws.elem[i]);   \
    wd.elem[i] = base::bits::CountLeadingZeros64(u64elem) - \
                 (64 - kMSARegSize / num_of_lanes);         \
  }                                                         \
  set_msa_register(instr_.WdValue(), wd.elem);              \
  TraceMSARegWr(wd.elem)

      switch (DecodeMsaDataFormat()) {
        case MSA_BYTE:
          NLZC_DF(ub, kMSALanesByte);
          break;
        case MSA_HALF:
          NLZC_DF(uh, kMSALanesHalf);
          break;
        case MSA_WORD:
          NLZC_DF(uw, kMSALanesWord);
          break;
        case MSA_DWORD:
          NLZC_DF(ud, kMSALanesDword);
          break;
        default:
          UNREACHABLE();
      }
#undef NLZC_DF
6123 6124 6125 6126 6127 6128
      break;
    default:
      UNREACHABLE();
  }
}

6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140
#define BIT(n) (0x1LL << n)
#define QUIET_BIT_S(nan) (bit_cast<int32_t>(nan) & BIT(22))
#define QUIET_BIT_D(nan) (bit_cast<int64_t>(nan) & BIT(51))
static inline bool isSnan(float fp) { return !QUIET_BIT_S(fp); }
static inline bool isSnan(double fp) { return !QUIET_BIT_D(fp); }
#undef QUIET_BIT_S
#undef QUIET_BIT_D

template <typename T_int, typename T_fp, typename T_src, typename T_dst>
T_int Msa2RFInstrHelper(uint32_t opcode, T_src src, T_dst& dst,
                        Simulator* sim) {
  typedef typename std::make_unsigned<T_int>::type T_uint;
6141
  switch (opcode) {
6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211
    case FCLASS: {
#define SNAN_BIT BIT(0)
#define QNAN_BIT BIT(1)
#define NEG_INFINITY_BIT BIT(2)
#define NEG_NORMAL_BIT BIT(3)
#define NEG_SUBNORMAL_BIT BIT(4)
#define NEG_ZERO_BIT BIT(5)
#define POS_INFINITY_BIT BIT(6)
#define POS_NORMAL_BIT BIT(7)
#define POS_SUBNORMAL_BIT BIT(8)
#define POS_ZERO_BIT BIT(9)
      T_fp element = *reinterpret_cast<T_fp*>(&src);
      switch (std::fpclassify(element)) {
        case FP_INFINITE:
          if (std::signbit(element)) {
            dst = NEG_INFINITY_BIT;
          } else {
            dst = POS_INFINITY_BIT;
          }
          break;
        case FP_NAN:
          if (isSnan(element)) {
            dst = SNAN_BIT;
          } else {
            dst = QNAN_BIT;
          }
          break;
        case FP_NORMAL:
          if (std::signbit(element)) {
            dst = NEG_NORMAL_BIT;
          } else {
            dst = POS_NORMAL_BIT;
          }
          break;
        case FP_SUBNORMAL:
          if (std::signbit(element)) {
            dst = NEG_SUBNORMAL_BIT;
          } else {
            dst = POS_SUBNORMAL_BIT;
          }
          break;
        case FP_ZERO:
          if (std::signbit(element)) {
            dst = NEG_ZERO_BIT;
          } else {
            dst = POS_ZERO_BIT;
          }
          break;
        default:
          UNREACHABLE();
      }
      break;
    }
#undef BIT
#undef SNAN_BIT
#undef QNAN_BIT
#undef NEG_INFINITY_BIT
#undef NEG_NORMAL_BIT
#undef NEG_SUBNORMAL_BIT
#undef NEG_ZERO_BIT
#undef POS_INFINITY_BIT
#undef POS_NORMAL_BIT
#undef POS_SUBNORMAL_BIT
#undef POS_ZERO_BIT
    case FTRUNC_S: {
      T_fp element = bit_cast<T_fp>(src);
      const T_int max_int = std::numeric_limits<T_int>::max();
      const T_int min_int = std::numeric_limits<T_int>::min();
      if (std::isnan(element)) {
        dst = 0;
6212 6213
      } else if (element >= max_int || element <= min_int) {
        dst = element >= max_int ? max_int : min_int;
6214 6215 6216 6217 6218 6219 6220 6221 6222 6223
      } else {
        dst = static_cast<T_int>(std::trunc(element));
      }
      break;
    }
    case FTRUNC_U: {
      T_fp element = bit_cast<T_fp>(src);
      const T_uint max_int = std::numeric_limits<T_uint>::max();
      if (std::isnan(element)) {
        dst = 0;
6224 6225
      } else if (element >= max_int || element <= 0) {
        dst = element >= max_int ? max_int : 0;
6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320
      } else {
        dst = static_cast<T_uint>(std::trunc(element));
      }
      break;
    }
    case FSQRT: {
      T_fp element = bit_cast<T_fp>(src);
      if (element < 0 || std::isnan(element)) {
        dst = bit_cast<T_int>(std::numeric_limits<T_fp>::quiet_NaN());
      } else {
        dst = bit_cast<T_int>(std::sqrt(element));
      }
      break;
    }
    case FRSQRT: {
      T_fp element = bit_cast<T_fp>(src);
      if (element < 0 || std::isnan(element)) {
        dst = bit_cast<T_int>(std::numeric_limits<T_fp>::quiet_NaN());
      } else {
        dst = bit_cast<T_int>(1 / std::sqrt(element));
      }
      break;
    }
    case FRCP: {
      T_fp element = bit_cast<T_fp>(src);
      if (std::isnan(element)) {
        dst = bit_cast<T_int>(std::numeric_limits<T_fp>::quiet_NaN());
      } else {
        dst = bit_cast<T_int>(1 / element);
      }
      break;
    }
    case FRINT: {
      T_fp element = bit_cast<T_fp>(src);
      if (std::isnan(element)) {
        dst = bit_cast<T_int>(std::numeric_limits<T_fp>::quiet_NaN());
      } else {
        T_int dummy;
        sim->round_according_to_msacsr<T_fp, T_int>(element, element, dummy);
        dst = bit_cast<T_int>(element);
      }
      break;
    }
    case FLOG2: {
      T_fp element = bit_cast<T_fp>(src);
      switch (std::fpclassify(element)) {
        case FP_NORMAL:
        case FP_SUBNORMAL:
          dst = bit_cast<T_int>(std::logb(element));
          break;
        case FP_ZERO:
          dst = bit_cast<T_int>(-std::numeric_limits<T_fp>::infinity());
          break;
        case FP_NAN:
          dst = bit_cast<T_int>(std::numeric_limits<T_fp>::quiet_NaN());
          break;
        case FP_INFINITE:
          if (element < 0) {
            dst = bit_cast<T_int>(std::numeric_limits<T_fp>::quiet_NaN());
          } else {
            dst = bit_cast<T_int>(std::numeric_limits<T_fp>::infinity());
          }
          break;
        default:
          UNREACHABLE();
      }
      break;
    }
    case FTINT_S: {
      T_fp element = bit_cast<T_fp>(src);
      const T_int max_int = std::numeric_limits<T_int>::max();
      const T_int min_int = std::numeric_limits<T_int>::min();
      if (std::isnan(element)) {
        dst = 0;
      } else if (element < min_int || element > max_int) {
        dst = element > max_int ? max_int : min_int;
      } else {
        sim->round_according_to_msacsr<T_fp, T_int>(element, element, dst);
      }
      break;
    }
    case FTINT_U: {
      T_fp element = bit_cast<T_fp>(src);
      const T_uint max_uint = std::numeric_limits<T_uint>::max();
      if (std::isnan(element)) {
        dst = 0;
      } else if (element < 0 || element > max_uint) {
        dst = element > max_uint ? max_uint : 0;
      } else {
        T_uint res;
        sim->round_according_to_msacsr<T_fp, T_uint>(element, element, res);
        dst = *reinterpret_cast<T_int*>(&res);
      }
      break;
    }
6321
    case FFINT_S:
6322 6323
      dst = bit_cast<T_int>(static_cast<T_fp>(src));
      break;
6324
    case FFINT_U:
6325 6326
      typedef typename std::make_unsigned<T_src>::type uT_src;
      dst = bit_cast<T_int>(static_cast<T_fp>(bit_cast<uT_src>(src)));
6327 6328 6329 6330
      break;
    default:
      UNREACHABLE();
  }
6331 6332 6333
  return 0;
}

6334 6335
template <typename T_int, typename T_fp, typename T_reg>
T_int Msa2RFInstrHelper2(uint32_t opcode, T_reg ws, int i) {
6336 6337
  switch (opcode) {
#define EXTRACT_FLOAT16_SIGN(fp16) (fp16 >> 15)
6338 6339
#define EXTRACT_FLOAT16_EXP(fp16) (fp16 >> 10 & 0x1F)
#define EXTRACT_FLOAT16_FRAC(fp16) (fp16 & 0x3FF)
6340 6341 6342 6343 6344 6345 6346 6347 6348
#define PACK_FLOAT32(sign, exp, frac) \
  static_cast<uint32_t>(((sign) << 31) + ((exp) << 23) + (frac))
#define FEXUP_DF(src_index)                                                   \
  uint_fast16_t element = ws.uh[src_index];                                   \
  uint_fast32_t aSign, aFrac;                                                 \
  int_fast32_t aExp;                                                          \
  aSign = EXTRACT_FLOAT16_SIGN(element);                                      \
  aExp = EXTRACT_FLOAT16_EXP(element);                                        \
  aFrac = EXTRACT_FLOAT16_FRAC(element);                                      \
6349
  if (V8_LIKELY(aExp && aExp != 0x1F)) {                                      \
6350
    return PACK_FLOAT32(aSign, aExp + 0x70, aFrac << 13);                     \
6351
  } else if (aExp == 0x1F) {                                                  \
6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410
    if (aFrac) {                                                              \
      return bit_cast<int32_t>(std::numeric_limits<float>::quiet_NaN());      \
    } else {                                                                  \
      return bit_cast<uint32_t>(std::numeric_limits<float>::infinity()) |     \
             static_cast<uint32_t>(aSign) << 31;                              \
    }                                                                         \
  } else {                                                                    \
    if (aFrac == 0) {                                                         \
      return PACK_FLOAT32(aSign, 0, 0);                                       \
    } else {                                                                  \
      int_fast16_t shiftCount =                                               \
          base::bits::CountLeadingZeros32(static_cast<uint32_t>(aFrac)) - 21; \
      aFrac <<= shiftCount;                                                   \
      aExp = -shiftCount;                                                     \
      return PACK_FLOAT32(aSign, aExp + 0x70, aFrac << 13);                   \
    }                                                                         \
  }
    case FEXUPL:
      if (std::is_same<int32_t, T_int>::value) {
        FEXUP_DF(i + kMSALanesWord)
      } else {
        return bit_cast<int64_t>(
            static_cast<double>(bit_cast<float>(ws.w[i + kMSALanesDword])));
      }
    case FEXUPR:
      if (std::is_same<int32_t, T_int>::value) {
        FEXUP_DF(i)
      } else {
        return bit_cast<int64_t>(static_cast<double>(bit_cast<float>(ws.w[i])));
      }
    case FFQL: {
      if (std::is_same<int32_t, T_int>::value) {
        return bit_cast<int32_t>(static_cast<float>(ws.h[i + kMSALanesWord]) /
                                 (1U << 15));
      } else {
        return bit_cast<int64_t>(static_cast<double>(ws.w[i + kMSALanesDword]) /
                                 (1U << 31));
      }
      break;
    }
    case FFQR: {
      if (std::is_same<int32_t, T_int>::value) {
        return bit_cast<int32_t>(static_cast<float>(ws.h[i]) / (1U << 15));
      } else {
        return bit_cast<int64_t>(static_cast<double>(ws.w[i]) / (1U << 31));
      }
      break;
      default:
        UNREACHABLE();
    }
  }
#undef EXTRACT_FLOAT16_SIGN
#undef EXTRACT_FLOAT16_EXP
#undef EXTRACT_FLOAT16_FRAC
#undef PACK_FLOAT32
#undef FEXUP_DF
}

void Simulator::DecodeTypeMsa2RF() {
6411
  DCHECK_EQ(kArchVariant, kMips64r6);
6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsa2RFMask;
  msa_reg_t wd, ws;
  get_msa_register(ws_reg(), &ws);
  if (opcode == FEXUPL || opcode == FEXUPR || opcode == FFQL ||
      opcode == FFQR) {
    switch (DecodeMsaDataFormat()) {
      case MSA_WORD:
        for (int i = 0; i < kMSALanesWord; i++) {
          wd.w[i] = Msa2RFInstrHelper2<int32_t, float>(opcode, ws, i);
        }
        break;
      case MSA_DWORD:
        for (int i = 0; i < kMSALanesDword; i++) {
          wd.d[i] = Msa2RFInstrHelper2<int64_t, double>(opcode, ws, i);
        }
        break;
      default:
        UNREACHABLE();
    }
  } else {
    switch (DecodeMsaDataFormat()) {
      case MSA_WORD:
        for (int i = 0; i < kMSALanesWord; i++) {
          Msa2RFInstrHelper<int32_t, float>(opcode, ws.w[i], wd.w[i], this);
        }
        break;
      case MSA_DWORD:
        for (int i = 0; i < kMSALanesDword; i++) {
          Msa2RFInstrHelper<int64_t, double>(opcode, ws.d[i], wd.d[i], this);
        }
        break;
      default:
        UNREACHABLE();
    }
  }
  set_msa_register(wd_reg(), &wd);
  TraceMSARegWr(&wd);
6450 6451
}

6452
void Simulator::DecodeTypeRegister() {
6453
  // ---------- Execution.
6454
  switch (instr_.OpcodeFieldRaw()) {
6455
    case COP1:
6456
      DecodeTypeRegisterCOP1();
6457 6458
      break;
    case COP1X:
6459
      DecodeTypeRegisterCOP1X();
6460 6461
      break;
    case SPECIAL:
6462
      DecodeTypeRegisterSPECIAL();
6463 6464
      break;
    case SPECIAL2:
6465
      DecodeTypeRegisterSPECIAL2();
6466 6467
      break;
    case SPECIAL3:
6468
      DecodeTypeRegisterSPECIAL3();
6469
      break;
6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486
    case MSA:
      switch (instr_.MSAMinorOpcodeField()) {
        case kMsaMinor3R:
          DecodeTypeMsa3R();
          break;
        case kMsaMinor3RF:
          DecodeTypeMsa3RF();
          break;
        case kMsaMinorVEC:
          DecodeTypeMsaVec();
          break;
        case kMsaMinor2R:
          DecodeTypeMsa2R();
          break;
        case kMsaMinor2RF:
          DecodeTypeMsa2RF();
          break;
6487 6488 6489
        case kMsaMinorELM:
          DecodeTypeMsaELM();
          break;
6490 6491 6492 6493
        default:
          UNREACHABLE();
      }
      break;
6494 6495 6496 6497
    // Unimplemented opcodes raised an error in the configuration step before,
    // so we can use the default here to set the destination register in common
    // cases.
    default:
6498
      UNREACHABLE();
6499 6500 6501 6502
  }
}


6503
// Type 2: instructions using a 16, 21 or 26 bits immediate. (e.g. beq, beqc).
6504
void Simulator::DecodeTypeImmediate() {
6505
  // Instruction fields.
6506 6507 6508
  Opcode op = instr_.OpcodeFieldRaw();
  int32_t rs_reg = instr_.RsValue();
  int64_t rs = get_register(instr_.RsValue());
6509
  uint64_t rs_u = static_cast<uint64_t>(rs);
6510
  int32_t rt_reg = instr_.RtValue();  // Destination register.
6511
  int64_t rt = get_register(rt_reg);
6512 6513
  int16_t imm16 = instr_.Imm16Value();
  int32_t imm18 = instr_.Imm18Value();
6514

6515
  int32_t ft_reg = instr_.FtValue();  // Destination register.
6516 6517

  // Zero extended immediate.
6518
  uint64_t oe_imm16 = 0xFFFF & imm16;
6519
  // Sign extended immediate.
6520
  int64_t se_imm16 = imm16;
6521
  int64_t se_imm18 = imm18 | ((imm18 & 0x20000) ? 0xFFFFFFFFFFFC0000 : 0);
6522

6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535
  // Next pc.
  int64_t next_pc = bad_ra;

  // Used for conditional branch instructions.
  bool execute_branch_delay_instruction = false;

  // Used for arithmetic instructions.
  int64_t alu_out = 0;

  // Used for memory instructions.
  int64_t addr = 0x0;
  // Alignment for 32-bit integers used in LWL, LWR, etc.
  const int kInt32AlignmentMask = sizeof(uint32_t) - 1;
6536 6537
  // Alignment for 64-bit integers used in LDL, LDR, etc.
  const int kInt64AlignmentMask = sizeof(uint64_t) - 1;
6538

6539
  // Branch instructions common part.
6540 6541 6542 6543
  auto BranchAndLinkHelper =
      [this, &next_pc, &execute_branch_delay_instruction](bool do_branch) {
        execute_branch_delay_instruction = true;
        int64_t current_pc = get_pc();
6544
        set_register(31, current_pc + 2 * kInstrSize);
6545 6546
        if (do_branch) {
          int16_t imm16 = instr_.Imm16Value();
6547
          next_pc = current_pc + (imm16 << 2) + kInstrSize;
6548
        } else {
6549
          next_pc = current_pc + 2 * kInstrSize;
6550 6551
        }
      };
6552

6553
  auto BranchHelper = [this, &next_pc,
6554 6555 6556 6557
                       &execute_branch_delay_instruction](bool do_branch) {
    execute_branch_delay_instruction = true;
    int64_t current_pc = get_pc();
    if (do_branch) {
6558
      int16_t imm16 = instr_.Imm16Value();
6559
      next_pc = current_pc + (imm16 << 2) + kInstrSize;
6560
    } else {
6561
      next_pc = current_pc + 2 * kInstrSize;
6562 6563 6564
    }
  };

6565 6566 6567 6568 6569 6570 6571
  auto BranchHelper_MSA = [this, &next_pc, imm16,
                           &execute_branch_delay_instruction](bool do_branch) {
    execute_branch_delay_instruction = true;
    int64_t current_pc = get_pc();
    const int32_t bitsIn16Int = sizeof(int16_t) * kBitsPerByte;
    if (do_branch) {
      if (FLAG_debug_code) {
6572
        int16_t bits = imm16 & 0xFC;
6573 6574 6575
        if (imm16 >= 0) {
          CHECK_EQ(bits, 0);
        } else {
6576
          CHECK_EQ(bits ^ 0xFC, 0);
6577 6578 6579 6580 6581 6582
        }
      }
      // jump range :[pc + kInstrSize - 512 * kInstrSize,
      //              pc + kInstrSize + 511 * kInstrSize]
      int16_t offset = static_cast<int16_t>(imm16 << (bitsIn16Int - 10)) >>
                       (bitsIn16Int - 12);
6583
      next_pc = current_pc + offset + kInstrSize;
6584
    } else {
6585
      next_pc = current_pc + 2 * kInstrSize;
6586 6587 6588
    }
  };

6589
  auto BranchAndLinkCompactHelper = [this, &next_pc](bool do_branch, int bits) {
6590 6591 6592
    int64_t current_pc = get_pc();
    CheckForbiddenSlot(current_pc);
    if (do_branch) {
6593
      int32_t imm = instr_.ImmValue(bits);
6594 6595
      imm <<= 32 - bits;
      imm >>= 32 - bits;
6596 6597
      next_pc = current_pc + (imm << 2) + kInstrSize;
      set_register(31, current_pc + kInstrSize);
6598 6599 6600
    }
  };

6601
  auto BranchCompactHelper = [this, &next_pc](bool do_branch, int bits) {
6602 6603 6604
    int64_t current_pc = get_pc();
    CheckForbiddenSlot(current_pc);
    if (do_branch) {
6605
      int32_t imm = instr_.ImmValue(bits);
6606 6607
      imm <<= 32 - bits;
      imm >>= 32 - bits;
6608
      next_pc = get_pc() + (imm << 2) + kInstrSize;
6609 6610 6611
    }
  };

6612 6613 6614
  switch (op) {
    // ------------- COP1. Coprocessor instructions.
    case COP1:
6615
      switch (instr_.RsFieldRaw()) {
6616
        case BC1: {  // Branch on coprocessor condition.
6617
          uint32_t cc = instr_.FBccValue();
6618 6619
          uint32_t fcsr_cc = get_fcsr_condition_bit(cc);
          uint32_t cc_value = test_fcsr_bit(fcsr_cc);
6620
          bool do_branch = (instr_.FBtrueValue()) ? cc_value : !cc_value;
6621
          BranchHelper(do_branch);
6622
          break;
6623
        }
6624
        case BC1EQZ:
6625
          BranchHelper(!(get_fpu_register(ft_reg) & 0x1));
6626 6627
          break;
        case BC1NEZ:
6628
          BranchHelper(get_fpu_register(ft_reg) & 0x1);
6629
          break;
6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646
        case BZ_V: {
          msa_reg_t wt;
          get_msa_register(wt_reg(), &wt);
          BranchHelper_MSA(wt.d[0] == 0 && wt.d[1] == 0);
        } break;
#define BZ_DF(witdh, lanes)          \
  {                                  \
    msa_reg_t wt;                    \
    get_msa_register(wt_reg(), &wt); \
    int i;                           \
    for (i = 0; i < lanes; ++i) {    \
      if (wt.witdh[i] == 0) {        \
        break;                       \
      }                              \
    }                                \
    BranchHelper_MSA(i != lanes);    \
  }
6647
        case BZ_B:
6648 6649
          BZ_DF(b, kMSALanesByte)
          break;
6650
        case BZ_H:
6651 6652
          BZ_DF(h, kMSALanesHalf)
          break;
6653
        case BZ_W:
6654 6655
          BZ_DF(w, kMSALanesWord)
          break;
6656
        case BZ_D:
6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676
          BZ_DF(d, kMSALanesDword)
          break;
#undef BZ_DF
        case BNZ_V: {
          msa_reg_t wt;
          get_msa_register(wt_reg(), &wt);
          BranchHelper_MSA(wt.d[0] != 0 || wt.d[1] != 0);
        } break;
#define BNZ_DF(witdh, lanes)         \
  {                                  \
    msa_reg_t wt;                    \
    get_msa_register(wt_reg(), &wt); \
    int i;                           \
    for (i = 0; i < lanes; ++i) {    \
      if (wt.witdh[i] == 0) {        \
        break;                       \
      }                              \
    }                                \
    BranchHelper_MSA(i == lanes);    \
  }
6677
        case BNZ_B:
6678 6679
          BNZ_DF(b, kMSALanesByte)
          break;
6680
        case BNZ_H:
6681 6682
          BNZ_DF(h, kMSALanesHalf)
          break;
6683
        case BNZ_W:
6684 6685
          BNZ_DF(w, kMSALanesWord)
          break;
6686
        case BNZ_D:
6687
          BNZ_DF(d, kMSALanesDword)
6688
          break;
6689
#undef BNZ_DF
6690 6691 6692 6693 6694 6695
        default:
          UNREACHABLE();
      }
      break;
    // ------------- REGIMM class.
    case REGIMM:
6696
      switch (instr_.RtFieldRaw()) {
6697
        case BLTZ:
6698
          BranchHelper(rs < 0);
6699 6700
          break;
        case BGEZ:
6701 6702 6703 6704
          BranchHelper(rs >= 0);
          break;
        case BLTZAL:
          BranchAndLinkHelper(rs < 0);
6705 6706
          break;
        case BGEZAL:
6707
          BranchAndLinkHelper(rs >= 0);
6708
          break;
6709 6710 6711 6712 6713 6714
        case DAHI:
          SetResult(rs_reg, rs + (se_imm16 << 32));
          break;
        case DATI:
          SetResult(rs_reg, rs + (se_imm16 << 48));
          break;
6715 6716 6717
        default:
          UNREACHABLE();
      }
6718
      break;  // case REGIMM.
6719 6720 6721 6722
    // ------------- Branch instructions.
    // When comparing to zero, the encoding of rt field is always 0, so we don't
    // need to replace rt with zero.
    case BEQ:
6723
      BranchHelper(rs == rt);
6724 6725
      break;
    case BNE:
6726
      BranchHelper(rs != rt);
6727
      break;
6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804
    case POP06:  // BLEZALC, BGEZALC, BGEUC, BLEZ (pre-r6)
      if (kArchVariant == kMips64r6) {
        if (rt_reg != 0) {
          if (rs_reg == 0) {  // BLEZALC
            BranchAndLinkCompactHelper(rt <= 0, 16);
          } else {
            if (rs_reg == rt_reg) {  // BGEZALC
              BranchAndLinkCompactHelper(rt >= 0, 16);
            } else {  // BGEUC
              BranchCompactHelper(
                  static_cast<uint64_t>(rs) >= static_cast<uint64_t>(rt), 16);
            }
          }
        } else {  // BLEZ
          BranchHelper(rs <= 0);
        }
      } else {  // BLEZ
        BranchHelper(rs <= 0);
      }
      break;
    case POP07:  // BGTZALC, BLTZALC, BLTUC, BGTZ (pre-r6)
      if (kArchVariant == kMips64r6) {
        if (rt_reg != 0) {
          if (rs_reg == 0) {  // BGTZALC
            BranchAndLinkCompactHelper(rt > 0, 16);
          } else {
            if (rt_reg == rs_reg) {  // BLTZALC
              BranchAndLinkCompactHelper(rt < 0, 16);
            } else {  // BLTUC
              BranchCompactHelper(
                  static_cast<uint64_t>(rs) < static_cast<uint64_t>(rt), 16);
            }
          }
        } else {  // BGTZ
          BranchHelper(rs > 0);
        }
      } else {  // BGTZ
        BranchHelper(rs > 0);
      }
      break;
    case POP26:  // BLEZC, BGEZC, BGEC/BLEC / BLEZL (pre-r6)
      if (kArchVariant == kMips64r6) {
        if (rt_reg != 0) {
          if (rs_reg == 0) {  // BLEZC
            BranchCompactHelper(rt <= 0, 16);
          } else {
            if (rs_reg == rt_reg) {  // BGEZC
              BranchCompactHelper(rt >= 0, 16);
            } else {  // BGEC/BLEC
              BranchCompactHelper(rs >= rt, 16);
            }
          }
        }
      } else {  // BLEZL
        BranchAndLinkHelper(rs <= 0);
      }
      break;
    case POP27:  // BGTZC, BLTZC, BLTC/BGTC / BGTZL (pre-r6)
      if (kArchVariant == kMips64r6) {
        if (rt_reg != 0) {
          if (rs_reg == 0) {  // BGTZC
            BranchCompactHelper(rt > 0, 16);
          } else {
            if (rs_reg == rt_reg) {  // BLTZC
              BranchCompactHelper(rt < 0, 16);
            } else {  // BLTC/BGTC
              BranchCompactHelper(rs < rt, 16);
            }
          }
        }
      } else {  // BGTZL
        BranchAndLinkHelper(rs > 0);
      }
      break;
    case POP66:           // BEQZC, JIC
      if (rs_reg != 0) {  // BEQZC
        BranchCompactHelper(rs == 0, 21);
6805 6806 6807 6808
      } else {  // JIC
        next_pc = rt + imm16;
      }
      break;
6809 6810 6811 6812 6813
    case POP76:           // BNEZC, JIALC
      if (rs_reg != 0) {  // BNEZC
        BranchCompactHelper(rs != 0, 21);
      } else {  // JIALC
        int64_t current_pc = get_pc();
6814
        set_register(31, current_pc + kInstrSize);
6815 6816
        next_pc = rt + imm16;
      }
6817
      break;
6818 6819
    case BC:
      BranchCompactHelper(true, 26);
6820
      break;
6821 6822 6823 6824 6825 6826
    case BALC:
      BranchAndLinkCompactHelper(true, 26);
      break;
    case POP10:  // BOVC, BEQZALC, BEQC / ADDI (pre-r6)
      if (kArchVariant == kMips64r6) {
        if (rs_reg >= rt_reg) {  // BOVC
6827 6828
          bool condition = !is_int32(rs) || !is_int32(rt) || !is_int32(rs + rt);
          BranchCompactHelper(condition, 16);
6829 6830 6831 6832 6833
        } else {
          if (rs_reg == 0) {  // BEQZALC
            BranchAndLinkCompactHelper(rt == 0, 16);
          } else {  // BEQC
            BranchCompactHelper(rt == rs, 16);
6834
          }
6835
        }
6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848
      } else {  // ADDI
        if (HaveSameSign(rs, se_imm16)) {
          if (rs > 0) {
            if (rs <= Registers::kMaxValue - se_imm16) {
              SignalException(kIntegerOverflow);
            }
          } else if (rs < 0) {
            if (rs >= Registers::kMinValue - se_imm16) {
              SignalException(kIntegerUnderflow);
            }
          }
        }
        SetResult(rt_reg, rs + se_imm16);
6849 6850
      }
      break;
6851 6852 6853
    case POP30:  // BNVC, BNEZALC, BNEC / DADDI (pre-r6)
      if (kArchVariant == kMips64r6) {
        if (rs_reg >= rt_reg) {  // BNVC
6854 6855
          bool condition = is_int32(rs) && is_int32(rt) && is_int32(rs + rt);
          BranchCompactHelper(condition, 16);
6856 6857 6858 6859 6860 6861 6862 6863 6864 6865
        } else {
          if (rs_reg == 0) {  // BNEZALC
            BranchAndLinkCompactHelper(rt != 0, 16);
          } else {  // BNEC
            BranchCompactHelper(rt != rs, 16);
          }
        }
      }
      break;
    // ------------- Arithmetic instructions.
6866
    case ADDIU: {
6867 6868
      int32_t alu32_out = static_cast<int32_t>(rs + se_imm16);
      // Sign-extend result of 32bit operation into 64bit register.
6869
      SetResult(rt_reg, static_cast<int64_t>(alu32_out));
6870
      break;
6871
    }
6872
    case DADDIU:
6873
      SetResult(rt_reg, rs + se_imm16);
6874 6875
      break;
    case SLTI:
6876
      SetResult(rt_reg, rs < se_imm16 ? 1 : 0);
6877 6878
      break;
    case SLTIU:
6879
      SetResult(rt_reg, rs_u < static_cast<uint64_t>(se_imm16) ? 1 : 0);
6880 6881
      break;
    case ANDI:
6882
      SetResult(rt_reg, rs & oe_imm16);
6883 6884
      break;
    case ORI:
6885
      SetResult(rt_reg, rs | oe_imm16);
6886 6887
      break;
    case XORI:
6888
      SetResult(rt_reg, rs ^ oe_imm16);
6889
      break;
6890 6891 6892
    case LUI:
      if (rs_reg != 0) {
        // AUI instruction.
6893
        DCHECK_EQ(kArchVariant, kMips64r6);
6894 6895 6896 6897 6898 6899 6900 6901 6902 6903
        int32_t alu32_out = static_cast<int32_t>(rs + (se_imm16 << 16));
        SetResult(rt_reg, static_cast<int64_t>(alu32_out));
      } else {
        // LUI instruction.
        int32_t alu32_out = static_cast<int32_t>(oe_imm16 << 16);
        // Sign-extend result of 32bit operation into 64bit register.
        SetResult(rt_reg, static_cast<int64_t>(alu32_out));
      }
      break;
    case DAUI:
6904 6905
      DCHECK_EQ(kArchVariant, kMips64r6);
      DCHECK_NE(rs_reg, 0);
6906
      SetResult(rt_reg, rs + (se_imm16 << 16));
6907 6908 6909
      break;
    // ------------- Memory instructions.
    case LB:
6910
      set_register(rt_reg, ReadB(rs + se_imm16));
6911 6912
      break;
    case LH:
6913
      set_register(rt_reg, ReadH(rs + se_imm16, instr_.instr()));
6914 6915 6916 6917 6918 6919 6920
      break;
    case LWL: {
      // al_offset is offset of the effective address within an aligned word.
      uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
      uint8_t byte_shift = kInt32AlignmentMask - al_offset;
      uint32_t mask = (1 << byte_shift * 8) - 1;
      addr = rs + se_imm16 - al_offset;
6921
      int32_t val = ReadW(addr, instr_.instr());
6922 6923 6924
      val <<= byte_shift * 8;
      val |= rt & mask;
      set_register(rt_reg, static_cast<int64_t>(val));
6925 6926 6927
      break;
    }
    case LW:
6928
      set_register(rt_reg, ReadW(rs + se_imm16, instr_.instr()));
6929 6930
      break;
    case LWU:
6931
      set_register(rt_reg, ReadWU(rs + se_imm16, instr_.instr()));
6932 6933
      break;
    case LD:
6934
      set_register(rt_reg, Read2W(rs + se_imm16, instr_.instr()));
6935 6936
      break;
    case LBU:
6937
      set_register(rt_reg, ReadBU(rs + se_imm16));
6938 6939
      break;
    case LHU:
6940
      set_register(rt_reg, ReadHU(rs + se_imm16, instr_.instr()));
6941 6942 6943 6944 6945 6946 6947
      break;
    case LWR: {
      // al_offset is offset of the effective address within an aligned word.
      uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
      uint8_t byte_shift = kInt32AlignmentMask - al_offset;
      uint32_t mask = al_offset ? (~0 << (byte_shift + 1) * 8) : 0;
      addr = rs + se_imm16 - al_offset;
6948
      alu_out = ReadW(addr, instr_.instr());
6949 6950
      alu_out = static_cast<uint32_t> (alu_out) >> al_offset * 8;
      alu_out |= rt & mask;
6951
      set_register(rt_reg, alu_out);
6952 6953
      break;
    }
6954 6955 6956 6957 6958 6959
    case LDL: {
      // al_offset is offset of the effective address within an aligned word.
      uint8_t al_offset = (rs + se_imm16) & kInt64AlignmentMask;
      uint8_t byte_shift = kInt64AlignmentMask - al_offset;
      uint64_t mask = (1UL << byte_shift * 8) - 1;
      addr = rs + se_imm16 - al_offset;
6960
      alu_out = Read2W(addr, instr_.instr());
6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971
      alu_out <<= byte_shift * 8;
      alu_out |= rt & mask;
      set_register(rt_reg, alu_out);
      break;
    }
    case LDR: {
      // al_offset is offset of the effective address within an aligned word.
      uint8_t al_offset = (rs + se_imm16) & kInt64AlignmentMask;
      uint8_t byte_shift = kInt64AlignmentMask - al_offset;
      uint64_t mask = al_offset ? (~0UL << (byte_shift + 1) * 8) : 0UL;
      addr = rs + se_imm16 - al_offset;
6972
      alu_out = Read2W(addr, instr_.instr());
6973 6974 6975 6976 6977
      alu_out = alu_out >> al_offset * 8;
      alu_out |= rt & mask;
      set_register(rt_reg, alu_out);
      break;
    }
6978
    case SB:
6979
      WriteB(rs + se_imm16, static_cast<int8_t>(rt));
6980 6981
      break;
    case SH:
6982
      WriteH(rs + se_imm16, static_cast<uint16_t>(rt), instr_.instr());
6983 6984 6985 6986 6987 6988
      break;
    case SWL: {
      uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
      uint8_t byte_shift = kInt32AlignmentMask - al_offset;
      uint32_t mask = byte_shift ? (~0 << (al_offset + 1) * 8) : 0;
      addr = rs + se_imm16 - al_offset;
6989
      uint64_t mem_value = ReadW(addr, instr_.instr()) & mask;
6990
      mem_value |= static_cast<uint32_t>(rt) >> byte_shift * 8;
6991
      WriteW(addr, static_cast<int32_t>(mem_value), instr_.instr());
6992 6993 6994
      break;
    }
    case SW:
6995
      WriteW(rs + se_imm16, static_cast<int32_t>(rt), instr_.instr());
6996
      break;
6997
    case SD:
6998
      Write2W(rs + se_imm16, rt, instr_.instr());
6999 7000 7001 7002 7003
      break;
    case SWR: {
      uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
      uint32_t mask = (1 << al_offset * 8) - 1;
      addr = rs + se_imm16 - al_offset;
7004
      uint64_t mem_value = ReadW(addr, instr_.instr());
7005
      mem_value = (rt << al_offset * 8) | (mem_value & mask);
7006
      WriteW(addr, static_cast<int32_t>(mem_value), instr_.instr());
7007 7008
      break;
    }
7009 7010 7011 7012 7013
    case SDL: {
      uint8_t al_offset = (rs + se_imm16) & kInt64AlignmentMask;
      uint8_t byte_shift = kInt64AlignmentMask - al_offset;
      uint64_t mask = byte_shift ? (~0UL << (al_offset + 1) * 8) : 0;
      addr = rs + se_imm16 - al_offset;
7014
      uint64_t mem_value = Read2W(addr, instr_.instr()) & mask;
7015
      mem_value |= static_cast<uint64_t>(rt) >> byte_shift * 8;
7016
      Write2W(addr, mem_value, instr_.instr());
7017 7018 7019 7020 7021 7022
      break;
    }
    case SDR: {
      uint8_t al_offset = (rs + se_imm16) & kInt64AlignmentMask;
      uint64_t mask = (1UL << al_offset * 8) - 1;
      addr = rs + se_imm16 - al_offset;
7023
      uint64_t mem_value = Read2W(addr, instr_.instr());
7024
      mem_value = (rt << al_offset * 8) | (mem_value & mask);
7025
      Write2W(addr, mem_value, instr_.instr());
7026 7027
      break;
    }
7028 7029
    case LL: {
      // LL/SC sequence cannot be simulated properly
7030
      DCHECK_EQ(kArchVariant, kMips64r2);
7031 7032 7033 7034 7035
      set_register(rt_reg, ReadW(rs + se_imm16, instr_.instr()));
      break;
    }
    case SC: {
      // LL/SC sequence cannot be simulated properly
7036
      DCHECK_EQ(kArchVariant, kMips64r2);
7037 7038 7039 7040 7041 7042
      WriteW(rs + se_imm16, static_cast<int32_t>(rt), instr_.instr());
      set_register(rt_reg, 1);
      break;
    }
    case LLD: {
      // LL/SC sequence cannot be simulated properly
7043
      DCHECK_EQ(kArchVariant, kMips64r2);
7044 7045 7046 7047 7048
      set_register(rt_reg, ReadD(rs + se_imm16, instr_.instr()));
      break;
    }
    case SCD: {
      // LL/SC sequence cannot be simulated properly
7049
      DCHECK_EQ(kArchVariant, kMips64r2);
7050 7051 7052 7053
      WriteD(rs + se_imm16, rt, instr_.instr());
      set_register(rt_reg, 1);
      break;
    }
7054
    case LWC1:
7055
      set_fpu_register(ft_reg, kFPUInvalidResult);  // Trash upper 32 bits.
7056 7057
      set_fpu_register_word(ft_reg,
                            ReadW(rs + se_imm16, instr_.instr(), FLOAT_DOUBLE));
7058 7059
      break;
    case LDC1:
7060
      set_fpu_register_double(ft_reg, ReadD(rs + se_imm16, instr_.instr()));
7061
      TraceMemRd(addr, get_fpu_register(ft_reg), DOUBLE);
7062
      break;
7063 7064
    case SWC1: {
      int32_t alu_out_32 = static_cast<int32_t>(get_fpu_register(ft_reg));
7065
      WriteW(rs + se_imm16, alu_out_32, instr_.instr());
7066 7067
      break;
    }
7068
    case SDC1:
7069
      WriteD(rs + se_imm16, get_fpu_register_double(ft_reg), instr_.instr());
7070
      TraceMemWr(rs + se_imm16, get_fpu_register(ft_reg), DWORD);
7071
      break;
7072 7073 7074
    // ------------- PC-Relative instructions.
    case PCREL: {
      // rt field: checking 5-bits.
7075
      int32_t imm21 = instr_.Imm21Value();
7076
      int64_t current_pc = get_pc();
7077 7078 7079 7080 7081 7082 7083 7084 7085 7086
      uint8_t rt = (imm21 >> kImm16Bits);
      switch (rt) {
        case ALUIPC:
          addr = current_pc + (se_imm16 << 16);
          alu_out = static_cast<int64_t>(~0x0FFFF) & addr;
          break;
        case AUIPC:
          alu_out = current_pc + (se_imm16 << 16);
          break;
        default: {
7087
          int32_t imm19 = instr_.Imm19Value();
7088 7089 7090 7091 7092 7093
          // rt field: checking the most significant 3-bits.
          rt = (imm21 >> kImm18Bits);
          switch (rt) {
            case LDPC:
              addr =
                  (current_pc & static_cast<int64_t>(~0x7)) + (se_imm18 << 3);
7094
              alu_out = Read2W(addr, instr_.instr());
7095 7096 7097 7098 7099 7100 7101
              break;
            default: {
              // rt field: checking the most significant 2-bits.
              rt = (imm21 >> kImm19Bits);
              switch (rt) {
                case LWUPC: {
                  // Set sign.
7102 7103 7104
                  imm19 <<= (kOpcodeBits + kRsBits + 2);
                  imm19 >>= (kOpcodeBits + kRsBits + 2);
                  addr = current_pc + (imm19 << 2);
7105 7106 7107 7108 7109 7110
                  uint32_t* ptr = reinterpret_cast<uint32_t*>(addr);
                  alu_out = *ptr;
                  break;
                }
                case LWPC: {
                  // Set sign.
7111 7112 7113
                  imm19 <<= (kOpcodeBits + kRsBits + 2);
                  imm19 >>= (kOpcodeBits + kRsBits + 2);
                  addr = current_pc + (imm19 << 2);
7114 7115 7116 7117
                  int32_t* ptr = reinterpret_cast<int32_t*>(addr);
                  alu_out = *ptr;
                  break;
                }
7118 7119
                case ADDIUPC: {
                  int64_t se_imm19 =
7120
                      imm19 | ((imm19 & 0x40000) ? 0xFFFFFFFFFFF80000 : 0);
7121 7122
                  alu_out = current_pc + (se_imm19 << 2);
                  break;
7123
                }
7124 7125 7126 7127 7128 7129 7130 7131 7132 7133
                default:
                  UNREACHABLE();
                  break;
              }
              break;
            }
          }
          break;
        }
      }
7134
      SetResult(rs_reg, alu_out);
7135 7136
      break;
    }
7137 7138 7139 7140
    case SPECIAL3: {
      switch (instr_.FunctionFieldRaw()) {
        case LL_R6: {
          // LL/SC sequence cannot be simulated properly
7141
          DCHECK_EQ(kArchVariant, kMips64r6);
7142 7143 7144 7145 7146 7147 7148
          int64_t base = get_register(instr_.BaseValue());
          int32_t offset9 = instr_.Imm9Value();
          set_register(rt_reg, ReadW(base + offset9, instr_.instr()));
          break;
        }
        case LLD_R6: {
          // LL/SC sequence cannot be simulated properly
7149
          DCHECK_EQ(kArchVariant, kMips64r6);
7150 7151 7152 7153 7154 7155 7156
          int64_t base = get_register(instr_.BaseValue());
          int32_t offset9 = instr_.Imm9Value();
          set_register(rt_reg, ReadD(base + offset9, instr_.instr()));
          break;
        }
        case SC_R6: {
          // LL/SC sequence cannot be simulated properly
7157
          DCHECK_EQ(kArchVariant, kMips64r6);
7158 7159 7160 7161 7162 7163 7164 7165
          int64_t base = get_register(instr_.BaseValue());
          int32_t offset9 = instr_.Imm9Value();
          WriteW(base + offset9, static_cast<int32_t>(rt), instr_.instr());
          set_register(rt_reg, 1);
          break;
        }
        case SCD_R6: {
          // LL/SC sequence cannot be simulated properly
7166
          DCHECK_EQ(kArchVariant, kMips64r6);
7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178
          int64_t base = get_register(instr_.BaseValue());
          int32_t offset9 = instr_.Imm9Value();
          WriteD(base + offset9, rt, instr_.instr());
          set_register(rt_reg, 1);
          break;
        }
        default:
          UNREACHABLE();
      }
      break;
    }

7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203
    case MSA:
      switch (instr_.MSAMinorOpcodeField()) {
        case kMsaMinorI8:
          DecodeTypeMsaI8();
          break;
        case kMsaMinorI5:
          DecodeTypeMsaI5();
          break;
        case kMsaMinorI10:
          DecodeTypeMsaI10();
          break;
        case kMsaMinorELM:
          DecodeTypeMsaELM();
          break;
        case kMsaMinorBIT:
          DecodeTypeMsaBIT();
          break;
        case kMsaMinorMI10:
          DecodeTypeMsaMI10();
          break;
        default:
          UNREACHABLE();
          break;
      }
      break;
7204 7205 7206 7207 7208 7209 7210 7211 7212
    default:
      UNREACHABLE();
  }

  if (execute_branch_delay_instruction) {
    // Execute branch delay slot
    // We don't check for end_sim_pc. First it should not be met as the current
    // pc is valid. Secondly a jump should always execute its branch delay slot.
    Instruction* branch_delay_instr =
7213
        reinterpret_cast<Instruction*>(get_pc() + kInstrSize);
7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224
    BranchDelayInstructionDecode(branch_delay_instr);
  }

  // If needed update pc after the branch delay execution.
  if (next_pc != bad_ra) {
    set_pc(next_pc);
  }
}


// Type 3: instructions using a 26 bytes immediate. (e.g. j, jal).
7225 7226
void Simulator::DecodeTypeJump() {
  SimInstruction simInstr = instr_;
7227
  // Get current pc.
7228
  int64_t current_pc = get_pc();
7229
  // Get unchanged bits of pc.
7230
  int64_t pc_high_bits = current_pc & 0xFFFFFFFFF0000000;
7231
  // Next pc.
7232
  int64_t next_pc = pc_high_bits | (simInstr.Imm26Value() << 2);
7233 7234 7235 7236 7237

  // Execute branch delay slot.
  // We don't check for end_sim_pc. First it should not be met as the current pc
  // is valid. Secondly a jump should always execute its branch delay slot.
  Instruction* branch_delay_instr =
7238
      reinterpret_cast<Instruction*>(current_pc + kInstrSize);
7239 7240 7241 7242
  BranchDelayInstructionDecode(branch_delay_instr);

  // Update pc and ra if necessary.
  // Do this after the branch delay execution.
7243
  if (simInstr.IsLinkingInstruction()) {
7244
    set_register(31, current_pc + 2 * kInstrSize);
7245 7246 7247 7248 7249 7250 7251 7252 7253
  }
  set_pc(next_pc);
  pc_modified_ = true;
}


// Executes the current instruction.
void Simulator::InstructionDecode(Instruction* instr) {
  if (v8::internal::FLAG_check_icache) {
7254
    CheckICache(i_cache(), instr);
7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267
  }
  pc_modified_ = false;

  v8::internal::EmbeddedVector<char, 256> buffer;

  if (::v8::internal::FLAG_trace_sim) {
    SNPrintF(trace_buf_, " ");
    disasm::NameConverter converter;
    disasm::Disassembler dasm(converter);
    // Use a reasonably large buffer.
    dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(instr));
  }

7268 7269
  instr_ = instr;
  switch (instr_.InstructionType()) {
7270
    case Instruction::kRegisterType:
7271
      DecodeTypeRegister();
7272 7273
      break;
    case Instruction::kImmediateType:
7274
      DecodeTypeImmediate();
7275 7276
      break;
    case Instruction::kJumpType:
7277
      DecodeTypeJump();
7278 7279 7280 7281 7282 7283
      break;
    default:
      UNSUPPORTED();
  }

  if (::v8::internal::FLAG_trace_sim) {
7284 7285 7286
    PrintF("  0x%08" PRIxPTR "   %-44s   %s\n",
           reinterpret_cast<intptr_t>(instr), buffer.start(),
           trace_buf_.start());
7287 7288 7289
  }

  if (!pc_modified_) {
7290
    set_register(pc, reinterpret_cast<int64_t>(instr) + kInstrSize);
7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310
  }
}



void Simulator::Execute() {
  // Get the PC to simulate. Cannot use the accessor here as we need the
  // raw PC value and not the one used as input to arithmetic instructions.
  int64_t program_counter = get_pc();
  if (::v8::internal::FLAG_stop_sim_at == 0) {
    // Fast version of the dispatch loop without checking whether the simulator
    // should be stopping at a particular executed instruction.
    while (program_counter != end_sim_pc) {
      Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
      icount_++;
      InstructionDecode(instr);
      program_counter = get_pc();
    }
  } else {
    // FLAG_stop_sim_at is at the non-default value. Stop in the debugger when
7311
    // we reach the particular instruction count.
7312 7313 7314
    while (program_counter != end_sim_pc) {
      Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
      icount_++;
7315
      if (icount_ == static_cast<int64_t>(::v8::internal::FLAG_stop_sim_at)) {
7316 7317 7318 7319 7320 7321 7322 7323 7324 7325
        MipsDebugger dbg(this);
        dbg.Debug();
      } else {
        InstructionDecode(instr);
      }
      program_counter = get_pc();
    }
  }
}

7326
void Simulator::CallInternal(Address entry) {
7327 7328 7329
  // Adjust JS-based stack limit to C-based stack limit.
  isolate_->stack_guard()->AdjustStackLimitForSimulator();

7330
  // Prepare to execute the code at entry.
7331
  set_register(pc, static_cast<int64_t>(entry));
7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394
  // Put down marker for end of simulation. The simulator will stop simulation
  // when the PC reaches this value. By saving the "end simulation" value into
  // the LR the simulation stops when returning to this call point.
  set_register(ra, end_sim_pc);

  // Remember the values of callee-saved registers.
  // The code below assumes that r9 is not used as sb (static base) in
  // simulator code and therefore is regarded as a callee-saved register.
  int64_t s0_val = get_register(s0);
  int64_t s1_val = get_register(s1);
  int64_t s2_val = get_register(s2);
  int64_t s3_val = get_register(s3);
  int64_t s4_val = get_register(s4);
  int64_t s5_val = get_register(s5);
  int64_t s6_val = get_register(s6);
  int64_t s7_val = get_register(s7);
  int64_t gp_val = get_register(gp);
  int64_t sp_val = get_register(sp);
  int64_t fp_val = get_register(fp);

  // Set up the callee-saved registers with a known value. To be able to check
  // that they are preserved properly across JS execution.
  int64_t callee_saved_value = icount_;
  set_register(s0, callee_saved_value);
  set_register(s1, callee_saved_value);
  set_register(s2, callee_saved_value);
  set_register(s3, callee_saved_value);
  set_register(s4, callee_saved_value);
  set_register(s5, callee_saved_value);
  set_register(s6, callee_saved_value);
  set_register(s7, callee_saved_value);
  set_register(gp, callee_saved_value);
  set_register(fp, callee_saved_value);

  // Start the simulation.
  Execute();

  // Check that the callee-saved registers have been preserved.
  CHECK_EQ(callee_saved_value, get_register(s0));
  CHECK_EQ(callee_saved_value, get_register(s1));
  CHECK_EQ(callee_saved_value, get_register(s2));
  CHECK_EQ(callee_saved_value, get_register(s3));
  CHECK_EQ(callee_saved_value, get_register(s4));
  CHECK_EQ(callee_saved_value, get_register(s5));
  CHECK_EQ(callee_saved_value, get_register(s6));
  CHECK_EQ(callee_saved_value, get_register(s7));
  CHECK_EQ(callee_saved_value, get_register(gp));
  CHECK_EQ(callee_saved_value, get_register(fp));

  // Restore callee-saved registers with the original value.
  set_register(s0, s0_val);
  set_register(s1, s1_val);
  set_register(s2, s2_val);
  set_register(s3, s3_val);
  set_register(s4, s4_val);
  set_register(s5, s5_val);
  set_register(s6, s6_val);
  set_register(s7, s7_val);
  set_register(gp, gp_val);
  set_register(sp, sp_val);
  set_register(fp, fp_val);
}

7395
intptr_t Simulator::CallImpl(Address entry, int argument_count,
7396 7397
                             const intptr_t* arguments) {
  constexpr int kRegisterPassedArguments = 8;
7398 7399 7400
  // Set up arguments.

  // First four arguments passed in registers in both ABI's.
7401 7402 7403 7404 7405
  int reg_arg_count = std::min(kRegisterPassedArguments, argument_count);
  if (reg_arg_count > 0) set_register(a0, arguments[0]);
  if (reg_arg_count > 1) set_register(a1, arguments[1]);
  if (reg_arg_count > 2) set_register(a2, arguments[2]);
  if (reg_arg_count > 2) set_register(a3, arguments[3]);
7406

7407 7408
  // Up to eight arguments passed in registers in N64 ABI.
  // TODO(plind): N64 ABI calls these regs a4 - a7. Clarify this.
7409 7410 7411 7412
  if (reg_arg_count > 4) set_register(a4, arguments[4]);
  if (reg_arg_count > 5) set_register(a5, arguments[5]);
  if (reg_arg_count > 6) set_register(a6, arguments[6]);
  if (reg_arg_count > 7) set_register(a7, arguments[7]);
7413 7414 7415 7416

  // Remaining arguments passed on stack.
  int64_t original_stack = get_register(sp);
  // Compute position of stack on entry to generated code.
7417 7418
  int stack_args_count = argument_count - reg_arg_count;
  int stack_args_size = stack_args_count * sizeof(*arguments) + kCArgsSlotsSize;
7419 7420 7421 7422 7423 7424 7425
  int64_t entry_stack = original_stack - stack_args_size;

  if (base::OS::ActivationFrameAlignment() != 0) {
    entry_stack &= -base::OS::ActivationFrameAlignment();
  }
  // Store remaining arguments on stack, from low to high memory.
  intptr_t* stack_argument = reinterpret_cast<intptr_t*>(entry_stack);
7426 7427
  memcpy(stack_argument + kCArgSlotCount, arguments + reg_arg_count,
         stack_args_count * sizeof(*arguments));
7428 7429 7430 7431 7432 7433 7434 7435
  set_register(sp, entry_stack);

  CallInternal(entry);

  // Pop stack passed arguments.
  CHECK_EQ(entry_stack, get_register(sp));
  set_register(sp, original_stack);

7436
  return get_register(v0);
7437 7438
}

7439
double Simulator::CallFP(Address entry, double d0, double d1) {
7440
  if (!IsMipsSoftFloatABI) {
7441
    const FPURegister fparg2 = f13;
7442 7443 7444 7445
    set_fpu_register_double(f12, d0);
    set_fpu_register_double(fparg2, d1);
  } else {
    int buffer[2];
7446
    DCHECK(sizeof(buffer[0]) * 2 == sizeof(d0));
7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479
    memcpy(buffer, &d0, sizeof(d0));
    set_dw_register(a0, buffer);
    memcpy(buffer, &d1, sizeof(d1));
    set_dw_register(a2, buffer);
  }
  CallInternal(entry);
  if (!IsMipsSoftFloatABI) {
    return get_fpu_register_double(f0);
  } else {
    return get_double_from_register_pair(v0);
  }
}


uintptr_t Simulator::PushAddress(uintptr_t address) {
  int64_t new_sp = get_register(sp) - sizeof(uintptr_t);
  uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp);
  *stack_slot = address;
  set_register(sp, new_sp);
  return new_sp;
}


uintptr_t Simulator::PopAddress() {
  int64_t current_sp = get_register(sp);
  uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(current_sp);
  uintptr_t address = *stack_slot;
  set_register(sp, current_sp + sizeof(uintptr_t));
  return address;
}


#undef UNSUPPORTED
7480 7481
}  // namespace internal
}  // namespace v8
7482 7483 7484 7485

#endif  // USE_SIMULATOR

#endif  // V8_TARGET_ARCH_MIPS64