simulator-mips64.cc 186 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// 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

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

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

namespace v8 {
namespace internal {

27 28
// Util functions.
inline bool HaveSameSign(int64_t a, int64_t b) { return ((a ^ b) >= 0); }
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

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;

  u0 = u & 0xffffffffL;
  u1 = u >> 32;
  v0 = v & 0xffffffffL;
  v1 = v >> 32;

  w0 = u0 * v0;
  t = u1 * v0 + (w0 >> 32);
  w1 = t & 0xffffffffL;
  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:
  // We set the breakpoint code to 0xfffff to easily recognize it.
  static const Instr kBreakpointInstr = SPECIAL | BREAK | 0xfffff << 6;
  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();
};

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

void MipsDebugger::Stop(Instruction* instr) {
  // Get the stop code.
  uint32_t code = instr->Bits(25, 6);
104
  PrintF("Simulator hit (%u)\n", code);
105 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 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
  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.
  if (sim_->break_pc_ != NULL) {
    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) {
  if (sim_->break_pc_ != NULL) {
    sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
  }

  sim_->break_pc_ = NULL;
  sim_->break_instr_ = 0;
  return true;
}


void MipsDebugger::UndoBreakpoints() {
  if (sim_->break_pc_ != NULL) {
    sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
  }
}


void MipsDebugger::RedoBreakpoints() {
  if (sim_->break_pc_ != NULL) {
    sim_->break_pc_->SetInstructionBits(kBreakpointInstr);
  }
}


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

  PrintF("\n");
  // at, v0, a0.
209 210
  PrintF("%3s: 0x%016" PRIx64 " %14" PRId64 "\t%3s: 0x%016" PRIx64 " %14" PRId64
         "\t%3s: 0x%016" PRIx64 " %14" PRId64 "\n",
211 212
         REG_INFO(1), REG_INFO(2), REG_INFO(4));
  // v1, a1.
213 214
  PrintF("%34s\t%3s: 0x%016" PRIx64 "  %14" PRId64 " \t%3s: 0x%016" PRIx64
         "  %14" PRId64 " \n",
215 216
         "", REG_INFO(3), REG_INFO(5));
  // a2.
217 218
  PrintF("%34s\t%34s\t%3s: 0x%016" PRIx64 "  %14" PRId64 " \n", "", "",
         REG_INFO(6));
219
  // a3.
220 221
  PrintF("%34s\t%34s\t%3s: 0x%016" PRIx64 "  %14" PRId64 " \n", "", "",
         REG_INFO(7));
222 223 224
  PrintF("\n");
  // a4-t3, s0-s7
  for (int i = 0; i < 8; i++) {
225 226 227
    PrintF("%3s: 0x%016" PRIx64 "  %14" PRId64 " \t%3s: 0x%016" PRIx64
           "  %14" PRId64 " \n",
           REG_INFO(8 + i), REG_INFO(16 + i));
228 229 230
  }
  PrintF("\n");
  // t8, k0, LO.
231 232
  PrintF("%3s: 0x%016" PRIx64 "  %14" PRId64 " \t%3s: 0x%016" PRIx64
         "  %14" PRId64 " \t%3s: 0x%016" PRIx64 "  %14" PRId64 " \n",
233 234
         REG_INFO(24), REG_INFO(26), REG_INFO(32));
  // t9, k1, HI.
235 236
  PrintF("%3s: 0x%016" PRIx64 "  %14" PRId64 " \t%3s: 0x%016" PRIx64
         "  %14" PRId64 " \t%3s: 0x%016" PRIx64 "  %14" PRId64 " \n",
237 238
         REG_INFO(25), REG_INFO(27), REG_INFO(33));
  // sp, fp, gp.
239 240
  PrintF("%3s: 0x%016" PRIx64 "  %14" PRId64 " \t%3s: 0x%016" PRIx64
         "  %14" PRId64 " \t%3s: 0x%016" PRIx64 "  %14" PRId64 " \n",
241 242
         REG_INFO(29), REG_INFO(30), REG_INFO(28));
  // pc.
243 244
  PrintF("%3s: 0x%016" PRIx64 "  %14" PRId64 " \t%3s: 0x%016" PRIx64
         "  %14" PRId64 " \n",
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
         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.
262 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
  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));
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

#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()));
332
      PrintF("  0x%016" PRIx64 "   %s\n", sim_->get_pc(), buffer.start());
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
      last_pc = sim_->get_pc();
    }
    char* line = ReadLine("sim> ");
    if (line == NULL) {
      break;
    } else {
      char* last_input = sim_->last_debugger_input();
      if (strcmp(line, "\n") == 0 && last_input != NULL) {
        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");
          sim_->set_pc(sim_->get_pc() + Instruction::kInstrSize);
        }
      } 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);
383 384
              PrintF("%s: 0x%08" PRIx64 "  %" PRId64 "  \n", arg1, value,
                     value);
385 386 387
            } else if (fpuregnum != kInvalidFPURegister) {
              value = GetFPURegisterValue(fpuregnum);
              dvalue = GetFPURegisterValueDouble(fpuregnum);
388
              PrintF("%3s: 0x%016" PRIx64 "  %16.4e\n",
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
                     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);
                value &= 0xffffffffUL;
                fvalue = GetFPURegisterValueFloat(fpuregnum);
405
                PrintF("%s: 0x%08" PRIx64 "  %11.4e\n", arg1, value, fvalue);
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
              } 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;
          OFStream os(stdout);
          if (GetValue(arg1, &value)) {
            Object* obj = reinterpret_cast<Object*>(value);
            os << arg1 << ": \n";
#ifdef DEBUG
            obj->Print(os);
            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) {
        int64_t* cur = NULL;
        int64_t* end = NULL;
        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) {
464
          PrintF("  0x%012" PRIxPTR " :  0x%016" PRIx64 "  %14" PRId64 " ",
465 466 467
                 reinterpret_cast<intptr_t>(cur), *cur, *cur);
          HeapObject* obj = reinterpret_cast<HeapObject*>(*cur);
          int64_t value = *cur;
468
          Heap* current_heap = sim_->isolate_->heap();
469 470
          if (((value & 1) == 0) ||
              current_heap->ContainsSlow(obj->address())) {
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
            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;

        byte* cur = NULL;
        byte* end = NULL;

        if (argc == 1) {
          cur = reinterpret_cast<byte*>(sim_->get_pc());
          end = cur + (10 * Instruction::kInstrSize);
        } 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>.
              end = cur + (10 * Instruction::kInstrSize);
            }
          } 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.
              end = cur + (value * Instruction::kInstrSize);
            }
          }
        } else {
          int64_t value1;
          int64_t value2;
          if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
            cur = reinterpret_cast<byte*>(value1);
            end = cur + (value2 * Instruction::kInstrSize);
          }
        }

        while (cur < end) {
          dasm.InstructionDecode(buffer, cur);
527 528
          PrintF("  0x%08" PRIxPTR "   %s\n", reinterpret_cast<intptr_t>(cur),
                 buffer.start());
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 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 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
          cur += Instruction::kInstrSize;
        }
      } 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) {
        if (!DeleteBreakpoint(NULL)) {
          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;
        intptr_t stop_pc = sim_->get_pc() -
            2 * Instruction::kInstrSize;
        Instruction* stop_instr = reinterpret_cast<Instruction*>(stop_pc);
        Instruction* msg_address =
          reinterpret_cast<Instruction*>(stop_pc +
              Instruction::kInstrSize);
        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;

        byte* cur = NULL;
        byte* end = NULL;

        if (argc == 1) {
          cur = reinterpret_cast<byte*>(sim_->get_pc());
          end = cur + (10 * Instruction::kInstrSize);
        } else if (argc == 2) {
          int64_t value;
          if (GetValue(arg1, &value)) {
            cur = reinterpret_cast<byte*>(value);
            // no length parameter passed, assume 10 instructions
            end = cur + (10 * Instruction::kInstrSize);
          }
        } else {
          int64_t value1;
          int64_t value2;
          if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
            cur = reinterpret_cast<byte*>(value1);
            end = cur + (value2 * Instruction::kInstrSize);
          }
        }

        while (cur < end) {
          dasm.InstructionDecode(buffer, cur);
649 650
          PrintF("  0x%08" PRIxPTR "   %s\n", reinterpret_cast<intptr_t>(cur),
                 buffer.start());
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 684 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 716 717 718
          cur += Instruction::kInstrSize;
        }
      } 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");
        PrintF("    stop and and give control to the Debugger.\n");
        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
}


static bool ICacheMatch(void* one, void* two) {
719 720
  DCHECK((reinterpret_cast<intptr_t>(one) & CachePage::kPageMask) == 0);
  DCHECK((reinterpret_cast<intptr_t>(two) & CachePage::kPageMask) == 0);
721 722 723 724 725 726 727 728 729
  return one == two;
}


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


730
static bool AllOnOnePage(uintptr_t start, size_t size) {
731 732 733 734 735 736 737 738 739 740 741
  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;
}

742 743
void Simulator::FlushICache(base::CustomMatcherHashMap* i_cache,
                            void* start_addr, size_t size) {
744 745 746 747 748 749 750 751 752 753 754
  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;
755
    DCHECK_EQ((int64_t)0, start & CachePage::kPageMask);
756 757 758 759 760 761 762
    offset = 0;
  }
  if (size != 0) {
    FlushOnePage(i_cache, start, size);
  }
}

763 764
CachePage* Simulator::GetCachePage(base::CustomMatcherHashMap* i_cache,
                                   void* page) {
lpy's avatar
lpy committed
765
  base::HashMap::Entry* entry = i_cache->LookupOrInsert(page, ICacheHash(page));
766 767 768 769 770 771 772 773 774
  if (entry->value == NULL) {
    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.
775 776
void Simulator::FlushOnePage(base::CustomMatcherHashMap* i_cache,
                             intptr_t start, size_t size) {
777 778 779 780
  DCHECK(size <= CachePage::kPageSize);
  DCHECK(AllOnOnePage(start, size - 1));
  DCHECK((start & CachePage::kLineMask) == 0);
  DCHECK((size & CachePage::kLineMask) == 0);
781 782 783 784 785 786 787
  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);
}

788 789
void Simulator::CheckICache(base::CustomMatcherHashMap* i_cache,
                            Instruction* instr) {
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
  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),
                       cache_page->CachedData(offset),
                       Instruction::kInstrSize));
  } else {
    // Cache miss.  Load memory into the cache.
    memcpy(cached_line, line, CachePage::kLineLength);
    *cache_valid_byte = CachePage::LINE_VALID;
  }
}


void Simulator::Initialize(Isolate* isolate) {
  if (isolate->simulator_initialized()) return;
  isolate->set_simulator_initialized(true);
  ::v8::internal::ExternalReference::set_redirector(isolate,
                                                    &RedirectExternalReference);
}


Simulator::Simulator(Isolate* isolate) : isolate_(isolate) {
  i_cache_ = isolate_->simulator_i_cache();
  if (i_cache_ == NULL) {
822
    i_cache_ = new base::CustomMatcherHashMap(&ICacheMatch);
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
    isolate_->set_simulator_i_cache(i_cache_);
  }
  Initialize(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;
  break_pc_ = NULL;
  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++) {
842 843
    FPUregisters_[2 * i] = 0;
    FPUregisters_[2 * i + 1] = 0;  // upper part for MSA ASE
844
  }
845 846 847 848 849 850

  if (kArchVariant == kMips64r6) {
    FCSR_ = kFCSRNaN2008FlagMask;
  } else {
    FCSR_ = 0;
  }
851 852 853 854 855 856 857 858 859 860 861 862 863 864

  // 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;

  last_debugger_input_ = NULL;
}


865
Simulator::~Simulator() { free(stack_); }
866 867 868 869 870 871 872 873 874 875 876


// When the generated code calls an external reference we need to catch that in
// the simulator.  The external reference will be a function compiled for the
// host architecture.  We need to call that function instead of trying to
// execute it with the simulator.  We do that by redirecting the external
// reference to a swi (software-interrupt) instruction that is handled by
// the simulator.  We write the original destination of the jump just at a known
// offset from the swi instruction so the simulator knows what to call.
class Redirection {
 public:
877 878
  Redirection(Isolate* isolate, void* external_function,
              ExternalReference::Type type)
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
      : external_function_(external_function),
        swi_instruction_(rtCallRedirInstr),
        type_(type),
        next_(NULL) {
    next_ = isolate->simulator_redirection();
    Simulator::current(isolate)->
        FlushICache(isolate->simulator_i_cache(),
                    reinterpret_cast<void*>(&swi_instruction_),
                    Instruction::kInstrSize);
    isolate->set_simulator_redirection(this);
  }

  void* address_of_swi_instruction() {
    return reinterpret_cast<void*>(&swi_instruction_);
  }

  void* external_function() { return external_function_; }
  ExternalReference::Type type() { return type_; }

898
  static Redirection* Get(Isolate* isolate, void* external_function,
899 900 901 902 903
                          ExternalReference::Type type) {
    Redirection* current = isolate->simulator_redirection();
    for (; current != NULL; current = current->next_) {
      if (current->external_function_ == external_function) return current;
    }
904
    return new Redirection(isolate, external_function, type);
905 906 907 908 909
  }

  static Redirection* FromSwiInstruction(Instruction* swi_instruction) {
    char* addr_of_swi = reinterpret_cast<char*>(swi_instruction);
    char* addr_of_redirection =
910
        addr_of_swi - offsetof(Redirection, swi_instruction_);
911 912 913 914 915 916 917 918 919
    return reinterpret_cast<Redirection*>(addr_of_redirection);
  }

  static void* ReverseRedirection(int64_t reg) {
    Redirection* redirection = FromSwiInstruction(
        reinterpret_cast<Instruction*>(reinterpret_cast<void*>(reg)));
    return redirection->external_function();
  }

920 921 922 923 924 925 926 927
  static void DeleteChain(Redirection* redirection) {
    while (redirection != nullptr) {
      Redirection* next = redirection->next_;
      delete redirection;
      redirection = next;
    }
  }

928 929 930 931 932 933 934 935
 private:
  void* external_function_;
  uint32_t swi_instruction_;
  ExternalReference::Type type_;
  Redirection* next_;
};


936
// static
937 938
void Simulator::TearDown(base::CustomMatcherHashMap* i_cache,
                         Redirection* first) {
939 940
  Redirection::DeleteChain(first);
  if (i_cache != nullptr) {
lpy's avatar
lpy committed
941
    for (base::HashMap::Entry* entry = i_cache->Start(); entry != nullptr;
942 943 944 945 946 947 948 949
         entry = i_cache->Next(entry)) {
      delete static_cast<CachePage*>(entry->value);
    }
    delete i_cache;
  }
}


950 951
void* Simulator::RedirectExternalReference(Isolate* isolate,
                                           void* external_function,
952
                                           ExternalReference::Type type) {
953 954
  base::LockGuard<base::Mutex> lock_guard(
      isolate->simulator_redirection_mutex());
955
  Redirection* redirection = Redirection::Get(isolate, external_function, type);
956 957 958 959 960 961 962 963
  return redirection->address_of_swi_instruction();
}


// Get the active Simulator for the current thread.
Simulator* Simulator::current(Isolate* isolate) {
  v8::internal::Isolate::PerIsolateThreadData* isolate_data =
       isolate->FindOrAllocatePerThreadDataForThisThread();
964 965
  DCHECK(isolate_data != NULL);
  DCHECK(isolate_data != NULL);
966 967 968 969 970 971 972 973 974 975 976 977 978 979

  Simulator* sim = isolate_data->simulator();
  if (sim == NULL) {
    // 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) {
980
  DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
981 982 983 984 985 986 987 988 989 990
  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) {
991
  DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
992 993 994 995 996 997 998
  registers_[reg] = dbl[1];
  registers_[reg] = registers_[reg] << 32;
  registers_[reg] += dbl[0];
}


void Simulator::set_fpu_register(int fpureg, int64_t value) {
999
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1000
  FPUregisters_[fpureg * 2] = value;
1001 1002 1003 1004 1005
}


void Simulator::set_fpu_register_word(int fpureg, int32_t value) {
  // Set ONLY lower 32-bits, leaving upper bits untouched.
1006
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1007 1008
  int32_t* pword;
  if (kArchEndian == kLittle) {
1009
    pword = reinterpret_cast<int32_t*>(&FPUregisters_[fpureg * 2]);
1010
  } else {
1011
    pword = reinterpret_cast<int32_t*>(&FPUregisters_[fpureg * 2]) + 1;
1012
  }
1013 1014 1015 1016 1017 1018
  *pword = value;
}


void Simulator::set_fpu_register_hi_word(int fpureg, int32_t value) {
  // Set ONLY upper 32-bits, leaving lower bits untouched.
1019
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1020 1021
  int32_t* phiword;
  if (kArchEndian == kLittle) {
1022
    phiword = (reinterpret_cast<int32_t*>(&FPUregisters_[fpureg * 2])) + 1;
1023
  } else {
1024
    phiword = reinterpret_cast<int32_t*>(&FPUregisters_[fpureg * 2]);
1025
  }
1026 1027 1028 1029 1030
  *phiword = value;
}


void Simulator::set_fpu_register_float(int fpureg, float value) {
1031
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1032
  *bit_cast<float*>(&FPUregisters_[fpureg * 2]) = value;
1033 1034 1035 1036
}


void Simulator::set_fpu_register_double(int fpureg, double value) {
1037
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1038
  *bit_cast<double*>(&FPUregisters_[fpureg * 2]) = value;
1039 1040 1041 1042 1043 1044
}


// 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 {
1045
  DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1046 1047 1048 1049 1050 1051 1052 1053 1054
  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.
1055
  DCHECK((reg >= 0) && (reg < kNumSimuRegisters) && ((reg % 2) == 0));
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067

  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 {
1068
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1069
  return FPUregisters_[fpureg * 2];
1070 1071 1072 1073
}


int32_t Simulator::get_fpu_register_word(int fpureg) const {
1074
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1075
  return static_cast<int32_t>(FPUregisters_[fpureg * 2] & 0xffffffff);
1076 1077 1078 1079
}


int32_t Simulator::get_fpu_register_signed_word(int fpureg) const {
1080
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1081
  return static_cast<int32_t>(FPUregisters_[fpureg * 2] & 0xffffffff);
1082 1083 1084
}


1085
int32_t Simulator::get_fpu_register_hi_word(int fpureg) const {
1086
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1087
  return static_cast<int32_t>((FPUregisters_[fpureg * 2] >> 32) & 0xffffffff);
1088 1089 1090 1091
}


float Simulator::get_fpu_register_float(int fpureg) const {
1092
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1093
  return *bit_cast<float*>(const_cast<int64_t*>(&FPUregisters_[fpureg * 2]));
1094 1095 1096 1097
}


double Simulator::get_fpu_register_double(int fpureg) const {
1098
  DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1099
  return *bit_cast<double*>(&FPUregisters_[fpureg * 2]);
1100 1101
}

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
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);
}
1113 1114 1115 1116 1117 1118

// 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) {
1119
    const int fparg2 = 13;
1120 1121
    *x = get_fpu_register_double(12);
    *y = get_fpu_register_double(fparg2);
1122
    *z = static_cast<int32_t>(get_register(a2));
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
  } 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);
}


1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
void Simulator::set_fcsr_rounding_mode(FPURoundingMode mode) {
  FCSR_ |= mode & kFPURoundingModeMask;
}


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


1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
// 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);
  }

1201
  if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) {
1202 1203 1204 1205
    set_fcsr_bit(kFCSRUnderflowFlagBit, true);
    ret = true;
  }

1206
  if (rounded > max_int32 || rounded < min_int32) {
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
    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;
1221 1222
  // 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.
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
  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);
  }

1235
  if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) {
1236 1237 1238 1239
    set_fcsr_bit(kFCSRUnderflowFlagBit, true);
    ret = true;
  }

1240
  if (rounded >= max_int64 || rounded < min_int64) {
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
    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;
}


1251 1252
// Sets the rounding error codes in FCSR based on the result of the rounding.
// Returns true if the operation was invalid.
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
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;
  }

1272
  if (rounded > max_int32 || rounded < min_int32) {
1273 1274 1275 1276 1277 1278 1279 1280 1281
    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;
}

1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
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) {
1324 1325
    // 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.
1326 1327 1328 1329
    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);
1330
    } else if (rounded >= max_int64) {
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
      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) {
1386 1387
    // 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.
1388 1389 1390 1391
    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);
1392
    } else if (rounded >= max_int64) {
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
      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);
  }
}

1404 1405 1406 1407 1408

// 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;
1409 1410
  // 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.
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
  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;
  }

1428
  if (rounded >= max_int64 || rounded < min_int64) {
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
    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;
}


1439
// For cvt instructions only
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 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 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
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--;
      }
      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--;
      }
      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;
  }
}


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 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 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
// 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--;
      }
      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--;
      }
      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;
  }
}


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 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
// 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() {
  if (1) {  // Flag for this was removed.
    MipsDebugger dbg(this);
    dbg.Debug();
  } else {
    base::OS::Abort();
  }
}

1641
void Simulator::TraceRegWr(int64_t value, TraceType t) {
1642
  if (::v8::internal::FLAG_trace_sim) {
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
    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();
    }
1684 1685 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 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
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();
    }
  }
}

1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
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_);
    }
  }
}

1777
// TODO(plind): consider making icount_ printing a flag option.
1778
void Simulator::TraceMemRd(int64_t addr, int64_t value, TraceType t) {
1779
  if (::v8::internal::FLAG_trace_sim) {
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
    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();
    }
1817 1818 1819 1820 1821 1822 1823 1824
  }
}


void Simulator::TraceMemWr(int64_t addr, int64_t value, TraceType t) {
  if (::v8::internal::FLAG_trace_sim) {
    switch (t) {
      case BYTE:
1825 1826 1827
        SNPrintF(trace_buf_, "               %02" PRIx8 " --> [%016" PRIx64
                             "]    (%" PRId64 ")",
                 static_cast<uint8_t>(value), addr, icount_);
1828 1829
        break;
      case HALF:
1830 1831 1832
        SNPrintF(trace_buf_, "            %04" PRIx16 " --> [%016" PRIx64
                             "]    (%" PRId64 ")",
                 static_cast<uint16_t>(value), addr, icount_);
1833 1834
        break;
      case WORD:
1835 1836 1837
        SNPrintF(trace_buf_,
                 "        %08" PRIx32 " --> [%016" PRIx64 "]    (%" PRId64 ")",
                 static_cast<uint32_t>(value), addr, icount_);
1838 1839
        break;
      case DWORD:
1840
        SNPrintF(trace_buf_,
1841
                 "%016" PRIx64 "  --> [%016" PRIx64 "]    (%" PRId64 " )",
1842 1843
                 value, addr, icount_);
        break;
1844 1845
      default:
        UNREACHABLE();
1846 1847 1848 1849 1850 1851 1852
    }
  }
}


// TODO(plind): sign-extend and zero-extend not implmented properly
// on all the ReadXX functions, I don't think re-interpret cast does it.
1853
int32_t Simulator::ReadW(int64_t addr, Instruction* instr, TraceType t) {
1854 1855
  if (addr >=0 && addr < 0x400) {
    // This has to be a NULL-dereference, drop into debugger.
1856 1857
    PrintF("Memory read from bad address: 0x%08" PRIx64 " , pc=0x%08" PRIxPTR
           " \n",
1858 1859 1860
           addr, reinterpret_cast<intptr_t>(instr));
    DieOrDebug();
  }
1861
  if ((addr & 0x3) == 0 || kArchVariant == kMips64r6) {
1862
    int32_t* ptr = reinterpret_cast<int32_t*>(addr);
1863
    TraceMemRd(addr, static_cast<int64_t>(*ptr), t);
1864 1865
    return *ptr;
  }
1866
  PrintF("Unaligned read at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR "\n", addr,
1867 1868 1869 1870 1871 1872 1873 1874 1875
         reinterpret_cast<intptr_t>(instr));
  DieOrDebug();
  return 0;
}


uint32_t Simulator::ReadWU(int64_t addr, Instruction* instr) {
  if (addr >=0 && addr < 0x400) {
    // This has to be a NULL-dereference, drop into debugger.
1876 1877
    PrintF("Memory read from bad address: 0x%08" PRIx64 " , pc=0x%08" PRIxPTR
           " \n",
1878 1879 1880
           addr, reinterpret_cast<intptr_t>(instr));
    DieOrDebug();
  }
1881
  if ((addr & 0x3) == 0 || kArchVariant == kMips64r6) {
1882
    uint32_t* ptr = reinterpret_cast<uint32_t*>(addr);
1883
    TraceMemRd(addr, static_cast<int64_t>(*ptr), WORD);
1884 1885
    return *ptr;
  }
1886
  PrintF("Unaligned read at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR "\n", addr,
1887 1888 1889 1890 1891 1892
         reinterpret_cast<intptr_t>(instr));
  DieOrDebug();
  return 0;
}


1893
void Simulator::WriteW(int64_t addr, int32_t value, Instruction* instr) {
1894 1895
  if (addr >= 0 && addr < 0x400) {
    // This has to be a NULL-dereference, drop into debugger.
1896 1897
    PrintF("Memory write to bad address: 0x%08" PRIx64 " , pc=0x%08" PRIxPTR
           " \n",
1898 1899 1900
           addr, reinterpret_cast<intptr_t>(instr));
    DieOrDebug();
  }
1901
  if ((addr & 0x3) == 0 || kArchVariant == kMips64r6) {
1902 1903 1904 1905 1906
    TraceMemWr(addr, value, WORD);
    int* ptr = reinterpret_cast<int*>(addr);
    *ptr = value;
    return;
  }
1907
  PrintF("Unaligned write at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR "\n", addr,
1908 1909 1910 1911 1912 1913 1914 1915
         reinterpret_cast<intptr_t>(instr));
  DieOrDebug();
}


int64_t Simulator::Read2W(int64_t addr, Instruction* instr) {
  if (addr >=0 && addr < 0x400) {
    // This has to be a NULL-dereference, drop into debugger.
1916 1917
    PrintF("Memory read from bad address: 0x%08" PRIx64 " , pc=0x%08" PRIxPTR
           " \n",
1918 1919 1920
           addr, reinterpret_cast<intptr_t>(instr));
    DieOrDebug();
  }
1921
  if ((addr & kPointerAlignmentMask) == 0 || kArchVariant == kMips64r6) {
1922 1923 1924 1925
    int64_t* ptr = reinterpret_cast<int64_t*>(addr);
    TraceMemRd(addr, *ptr);
    return *ptr;
  }
1926
  PrintF("Unaligned read at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR "\n", addr,
1927 1928 1929 1930 1931 1932 1933 1934 1935
         reinterpret_cast<intptr_t>(instr));
  DieOrDebug();
  return 0;
}


void Simulator::Write2W(int64_t addr, int64_t value, Instruction* instr) {
  if (addr >= 0 && addr < 0x400) {
    // This has to be a NULL-dereference, drop into debugger.
1936 1937
    PrintF("Memory write to bad address: 0x%08" PRIx64 " , pc=0x%08" PRIxPTR
           "\n",
1938 1939 1940
           addr, reinterpret_cast<intptr_t>(instr));
    DieOrDebug();
  }
1941
  if ((addr & kPointerAlignmentMask) == 0 || kArchVariant == kMips64r6) {
1942 1943 1944 1945 1946
    TraceMemWr(addr, value, DWORD);
    int64_t* ptr = reinterpret_cast<int64_t*>(addr);
    *ptr = value;
    return;
  }
1947
  PrintF("Unaligned write at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR "\n", addr,
1948 1949 1950 1951 1952 1953
         reinterpret_cast<intptr_t>(instr));
  DieOrDebug();
}


double Simulator::ReadD(int64_t addr, Instruction* instr) {
1954
  if ((addr & kDoubleAlignmentMask) == 0 || kArchVariant == kMips64r6) {
1955 1956 1957
    double* ptr = reinterpret_cast<double*>(addr);
    return *ptr;
  }
1958 1959
  PrintF("Unaligned (double) read at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR "\n",
         addr, reinterpret_cast<intptr_t>(instr));
1960 1961 1962 1963 1964 1965
  base::OS::Abort();
  return 0;
}


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


uint16_t Simulator::ReadHU(int64_t addr, Instruction* instr) {
1979
  if ((addr & 1) == 0 || kArchVariant == kMips64r6) {
1980 1981 1982 1983
    uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
    TraceMemRd(addr, static_cast<int64_t>(*ptr));
    return *ptr;
  }
1984 1985 1986
  PrintF("Unaligned unsigned halfword read at 0x%08" PRIx64
         " , pc=0x%08" V8PRIxPTR "\n",
         addr, reinterpret_cast<intptr_t>(instr));
1987 1988 1989 1990 1991 1992
  DieOrDebug();
  return 0;
}


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


void Simulator::WriteH(int64_t addr, uint16_t value, Instruction* instr) {
2007
  if ((addr & 1) == 0 || kArchVariant == kMips64r6) {
2008 2009 2010 2011 2012
    TraceMemWr(addr, value, HALF);
    uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
    *ptr = value;
    return;
  }
2013 2014 2015
  PrintF("Unaligned unsigned halfword write at 0x%08" PRIx64
         " , pc=0x%08" V8PRIxPTR "\n",
         addr, reinterpret_cast<intptr_t>(instr));
2016 2017 2018 2019 2020
  DieOrDebug();
}


void Simulator::WriteH(int64_t addr, int16_t value, Instruction* instr) {
2021
  if ((addr & 1) == 0 || kArchVariant == kMips64r6) {
2022 2023 2024 2025 2026
    TraceMemWr(addr, value, HALF);
    int16_t* ptr = reinterpret_cast<int16_t*>(addr);
    *ptr = value;
    return;
  }
2027 2028 2029
  PrintF("Unaligned halfword write at 0x%08" PRIx64 " , pc=0x%08" V8PRIxPTR
         "\n",
         addr, reinterpret_cast<intptr_t>(instr));
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
  DieOrDebug();
}


uint32_t Simulator::ReadBU(int64_t addr) {
  uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
  TraceMemRd(addr, static_cast<int64_t>(*ptr));
  return *ptr & 0xff;
}


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;
}


// Returns the limit of the stack area to enable checking for stack overflows.
2063 2064 2065 2066 2067 2068 2069 2070 2071
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.
2072 2073 2074 2075 2076 2077
  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) {
2078
  PrintF("Simulator found unsupported instruction:\n 0x%08" PRIxPTR " : %s\n",
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
         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.

2091 2092 2093 2094 2095
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);
2096

2097 2098 2099
typedef ObjectTriple (*SimulatorRuntimeTripleCall)(int64_t arg0, int64_t arg1,
                                                   int64_t arg2, int64_t arg3,
                                                   int64_t arg4);
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118

// 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.
2119
void Simulator::SoftwareInterrupt() {
2120 2121 2122
  // 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.
2123 2124
  int32_t func = instr_.FunctionFieldRaw();
  uint32_t code = (func == BREAK) ? instr_.Bits(25, 6) : -1;
2125
  // We first check if we met a call_rt_redirected.
2126 2127
  if (instr_.InstructionBits() == rtCallRedirInstr) {
    Redirection* redirection = Redirection::FromSwiInstruction(instr_.instr());
2128 2129 2130

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

2131 2132 2133 2134
    int64_t arg0 = get_register(a0);
    int64_t arg1 = get_register(a1);
    int64_t arg2 = get_register(a2);
    int64_t arg3 = get_register(a3);
2135 2136 2137 2138 2139 2140
    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);
2141

2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
    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",
2199 2200
                   static_cast<void*>(FUNCTION_ADDR(generic_target)), dval0,
                   dval1);
2201 2202 2203
            break;
          case ExternalReference::BUILTIN_FP_CALL:
            PrintF("Call to host function at %p with arg %f",
2204
                   static_cast<void*>(FUNCTION_ADDR(generic_target)), dval0);
2205 2206 2207
            break;
          case ExternalReference::BUILTIN_FP_INT_CALL:
            PrintF("Call to host function at %p with args %f, %d",
2208 2209
                   static_cast<void*>(FUNCTION_ADDR(generic_target)), dval0,
                   ival);
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 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
            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) {
2267 2268
        PrintF("Call to host function at %p args %08" PRIx64 " \n",
               reinterpret_cast<void*>(external), arg0);
2269 2270 2271 2272 2273 2274 2275
      }
      SimulatorRuntimeDirectApiCall target =
          reinterpret_cast<SimulatorRuntimeDirectApiCall>(external);
      target(arg0);
    } else if (
        redirection->type() == ExternalReference::PROFILING_API_CALL) {
      if (::v8::internal::FLAG_trace_sim) {
2276 2277 2278
        PrintF("Call to host function at %p args %08" PRIx64 "  %08" PRIx64
               " \n",
               reinterpret_cast<void*>(external), arg0, arg1);
2279 2280 2281 2282 2283 2284 2285
      }
      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) {
2286 2287 2288
        PrintF("Call to host function at %p args %08" PRIx64 "  %08" PRIx64
               " \n",
               reinterpret_cast<void*>(external), arg0, arg1);
2289 2290 2291 2292 2293 2294 2295
      }
      SimulatorRuntimeDirectGetterCall target =
          reinterpret_cast<SimulatorRuntimeDirectGetterCall>(external);
      target(arg0, arg1);
    } else if (
        redirection->type() == ExternalReference::PROFILING_GETTER_CALL) {
      if (::v8::internal::FLAG_trace_sim) {
2296 2297 2298
        PrintF("Call to host function at %p args %08" PRIx64 "  %08" PRIx64
               "  %08" PRIx64 " \n",
               reinterpret_cast<void*>(external), arg0, arg1, arg2);
2299 2300 2301 2302
      }
      SimulatorRuntimeProfilingGetterCall target =
          reinterpret_cast<SimulatorRuntimeProfilingGetterCall>(external);
      target(arg0, arg1, Redirection::ReverseRedirection(arg2));
2303 2304 2305 2306 2307 2308 2309 2310 2311
    } else if (redirection->type() == ExternalReference::BUILTIN_CALL_TRIPLE) {
      // builtin call returning ObjectTriple.
      SimulatorRuntimeTripleCall target =
          reinterpret_cast<SimulatorRuntimeTripleCall>(external);
      if (::v8::internal::FLAG_trace_sim) {
        PrintF(
            "Call to host triple returning runtime function %p "
            "args %016" PRIx64 ", %016" PRIx64 ", %016" PRIx64 ", %016" PRIx64
            ", %016" PRIx64 "\n",
2312 2313
            static_cast<void*>(FUNCTION_ADDR(target)), arg1, arg2, arg3, arg4,
            arg5);
2314 2315 2316 2317 2318
      }
      // arg0 is a hidden argument pointing to the return location, so don't
      // pass it to the target function.
      ObjectTriple result = target(arg1, arg2, arg3, arg4, arg5);
      if (::v8::internal::FLAG_trace_sim) {
2319 2320
        PrintF("Returned { %p, %p, %p }\n", static_cast<void*>(result.x),
               static_cast<void*>(result.y), static_cast<void*>(result.z));
2321 2322 2323 2324 2325
      }
      // Return is passed back in address pointed to by hidden first argument.
      ObjectTriple* sim_result = reinterpret_cast<ObjectTriple*>(arg0);
      *sim_result = result;
      set_register(v0, arg0);
2326
    } else {
2327 2328
      DCHECK(redirection->type() == ExternalReference::BUILTIN_CALL ||
             redirection->type() == ExternalReference::BUILTIN_CALL_PAIR);
2329 2330 2331 2332 2333
      SimulatorRuntimeCall target =
                  reinterpret_cast<SimulatorRuntimeCall>(external);
      if (::v8::internal::FLAG_trace_sim) {
        PrintF(
            "Call to host function at %p "
2334
            "args %08" PRIx64 " , %08" PRIx64 " , %08" PRIx64 " , %08" PRIx64
2335 2336
            " , %08" PRIx64 " , %08" PRIx64 " , %08" PRIx64 " , %08" PRIx64
            " , %08" PRIx64 " \n",
2337
            static_cast<void*>(FUNCTION_ADDR(target)), arg0, arg1, arg2, arg3,
2338
            arg4, arg5, arg6, arg7, arg8);
2339
      }
2340 2341
      ObjectPair result =
          target(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
2342 2343 2344 2345
      set_register(v0, (int64_t)(result.x));
      set_register(v1, (int64_t)(result.y));
    }
     if (::v8::internal::FLAG_trace_sim) {
2346 2347
       PrintF("Returned %08" PRIx64 "  : %08" PRIx64 " \n", get_register(v1),
              get_register(v0));
2348 2349 2350 2351 2352 2353 2354 2355 2356
    }
    set_register(ra, saved_ra);
    set_pc(get_register(ra));

  } else if (func == BREAK && code <= kMaxStopCode) {
    if (IsWatchpoint(code)) {
      PrintWatchpoint(code);
    } else {
      IncreaseStopCounter(code);
2357
      HandleStop(code, instr_.instr());
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
    }
  } 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_;
2376 2377
  PrintF("\n---- break %" PRId64 "  marker: %3d  (instr count: %8" PRId64
         " ) ----------"
2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
         "----------------------------------",
         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) {
2402 2403
  DCHECK(code <= kMaxStopCode);
  DCHECK(code > kMaxWatchpointCode);
2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
  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) {
2423
  DCHECK(code <= kMaxStopCode);
2424
  if ((watched_stops_[code].count & ~(1 << 31)) == 0x7fffffff) {
2425 2426 2427 2428
    PrintF("Stop counter for code %" PRId64
           "  has overflowed.\n"
           "Enabling this code and reseting the counter to 0.\n",
           code);
2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
    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) {
2451
      PrintF("stop %" PRId64 "  - 0x%" PRIx64 " : \t%s, \tcounter = %i, \t%s\n",
2452 2453
             code, code, state, count, watched_stops_[code].desc);
    } else {
2454 2455
      PrintF("stop %" PRId64 "  - 0x%" PRIx64 " : \t%s, \tcounter = %i\n", code,
             code, state, count);
2456 2457 2458 2459 2460
    }
  }
}


2461 2462 2463
void Simulator::SignalException(Exception e) {
  V8_Fatal(__FILE__, __LINE__, "Error: Exception %i raised.",
           static_cast<int>(e));
2464 2465
}

2466 2467
// Min/Max template functions for Double and Single arguments.

2468
template <typename T>
2469
static T FPAbs(T a);
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481

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

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

template <typename T>
2482
static bool FPUProcessNaNsAndZeros(T a, T b, MaxMinKind kind, T& result) {
2483 2484 2485 2486 2487 2488 2489 2490
  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.
2491 2492 2493
    // std::signbit() returns int 0 or 1 so substracting MaxMinKind::kMax
    // negates the result.
    result = std::signbit(b) - static_cast<int>(kind) ? b : a;
2494 2495 2496 2497 2498 2499 2500
  } else {
    return false;
  }
  return true;
}

template <typename T>
2501
static T FPUMin(T a, T b) {
2502
  T result;
2503
  if (FPUProcessNaNsAndZeros(a, b, MaxMinKind::kMin, result)) {
2504 2505 2506 2507 2508 2509 2510
    return result;
  } else {
    return b < a ? b : a;
  }
}

template <typename T>
2511
static T FPUMax(T a, T b) {
2512
  T result;
2513
  if (FPUProcessNaNsAndZeros(a, b, MaxMinKind::kMax, result)) {
2514 2515 2516 2517 2518 2519 2520
    return result;
  } else {
    return b > a ? b : a;
  }
}

template <typename T>
2521
static T FPUMinA(T a, T b) {
2522
  T result;
2523
  if (!FPUProcessNaNsAndZeros(a, b, MaxMinKind::kMin, result)) {
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535
    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>
2536
static T FPUMaxA(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
    if (FPAbs(a) > FPAbs(b)) {
      result = a;
    } else if (FPAbs(b) > FPAbs(a)) {
      result = b;
    } else {
      result = a > b ? a : b;
    }
  }
  return result;
}
2549

2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 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
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;
}

2593 2594
// Handle execution based on instruction types.

2595
void Simulator::DecodeTypeRegisterSRsType() {
2596
  float fs, ft, fd;
2597 2598 2599
  fs = get_fpu_register_float(fs_reg());
  ft = get_fpu_register_float(ft_reg());
  fd = get_fpu_register_float(fd_reg());
2600 2601
  int32_t ft_int = bit_cast<int32_t>(ft);
  int32_t fd_int = bit_cast<int32_t>(fd);
2602
  uint32_t cc, fcsr_cc;
2603
  cc = instr_.FCccValue();
2604
  fcsr_cc = get_fcsr_condition_bit(cc);
2605
  switch (instr_.FunctionFieldRaw()) {
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637
    case RINT: {
      DCHECK(kArchVariant == kMips64r6);
      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;
      }
2638
      SetFPUFloatResult(fd_reg(), result);
2639 2640 2641 2642 2643 2644
      if (result != fs) {
        set_fcsr_bit(kFCSRInexactFlagBit, true);
      }
      break;
    }
    case ADD_S:
2645
      SetFPUFloatResult(
2646 2647 2648
          fd_reg(),
          FPUCanonalizeOperation([](float lhs, float rhs) { return lhs + rhs; },
                                 fs, ft));
2649
      break;
2650
    case SUB_S:
2651
      SetFPUFloatResult(
2652 2653 2654
          fd_reg(),
          FPUCanonalizeOperation([](float lhs, float rhs) { return lhs - rhs; },
                                 fs, ft));
2655
      break;
2656 2657
    case MADDF_S:
      DCHECK(kArchVariant == kMips64r6);
2658
      SetFPUFloatResult(fd_reg(), std::fma(fs, ft, fd));
2659 2660 2661
      break;
    case MSUBF_S:
      DCHECK(kArchVariant == kMips64r6);
2662
      SetFPUFloatResult(fd_reg(), std::fma(-fs, ft, fd));
2663
      break;
2664
    case MUL_S:
2665
      SetFPUFloatResult(
2666 2667 2668
          fd_reg(),
          FPUCanonalizeOperation([](float lhs, float rhs) { return lhs * rhs; },
                                 fs, ft));
2669
      break;
2670
    case DIV_S:
2671
      SetFPUFloatResult(
2672 2673 2674
          fd_reg(),
          FPUCanonalizeOperation([](float lhs, float rhs) { return lhs / rhs; },
                                 fs, ft));
2675
      break;
2676
    case ABS_S:
2677 2678
      SetFPUFloatResult(fd_reg(), FPUCanonalizeOperation(
                                      [](float fs) { return FPAbs(fs); }, fs));
2679
      break;
2680
    case MOV_S:
2681
      SetFPUFloatResult(fd_reg(), fs);
2682
      break;
2683
    case NEG_S:
2684 2685 2686
      SetFPUFloatResult(fd_reg(),
                        FPUCanonalizeOperation([](float src) { return -src; },
                                               KeepSign::yes, fs));
2687
      break;
2688
    case SQRT_S:
2689
      SetFPUFloatResult(
2690 2691
          fd_reg(),
          FPUCanonalizeOperation([](float src) { return std::sqrt(src); }, fs));
2692
      break;
2693
    case RSQRT_S:
2694
      SetFPUFloatResult(
2695 2696
          fd_reg(), FPUCanonalizeOperation(
                        [](float src) { return 1.0 / std::sqrt(src); }, fs));
2697
      break;
2698
    case RECIP_S:
2699 2700
      SetFPUFloatResult(fd_reg(), FPUCanonalizeOperation(
                                      [](float src) { return 1.0 / src; }, fs));
2701
      break;
2702 2703
    case C_F_D:
      set_fcsr_bit(fcsr_cc, false);
2704
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2705
      break;
2706 2707
    case C_UN_D:
      set_fcsr_bit(fcsr_cc, std::isnan(fs) || std::isnan(ft));
2708
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2709 2710 2711
      break;
    case C_EQ_D:
      set_fcsr_bit(fcsr_cc, (fs == ft));
2712
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2713 2714 2715
      break;
    case C_UEQ_D:
      set_fcsr_bit(fcsr_cc, (fs == ft) || (std::isnan(fs) || std::isnan(ft)));
2716
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2717 2718 2719
      break;
    case C_OLT_D:
      set_fcsr_bit(fcsr_cc, (fs < ft));
2720
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2721 2722 2723
      break;
    case C_ULT_D:
      set_fcsr_bit(fcsr_cc, (fs < ft) || (std::isnan(fs) || std::isnan(ft)));
2724
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2725 2726 2727
      break;
    case C_OLE_D:
      set_fcsr_bit(fcsr_cc, (fs <= ft));
2728
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2729 2730 2731
      break;
    case C_ULE_D:
      set_fcsr_bit(fcsr_cc, (fs <= ft) || (std::isnan(fs) || std::isnan(ft)));
2732
      TraceRegWr(test_fcsr_bit(fcsr_cc));
2733
      break;
2734
    case CVT_D_S:
2735
      SetFPUDoubleResult(fd_reg(), static_cast<double>(fs));
2736
      break;
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797
    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;
      uint32_t exponent = (classed >> 23) & 0x000000ff;
      uint32_t mantissa = classed & 0x007fffff;
      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;
      if (!negInf && !posInf && (exponent == 0xff)) {
        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;

      DCHECK(result != 0);

      fResult = bit_cast<float>(result);
2798
      SetFPUFloatResult(fd_reg(), fResult);
2799 2800 2801 2802 2803 2804
      break;
    }
    case CVT_L_S: {
      float rounded;
      int64_t result;
      round64_according_to_fcsr(fs, rounded, result, fs);
2805
      SetFPUResult(fd_reg(), result);
2806
      if (set_fcsr_round64_error(fs, rounded)) {
2807
        set_fpu_register_invalid_result64(fs, rounded);
2808 2809 2810 2811 2812 2813 2814
      }
      break;
    }
    case CVT_W_S: {
      float rounded;
      int32_t result;
      round_according_to_fcsr(fs, rounded, result, fs);
2815
      SetFPUWordResult(fd_reg(), result);
2816
      if (set_fcsr_round_error(fs, rounded)) {
2817
        set_fpu_register_word_invalid_result(fs, rounded);
2818 2819 2820
      }
      break;
    }
2821 2822 2823
    case TRUNC_W_S: {  // Truncate single to word (round towards 0).
      float rounded = trunc(fs);
      int32_t result = static_cast<int32_t>(rounded);
2824
      SetFPUWordResult(fd_reg(), result);
2825
      if (set_fcsr_round_error(fs, rounded)) {
2826
        set_fpu_register_word_invalid_result(fs, rounded);
2827 2828 2829 2830 2831
      }
    } break;
    case TRUNC_L_S: {  // Mips64r2 instruction.
      float rounded = trunc(fs);
      int64_t result = static_cast<int64_t>(rounded);
2832
      SetFPUResult(fd_reg(), result);
2833
      if (set_fcsr_round64_error(fs, rounded)) {
2834
        set_fpu_register_invalid_result64(fs, rounded);
2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845
      }
      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--;
      }
2846
      SetFPUWordResult(fd_reg(), result);
2847
      if (set_fcsr_round_error(fs, rounded)) {
2848
        set_fpu_register_word_invalid_result(fs, rounded);
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
      }
      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);
2861
      SetFPUResult(fd_reg(), i64);
2862
      if (set_fcsr_round64_error(fs, rounded)) {
2863
        set_fpu_register_invalid_result64(fs, rounded);
2864 2865 2866 2867 2868 2869
      }
      break;
    }
    case FLOOR_L_S: {  // Mips64r2 instruction.
      float rounded = floor(fs);
      int64_t result = static_cast<int64_t>(rounded);
2870
      SetFPUResult(fd_reg(), result);
2871
      if (set_fcsr_round64_error(fs, rounded)) {
2872
        set_fpu_register_invalid_result64(fs, rounded);
2873 2874 2875 2876 2877 2878 2879
      }
      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);
2880
      SetFPUWordResult(fd_reg(), result);
2881
      if (set_fcsr_round_error(fs, rounded)) {
2882
        set_fpu_register_word_invalid_result(fs, rounded);
2883 2884 2885 2886 2887 2888
      }
    } 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);
2889
      SetFPUWordResult(fd_reg(), result);
2890
      if (set_fcsr_round_error(fs, rounded)) {
2891
        set_fpu_register_invalid_result(fs, rounded);
2892 2893 2894 2895 2896
      }
    } break;
    case CEIL_L_S: {  // Mips64r2 instruction.
      float rounded = ceil(fs);
      int64_t result = static_cast<int64_t>(rounded);
2897
      SetFPUResult(fd_reg(), result);
2898
      if (set_fcsr_round64_error(fs, rounded)) {
2899
        set_fpu_register_invalid_result64(fs, rounded);
2900 2901 2902 2903 2904
      }
      break;
    }
    case MINA:
      DCHECK(kArchVariant == kMips64r6);
2905
      SetFPUFloatResult(fd_reg(), FPUMinA(ft, fs));
2906 2907 2908
      break;
    case MAXA:
      DCHECK(kArchVariant == kMips64r6);
2909
      SetFPUFloatResult(fd_reg(), FPUMaxA(ft, fs));
2910 2911 2912
      break;
    case MIN:
      DCHECK(kArchVariant == kMips64r6);
2913
      SetFPUFloatResult(fd_reg(), FPUMin(ft, fs));
2914 2915 2916
      break;
    case MAX:
      DCHECK(kArchVariant == kMips64r6);
2917
      SetFPUFloatResult(fd_reg(), FPUMax(ft, fs));
2918 2919 2920
      break;
    case SEL:
      DCHECK(kArchVariant == kMips64r6);
2921
      SetFPUFloatResult(fd_reg(), (fd_int & 0x1) == 0 ? fs : ft);
2922 2923 2924
      break;
    case SELEQZ_C:
      DCHECK(kArchVariant == kMips64r6);
2925 2926 2927
      SetFPUFloatResult(
          fd_reg(),
          (ft_int & 0x1) == 0 ? get_fpu_register_float(fs_reg()) : 0.0);
2928 2929 2930
      break;
    case SELNEZ_C:
      DCHECK(kArchVariant == kMips64r6);
2931 2932 2933
      SetFPUFloatResult(
          fd_reg(),
          (ft_int & 0x1) != 0 ? get_fpu_register_float(fs_reg()) : 0.0);
2934 2935 2936
      break;
    case MOVZ_C: {
      DCHECK(kArchVariant == kMips64r2);
2937
      if (rt() == 0) {
2938
        SetFPUFloatResult(fd_reg(), fs);
2939 2940 2941 2942 2943
      }
      break;
    }
    case MOVN_C: {
      DCHECK(kArchVariant == kMips64r2);
2944
      if (rt() != 0) {
2945
        SetFPUFloatResult(fd_reg(), fs);
2946 2947 2948 2949 2950
      }
      break;
    }
    case MOVF: {
      // Same function field for MOVT.D and MOVF.D
2951
      uint32_t ft_cc = (ft_reg() >> 2) & 0x7;
2952 2953
      ft_cc = get_fcsr_condition_bit(ft_cc);

2954
      if (instr_.Bit(16)) {  // Read Tf bit.
2955
        // MOVT.D
2956
        if (test_fcsr_bit(ft_cc)) SetFPUFloatResult(fd_reg(), fs);
2957 2958
      } else {
        // MOVF.D
2959
        if (!test_fcsr_bit(ft_cc)) SetFPUFloatResult(fd_reg(), fs);
2960 2961 2962
      }
      break;
    }
2963
    default:
2964
      // TRUNC_W_S ROUND_W_S ROUND_L_S FLOOR_W_S FLOOR_L_S
2965 2966 2967 2968 2969 2970
      // CEIL_W_S CEIL_L_S CVT_PS_S are unimplemented.
      UNREACHABLE();
  }
}


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

      DCHECK(result != 0);

      dResult = bit_cast<double>(result);
3329
      SetFPUDoubleResult(fd_reg(), dResult);
3330 3331 3332 3333
      break;
    }
    case C_F_D: {
      set_fcsr_bit(fcsr_cc, false);
3334
      TraceRegWr(test_fcsr_bit(fcsr_cc));
3335
      break;
3336
    }
3337 3338 3339 3340 3341 3342
    default:
      UNREACHABLE();
  }
}


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


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

3526 3527

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


3594
void Simulator::DecodeTypeRegisterCOP1X() {
3595
  switch (instr_.FunctionFieldRaw()) {
3596 3597 3598 3599 3600 3601
    case MADD_S: {
      DCHECK(kArchVariant == kMips64r2);
      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());
3602
      SetFPUFloatResult(fd_reg(), fs * ft + fr);
3603 3604 3605 3606 3607 3608 3609 3610
      break;
    }
    case MSUB_S: {
      DCHECK(kArchVariant == kMips64r2);
      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());
3611
      SetFPUFloatResult(fd_reg(), fs * ft - fr);
3612 3613 3614 3615
      break;
    }
    case MADD_D: {
      DCHECK(kArchVariant == kMips64r2);
3616
      double fr, ft, fs;
3617 3618 3619
      fr = get_fpu_register_double(fr_reg());
      fs = get_fpu_register_double(fs_reg());
      ft = get_fpu_register_double(ft_reg());
3620
      SetFPUDoubleResult(fd_reg(), fs * ft + fr);
3621
      break;
3622 3623 3624 3625 3626 3627 3628
    }
    case MSUB_D: {
      DCHECK(kArchVariant == kMips64r2);
      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());
3629
      SetFPUDoubleResult(fd_reg(), fs * ft - fr);
3630 3631
      break;
    }
3632 3633 3634 3635 3636 3637
    default:
      UNREACHABLE();
  }
}


3638 3639 3640 3641 3642 3643
void Simulator::DecodeTypeRegisterSPECIAL() {
  int64_t i64hilo;
  uint64_t u64hilo;
  int64_t alu_out;
  bool do_interrupt = false;

3644
  switch (instr_.FunctionFieldRaw()) {
3645 3646
    case SELEQZ_S:
      DCHECK(kArchVariant == kMips64r6);
3647
      SetResult(rd_reg(), rt() == 0 ? rs() : 0);
3648 3649 3650
      break;
    case SELNEZ_S:
      DCHECK(kArchVariant == kMips64r6);
3651
      SetResult(rd_reg(), rt() != 0 ? rs() : 0);
3652 3653
      break;
    case JR: {
3654 3655
      int64_t next_pc = rs();
      int64_t current_pc = get_pc();
3656 3657 3658 3659 3660 3661 3662 3663
      Instruction* branch_delay_instr =
          reinterpret_cast<Instruction*>(current_pc + Instruction::kInstrSize);
      BranchDelayInstructionDecode(branch_delay_instr);
      set_pc(next_pc);
      pc_modified_ = true;
      break;
    }
    case JALR: {
3664 3665 3666
      int64_t next_pc = rs();
      int64_t current_pc = get_pc();
      int32_t return_addr_reg = rd_reg();
3667 3668 3669 3670 3671 3672 3673 3674
      Instruction* branch_delay_instr =
          reinterpret_cast<Instruction*>(current_pc + Instruction::kInstrSize);
      BranchDelayInstructionDecode(branch_delay_instr);
      set_register(return_addr_reg, current_pc + 2 * Instruction::kInstrSize);
      set_pc(next_pc);
      pc_modified_ = true;
      break;
    }
3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689
    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());
3690
      } else if (rs_reg() == 1) {
3691 3692 3693 3694 3695 3696
        // 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())));
3697 3698
      } else {
        UNREACHABLE();
3699 3700 3701 3702
      }
      SetResult(rd_reg(), alu_out);
      break;
    case DSRL:
3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716
      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);
3717 3718
      break;
    case DSRL32:
3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733
      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);
3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768
      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.
3769
        alu_out = static_cast<int64_t>(rt_u() >> rs());
3770 3771 3772 3773
      } 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.
3774 3775
        alu_out =
            static_cast<int64_t>(base::bits::RotateRight64(rt_u(), rs_u()));
3776 3777 3778 3779 3780 3781 3782 3783 3784
      }
      SetResult(rd_reg(), alu_out);
      break;
    case SRAV:
      SetResult(rd_reg(), (int32_t)rt() >> rs());
      break;
    case DSRAV:
      SetResult(rd_reg(), rt() >> rs());
      break;
3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798
    case LSA: {
      DCHECK(kArchVariant == kMips64r6);
      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:
      DCHECK(kArchVariant == kMips64r6);
      SetResult(rd_reg(), (rs() << (lsa_sa() + 1)) + rt());
      break;
3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810
    case MFHI:  // MFHI == CLZ on R6.
      if (kArchVariant != kMips64r6) {
        DCHECK(sa() == 0);
        alu_out = get_register(HI);
      } else {
        // MIPS spec: If no bits were set in GPR rs(), the result written to
        // GPR rd() is 32.
        DCHECK(sa() == 1);
        alu_out = base::bits::CountLeadingZeros32(static_cast<int32_t>(rs_u()));
      }
      SetResult(rd_reg(), alu_out);
      break;
3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821
    case MFLO:  // MFLO == DCLZ on R6.
      if (kArchVariant != kMips64r6) {
        DCHECK(sa() == 0);
        alu_out = get_register(LO);
      } else {
        // MIPS spec: If no bits were set in GPR rs(), the result written to
        // GPR rd() is 64.
        DCHECK(sa() == 1);
        alu_out = base::bits::CountLeadingZeros64(static_cast<int64_t>(rs_u()));
      }
      SetResult(rd_reg(), alu_out);
3822
      break;
3823
    // Instructions using HI and LO registers.
3824 3825 3826 3827
    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);
3828 3829 3830 3831
      if (kArchVariant != kMips64r6) {
        set_register(LO, static_cast<int32_t>(i64hilo & 0xffffffff));
        set_register(HI, static_cast<int32_t>(i64hilo >> 32));
      } else {
3832
        switch (sa()) {
3833
          case MUL_OP:
3834
            SetResult(rd_reg(), static_cast<int32_t>(i64hilo & 0xffffffff));
3835 3836
            break;
          case MUH_OP:
3837
            SetResult(rd_reg(), static_cast<int32_t>(i64hilo >> 32));
3838 3839 3840 3841 3842 3843 3844
            break;
          default:
            UNIMPLEMENTED_MIPS();
            break;
        }
      }
      break;
3845
    }
3846
    case MULTU:
3847 3848
      u64hilo = static_cast<uint64_t>(rs_u() & 0xffffffff) *
                static_cast<uint64_t>(rt_u() & 0xffffffff);
3849 3850 3851 3852 3853 3854
      if (kArchVariant != kMips64r6) {
        set_register(LO, static_cast<int32_t>(u64hilo & 0xffffffff));
        set_register(HI, static_cast<int32_t>(u64hilo >> 32));
      } else {
        switch (sa()) {
          case MUL_OP:
3855
            SetResult(rd_reg(), static_cast<int32_t>(u64hilo & 0xffffffff));
3856 3857
            break;
          case MUH_OP:
3858
            SetResult(rd_reg(), static_cast<int32_t>(u64hilo >> 32));
3859 3860 3861 3862 3863 3864
            break;
          default:
            UNIMPLEMENTED_MIPS();
            break;
        }
      }
3865 3866 3867
      break;
    case DMULT:  // DMULT == D_MUL_MUH.
      if (kArchVariant != kMips64r6) {
3868 3869
        set_register(LO, rs() * rt());
        set_register(HI, MultiplyHighSigned(rs(), rt()));
3870
      } else {
3871
        switch (sa()) {
3872
          case MUL_OP:
3873
            SetResult(rd_reg(), rs() * rt());
3874 3875
            break;
          case MUH_OP:
3876
            SetResult(rd_reg(), MultiplyHighSigned(rs(), rt()));
3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887
            break;
          default:
            UNIMPLEMENTED_MIPS();
            break;
        }
      }
      break;
    case DMULTU:
      UNIMPLEMENTED_MIPS();
      break;
    case DIV:
3888 3889
    case DDIV: {
      const int64_t int_min_value =
3890
          instr_.FunctionFieldRaw() == DIV ? INT_MIN : LONG_MIN;
3891 3892 3893 3894 3895 3896
      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.
3897
          if (rs() == int_min_value && rt() == -1) {
3898
            set_register(LO, int_min_value);
3899
            set_register(HI, 0);
3900 3901 3902
          } else if (rt() != 0) {
            set_register(LO, rs() / rt());
            set_register(HI, rs() % rt());
3903 3904 3905
          }
          break;
        case kMips64r6:
3906
          switch (sa()) {
3907
            case DIV_OP:
3908
              if (rs() == int_min_value && rt() == -1) {
3909
                SetResult(rd_reg(), int_min_value);
3910
              } else if (rt() != 0) {
3911
                SetResult(rd_reg(), rs() / rt());
3912 3913 3914
              }
              break;
            case MOD_OP:
3915
              if (rs() == int_min_value && rt() == -1) {
3916
                SetResult(rd_reg(), 0);
3917
              } else if (rt() != 0) {
3918
                SetResult(rd_reg(), rs() % rt());
3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929
              }
              break;
            default:
              UNIMPLEMENTED_MIPS();
              break;
          }
          break;
        default:
          break;
      }
      break;
3930
    }
3931
    case DIVU:
3932 3933 3934 3935
      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());
3936
          switch (sa()) {
3937 3938
            case DIV_OP:
              if (rt_u_32 != 0) {
3939
                SetResult(rd_reg(), rs_u_32 / rt_u_32);
3940 3941 3942 3943
              }
              break;
            case MOD_OP:
              if (rt_u() != 0) {
3944
                SetResult(rd_reg(), rs_u_32 % rt_u_32);
3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959
              }
              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);
          }
        }
3960 3961
      }
      break;
3962
    case DDIVU:
3963 3964
      switch (kArchVariant) {
        case kMips64r6: {
3965
          switch (instr_.SaValue()) {
3966 3967
            case DIV_OP:
              if (rt_u() != 0) {
3968
                SetResult(rd_reg(), rs_u() / rt_u());
3969 3970 3971 3972
              }
              break;
            case MOD_OP:
              if (rt_u() != 0) {
3973
                SetResult(rd_reg(), rs_u() % rt_u());
3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986
              }
              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());
          }
        }
3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 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
      }
      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;
4055 4056
    // Break and trap instructions.
    case BREAK:
4057 4058
      do_interrupt = true;
      break;
4059
    case TGE:
4060 4061
      do_interrupt = rs() >= rt();
      break;
4062
    case TGEU:
4063 4064
      do_interrupt = rs_u() >= rt_u();
      break;
4065
    case TLT:
4066 4067
      do_interrupt = rs() < rt();
      break;
4068
    case TLTU:
4069 4070
      do_interrupt = rs_u() < rt_u();
      break;
4071
    case TEQ:
4072 4073
      do_interrupt = rs() == rt();
      break;
4074
    case TNE:
4075
      do_interrupt = rs() != rt();
4076
      break;
4077 4078 4079
    case SYNC:
      // TODO(palfia): Ignore sync instruction for now.
      break;
4080 4081
    // Conditional moves.
    case MOVN:
4082 4083
      if (rt()) {
        SetResult(rd_reg(), rs());
4084 4085 4086
      }
      break;
    case MOVCI: {
4087
      uint32_t cc = instr_.FBccValue();
4088
      uint32_t fcsr_cc = get_fcsr_condition_bit(cc);
4089
      if (instr_.Bit(16)) {  // Read Tf bit.
4090
        if (test_fcsr_bit(fcsr_cc)) SetResult(rd_reg(), rs());
4091
      } else {
4092
        if (!test_fcsr_bit(fcsr_cc)) SetResult(rd_reg(), rs());
4093 4094 4095 4096
      }
      break;
    }
    case MOVZ:
4097 4098
      if (!rt()) {
        SetResult(rd_reg(), rs());
4099 4100
      }
      break;
4101 4102 4103 4104
    default:
      UNREACHABLE();
  }
  if (do_interrupt) {
4105
    SoftwareInterrupt();
4106 4107 4108 4109
  }
}


4110 4111
void Simulator::DecodeTypeRegisterSPECIAL2() {
  int64_t alu_out;
4112
  switch (instr_.FunctionFieldRaw()) {
4113
    case MUL:
4114 4115
      alu_out = static_cast<int32_t>(rs_u()) * static_cast<int32_t>(rt_u());
      SetResult(rd_reg(), alu_out);
4116 4117 4118 4119
      // HI and LO are UNPREDICTABLE after the operation.
      set_register(LO, Unpredictable);
      set_register(HI, Unpredictable);
      break;
4120 4121 4122 4123
    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()));
4124 4125 4126 4127 4128 4129 4130
      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);
4131 4132 4133 4134
      break;
    default:
      alu_out = 0x12345678;
      UNREACHABLE();
4135 4136 4137 4138
  }
}


4139 4140
void Simulator::DecodeTypeRegisterSPECIAL3() {
  int64_t alu_out;
4141
  switch (instr_.FunctionFieldRaw()) {
4142 4143 4144
    case EXT: {  // Mips32r2 instruction.
      // Interpret rd field as 5-bit msbd of extract.
      uint16_t msbd = rd_reg();
4145 4146
      // Interpret sa field as 5-bit lsb of extract.
      uint16_t lsb = sa();
4147
      uint16_t size = msbd + 1;
4148 4149 4150 4151 4152
      uint64_t mask = (1ULL << size) - 1;
      alu_out = static_cast<int32_t>((rs_u() & (mask << lsb)) >> lsb);
      SetResult(rt_reg(), alu_out);
      break;
    }
4153
    case DEXT: {  // Mips64r2 instruction.
4154 4155
      // Interpret rd field as 5-bit msbd of extract.
      uint16_t msbd = rd_reg();
4156 4157
      // Interpret sa field as 5-bit lsb of extract.
      uint16_t lsb = sa();
4158
      uint16_t size = msbd + 1;
4159
      uint64_t mask = (size == 64) ? UINT64_MAX : (1ULL << size) - 1;
4160 4161 4162 4163
      alu_out = static_cast<int64_t>((rs_u() & (mask << lsb)) >> lsb);
      SetResult(rt_reg(), alu_out);
      break;
    }
4164
    case DEXTM: {
4165 4166
      // Interpret rd field as 5-bit msbdminus32 of extract.
      uint16_t msbdminus32 = rd_reg();
4167 4168
      // Interpret sa field as 5-bit lsb of extract.
      uint16_t lsb = sa();
4169
      uint16_t size = msbdminus32 + 1 + 32;
4170
      uint64_t mask = (size == 64) ? UINT64_MAX : (1ULL << size) - 1;
4171 4172 4173 4174 4175
      alu_out = static_cast<int64_t>((rs_u() & (mask << lsb)) >> lsb);
      SetResult(rt_reg(), alu_out);
      break;
    }
    case DEXTU: {
4176 4177 4178 4179
      // 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.
4180
      uint16_t lsb = sa() + 32;
4181
      uint16_t size = msbd + 1;
4182
      uint64_t mask = (size == 64) ? UINT64_MAX : (1ULL << size) - 1;
4183 4184 4185 4186
      alu_out = static_cast<int64_t>((rs_u() & (mask << lsb)) >> lsb);
      SetResult(rt_reg(), alu_out);
      break;
    }
4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 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
    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;
    }
4237
    case BSHFL: {
4238
      int32_t sa = instr_.SaFieldRaw() >> kSaShift;
4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263
      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;
            i_byte = input & 0xff;

            // 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;
        }
4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274
        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);
4275
          break;
4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314
        }
        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;
        }
4315
        default: {
4316
          const uint8_t bp2 = instr_.Bp2Value();
4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337
          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);
4338
      break;
4339 4340
    }
    case DBSHFL: {
4341
      int32_t sa = instr_.SaFieldRaw() >> kSaShift;
4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372
      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;
                i_byte = input & 0xff;

                // 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;
        }
4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389
        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);
4390
          break;
4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413
        }
        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;
        }
4414
        default: {
4415
          const uint8_t bp3 = instr_.Bp3Value();
4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436
          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);
4437
      break;
4438
    }
4439 4440 4441 4442 4443
    default:
      UNREACHABLE();
  }
}

4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 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
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() {
  DCHECK(kArchVariant == kMips64r6);
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaI8Mask;
4525 4526
  int8_t i8 = instr_.MsaImm8Value();
  msa_reg_t ws, wd;
4527 4528 4529

  switch (opcode) {
    case ANDI_B:
4530 4531 4532 4533 4534 4535 4536
      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;
4537
    case ORI_B:
4538 4539 4540 4541 4542 4543 4544
      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;
4545
    case NORI_B:
4546 4547 4548 4549 4550 4551 4552
      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;
4553
    case XORI_B:
4554 4555 4556 4557 4558 4559 4560
      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;
4561
    case BMNZI_B:
4562 4563 4564 4565 4566 4567 4568 4569
      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;
4570
    case BMZI_B:
4571 4572 4573 4574 4575 4576 4577 4578
      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;
4579
    case BSELI_B:
4580 4581 4582 4583 4584 4585 4586 4587
      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;
4588
    case SHF_B:
4589 4590 4591 4592 4593 4594 4595 4596 4597
      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;
4598
    case SHF_H:
4599 4600 4601 4602 4603 4604 4605 4606 4607
      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;
4608
    case SHF_W:
4609 4610 4611 4612 4613 4614 4615
      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);
4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664
      break;
    default:
      UNREACHABLE();
  }
}

void Simulator::DecodeTypeMsaI5() {
  DCHECK(kArchVariant == kMips64r6);
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaI5Mask;

  switch (opcode) {
    case ADDVI:
    case SUBVI:
    case MAXI_S:
    case MAXI_U:
    case MINI_S:
    case MINI_U:
    case CEQI:
    case CLTI_S:
    case CLTI_U:
    case CLEI_S:
    case CLEI_U:
      UNIMPLEMENTED();
      break;
    default:
      UNREACHABLE();
  }
}

void Simulator::DecodeTypeMsaI10() {
  DCHECK(kArchVariant == kMips64r6);
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaI5Mask;
  if (opcode == LDI) {
    UNIMPLEMENTED();
  } else {
    UNREACHABLE();
  }
}

void Simulator::DecodeTypeMsaELM() {
  DCHECK(kArchVariant == kMips64r6);
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaELMMask;
  int32_t n = instr_.MsaElmNValue();
  int64_t alu_out;
  switch (opcode) {
    case COPY_S:
4665 4666
    case COPY_U: {
      msa_reg_t ws;
4667
      switch (DecodeMsaDataFormat()) {
4668 4669 4670 4671
        case MSA_BYTE:
          DCHECK(n < kMSALanesByte);
          get_msa_register(instr_.WsValue(), ws.b);
          alu_out = static_cast<int32_t>(ws.b[n]);
4672 4673
          SetResult(wd_reg(), (opcode == COPY_U) ? alu_out & 0xFFu : alu_out);
          break;
4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707
        case MSA_HALF:
          DCHECK(n < kMSALanesHalf);
          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:
          DCHECK(n < kMSALanesWord);
          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:
          DCHECK(n < kMSALanesDword);
          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: {
          DCHECK(n < kMSALanesByte);
          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;
4708 4709
        }
        case MSA_HALF: {
4710 4711 4712 4713 4714 4715
          DCHECK(n < kMSALanesHalf);
          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);
4716 4717 4718
          break;
        }
        case MSA_WORD: {
4719 4720 4721 4722 4723 4724
          DCHECK(n < kMSALanesWord);
          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);
4725 4726 4727
          break;
        }
        case MSA_DWORD: {
4728 4729 4730 4731 4732 4733
          DCHECK(n < kMSALanesDword);
          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);
4734 4735 4736 4737 4738
          break;
        }
        default:
          UNREACHABLE();
      }
4739
    } break;
4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938
    case SLDI:
    case SPLATI:
    case INSVE:
      UNIMPLEMENTED();
      break;
    default:
      UNREACHABLE();
  }
}

void Simulator::DecodeTypeMsaBIT() {
  DCHECK(kArchVariant == kMips64r6);
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaBITMask;

  switch (opcode) {
    case SLLI:
    case SRAI:
    case SRLI:
    case BCLRI:
    case BSETI:
    case BNEGI:
    case BINSLI:
    case BINSRI:
    case SAT_S:
    case SAT_U:
    case SRARI:
    case SRLRI:
      UNIMPLEMENTED();
      break;
    default:
      UNREACHABLE();
  }
}

void Simulator::DecodeTypeMsaMI10() {
  DCHECK(kArchVariant == kMips64r6);
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaMI10Mask;
  if (opcode == MSA_LD) {
    UNIMPLEMENTED();
  } else if (opcode == MSA_ST) {
    UNIMPLEMENTED();
  } else {
    UNREACHABLE();
  }
}

void Simulator::DecodeTypeMsa3R() {
  DCHECK(kArchVariant == kMips64r6);
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsa3RMask;
  switch (opcode) {
    case SLL_MSA:
    case SRA_MSA:
    case SRL_MSA:
    case BCLR:
    case BSET:
    case BNEG:
    case BINSL:
    case BINSR:
    case ADDV:
    case SUBV:
    case MAX_S:
    case MAX_U:
    case MIN_S:
    case MIN_U:
    case MAX_A:
    case MIN_A:
    case CEQ:
    case CLT_S:
    case CLT_U:
    case CLE_S:
    case CLE_U:
    case ADD_A:
    case ADDS_A:
    case ADDS_S:
    case ADDS_U:
    case AVE_S:
    case AVE_U:
    case AVER_S:
    case AVER_U:
    case SUBS_S:
    case SUBS_U:
    case SUBSUS_U:
    case SUBSUU_S:
    case ASUB_S:
    case ASUB_U:
    case MULV:
    case MADDV:
    case MSUBV:
    case DIV_S_MSA:
    case DIV_U:
    case MOD_S:
    case MOD_U:
    case DOTP_S:
    case DOTP_U:
    case DPADD_S:
    case DPADD_U:
    case DPSUB_S:
    case DPSUB_U:
    case SLD:
    case SPLAT:
    case PCKEV:
    case PCKOD:
    case ILVL:
    case ILVR:
    case ILVEV:
    case ILVOD:
    case VSHF:
    case SRAR:
    case SRLR:
    case HADD_S:
    case HADD_U:
    case HSUB_S:
    case HSUB_U:
      UNIMPLEMENTED();
      break;
    default:
      UNREACHABLE();
  }
}

void Simulator::DecodeTypeMsa3RF() {
  DCHECK(kArchVariant == kMips64r6);
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsa3RFMask;
  switch (opcode) {
    case FCAF:
    case FCUN:
    case FCEQ:
    case FCUEQ:
    case FCLT:
    case FCULT:
    case FCLE:
    case FCULE:
    case FSAF:
    case FSUN:
    case FSEQ:
    case FSUEQ:
    case FSLT:
    case FSULT:
    case FSLE:
    case FSULE:
    case FADD:
    case FSUB:
    case FMUL:
    case FDIV:
    case FMADD:
    case FMSUB:
    case FEXP2:
    case FEXDO:
    case FTQ:
    case FMIN:
    case FMIN_A:
    case FMAX:
    case FMAX_A:
    case FCOR:
    case FCUNE:
    case FCNE:
    case MUL_Q:
    case MADD_Q:
    case MSUB_Q:
    case FSOR:
    case FSUNE:
    case FSNE:
    case MULR_Q:
    case MADDR_Q:
    case MSUBR_Q:
      UNIMPLEMENTED();
      break;
    default:
      UNREACHABLE();
  }
}

void Simulator::DecodeTypeMsaVec() {
  DCHECK(kArchVariant == kMips64r6);
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsaVECMask;
  switch (opcode) {
    case AND_V:
    case OR_V:
    case NOR_V:
    case XOR_V:
    case BMNZ_V:
    case BMZ_V:
    case BSEL_V:
      UNIMPLEMENTED();
      break;
    default:
      UNREACHABLE();
  }
}

void Simulator::DecodeTypeMsa2R() {
  DCHECK(kArchVariant == kMips64r6);
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsa2RMask;
4939
  msa_reg_t wd;
4940 4941 4942 4943 4944
  switch (opcode) {
    case FILL:
      switch (DecodeMsaDataFormat()) {
        case MSA_BYTE: {
          int64_t rs = get_register(instr_.WsValue());
4945 4946
          for (int i = 0; i < kMSALanesByte; i++) {
            wd.b[i] = rs & 0xFFu;
4947
          }
4948 4949
          set_msa_register(instr_.WdValue(), wd.b);
          TraceMSARegWr(wd.b);
4950 4951 4952 4953
          break;
        }
        case MSA_HALF: {
          int64_t rs = get_register(instr_.WsValue());
4954 4955
          for (int i = 0; i < kMSALanesHalf; i++) {
            wd.h[i] = rs & 0xFFFFu;
4956
          }
4957 4958
          set_msa_register(instr_.WdValue(), wd.h);
          TraceMSARegWr(wd.h);
4959 4960 4961 4962
          break;
        }
        case MSA_WORD: {
          int64_t rs = get_register(instr_.WsValue());
4963 4964
          for (int i = 0; i < kMSALanesWord; i++) {
            wd.w[i] = rs & 0xFFFFFFFFu;
4965
          }
4966 4967
          set_msa_register(instr_.WdValue(), wd.w);
          TraceMSARegWr(wd.w);
4968 4969 4970 4971
          break;
        }
        case MSA_DWORD: {
          int64_t rs = get_register(instr_.WsValue());
4972 4973 4974
          wd.d[0] = wd.d[1] = rs;
          set_msa_register(instr_.WdValue(), wd.d);
          TraceMSARegWr(wd.d);
4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018
          break;
        }
        default:
          UNREACHABLE();
      }
      break;
    case PCNT:
    case NLOC:
    case NLZC:
      UNIMPLEMENTED();
      break;
    default:
      UNREACHABLE();
  }
}

void Simulator::DecodeTypeMsa2RF() {
  DCHECK(kArchVariant == kMips64r6);
  DCHECK(CpuFeatures::IsSupported(MIPS_SIMD));
  uint32_t opcode = instr_.InstructionBits() & kMsa2RFMask;
  switch (opcode) {
    case FCLASS:
    case FTRUNC_S:
    case FTRUNC_U:
    case FSQRT:
    case FRSQRT:
    case FRCP:
    case FRINT:
    case FLOG2:
    case FEXUPL:
    case FEXUPR:
    case FFQL:
    case FFQR:
    case FTINT_S:
    case FTINT_U:
    case FFINT_S:
    case FFINT_U:
      UNIMPLEMENTED();
      break;
    default:
      UNREACHABLE();
  }
}

5019
void Simulator::DecodeTypeRegister() {
5020
  // ---------- Execution.
5021
  switch (instr_.OpcodeFieldRaw()) {
5022
    case COP1:
5023
      DecodeTypeRegisterCOP1();
5024 5025
      break;
    case COP1X:
5026
      DecodeTypeRegisterCOP1X();
5027 5028
      break;
    case SPECIAL:
5029
      DecodeTypeRegisterSPECIAL();
5030 5031
      break;
    case SPECIAL2:
5032
      DecodeTypeRegisterSPECIAL2();
5033 5034
      break;
    case SPECIAL3:
5035
      DecodeTypeRegisterSPECIAL3();
5036
      break;
5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057
    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;
        default:
          UNREACHABLE();
      }
      break;
5058 5059 5060 5061
    // 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:
5062
      UNREACHABLE();
5063 5064 5065 5066
  }
}


5067
// Type 2: instructions using a 16, 21 or 26 bits immediate. (e.g. beq, beqc).
5068
void Simulator::DecodeTypeImmediate() {
5069
  // Instruction fields.
5070 5071 5072
  Opcode op = instr_.OpcodeFieldRaw();
  int32_t rs_reg = instr_.RsValue();
  int64_t rs = get_register(instr_.RsValue());
5073
  uint64_t rs_u = static_cast<uint64_t>(rs);
5074
  int32_t rt_reg = instr_.RtValue();  // Destination register.
5075
  int64_t rt = get_register(rt_reg);
5076 5077
  int16_t imm16 = instr_.Imm16Value();
  int32_t imm18 = instr_.Imm18Value();
5078

5079
  int32_t ft_reg = instr_.FtValue();  // Destination register.
5080 5081

  // Zero extended immediate.
5082
  uint64_t oe_imm16 = 0xffff & imm16;
5083
  // Sign extended immediate.
5084
  int64_t se_imm16 = imm16;
5085 5086
  int64_t se_imm18 = imm18 | ((imm18 & 0x20000) ? 0xfffffffffffc0000 : 0);

5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099
  // 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;
5100 5101
  // Alignment for 64-bit integers used in LDL, LDR, etc.
  const int kInt64AlignmentMask = sizeof(uint64_t) - 1;
5102

5103
  // Branch instructions common part.
5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115
  auto BranchAndLinkHelper =
      [this, &next_pc, &execute_branch_delay_instruction](bool do_branch) {
        execute_branch_delay_instruction = true;
        int64_t current_pc = get_pc();
        if (do_branch) {
          int16_t imm16 = instr_.Imm16Value();
          next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
          set_register(31, current_pc + 2 * Instruction::kInstrSize);
        } else {
          next_pc = current_pc + 2 * Instruction::kInstrSize;
        }
      };
5116

5117
  auto BranchHelper = [this, &next_pc,
5118 5119 5120 5121
                       &execute_branch_delay_instruction](bool do_branch) {
    execute_branch_delay_instruction = true;
    int64_t current_pc = get_pc();
    if (do_branch) {
5122
      int16_t imm16 = instr_.Imm16Value();
5123 5124 5125 5126 5127 5128
      next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
    } else {
      next_pc = current_pc + 2 * Instruction::kInstrSize;
    }
  };

5129
  auto BranchAndLinkCompactHelper = [this, &next_pc](bool do_branch, int bits) {
5130 5131 5132
    int64_t current_pc = get_pc();
    CheckForbiddenSlot(current_pc);
    if (do_branch) {
5133
      int32_t imm = instr_.ImmValue(bits);
5134 5135 5136 5137 5138 5139 5140
      imm <<= 32 - bits;
      imm >>= 32 - bits;
      next_pc = current_pc + (imm << 2) + Instruction::kInstrSize;
      set_register(31, current_pc + Instruction::kInstrSize);
    }
  };

5141
  auto BranchCompactHelper = [this, &next_pc](bool do_branch, int bits) {
5142 5143 5144
    int64_t current_pc = get_pc();
    CheckForbiddenSlot(current_pc);
    if (do_branch) {
5145
      int32_t imm = instr_.ImmValue(bits);
5146 5147 5148 5149 5150 5151
      imm <<= 32 - bits;
      imm >>= 32 - bits;
      next_pc = get_pc() + (imm << 2) + Instruction::kInstrSize;
    }
  };

5152 5153 5154
  switch (op) {
    // ------------- COP1. Coprocessor instructions.
    case COP1:
5155
      switch (instr_.RsFieldRaw()) {
5156
        case BC1: {  // Branch on coprocessor condition.
5157
          uint32_t cc = instr_.FBccValue();
5158 5159
          uint32_t fcsr_cc = get_fcsr_condition_bit(cc);
          uint32_t cc_value = test_fcsr_bit(fcsr_cc);
5160
          bool do_branch = (instr_.FBtrueValue()) ? cc_value : !cc_value;
5161
          BranchHelper(do_branch);
5162
          break;
5163
        }
5164
        case BC1EQZ:
5165
          BranchHelper(!(get_fpu_register(ft_reg) & 0x1));
5166 5167
          break;
        case BC1NEZ:
5168
          BranchHelper(get_fpu_register(ft_reg) & 0x1);
5169
          break;
5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181
        case BZ_V:
        case BZ_B:
        case BZ_H:
        case BZ_W:
        case BZ_D:
        case BNZ_V:
        case BNZ_B:
        case BNZ_H:
        case BNZ_W:
        case BNZ_D:
          UNIMPLEMENTED();
          break;
5182 5183 5184 5185 5186 5187
        default:
          UNREACHABLE();
      }
      break;
    // ------------- REGIMM class.
    case REGIMM:
5188
      switch (instr_.RtFieldRaw()) {
5189
        case BLTZ:
5190
          BranchHelper(rs < 0);
5191 5192
          break;
        case BGEZ:
5193 5194 5195 5196
          BranchHelper(rs >= 0);
          break;
        case BLTZAL:
          BranchAndLinkHelper(rs < 0);
5197 5198
          break;
        case BGEZAL:
5199
          BranchAndLinkHelper(rs >= 0);
5200
          break;
5201 5202 5203 5204 5205 5206
        case DAHI:
          SetResult(rs_reg, rs + (se_imm16 << 32));
          break;
        case DATI:
          SetResult(rs_reg, rs + (se_imm16 << 48));
          break;
5207 5208 5209
        default:
          UNREACHABLE();
      }
5210
      break;  // case REGIMM.
5211 5212 5213 5214
    // ------------- 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:
5215
      BranchHelper(rs == rt);
5216 5217
      break;
    case BNE:
5218
      BranchHelper(rs != rt);
5219
      break;
5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 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 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296
    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);
5297 5298 5299 5300
      } else {  // JIC
        next_pc = rt + imm16;
      }
      break;
5301 5302 5303 5304 5305 5306 5307 5308
    case POP76:           // BNEZC, JIALC
      if (rs_reg != 0) {  // BNEZC
        BranchCompactHelper(rs != 0, 21);
      } else {  // JIALC
        int64_t current_pc = get_pc();
        set_register(31, current_pc + Instruction::kInstrSize);
        next_pc = rt + imm16;
      }
5309
      break;
5310 5311
    case BC:
      BranchCompactHelper(true, 26);
5312
      break;
5313 5314 5315 5316 5317 5318
    case BALC:
      BranchAndLinkCompactHelper(true, 26);
      break;
    case POP10:  // BOVC, BEQZALC, BEQC / ADDI (pre-r6)
      if (kArchVariant == kMips64r6) {
        if (rs_reg >= rt_reg) {  // BOVC
5319 5320
          bool condition = !is_int32(rs) || !is_int32(rt) || !is_int32(rs + rt);
          BranchCompactHelper(condition, 16);
5321 5322 5323 5324 5325
        } else {
          if (rs_reg == 0) {  // BEQZALC
            BranchAndLinkCompactHelper(rt == 0, 16);
          } else {  // BEQC
            BranchCompactHelper(rt == rs, 16);
5326
          }
5327
        }
5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340
      } 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);
5341 5342
      }
      break;
5343 5344 5345
    case POP30:  // BNVC, BNEZALC, BNEC / DADDI (pre-r6)
      if (kArchVariant == kMips64r6) {
        if (rs_reg >= rt_reg) {  // BNVC
5346 5347
          bool condition = is_int32(rs) && is_int32(rt) && is_int32(rs + rt);
          BranchCompactHelper(condition, 16);
5348 5349 5350 5351 5352 5353 5354 5355 5356 5357
        } else {
          if (rs_reg == 0) {  // BNEZALC
            BranchAndLinkCompactHelper(rt != 0, 16);
          } else {  // BNEC
            BranchCompactHelper(rt != rs, 16);
          }
        }
      }
      break;
    // ------------- Arithmetic instructions.
5358
    case ADDIU: {
5359
      DCHECK(is_int32(rs));
5360 5361
      int32_t alu32_out = static_cast<int32_t>(rs + se_imm16);
      // Sign-extend result of 32bit operation into 64bit register.
5362
      SetResult(rt_reg, static_cast<int64_t>(alu32_out));
5363
      break;
5364
    }
5365
    case DADDIU:
5366
      SetResult(rt_reg, rs + se_imm16);
5367 5368
      break;
    case SLTI:
5369
      SetResult(rt_reg, rs < se_imm16 ? 1 : 0);
5370 5371
      break;
    case SLTIU:
5372
      SetResult(rt_reg, rs_u < static_cast<uint64_t>(se_imm16) ? 1 : 0);
5373 5374
      break;
    case ANDI:
5375
      SetResult(rt_reg, rs & oe_imm16);
5376 5377
      break;
    case ORI:
5378
      SetResult(rt_reg, rs | oe_imm16);
5379 5380
      break;
    case XORI:
5381
      SetResult(rt_reg, rs ^ oe_imm16);
5382
      break;
5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399
    case LUI:
      if (rs_reg != 0) {
        // AUI instruction.
        DCHECK(kArchVariant == kMips64r6);
        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:
      DCHECK(kArchVariant == kMips64r6);
      DCHECK(rs_reg != 0);
      SetResult(rt_reg, rs + (se_imm16 << 16));
5400 5401 5402
      break;
    // ------------- Memory instructions.
    case LB:
5403
      set_register(rt_reg, ReadB(rs + se_imm16));
5404 5405
      break;
    case LH:
5406
      set_register(rt_reg, ReadH(rs + se_imm16, instr_.instr()));
5407 5408 5409 5410 5411 5412 5413
      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;
5414
      int32_t val = ReadW(addr, instr_.instr());
5415 5416 5417
      val <<= byte_shift * 8;
      val |= rt & mask;
      set_register(rt_reg, static_cast<int64_t>(val));
5418 5419 5420
      break;
    }
    case LW:
5421
      set_register(rt_reg, ReadW(rs + se_imm16, instr_.instr()));
5422 5423
      break;
    case LWU:
5424
      set_register(rt_reg, ReadWU(rs + se_imm16, instr_.instr()));
5425 5426
      break;
    case LD:
5427
      set_register(rt_reg, Read2W(rs + se_imm16, instr_.instr()));
5428 5429
      break;
    case LBU:
5430
      set_register(rt_reg, ReadBU(rs + se_imm16));
5431 5432
      break;
    case LHU:
5433
      set_register(rt_reg, ReadHU(rs + se_imm16, instr_.instr()));
5434 5435 5436 5437 5438 5439 5440
      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;
5441
      alu_out = ReadW(addr, instr_.instr());
5442 5443
      alu_out = static_cast<uint32_t> (alu_out) >> al_offset * 8;
      alu_out |= rt & mask;
5444
      set_register(rt_reg, alu_out);
5445 5446
      break;
    }
5447 5448 5449 5450 5451 5452
    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;
5453
      alu_out = Read2W(addr, instr_.instr());
5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464
      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;
5465
      alu_out = Read2W(addr, instr_.instr());
5466 5467 5468 5469 5470
      alu_out = alu_out >> al_offset * 8;
      alu_out |= rt & mask;
      set_register(rt_reg, alu_out);
      break;
    }
5471
    case SB:
5472
      WriteB(rs + se_imm16, static_cast<int8_t>(rt));
5473 5474
      break;
    case SH:
5475
      WriteH(rs + se_imm16, static_cast<uint16_t>(rt), instr_.instr());
5476 5477 5478 5479 5480 5481
      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;
5482
      uint64_t mem_value = ReadW(addr, instr_.instr()) & mask;
5483
      mem_value |= static_cast<uint32_t>(rt) >> byte_shift * 8;
5484
      WriteW(addr, static_cast<int32_t>(mem_value), instr_.instr());
5485 5486 5487
      break;
    }
    case SW:
5488
      WriteW(rs + se_imm16, static_cast<int32_t>(rt), instr_.instr());
5489
      break;
5490
    case SD:
5491
      Write2W(rs + se_imm16, rt, instr_.instr());
5492 5493 5494 5495 5496
      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;
5497
      uint64_t mem_value = ReadW(addr, instr_.instr());
5498
      mem_value = (rt << al_offset * 8) | (mem_value & mask);
5499
      WriteW(addr, static_cast<int32_t>(mem_value), instr_.instr());
5500 5501
      break;
    }
5502 5503 5504 5505 5506
    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;
5507
      uint64_t mem_value = Read2W(addr, instr_.instr()) & mask;
5508
      mem_value |= rt >> byte_shift * 8;
5509
      Write2W(addr, mem_value, instr_.instr());
5510 5511 5512 5513 5514 5515
      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;
5516
      uint64_t mem_value = Read2W(addr, instr_.instr());
5517
      mem_value = (rt << al_offset * 8) | (mem_value & mask);
5518
      Write2W(addr, mem_value, instr_.instr());
5519 5520
      break;
    }
5521
    case LWC1:
5522
      set_fpu_register(ft_reg, kFPUInvalidResult);  // Trash upper 32 bits.
5523 5524
      set_fpu_register_word(ft_reg,
                            ReadW(rs + se_imm16, instr_.instr(), FLOAT_DOUBLE));
5525 5526
      break;
    case LDC1:
5527
      set_fpu_register_double(ft_reg, ReadD(rs + se_imm16, instr_.instr()));
5528
      TraceMemRd(addr, get_fpu_register(ft_reg), DOUBLE);
5529
      break;
5530 5531
    case SWC1: {
      int32_t alu_out_32 = static_cast<int32_t>(get_fpu_register(ft_reg));
5532
      WriteW(rs + se_imm16, alu_out_32, instr_.instr());
5533 5534
      break;
    }
5535
    case SDC1:
5536
      WriteD(rs + se_imm16, get_fpu_register_double(ft_reg), instr_.instr());
5537
      TraceMemWr(rs + se_imm16, get_fpu_register(ft_reg), DWORD);
5538
      break;
5539 5540 5541
    // ------------- PC-Relative instructions.
    case PCREL: {
      // rt field: checking 5-bits.
5542
      int32_t imm21 = instr_.Imm21Value();
5543
      int64_t current_pc = get_pc();
5544 5545 5546 5547 5548 5549 5550 5551 5552 5553
      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: {
5554
          int32_t imm19 = instr_.Imm19Value();
5555 5556 5557 5558 5559 5560
          // 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);
5561
              alu_out = Read2W(addr, instr_.instr());
5562 5563 5564 5565 5566 5567 5568
              break;
            default: {
              // rt field: checking the most significant 2-bits.
              rt = (imm21 >> kImm19Bits);
              switch (rt) {
                case LWUPC: {
                  // Set sign.
5569 5570 5571
                  imm19 <<= (kOpcodeBits + kRsBits + 2);
                  imm19 >>= (kOpcodeBits + kRsBits + 2);
                  addr = current_pc + (imm19 << 2);
5572 5573 5574 5575 5576 5577
                  uint32_t* ptr = reinterpret_cast<uint32_t*>(addr);
                  alu_out = *ptr;
                  break;
                }
                case LWPC: {
                  // Set sign.
5578 5579 5580
                  imm19 <<= (kOpcodeBits + kRsBits + 2);
                  imm19 >>= (kOpcodeBits + kRsBits + 2);
                  addr = current_pc + (imm19 << 2);
5581 5582 5583 5584
                  int32_t* ptr = reinterpret_cast<int32_t*>(addr);
                  alu_out = *ptr;
                  break;
                }
5585 5586 5587
                case ADDIUPC: {
                  int64_t se_imm19 =
                      imm19 | ((imm19 & 0x40000) ? 0xfffffffffff80000 : 0);
5588 5589
                  alu_out = current_pc + (se_imm19 << 2);
                  break;
5590
                }
5591 5592 5593 5594 5595 5596 5597 5598 5599 5600
                default:
                  UNREACHABLE();
                  break;
              }
              break;
            }
          }
          break;
        }
      }
5601
      SetResult(rs_reg, alu_out);
5602 5603
      break;
    }
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
    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;
5629 5630 5631 5632 5633 5634 5635 5636 5637
    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 =
5638
        reinterpret_cast<Instruction*>(get_pc() + Instruction::kInstrSize);
5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649
    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).
5650 5651
void Simulator::DecodeTypeJump() {
  SimInstruction simInstr = instr_;
5652
  // Get current pc.
5653
  int64_t current_pc = get_pc();
5654
  // Get unchanged bits of pc.
5655
  int64_t pc_high_bits = current_pc & 0xfffffffff0000000;
5656
  // Next pc.
5657
  int64_t next_pc = pc_high_bits | (simInstr.Imm26Value() << 2);
5658 5659 5660 5661 5662 5663 5664 5665 5666 5667

  // 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 =
      reinterpret_cast<Instruction*>(current_pc + Instruction::kInstrSize);
  BranchDelayInstructionDecode(branch_delay_instr);

  // Update pc and ra if necessary.
  // Do this after the branch delay execution.
5668
  if (simInstr.IsLinkingInstruction()) {
5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692
    set_register(31, current_pc + 2 * Instruction::kInstrSize);
  }
  set_pc(next_pc);
  pc_modified_ = true;
}


// Executes the current instruction.
void Simulator::InstructionDecode(Instruction* instr) {
  if (v8::internal::FLAG_check_icache) {
    CheckICache(isolate_->simulator_i_cache(), instr);
  }
  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));
  }

5693 5694
  instr_ = instr;
  switch (instr_.InstructionType()) {
5695
    case Instruction::kRegisterType:
5696
      DecodeTypeRegister();
5697 5698
      break;
    case Instruction::kImmediateType:
5699
      DecodeTypeImmediate();
5700 5701
      break;
    case Instruction::kJumpType:
5702
      DecodeTypeJump();
5703 5704 5705 5706 5707 5708
      break;
    default:
      UNSUPPORTED();
  }

  if (::v8::internal::FLAG_trace_sim) {
5709 5710 5711
    PrintF("  0x%08" PRIxPTR "   %-44s   %s\n",
           reinterpret_cast<intptr_t>(instr), buffer.start(),
           trace_buf_.start());
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
  }

  if (!pc_modified_) {
    set_register(pc, reinterpret_cast<int64_t>(instr) +
                 Instruction::kInstrSize);
  }
}



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
    // we reach the particular instuction count.
    while (program_counter != end_sim_pc) {
      Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
      icount_++;
5741
      if (icount_ == static_cast<int64_t>(::v8::internal::FLAG_stop_sim_at)) {
5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753
        MipsDebugger dbg(this);
        dbg.Debug();
      } else {
        InstructionDecode(instr);
      }
      program_counter = get_pc();
    }
  }
}


void Simulator::CallInternal(byte* entry) {
5754 5755 5756
  // Adjust JS-based stack limit to C-based stack limit.
  isolate_->stack_guard()->AdjustStackLimitForSimulator();

5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823
  // Prepare to execute the code at entry.
  set_register(pc, reinterpret_cast<int64_t>(entry));
  // 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);
}


int64_t Simulator::Call(byte* entry, int argument_count, ...) {
5824
  const int kRegisterPassedArguments = 8;
5825 5826 5827 5828 5829
  va_list parameters;
  va_start(parameters, argument_count);
  // Set up arguments.

  // First four arguments passed in registers in both ABI's.
5830
  DCHECK(argument_count >= 4);
5831 5832 5833 5834 5835
  set_register(a0, va_arg(parameters, int64_t));
  set_register(a1, va_arg(parameters, int64_t));
  set_register(a2, va_arg(parameters, int64_t));
  set_register(a3, va_arg(parameters, int64_t));

5836 5837 5838 5839 5840 5841
  // Up to eight arguments passed in registers in N64 ABI.
  // TODO(plind): N64 ABI calls these regs a4 - a7. Clarify this.
  if (argument_count >= 5) set_register(a4, va_arg(parameters, int64_t));
  if (argument_count >= 6) set_register(a5, va_arg(parameters, int64_t));
  if (argument_count >= 7) set_register(a6, va_arg(parameters, int64_t));
  if (argument_count >= 8) set_register(a7, va_arg(parameters, int64_t));
5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875

  // Remaining arguments passed on stack.
  int64_t original_stack = get_register(sp);
  // Compute position of stack on entry to generated code.
  int stack_args_count = (argument_count > kRegisterPassedArguments) ?
                         (argument_count - kRegisterPassedArguments) : 0;
  int stack_args_size = stack_args_count * sizeof(int64_t) + kCArgsSlotsSize;
  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);
  for (int i = kRegisterPassedArguments; i < argument_count; i++) {
    int stack_index = i - kRegisterPassedArguments + kCArgSlotCount;
    stack_argument[stack_index] = va_arg(parameters, int64_t);
  }
  va_end(parameters);
  set_register(sp, entry_stack);

  CallInternal(entry);

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

  int64_t result = get_register(v0);
  return result;
}


double Simulator::CallFP(byte* entry, double d0, double d1) {
  if (!IsMipsSoftFloatABI) {
5876
    const FPURegister fparg2 = f13;
5877 5878 5879 5880
    set_fpu_register_double(f12, d0);
    set_fpu_register_double(fparg2, d1);
  } else {
    int buffer[2];
5881
    DCHECK(sizeof(buffer[0]) * 2 == sizeof(d0));
5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914
    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
5915 5916
}  // namespace internal
}  // namespace v8
5917 5918 5919 5920

#endif  // USE_SIMULATOR

#endif  // V8_TARGET_ARCH_MIPS64