1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
12 #if V8_TARGET_ARCH_MIPS64
14 #include "src/assembler.h"
15 #include "src/base/bits.h"
16 #include "src/disasm.h"
17 #include "src/mips64/constants-mips64.h"
18 #include "src/mips64/simulator-mips64.h"
19 #include "src/ostreams.h"
21 // Only build the simulator if not compiling for real MIPS hardware.
22 #if defined(USE_SIMULATOR)
28 bool HaveSameSign(int64_t a, int64_t b) {
29 return ((a ^ b) >= 0);
33 uint32_t get_fcsr_condition_bit(uint32_t cc) {
42 static int64_t MultiplyHighSigned(int64_t u, int64_t v) {
44 int64_t u1, v1, w1, w2, t;
52 t = u1 * v0 + (w0 >> 32);
57 return u1 * v1 + w2 + (w1 >> 32);
61 // This macro provides a platform independent use of sscanf. The reason for
62 // SScanF not being implemented in a platform independent was through
63 // ::v8::internal::OS in the same way as SNPrintF is that the Windows C Run-Time
64 // Library does not provide vsscanf.
65 #define SScanF sscanf // NOLINT
67 // The MipsDebugger class is used by the simulator while debugging simulated
71 explicit MipsDebugger(Simulator* sim) : sim_(sim) { }
74 void Stop(Instruction* instr);
76 // Print all registers with a nice formatting.
78 void PrintAllRegsIncludingFPU();
81 // We set the breakpoint code to 0xfffff to easily recognize it.
82 static const Instr kBreakpointInstr = SPECIAL | BREAK | 0xfffff << 6;
83 static const Instr kNopInstr = 0x0;
87 int64_t GetRegisterValue(int regnum);
88 int64_t GetFPURegisterValue(int regnum);
89 float GetFPURegisterValueFloat(int regnum);
90 double GetFPURegisterValueDouble(int regnum);
91 bool GetValue(const char* desc, int64_t* value);
93 // Set or delete a breakpoint. Returns true if successful.
94 bool SetBreakpoint(Instruction* breakpc);
95 bool DeleteBreakpoint(Instruction* breakpc);
97 // Undo and redo all breakpoints. This is needed to bracket disassembly and
98 // execution to skip past breakpoints when run from the debugger.
99 void UndoBreakpoints();
100 void RedoBreakpoints();
104 MipsDebugger::~MipsDebugger() {
108 #ifdef GENERATED_CODE_COVERAGE
109 static FILE* coverage_log = NULL;
112 static void InitializeCoverage() {
113 char* file_name = getenv("V8_GENERATED_CODE_COVERAGE_LOG");
114 if (file_name != NULL) {
115 coverage_log = fopen(file_name, "aw+");
120 void MipsDebugger::Stop(Instruction* instr) {
121 // Get the stop code.
122 uint32_t code = instr->Bits(25, 6);
123 // Retrieve the encoded address, which comes just after this stop.
125 reinterpret_cast<char**>(sim_->get_pc() + Instr::kInstrSize);
126 char* msg = *msg_address;
129 // Update this stop description.
130 if (!watched_stops_[code].desc) {
131 watched_stops_[code].desc = msg;
134 if (strlen(msg) > 0) {
135 if (coverage_log != NULL) {
136 fprintf(coverage_log, "%s\n", str);
137 fflush(coverage_log);
139 // Overwrite the instruction and address with nops.
140 instr->SetInstructionBits(kNopInstr);
141 reinterpret_cast<Instr*>(msg_address)->SetInstructionBits(kNopInstr);
143 // TODO(yuyin): 2 -> 3?
144 sim_->set_pc(sim_->get_pc() + 3 * Instruction::kInstructionSize);
148 #else // GENERATED_CODE_COVERAGE
150 #define UNSUPPORTED() printf("Unsupported instruction.\n");
152 static void InitializeCoverage() {}
155 void MipsDebugger::Stop(Instruction* instr) {
156 // Get the stop code.
157 uint32_t code = instr->Bits(25, 6);
158 // Retrieve the encoded address, which comes just after this stop.
159 char* msg = *reinterpret_cast<char**>(sim_->get_pc() +
160 Instruction::kInstrSize);
161 // Update this stop description.
162 if (!sim_->watched_stops_[code].desc) {
163 sim_->watched_stops_[code].desc = msg;
165 PrintF("Simulator hit %s (%u)\n", msg, code);
166 // TODO(yuyin): 2 -> 3?
167 sim_->set_pc(sim_->get_pc() + 3 * Instruction::kInstrSize);
170 #endif // GENERATED_CODE_COVERAGE
173 int64_t MipsDebugger::GetRegisterValue(int regnum) {
174 if (regnum == kNumSimuRegisters) {
175 return sim_->get_pc();
177 return sim_->get_register(regnum);
182 int64_t MipsDebugger::GetFPURegisterValue(int regnum) {
183 if (regnum == kNumFPURegisters) {
184 return sim_->get_pc();
186 return sim_->get_fpu_register(regnum);
191 float MipsDebugger::GetFPURegisterValueFloat(int regnum) {
192 if (regnum == kNumFPURegisters) {
193 return sim_->get_pc();
195 return sim_->get_fpu_register_float(regnum);
200 double MipsDebugger::GetFPURegisterValueDouble(int regnum) {
201 if (regnum == kNumFPURegisters) {
202 return sim_->get_pc();
204 return sim_->get_fpu_register_double(regnum);
209 bool MipsDebugger::GetValue(const char* desc, int64_t* value) {
210 int regnum = Registers::Number(desc);
211 int fpuregnum = FPURegisters::Number(desc);
213 if (regnum != kInvalidRegister) {
214 *value = GetRegisterValue(regnum);
216 } else if (fpuregnum != kInvalidFPURegister) {
217 *value = GetFPURegisterValue(fpuregnum);
219 } else if (strncmp(desc, "0x", 2) == 0) {
220 return SScanF(desc + 2, "%" SCNx64,
221 reinterpret_cast<uint64_t*>(value)) == 1;
223 return SScanF(desc, "%" SCNu64, reinterpret_cast<uint64_t*>(value)) == 1;
229 bool MipsDebugger::SetBreakpoint(Instruction* breakpc) {
230 // Check if a breakpoint can be set. If not return without any side-effects.
231 if (sim_->break_pc_ != NULL) {
235 // Set the breakpoint.
236 sim_->break_pc_ = breakpc;
237 sim_->break_instr_ = breakpc->InstructionBits();
238 // Not setting the breakpoint instruction in the code itself. It will be set
239 // when the debugger shell continues.
244 bool MipsDebugger::DeleteBreakpoint(Instruction* breakpc) {
245 if (sim_->break_pc_ != NULL) {
246 sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
249 sim_->break_pc_ = NULL;
250 sim_->break_instr_ = 0;
255 void MipsDebugger::UndoBreakpoints() {
256 if (sim_->break_pc_ != NULL) {
257 sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
262 void MipsDebugger::RedoBreakpoints() {
263 if (sim_->break_pc_ != NULL) {
264 sim_->break_pc_->SetInstructionBits(kBreakpointInstr);
269 void MipsDebugger::PrintAllRegs() {
270 #define REG_INFO(n) Registers::Name(n), GetRegisterValue(n), GetRegisterValue(n)
274 PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
275 REG_INFO(1), REG_INFO(2), REG_INFO(4));
277 PrintF("%34s\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
278 "", REG_INFO(3), REG_INFO(5));
280 PrintF("%34s\t%34s\t%3s: 0x%016lx %14ld\n", "", "", REG_INFO(6));
282 PrintF("%34s\t%34s\t%3s: 0x%016lx %14ld\n", "", "", REG_INFO(7));
285 for (int i = 0; i < 8; i++) {
286 PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
287 REG_INFO(8+i), REG_INFO(16+i));
291 PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
292 REG_INFO(24), REG_INFO(26), REG_INFO(32));
294 PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
295 REG_INFO(25), REG_INFO(27), REG_INFO(33));
297 PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
298 REG_INFO(29), REG_INFO(30), REG_INFO(28));
300 PrintF("%3s: 0x%016lx %14ld\t%3s: 0x%016lx %14ld\n",
301 REG_INFO(31), REG_INFO(34));
308 void MipsDebugger::PrintAllRegsIncludingFPU() {
309 #define FPU_REG_INFO(n) FPURegisters::Name(n), \
310 GetFPURegisterValue(n), \
311 GetFPURegisterValueDouble(n)
316 // f0, f1, f2, ... f31.
317 // TODO(plind): consider printing 2 columns for space efficiency.
318 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(0) );
319 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(1) );
320 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(2) );
321 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(3) );
322 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(4) );
323 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(5) );
324 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(6) );
325 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(7) );
326 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(8) );
327 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(9) );
328 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(10));
329 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(11));
330 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(12));
331 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(13));
332 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(14));
333 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(15));
334 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(16));
335 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(17));
336 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(18));
337 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(19));
338 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(20));
339 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(21));
340 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(22));
341 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(23));
342 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(24));
343 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(25));
344 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(26));
345 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(27));
346 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(28));
347 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(29));
348 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(30));
349 PrintF("%3s: 0x%016lx %16.4e\n", FPU_REG_INFO(31));
356 void MipsDebugger::Debug() {
357 intptr_t last_pc = -1;
360 #define COMMAND_SIZE 63
364 #define XSTR(a) STR(a)
366 char cmd[COMMAND_SIZE + 1];
367 char arg1[ARG_SIZE + 1];
368 char arg2[ARG_SIZE + 1];
369 char* argv[3] = { cmd, arg1, arg2 };
371 // Make sure to have a proper terminating character if reaching the limit.
372 cmd[COMMAND_SIZE] = 0;
376 // Undo all set breakpoints while running in the debugger shell. This will
377 // make them invisible to all commands.
380 while (!done && (sim_->get_pc() != Simulator::end_sim_pc)) {
381 if (last_pc != sim_->get_pc()) {
382 disasm::NameConverter converter;
383 disasm::Disassembler dasm(converter);
384 // Use a reasonably large buffer.
385 v8::internal::EmbeddedVector<char, 256> buffer;
386 dasm.InstructionDecode(buffer,
387 reinterpret_cast<byte*>(sim_->get_pc()));
388 PrintF(" 0x%016lx %s\n", sim_->get_pc(), buffer.start());
389 last_pc = sim_->get_pc();
391 char* line = ReadLine("sim> ");
395 char* last_input = sim_->last_debugger_input();
396 if (strcmp(line, "\n") == 0 && last_input != NULL) {
399 // Ownership is transferred to sim_;
400 sim_->set_last_debugger_input(line);
402 // Use sscanf to parse the individual parts of the command line. At the
403 // moment no command expects more than two parameters.
404 int argc = SScanF(line,
405 "%" XSTR(COMMAND_SIZE) "s "
406 "%" XSTR(ARG_SIZE) "s "
407 "%" XSTR(ARG_SIZE) "s",
409 if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) {
410 Instruction* instr = reinterpret_cast<Instruction*>(sim_->get_pc());
411 if (!(instr->IsTrap()) ||
412 instr->InstructionBits() == rtCallRedirInstr) {
413 sim_->InstructionDecode(
414 reinterpret_cast<Instruction*>(sim_->get_pc()));
416 // Allow si to jump over generated breakpoints.
417 PrintF("/!\\ Jumping over generated breakpoint.\n");
418 sim_->set_pc(sim_->get_pc() + Instruction::kInstrSize);
420 } else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) {
421 // Execute the one instruction we broke at with breakpoints disabled.
422 sim_->InstructionDecode(reinterpret_cast<Instruction*>(sim_->get_pc()));
423 // Leave the debugger shell.
425 } else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) {
429 if (strcmp(arg1, "all") == 0) {
431 } else if (strcmp(arg1, "allf") == 0) {
432 PrintAllRegsIncludingFPU();
434 int regnum = Registers::Number(arg1);
435 int fpuregnum = FPURegisters::Number(arg1);
437 if (regnum != kInvalidRegister) {
438 value = GetRegisterValue(regnum);
439 PrintF("%s: 0x%08lx %ld \n", arg1, value, value);
440 } else if (fpuregnum != kInvalidFPURegister) {
441 value = GetFPURegisterValue(fpuregnum);
442 dvalue = GetFPURegisterValueDouble(fpuregnum);
443 PrintF("%3s: 0x%016lx %16.4e\n",
444 FPURegisters::Name(fpuregnum), value, dvalue);
446 PrintF("%s unrecognized\n", arg1);
451 if (strcmp(arg2, "single") == 0) {
454 int fpuregnum = FPURegisters::Number(arg1);
456 if (fpuregnum != kInvalidFPURegister) {
457 value = GetFPURegisterValue(fpuregnum);
458 value &= 0xffffffffUL;
459 fvalue = GetFPURegisterValueFloat(fpuregnum);
460 PrintF("%s: 0x%08lx %11.4e\n", arg1, value, fvalue);
462 PrintF("%s unrecognized\n", arg1);
465 PrintF("print <fpu register> single\n");
468 PrintF("print <register> or print <fpu register> single\n");
471 } else if ((strcmp(cmd, "po") == 0)
472 || (strcmp(cmd, "printobject") == 0)) {
476 if (GetValue(arg1, &value)) {
477 Object* obj = reinterpret_cast<Object*>(value);
478 os << arg1 << ": \n";
483 os << Brief(obj) << "\n";
486 os << arg1 << " unrecognized\n";
489 PrintF("printobject <value>\n");
491 } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) {
496 if (strcmp(cmd, "stack") == 0) {
497 cur = reinterpret_cast<int64_t*>(sim_->get_register(Simulator::sp));
498 } else { // Command "mem".
500 if (!GetValue(arg1, &value)) {
501 PrintF("%s unrecognized\n", arg1);
504 cur = reinterpret_cast<int64_t*>(value);
509 if (argc == next_arg) {
512 if (!GetValue(argv[next_arg], &words)) {
519 PrintF(" 0x%012lx: 0x%016lx %14ld",
520 reinterpret_cast<intptr_t>(cur), *cur, *cur);
521 HeapObject* obj = reinterpret_cast<HeapObject*>(*cur);
522 int64_t value = *cur;
523 Heap* current_heap = v8::internal::Isolate::Current()->heap();
524 if (((value & 1) == 0) || current_heap->Contains(obj)) {
526 if ((value & 1) == 0) {
527 PrintF("smi %d", static_cast<int>(value >> 32));
537 } else if ((strcmp(cmd, "disasm") == 0) ||
538 (strcmp(cmd, "dpc") == 0) ||
539 (strcmp(cmd, "di") == 0)) {
540 disasm::NameConverter converter;
541 disasm::Disassembler dasm(converter);
542 // Use a reasonably large buffer.
543 v8::internal::EmbeddedVector<char, 256> buffer;
549 cur = reinterpret_cast<byte*>(sim_->get_pc());
550 end = cur + (10 * Instruction::kInstrSize);
551 } else if (argc == 2) {
552 int regnum = Registers::Number(arg1);
553 if (regnum != kInvalidRegister || strncmp(arg1, "0x", 2) == 0) {
554 // The argument is an address or a register name.
556 if (GetValue(arg1, &value)) {
557 cur = reinterpret_cast<byte*>(value);
558 // Disassemble 10 instructions at <arg1>.
559 end = cur + (10 * Instruction::kInstrSize);
562 // The argument is the number of instructions.
564 if (GetValue(arg1, &value)) {
565 cur = reinterpret_cast<byte*>(sim_->get_pc());
566 // Disassemble <arg1> instructions.
567 end = cur + (value * Instruction::kInstrSize);
573 if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
574 cur = reinterpret_cast<byte*>(value1);
575 end = cur + (value2 * Instruction::kInstrSize);
580 dasm.InstructionDecode(buffer, cur);
581 PrintF(" 0x%08lx %s\n",
582 reinterpret_cast<intptr_t>(cur), buffer.start());
583 cur += Instruction::kInstrSize;
585 } else if (strcmp(cmd, "gdb") == 0) {
586 PrintF("relinquishing control to gdb\n");
587 v8::base::OS::DebugBreak();
588 PrintF("regaining control from gdb\n");
589 } else if (strcmp(cmd, "break") == 0) {
592 if (GetValue(arg1, &value)) {
593 if (!SetBreakpoint(reinterpret_cast<Instruction*>(value))) {
594 PrintF("setting breakpoint failed\n");
597 PrintF("%s unrecognized\n", arg1);
600 PrintF("break <address>\n");
602 } else if (strcmp(cmd, "del") == 0) {
603 if (!DeleteBreakpoint(NULL)) {
604 PrintF("deleting breakpoint failed\n");
606 } else if (strcmp(cmd, "flags") == 0) {
607 PrintF("No flags on MIPS !\n");
608 } else if (strcmp(cmd, "stop") == 0) {
610 intptr_t stop_pc = sim_->get_pc() -
611 2 * Instruction::kInstrSize;
612 Instruction* stop_instr = reinterpret_cast<Instruction*>(stop_pc);
613 Instruction* msg_address =
614 reinterpret_cast<Instruction*>(stop_pc +
615 Instruction::kInstrSize);
616 if ((argc == 2) && (strcmp(arg1, "unstop") == 0)) {
617 // Remove the current stop.
618 if (sim_->IsStopInstruction(stop_instr)) {
619 stop_instr->SetInstructionBits(kNopInstr);
620 msg_address->SetInstructionBits(kNopInstr);
622 PrintF("Not at debugger stop.\n");
624 } else if (argc == 3) {
625 // Print information about all/the specified breakpoint(s).
626 if (strcmp(arg1, "info") == 0) {
627 if (strcmp(arg2, "all") == 0) {
628 PrintF("Stop information:\n");
629 for (uint32_t i = kMaxWatchpointCode + 1;
632 sim_->PrintStopInfo(i);
634 } else if (GetValue(arg2, &value)) {
635 sim_->PrintStopInfo(value);
637 PrintF("Unrecognized argument.\n");
639 } else if (strcmp(arg1, "enable") == 0) {
640 // Enable all/the specified breakpoint(s).
641 if (strcmp(arg2, "all") == 0) {
642 for (uint32_t i = kMaxWatchpointCode + 1;
647 } else if (GetValue(arg2, &value)) {
648 sim_->EnableStop(value);
650 PrintF("Unrecognized argument.\n");
652 } else if (strcmp(arg1, "disable") == 0) {
653 // Disable all/the specified breakpoint(s).
654 if (strcmp(arg2, "all") == 0) {
655 for (uint32_t i = kMaxWatchpointCode + 1;
658 sim_->DisableStop(i);
660 } else if (GetValue(arg2, &value)) {
661 sim_->DisableStop(value);
663 PrintF("Unrecognized argument.\n");
667 PrintF("Wrong usage. Use help command for more information.\n");
669 } else if ((strcmp(cmd, "stat") == 0) || (strcmp(cmd, "st") == 0)) {
670 // Print registers and disassemble.
674 disasm::NameConverter converter;
675 disasm::Disassembler dasm(converter);
676 // Use a reasonably large buffer.
677 v8::internal::EmbeddedVector<char, 256> buffer;
683 cur = reinterpret_cast<byte*>(sim_->get_pc());
684 end = cur + (10 * Instruction::kInstrSize);
685 } else if (argc == 2) {
687 if (GetValue(arg1, &value)) {
688 cur = reinterpret_cast<byte*>(value);
689 // no length parameter passed, assume 10 instructions
690 end = cur + (10 * Instruction::kInstrSize);
695 if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
696 cur = reinterpret_cast<byte*>(value1);
697 end = cur + (value2 * Instruction::kInstrSize);
702 dasm.InstructionDecode(buffer, cur);
703 PrintF(" 0x%08lx %s\n",
704 reinterpret_cast<intptr_t>(cur), buffer.start());
705 cur += Instruction::kInstrSize;
707 } else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) {
709 PrintF(" continue execution (alias 'c')\n");
711 PrintF(" step one instruction (alias 'si')\n");
712 PrintF("print <register>\n");
713 PrintF(" print register content (alias 'p')\n");
714 PrintF(" use register name 'all' to print all registers\n");
715 PrintF("printobject <register>\n");
716 PrintF(" print an object from a register (alias 'po')\n");
717 PrintF("stack [<words>]\n");
718 PrintF(" dump stack content, default dump 10 words)\n");
719 PrintF("mem <address> [<words>]\n");
720 PrintF(" dump memory content, default dump 10 words)\n");
722 PrintF(" print flags\n");
723 PrintF("disasm [<instructions>]\n");
724 PrintF("disasm [<address/register>]\n");
725 PrintF("disasm [[<address/register>] <instructions>]\n");
726 PrintF(" disassemble code, default is 10 instructions\n");
727 PrintF(" from pc (alias 'di')\n");
729 PrintF(" enter gdb\n");
730 PrintF("break <address>\n");
731 PrintF(" set a break point on the address\n");
733 PrintF(" delete the breakpoint\n");
734 PrintF("stop feature:\n");
735 PrintF(" Description:\n");
736 PrintF(" Stops are debug instructions inserted by\n");
737 PrintF(" the Assembler::stop() function.\n");
738 PrintF(" When hitting a stop, the Simulator will\n");
739 PrintF(" stop and and give control to the Debugger.\n");
740 PrintF(" All stop codes are watched:\n");
741 PrintF(" - They can be enabled / disabled: the Simulator\n");
742 PrintF(" will / won't stop when hitting them.\n");
743 PrintF(" - The Simulator keeps track of how many times they \n");
744 PrintF(" are met. (See the info command.) Going over a\n");
745 PrintF(" disabled stop still increases its counter. \n");
746 PrintF(" Commands:\n");
747 PrintF(" stop info all/<code> : print infos about number <code>\n");
748 PrintF(" or all stop(s).\n");
749 PrintF(" stop enable/disable all/<code> : enables / disables\n");
750 PrintF(" all or number <code> stop(s)\n");
751 PrintF(" stop unstop\n");
752 PrintF(" ignore the stop instruction at the current location\n");
753 PrintF(" from now on\n");
755 PrintF("Unknown command: %s\n", cmd);
760 // Add all the breakpoints back to stop execution and enter the debugger
772 static bool ICacheMatch(void* one, void* two) {
773 DCHECK((reinterpret_cast<intptr_t>(one) & CachePage::kPageMask) == 0);
774 DCHECK((reinterpret_cast<intptr_t>(two) & CachePage::kPageMask) == 0);
779 static uint32_t ICacheHash(void* key) {
780 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(key)) >> 2;
784 static bool AllOnOnePage(uintptr_t start, int size) {
785 intptr_t start_page = (start & ~CachePage::kPageMask);
786 intptr_t end_page = ((start + size) & ~CachePage::kPageMask);
787 return start_page == end_page;
791 void Simulator::set_last_debugger_input(char* input) {
792 DeleteArray(last_debugger_input_);
793 last_debugger_input_ = input;
797 void Simulator::FlushICache(v8::internal::HashMap* i_cache,
800 int64_t start = reinterpret_cast<int64_t>(start_addr);
801 int64_t intra_line = (start & CachePage::kLineMask);
804 size = ((size - 1) | CachePage::kLineMask) + 1;
805 int offset = (start & CachePage::kPageMask);
806 while (!AllOnOnePage(start, size - 1)) {
807 int bytes_to_flush = CachePage::kPageSize - offset;
808 FlushOnePage(i_cache, start, bytes_to_flush);
809 start += bytes_to_flush;
810 size -= bytes_to_flush;
811 DCHECK_EQ((uint64_t)0, start & CachePage::kPageMask);
815 FlushOnePage(i_cache, start, size);
820 CachePage* Simulator::GetCachePage(v8::internal::HashMap* i_cache, void* page) {
821 v8::internal::HashMap::Entry* entry = i_cache->Lookup(page,
824 if (entry->value == NULL) {
825 CachePage* new_page = new CachePage();
826 entry->value = new_page;
828 return reinterpret_cast<CachePage*>(entry->value);
832 // Flush from start up to and not including start + size.
833 void Simulator::FlushOnePage(v8::internal::HashMap* i_cache,
836 DCHECK(size <= CachePage::kPageSize);
837 DCHECK(AllOnOnePage(start, size - 1));
838 DCHECK((start & CachePage::kLineMask) == 0);
839 DCHECK((size & CachePage::kLineMask) == 0);
840 void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask));
841 int offset = (start & CachePage::kPageMask);
842 CachePage* cache_page = GetCachePage(i_cache, page);
843 char* valid_bytemap = cache_page->ValidityByte(offset);
844 memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift);
848 void Simulator::CheckICache(v8::internal::HashMap* i_cache,
849 Instruction* instr) {
850 int64_t address = reinterpret_cast<int64_t>(instr);
851 void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask));
852 void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask));
853 int offset = (address & CachePage::kPageMask);
854 CachePage* cache_page = GetCachePage(i_cache, page);
855 char* cache_valid_byte = cache_page->ValidityByte(offset);
856 bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID);
857 char* cached_line = cache_page->CachedData(offset & ~CachePage::kLineMask);
859 // Check that the data in memory matches the contents of the I-cache.
860 CHECK_EQ(0, memcmp(reinterpret_cast<void*>(instr),
861 cache_page->CachedData(offset),
862 Instruction::kInstrSize));
864 // Cache miss. Load memory into the cache.
865 memcpy(cached_line, line, CachePage::kLineLength);
866 *cache_valid_byte = CachePage::LINE_VALID;
871 void Simulator::Initialize(Isolate* isolate) {
872 if (isolate->simulator_initialized()) return;
873 isolate->set_simulator_initialized(true);
874 ::v8::internal::ExternalReference::set_redirector(isolate,
875 &RedirectExternalReference);
879 Simulator::Simulator(Isolate* isolate) : isolate_(isolate) {
880 i_cache_ = isolate_->simulator_i_cache();
881 if (i_cache_ == NULL) {
882 i_cache_ = new v8::internal::HashMap(&ICacheMatch);
883 isolate_->set_simulator_i_cache(i_cache_);
886 // Set up simulator support first. Some of this information is needed to
887 // setup the architecture state.
888 stack_size_ = FLAG_sim_stack_size * KB;
889 stack_ = reinterpret_cast<char*>(malloc(stack_size_));
890 pc_modified_ = false;
896 // Set up architecture state.
897 // All registers are initialized to zero to start with.
898 for (int i = 0; i < kNumSimuRegisters; i++) {
901 for (int i = 0; i < kNumFPURegisters; i++) {
902 FPUregisters_[i] = 0;
906 // The sp is initialized to point to the bottom (high address) of the
907 // allocated stack area. To be safe in potential stack underflows we leave
908 // some buffer below.
909 registers_[sp] = reinterpret_cast<int64_t>(stack_) + stack_size_ - 64;
910 // The ra and pc are initialized to a known bad value that will cause an
911 // access violation if the simulator ever tries to execute it.
912 registers_[pc] = bad_ra;
913 registers_[ra] = bad_ra;
914 InitializeCoverage();
915 for (int i = 0; i < kNumExceptions; i++) {
919 last_debugger_input_ = NULL;
923 Simulator::~Simulator() {
927 // When the generated code calls an external reference we need to catch that in
928 // the simulator. The external reference will be a function compiled for the
929 // host architecture. We need to call that function instead of trying to
930 // execute it with the simulator. We do that by redirecting the external
931 // reference to a swi (software-interrupt) instruction that is handled by
932 // the simulator. We write the original destination of the jump just at a known
933 // offset from the swi instruction so the simulator knows what to call.
936 Redirection(void* external_function, ExternalReference::Type type)
937 : external_function_(external_function),
938 swi_instruction_(rtCallRedirInstr),
941 Isolate* isolate = Isolate::Current();
942 next_ = isolate->simulator_redirection();
943 Simulator::current(isolate)->
944 FlushICache(isolate->simulator_i_cache(),
945 reinterpret_cast<void*>(&swi_instruction_),
946 Instruction::kInstrSize);
947 isolate->set_simulator_redirection(this);
950 void* address_of_swi_instruction() {
951 return reinterpret_cast<void*>(&swi_instruction_);
954 void* external_function() { return external_function_; }
955 ExternalReference::Type type() { return type_; }
957 static Redirection* Get(void* external_function,
958 ExternalReference::Type type) {
959 Isolate* isolate = Isolate::Current();
960 Redirection* current = isolate->simulator_redirection();
961 for (; current != NULL; current = current->next_) {
962 if (current->external_function_ == external_function) return current;
964 return new Redirection(external_function, type);
967 static Redirection* FromSwiInstruction(Instruction* swi_instruction) {
968 char* addr_of_swi = reinterpret_cast<char*>(swi_instruction);
969 char* addr_of_redirection =
970 addr_of_swi - OFFSET_OF(Redirection, swi_instruction_);
971 return reinterpret_cast<Redirection*>(addr_of_redirection);
974 static void* ReverseRedirection(int64_t reg) {
975 Redirection* redirection = FromSwiInstruction(
976 reinterpret_cast<Instruction*>(reinterpret_cast<void*>(reg)));
977 return redirection->external_function();
981 void* external_function_;
982 uint32_t swi_instruction_;
983 ExternalReference::Type type_;
988 void* Simulator::RedirectExternalReference(void* external_function,
989 ExternalReference::Type type) {
990 Redirection* redirection = Redirection::Get(external_function, type);
991 return redirection->address_of_swi_instruction();
995 // Get the active Simulator for the current thread.
996 Simulator* Simulator::current(Isolate* isolate) {
997 v8::internal::Isolate::PerIsolateThreadData* isolate_data =
998 isolate->FindOrAllocatePerThreadDataForThisThread();
999 DCHECK(isolate_data != NULL);
1000 DCHECK(isolate_data != NULL);
1002 Simulator* sim = isolate_data->simulator();
1004 // TODO(146): delete the simulator object when a thread/isolate goes away.
1005 sim = new Simulator(isolate);
1006 isolate_data->set_simulator(sim);
1012 // Sets the register in the architecture state. It will also deal with updating
1013 // Simulator internal state for special registers such as PC.
1014 void Simulator::set_register(int reg, int64_t value) {
1015 DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1017 pc_modified_ = true;
1020 // Zero register always holds 0.
1021 registers_[reg] = (reg == 0) ? 0 : value;
1025 void Simulator::set_dw_register(int reg, const int* dbl) {
1026 DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1027 registers_[reg] = dbl[1];
1028 registers_[reg] = registers_[reg] << 32;
1029 registers_[reg] += dbl[0];
1033 void Simulator::set_fpu_register(int fpureg, int64_t value) {
1034 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1035 FPUregisters_[fpureg] = value;
1039 void Simulator::set_fpu_register_word(int fpureg, int32_t value) {
1040 // Set ONLY lower 32-bits, leaving upper bits untouched.
1041 // TODO(plind): big endian issue.
1042 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1043 int32_t *pword = reinterpret_cast<int32_t*>(&FPUregisters_[fpureg]);
1048 void Simulator::set_fpu_register_hi_word(int fpureg, int32_t value) {
1049 // Set ONLY upper 32-bits, leaving lower bits untouched.
1050 // TODO(plind): big endian issue.
1051 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1052 int32_t *phiword = (reinterpret_cast<int32_t*>(&FPUregisters_[fpureg])) + 1;
1057 void Simulator::set_fpu_register_float(int fpureg, float value) {
1058 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1059 *bit_cast<float*>(&FPUregisters_[fpureg]) = value;
1063 void Simulator::set_fpu_register_double(int fpureg, double value) {
1064 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1065 *bit_cast<double*>(&FPUregisters_[fpureg]) = value;
1069 // Get the register from the architecture state. This function does handle
1070 // the special case of accessing the PC register.
1071 int64_t Simulator::get_register(int reg) const {
1072 DCHECK((reg >= 0) && (reg < kNumSimuRegisters));
1076 return registers_[reg] + ((reg == pc) ? Instruction::kPCReadOffset : 0);
1080 double Simulator::get_double_from_register_pair(int reg) {
1081 // TODO(plind): bad ABI stuff, refactor or remove.
1082 DCHECK((reg >= 0) && (reg < kNumSimuRegisters) && ((reg % 2) == 0));
1084 double dm_val = 0.0;
1085 // Read the bits from the unsigned integer register_[] array
1086 // into the double precision floating point value and return it.
1087 char buffer[sizeof(registers_[0])];
1088 memcpy(buffer, ®isters_[reg], sizeof(registers_[0]));
1089 memcpy(&dm_val, buffer, sizeof(registers_[0]));
1094 int64_t Simulator::get_fpu_register(int fpureg) const {
1095 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1096 return FPUregisters_[fpureg];
1100 int32_t Simulator::get_fpu_register_word(int fpureg) const {
1101 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1102 return static_cast<int32_t>(FPUregisters_[fpureg] & 0xffffffff);
1106 int32_t Simulator::get_fpu_register_signed_word(int fpureg) const {
1107 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1108 return static_cast<int32_t>(FPUregisters_[fpureg] & 0xffffffff);
1112 int32_t Simulator::get_fpu_register_hi_word(int fpureg) const {
1113 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1114 return static_cast<int32_t>((FPUregisters_[fpureg] >> 32) & 0xffffffff);
1118 float Simulator::get_fpu_register_float(int fpureg) const {
1119 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1120 return *bit_cast<float*>(const_cast<int64_t*>(&FPUregisters_[fpureg]));
1124 double Simulator::get_fpu_register_double(int fpureg) const {
1125 DCHECK((fpureg >= 0) && (fpureg < kNumFPURegisters));
1126 return *bit_cast<double*>(&FPUregisters_[fpureg]);
1130 // Runtime FP routines take up to two double arguments and zero
1131 // or one integer arguments. All are constructed here,
1132 // from a0-a3 or f12 and f13 (n64), or f14 (O32).
1133 void Simulator::GetFpArgs(double* x, double* y, int32_t* z) {
1134 if (!IsMipsSoftFloatABI) {
1135 const int fparg2 = (kMipsAbi == kN64) ? 13 : 14;
1136 *x = get_fpu_register_double(12);
1137 *y = get_fpu_register_double(fparg2);
1138 *z = get_register(a2);
1140 // TODO(plind): bad ABI stuff, refactor or remove.
1141 // We use a char buffer to get around the strict-aliasing rules which
1142 // otherwise allow the compiler to optimize away the copy.
1143 char buffer[sizeof(*x)];
1144 int32_t* reg_buffer = reinterpret_cast<int32_t*>(buffer);
1146 // Registers a0 and a1 -> x.
1147 reg_buffer[0] = get_register(a0);
1148 reg_buffer[1] = get_register(a1);
1149 memcpy(x, buffer, sizeof(buffer));
1150 // Registers a2 and a3 -> y.
1151 reg_buffer[0] = get_register(a2);
1152 reg_buffer[1] = get_register(a3);
1153 memcpy(y, buffer, sizeof(buffer));
1155 reg_buffer[0] = get_register(a2);
1156 memcpy(z, buffer, sizeof(*z));
1161 // The return value is either in v0/v1 or f0.
1162 void Simulator::SetFpResult(const double& result) {
1163 if (!IsMipsSoftFloatABI) {
1164 set_fpu_register_double(0, result);
1166 char buffer[2 * sizeof(registers_[0])];
1167 int64_t* reg_buffer = reinterpret_cast<int64_t*>(buffer);
1168 memcpy(buffer, &result, sizeof(buffer));
1169 // Copy result to v0 and v1.
1170 set_register(v0, reg_buffer[0]);
1171 set_register(v1, reg_buffer[1]);
1176 // Helper functions for setting and testing the FCSR register's bits.
1177 void Simulator::set_fcsr_bit(uint32_t cc, bool value) {
1181 FCSR_ &= ~(1 << cc);
1186 bool Simulator::test_fcsr_bit(uint32_t cc) {
1187 return FCSR_ & (1 << cc);
1191 // Sets the rounding error codes in FCSR based on the result of the rounding.
1192 // Returns true if the operation was invalid.
1193 bool Simulator::set_fcsr_round_error(double original, double rounded) {
1195 double max_int32 = std::numeric_limits<int32_t>::max();
1196 double min_int32 = std::numeric_limits<int32_t>::min();
1198 if (!std::isfinite(original) || !std::isfinite(rounded)) {
1199 set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
1203 if (original != rounded) {
1204 set_fcsr_bit(kFCSRInexactFlagBit, true);
1207 if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) {
1208 set_fcsr_bit(kFCSRUnderflowFlagBit, true);
1212 if (rounded > max_int32 || rounded < min_int32) {
1213 set_fcsr_bit(kFCSROverflowFlagBit, true);
1214 // The reference is not really clear but it seems this is required:
1215 set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
1223 // Sets the rounding error codes in FCSR based on the result of the rounding.
1224 // Returns true if the operation was invalid.
1225 bool Simulator::set_fcsr_round64_error(double original, double rounded) {
1227 double max_int64 = std::numeric_limits<int64_t>::max();
1228 double min_int64 = std::numeric_limits<int64_t>::min();
1230 if (!std::isfinite(original) || !std::isfinite(rounded)) {
1231 set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
1235 if (original != rounded) {
1236 set_fcsr_bit(kFCSRInexactFlagBit, true);
1239 if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) {
1240 set_fcsr_bit(kFCSRUnderflowFlagBit, true);
1244 if (rounded > max_int64 || rounded < min_int64) {
1245 set_fcsr_bit(kFCSROverflowFlagBit, true);
1246 // The reference is not really clear but it seems this is required:
1247 set_fcsr_bit(kFCSRInvalidOpFlagBit, true);
1255 // Raw access to the PC register.
1256 void Simulator::set_pc(int64_t value) {
1257 pc_modified_ = true;
1258 registers_[pc] = value;
1262 bool Simulator::has_bad_pc() const {
1263 return ((registers_[pc] == bad_ra) || (registers_[pc] == end_sim_pc));
1267 // Raw access to the PC register without the special adjustment when reading.
1268 int64_t Simulator::get_pc() const {
1269 return registers_[pc];
1273 // The MIPS cannot do unaligned reads and writes. On some MIPS platforms an
1274 // interrupt is caused. On others it does a funky rotation thing. For now we
1275 // simply disallow unaligned reads, but at some point we may want to move to
1276 // emulating the rotate behaviour. Note that simulator runs have the runtime
1277 // system running directly on the host system and only generated code is
1278 // executed in the simulator. Since the host is typically IA32 we will not
1279 // get the correct MIPS-like behaviour on unaligned accesses.
1281 // TODO(plind): refactor this messy debug code when we do unaligned access.
1282 void Simulator::DieOrDebug() {
1283 if (1) { // Flag for this was removed.
1284 MipsDebugger dbg(this);
1292 void Simulator::TraceRegWr(int64_t value) {
1293 if (::v8::internal::FLAG_trace_sim) {
1294 SNPrintF(trace_buf_, "%016lx", value);
1299 // TODO(plind): consider making icount_ printing a flag option.
1300 void Simulator::TraceMemRd(int64_t addr, int64_t value) {
1301 if (::v8::internal::FLAG_trace_sim) {
1302 SNPrintF(trace_buf_, "%016lx <-- [%016lx] (%ld)",
1303 value, addr, icount_);
1308 void Simulator::TraceMemWr(int64_t addr, int64_t value, TraceType t) {
1309 if (::v8::internal::FLAG_trace_sim) {
1312 SNPrintF(trace_buf_, " %02x --> [%016lx]",
1313 static_cast<int8_t>(value), addr);
1316 SNPrintF(trace_buf_, " %04x --> [%016lx]",
1317 static_cast<int16_t>(value), addr);
1320 SNPrintF(trace_buf_, " %08x --> [%016lx]",
1321 static_cast<int32_t>(value), addr);
1324 SNPrintF(trace_buf_, "%016lx --> [%016lx] (%ld)",
1325 value, addr, icount_);
1332 // TODO(plind): sign-extend and zero-extend not implmented properly
1333 // on all the ReadXX functions, I don't think re-interpret cast does it.
1334 int32_t Simulator::ReadW(int64_t addr, Instruction* instr) {
1335 if (addr >=0 && addr < 0x400) {
1336 // This has to be a NULL-dereference, drop into debugger.
1337 PrintF("Memory read from bad address: 0x%08lx, pc=0x%08lx\n",
1338 addr, reinterpret_cast<intptr_t>(instr));
1341 if ((addr & 0x3) == 0) {
1342 int32_t* ptr = reinterpret_cast<int32_t*>(addr);
1343 TraceMemRd(addr, static_cast<int64_t>(*ptr));
1346 PrintF("Unaligned read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1348 reinterpret_cast<intptr_t>(instr));
1354 uint32_t Simulator::ReadWU(int64_t addr, Instruction* instr) {
1355 if (addr >=0 && addr < 0x400) {
1356 // This has to be a NULL-dereference, drop into debugger.
1357 PrintF("Memory read from bad address: 0x%08lx, pc=0x%08lx\n",
1358 addr, reinterpret_cast<intptr_t>(instr));
1361 if ((addr & 0x3) == 0) {
1362 uint32_t* ptr = reinterpret_cast<uint32_t*>(addr);
1363 TraceMemRd(addr, static_cast<int64_t>(*ptr));
1366 PrintF("Unaligned read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1368 reinterpret_cast<intptr_t>(instr));
1374 void Simulator::WriteW(int64_t addr, int value, Instruction* instr) {
1375 if (addr >= 0 && addr < 0x400) {
1376 // This has to be a NULL-dereference, drop into debugger.
1377 PrintF("Memory write to bad address: 0x%08lx, pc=0x%08lx\n",
1378 addr, reinterpret_cast<intptr_t>(instr));
1381 if ((addr & 0x3) == 0) {
1382 TraceMemWr(addr, value, WORD);
1383 int* ptr = reinterpret_cast<int*>(addr);
1387 PrintF("Unaligned write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1389 reinterpret_cast<intptr_t>(instr));
1394 int64_t Simulator::Read2W(int64_t addr, Instruction* instr) {
1395 if (addr >=0 && addr < 0x400) {
1396 // This has to be a NULL-dereference, drop into debugger.
1397 PrintF("Memory read from bad address: 0x%08lx, pc=0x%08lx\n",
1398 addr, reinterpret_cast<intptr_t>(instr));
1401 if ((addr & kPointerAlignmentMask) == 0) {
1402 int64_t* ptr = reinterpret_cast<int64_t*>(addr);
1403 TraceMemRd(addr, *ptr);
1406 PrintF("Unaligned read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1408 reinterpret_cast<intptr_t>(instr));
1414 void Simulator::Write2W(int64_t addr, int64_t value, Instruction* instr) {
1415 if (addr >= 0 && addr < 0x400) {
1416 // This has to be a NULL-dereference, drop into debugger.
1417 PrintF("Memory write to bad address: 0x%08lx, pc=0x%08lx\n",
1418 addr, reinterpret_cast<intptr_t>(instr));
1421 if ((addr & kPointerAlignmentMask) == 0) {
1422 TraceMemWr(addr, value, DWORD);
1423 int64_t* ptr = reinterpret_cast<int64_t*>(addr);
1427 PrintF("Unaligned write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1429 reinterpret_cast<intptr_t>(instr));
1434 double Simulator::ReadD(int64_t addr, Instruction* instr) {
1435 if ((addr & kDoubleAlignmentMask) == 0) {
1436 double* ptr = reinterpret_cast<double*>(addr);
1439 PrintF("Unaligned (double) read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1441 reinterpret_cast<intptr_t>(instr));
1447 void Simulator::WriteD(int64_t addr, double value, Instruction* instr) {
1448 if ((addr & kDoubleAlignmentMask) == 0) {
1449 double* ptr = reinterpret_cast<double*>(addr);
1453 PrintF("Unaligned (double) write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1455 reinterpret_cast<intptr_t>(instr));
1460 uint16_t Simulator::ReadHU(int64_t addr, Instruction* instr) {
1461 if ((addr & 1) == 0) {
1462 uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
1463 TraceMemRd(addr, static_cast<int64_t>(*ptr));
1466 PrintF("Unaligned unsigned halfword read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1468 reinterpret_cast<intptr_t>(instr));
1474 int16_t Simulator::ReadH(int64_t addr, Instruction* instr) {
1475 if ((addr & 1) == 0) {
1476 int16_t* ptr = reinterpret_cast<int16_t*>(addr);
1477 TraceMemRd(addr, static_cast<int64_t>(*ptr));
1480 PrintF("Unaligned signed halfword read at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1482 reinterpret_cast<intptr_t>(instr));
1488 void Simulator::WriteH(int64_t addr, uint16_t value, Instruction* instr) {
1489 if ((addr & 1) == 0) {
1490 TraceMemWr(addr, value, HALF);
1491 uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
1496 "Unaligned unsigned halfword write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1498 reinterpret_cast<intptr_t>(instr));
1503 void Simulator::WriteH(int64_t addr, int16_t value, Instruction* instr) {
1504 if ((addr & 1) == 0) {
1505 TraceMemWr(addr, value, HALF);
1506 int16_t* ptr = reinterpret_cast<int16_t*>(addr);
1510 PrintF("Unaligned halfword write at 0x%08lx, pc=0x%08" V8PRIxPTR "\n",
1512 reinterpret_cast<intptr_t>(instr));
1517 uint32_t Simulator::ReadBU(int64_t addr) {
1518 uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
1519 TraceMemRd(addr, static_cast<int64_t>(*ptr));
1524 int32_t Simulator::ReadB(int64_t addr) {
1525 int8_t* ptr = reinterpret_cast<int8_t*>(addr);
1526 TraceMemRd(addr, static_cast<int64_t>(*ptr));
1531 void Simulator::WriteB(int64_t addr, uint8_t value) {
1532 TraceMemWr(addr, value, BYTE);
1533 uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
1538 void Simulator::WriteB(int64_t addr, int8_t value) {
1539 TraceMemWr(addr, value, BYTE);
1540 int8_t* ptr = reinterpret_cast<int8_t*>(addr);
1545 // Returns the limit of the stack area to enable checking for stack overflows.
1546 uintptr_t Simulator::StackLimit() const {
1547 // Leave a safety margin of 1024 bytes to prevent overrunning the stack when
1549 return reinterpret_cast<uintptr_t>(stack_) + 1024;
1553 // Unsupported instructions use Format to print an error and stop execution.
1554 void Simulator::Format(Instruction* instr, const char* format) {
1555 PrintF("Simulator found unsupported instruction:\n 0x%08lx: %s\n",
1556 reinterpret_cast<intptr_t>(instr), format);
1557 UNIMPLEMENTED_MIPS();
1561 // Calls into the V8 runtime are based on this very simple interface.
1562 // Note: To be able to return two values from some calls the code in runtime.cc
1563 // uses the ObjectPair which is essentially two 32-bit values stuffed into a
1564 // 64-bit value. With the code below we assume that all runtime calls return
1565 // 64 bits of result. If they don't, the v1 result register contains a bogus
1566 // value, which is fine because it is caller-saved.
1573 typedef ObjectPair (*SimulatorRuntimeCall)(int64_t arg0,
1581 // These prototypes handle the four types of FP calls.
1582 typedef int64_t (*SimulatorRuntimeCompareCall)(double darg0, double darg1);
1583 typedef double (*SimulatorRuntimeFPFPCall)(double darg0, double darg1);
1584 typedef double (*SimulatorRuntimeFPCall)(double darg0);
1585 typedef double (*SimulatorRuntimeFPIntCall)(double darg0, int32_t arg0);
1587 // This signature supports direct call in to API function native callback
1588 // (refer to InvocationCallback in v8.h).
1589 typedef void (*SimulatorRuntimeDirectApiCall)(int64_t arg0);
1590 typedef void (*SimulatorRuntimeProfilingApiCall)(int64_t arg0, void* arg1);
1592 // This signature supports direct call to accessor getter callback.
1593 typedef void (*SimulatorRuntimeDirectGetterCall)(int64_t arg0, int64_t arg1);
1594 typedef void (*SimulatorRuntimeProfilingGetterCall)(
1595 int64_t arg0, int64_t arg1, void* arg2);
1597 // Software interrupt instructions are used by the simulator to call into the
1598 // C-based V8 runtime. They are also used for debugging with simulator.
1599 void Simulator::SoftwareInterrupt(Instruction* instr) {
1600 // There are several instructions that could get us here,
1601 // the break_ instruction, or several variants of traps. All
1602 // Are "SPECIAL" class opcode, and are distinuished by function.
1603 int32_t func = instr->FunctionFieldRaw();
1604 uint32_t code = (func == BREAK) ? instr->Bits(25, 6) : -1;
1605 // We first check if we met a call_rt_redirected.
1606 if (instr->InstructionBits() == rtCallRedirInstr) {
1607 Redirection* redirection = Redirection::FromSwiInstruction(instr);
1608 int64_t arg0 = get_register(a0);
1609 int64_t arg1 = get_register(a1);
1610 int64_t arg2 = get_register(a2);
1611 int64_t arg3 = get_register(a3);
1614 if (kMipsAbi == kN64) {
1615 arg4 = get_register(a4); // Abi n64 register a4.
1616 arg5 = get_register(a5); // Abi n64 register a5.
1617 } else { // Abi O32.
1618 int64_t* stack_pointer = reinterpret_cast<int64_t*>(get_register(sp));
1619 // Args 4 and 5 are on the stack after the reserved space for args 0..3.
1620 arg4 = stack_pointer[4];
1621 arg5 = stack_pointer[5];
1624 (redirection->type() == ExternalReference::BUILTIN_FP_FP_CALL) ||
1625 (redirection->type() == ExternalReference::BUILTIN_COMPARE_CALL) ||
1626 (redirection->type() == ExternalReference::BUILTIN_FP_CALL) ||
1627 (redirection->type() == ExternalReference::BUILTIN_FP_INT_CALL);
1629 if (!IsMipsSoftFloatABI) {
1630 // With the hard floating point calling convention, double
1631 // arguments are passed in FPU registers. Fetch the arguments
1632 // from there and call the builtin using soft floating point
1634 switch (redirection->type()) {
1635 case ExternalReference::BUILTIN_FP_FP_CALL:
1636 case ExternalReference::BUILTIN_COMPARE_CALL:
1637 arg0 = get_fpu_register(f12);
1638 arg1 = get_fpu_register(f13);
1639 arg2 = get_fpu_register(f14);
1640 arg3 = get_fpu_register(f15);
1642 case ExternalReference::BUILTIN_FP_CALL:
1643 arg0 = get_fpu_register(f12);
1644 arg1 = get_fpu_register(f13);
1646 case ExternalReference::BUILTIN_FP_INT_CALL:
1647 arg0 = get_fpu_register(f12);
1648 arg1 = get_fpu_register(f13);
1649 arg2 = get_register(a2);
1656 // This is dodgy but it works because the C entry stubs are never moved.
1657 // See comment in codegen-arm.cc and bug 1242173.
1658 int64_t saved_ra = get_register(ra);
1661 reinterpret_cast<intptr_t>(redirection->external_function());
1663 // Based on CpuFeatures::IsSupported(FPU), Mips will use either hardware
1664 // FPU, or gcc soft-float routines. Hardware FPU is simulated in this
1665 // simulator. Soft-float has additional abstraction of ExternalReference,
1666 // to support serialization.
1668 double dval0, dval1; // one or two double parameters
1669 int32_t ival; // zero or one integer parameters
1670 int64_t iresult = 0; // integer return value
1671 double dresult = 0; // double return value
1672 GetFpArgs(&dval0, &dval1, &ival);
1673 SimulatorRuntimeCall generic_target =
1674 reinterpret_cast<SimulatorRuntimeCall>(external);
1675 if (::v8::internal::FLAG_trace_sim) {
1676 switch (redirection->type()) {
1677 case ExternalReference::BUILTIN_FP_FP_CALL:
1678 case ExternalReference::BUILTIN_COMPARE_CALL:
1679 PrintF("Call to host function at %p with args %f, %f",
1680 FUNCTION_ADDR(generic_target), dval0, dval1);
1682 case ExternalReference::BUILTIN_FP_CALL:
1683 PrintF("Call to host function at %p with arg %f",
1684 FUNCTION_ADDR(generic_target), dval0);
1686 case ExternalReference::BUILTIN_FP_INT_CALL:
1687 PrintF("Call to host function at %p with args %f, %d",
1688 FUNCTION_ADDR(generic_target), dval0, ival);
1695 switch (redirection->type()) {
1696 case ExternalReference::BUILTIN_COMPARE_CALL: {
1697 SimulatorRuntimeCompareCall target =
1698 reinterpret_cast<SimulatorRuntimeCompareCall>(external);
1699 iresult = target(dval0, dval1);
1700 set_register(v0, static_cast<int64_t>(iresult));
1701 // set_register(v1, static_cast<int64_t>(iresult >> 32));
1704 case ExternalReference::BUILTIN_FP_FP_CALL: {
1705 SimulatorRuntimeFPFPCall target =
1706 reinterpret_cast<SimulatorRuntimeFPFPCall>(external);
1707 dresult = target(dval0, dval1);
1708 SetFpResult(dresult);
1711 case ExternalReference::BUILTIN_FP_CALL: {
1712 SimulatorRuntimeFPCall target =
1713 reinterpret_cast<SimulatorRuntimeFPCall>(external);
1714 dresult = target(dval0);
1715 SetFpResult(dresult);
1718 case ExternalReference::BUILTIN_FP_INT_CALL: {
1719 SimulatorRuntimeFPIntCall target =
1720 reinterpret_cast<SimulatorRuntimeFPIntCall>(external);
1721 dresult = target(dval0, ival);
1722 SetFpResult(dresult);
1729 if (::v8::internal::FLAG_trace_sim) {
1730 switch (redirection->type()) {
1731 case ExternalReference::BUILTIN_COMPARE_CALL:
1732 PrintF("Returned %08x\n", static_cast<int32_t>(iresult));
1734 case ExternalReference::BUILTIN_FP_FP_CALL:
1735 case ExternalReference::BUILTIN_FP_CALL:
1736 case ExternalReference::BUILTIN_FP_INT_CALL:
1737 PrintF("Returned %f\n", dresult);
1744 } else if (redirection->type() == ExternalReference::DIRECT_API_CALL) {
1745 if (::v8::internal::FLAG_trace_sim) {
1746 PrintF("Call to host function at %p args %08lx\n",
1747 reinterpret_cast<void*>(external), arg0);
1749 SimulatorRuntimeDirectApiCall target =
1750 reinterpret_cast<SimulatorRuntimeDirectApiCall>(external);
1753 redirection->type() == ExternalReference::PROFILING_API_CALL) {
1754 if (::v8::internal::FLAG_trace_sim) {
1755 PrintF("Call to host function at %p args %08lx %08lx\n",
1756 reinterpret_cast<void*>(external), arg0, arg1);
1758 SimulatorRuntimeProfilingApiCall target =
1759 reinterpret_cast<SimulatorRuntimeProfilingApiCall>(external);
1760 target(arg0, Redirection::ReverseRedirection(arg1));
1762 redirection->type() == ExternalReference::DIRECT_GETTER_CALL) {
1763 if (::v8::internal::FLAG_trace_sim) {
1764 PrintF("Call to host function at %p args %08lx %08lx\n",
1765 reinterpret_cast<void*>(external), arg0, arg1);
1767 SimulatorRuntimeDirectGetterCall target =
1768 reinterpret_cast<SimulatorRuntimeDirectGetterCall>(external);
1771 redirection->type() == ExternalReference::PROFILING_GETTER_CALL) {
1772 if (::v8::internal::FLAG_trace_sim) {
1773 PrintF("Call to host function at %p args %08lx %08lx %08lx\n",
1774 reinterpret_cast<void*>(external), arg0, arg1, arg2);
1776 SimulatorRuntimeProfilingGetterCall target =
1777 reinterpret_cast<SimulatorRuntimeProfilingGetterCall>(external);
1778 target(arg0, arg1, Redirection::ReverseRedirection(arg2));
1780 SimulatorRuntimeCall target =
1781 reinterpret_cast<SimulatorRuntimeCall>(external);
1782 if (::v8::internal::FLAG_trace_sim) {
1784 "Call to host function at %p "
1785 "args %08lx, %08lx, %08lx, %08lx, %08lx, %08lx\n",
1786 FUNCTION_ADDR(target),
1794 // int64_t result = target(arg0, arg1, arg2, arg3, arg4, arg5);
1795 // set_register(v0, static_cast<int32_t>(result));
1796 // set_register(v1, static_cast<int32_t>(result >> 32));
1797 ObjectPair result = target(arg0, arg1, arg2, arg3, arg4, arg5);
1798 set_register(v0, (int64_t)(result.x));
1799 set_register(v1, (int64_t)(result.y));
1801 if (::v8::internal::FLAG_trace_sim) {
1802 PrintF("Returned %08lx : %08lx\n", get_register(v1), get_register(v0));
1804 set_register(ra, saved_ra);
1805 set_pc(get_register(ra));
1807 } else if (func == BREAK && code <= kMaxStopCode) {
1808 if (IsWatchpoint(code)) {
1809 PrintWatchpoint(code);
1811 IncreaseStopCounter(code);
1812 HandleStop(code, instr);
1815 // All remaining break_ codes, and all traps are handled here.
1816 MipsDebugger dbg(this);
1822 // Stop helper functions.
1823 bool Simulator::IsWatchpoint(uint64_t code) {
1824 return (code <= kMaxWatchpointCode);
1828 void Simulator::PrintWatchpoint(uint64_t code) {
1829 MipsDebugger dbg(this);
1831 PrintF("\n---- break %ld marker: %3d (instr count: %8ld) ----------"
1832 "----------------------------------",
1833 code, break_count_, icount_);
1834 dbg.PrintAllRegs(); // Print registers and continue running.
1838 void Simulator::HandleStop(uint64_t code, Instruction* instr) {
1839 // Stop if it is enabled, otherwise go on jumping over the stop
1840 // and the message address.
1841 if (IsEnabledStop(code)) {
1842 MipsDebugger dbg(this);
1845 set_pc(get_pc() + 2 * Instruction::kInstrSize);
1850 bool Simulator::IsStopInstruction(Instruction* instr) {
1851 int32_t func = instr->FunctionFieldRaw();
1852 uint32_t code = static_cast<uint32_t>(instr->Bits(25, 6));
1853 return (func == BREAK) && code > kMaxWatchpointCode && code <= kMaxStopCode;
1857 bool Simulator::IsEnabledStop(uint64_t code) {
1858 DCHECK(code <= kMaxStopCode);
1859 DCHECK(code > kMaxWatchpointCode);
1860 return !(watched_stops_[code].count & kStopDisabledBit);
1864 void Simulator::EnableStop(uint64_t code) {
1865 if (!IsEnabledStop(code)) {
1866 watched_stops_[code].count &= ~kStopDisabledBit;
1871 void Simulator::DisableStop(uint64_t code) {
1872 if (IsEnabledStop(code)) {
1873 watched_stops_[code].count |= kStopDisabledBit;
1878 void Simulator::IncreaseStopCounter(uint64_t code) {
1879 DCHECK(code <= kMaxStopCode);
1880 if ((watched_stops_[code].count & ~(1 << 31)) == 0x7fffffff) {
1881 PrintF("Stop counter for code %ld has overflowed.\n"
1882 "Enabling this code and reseting the counter to 0.\n", code);
1883 watched_stops_[code].count = 0;
1886 watched_stops_[code].count++;
1891 // Print a stop status.
1892 void Simulator::PrintStopInfo(uint64_t code) {
1893 if (code <= kMaxWatchpointCode) {
1894 PrintF("That is a watchpoint, not a stop.\n");
1896 } else if (code > kMaxStopCode) {
1897 PrintF("Code too large, only %u stops can be used\n", kMaxStopCode + 1);
1900 const char* state = IsEnabledStop(code) ? "Enabled" : "Disabled";
1901 int32_t count = watched_stops_[code].count & ~kStopDisabledBit;
1902 // Don't print the state of unused breakpoints.
1904 if (watched_stops_[code].desc) {
1905 PrintF("stop %ld - 0x%lx: \t%s, \tcounter = %i, \t%s\n",
1906 code, code, state, count, watched_stops_[code].desc);
1908 PrintF("stop %ld - 0x%lx: \t%s, \tcounter = %i\n",
1909 code, code, state, count);
1915 void Simulator::SignalExceptions() {
1916 for (int i = 1; i < kNumExceptions; i++) {
1917 if (exceptions[i] != 0) {
1918 V8_Fatal(__FILE__, __LINE__, "Error: Exception %i raised.", i);
1924 // Handle execution based on instruction types.
1926 void Simulator::ConfigureTypeRegister(Instruction* instr,
1931 int64_t* return_addr_reg,
1933 int64_t* i128resultH,
1934 int64_t* i128resultL) {
1935 // Every local variable declared here needs to be const.
1936 // This is to make sure that changed values are sent back to
1937 // DecodeTypeRegister correctly.
1939 // Instruction fields.
1940 const Opcode op = instr->OpcodeFieldRaw();
1941 const int64_t rs_reg = instr->RsValue();
1942 const int64_t rs = get_register(rs_reg);
1943 const uint64_t rs_u = static_cast<uint64_t>(rs);
1944 const int64_t rt_reg = instr->RtValue();
1945 const int64_t rt = get_register(rt_reg);
1946 const uint64_t rt_u = static_cast<uint64_t>(rt);
1947 const int64_t rd_reg = instr->RdValue();
1948 const uint64_t sa = instr->SaValue();
1950 const int32_t fs_reg = instr->FsValue();
1953 // ---------- Configuration.
1955 case COP1: // Coprocessor instructions.
1956 switch (instr->RsFieldRaw()) {
1958 // At the moment only FCSR is supported.
1959 DCHECK(fs_reg == kFCSRRegister);
1963 *alu_out = static_cast<int64_t>(get_fpu_register_word(fs_reg));
1966 *alu_out = get_fpu_register(fs_reg);
1969 *alu_out = get_fpu_register_hi_word(fs_reg);
1980 // Do everything in the execution step.
1983 // BC1 BC1EQZ BC1NEZ handled in DecodeTypeImmed, should never come here.
1990 switch (instr->FunctionFieldRaw()) {
1993 *next_pc = get_register(instr->RsValue());
1994 *return_addr_reg = instr->RdValue();
1997 *alu_out = (int32_t)rt << sa;
2000 *alu_out = rt << sa;
2003 *alu_out = rt << sa << 32;
2007 // Regular logical right shift of a word by a fixed number of
2008 // bits instruction. RS field is always equal to 0.
2009 *alu_out = (uint32_t)rt_u >> sa;
2011 // Logical right-rotate of a word by a fixed number of bits. This
2012 // is special case of SRL instruction, added in MIPS32 Release 2.
2013 // RS field is equal to 00001.
2014 *alu_out = ((uint32_t)rt_u >> sa) | ((uint32_t)rt_u << (32 - sa));
2018 *alu_out = rt_u >> sa;
2021 *alu_out = rt_u >> sa >> 32;
2024 *alu_out = (int32_t)rt >> sa;
2027 *alu_out = rt >> sa;
2030 *alu_out = rt >> sa >> 32;
2033 *alu_out = (int32_t)rt << rs;
2036 *alu_out = rt << rs;
2040 // Regular logical right-shift of a word by a variable number of
2041 // bits instruction. SA field is always equal to 0.
2042 *alu_out = (uint32_t)rt_u >> rs;
2044 // Logical right-rotate of a word by a variable number of bits.
2045 // This is special case od SRLV instruction, added in MIPS32
2046 // Release 2. SA field is equal to 00001.
2048 ((uint32_t)rt_u >> rs_u) | ((uint32_t)rt_u << (32 - rs_u));
2053 // Regular logical right-shift of a word by a variable number of
2054 // bits instruction. SA field is always equal to 0.
2055 *alu_out = rt_u >> rs;
2057 // Logical right-rotate of a word by a variable number of bits.
2058 // This is special case od SRLV instruction, added in MIPS32
2059 // Release 2. SA field is equal to 00001.
2060 *alu_out = (rt_u >> rs_u) | (rt_u << (32 - rs_u));
2064 *alu_out = (int32_t)rt >> rs;
2067 *alu_out = rt >> rs;
2069 case MFHI: // MFHI == CLZ on R6.
2070 if (kArchVariant != kMips64r6) {
2071 DCHECK(instr->SaValue() == 0);
2072 *alu_out = get_register(HI);
2074 // MIPS spec: If no bits were set in GPR rs, the result written to
2076 DCHECK(instr->SaValue() == 1);
2077 *alu_out = base::bits::CountLeadingZeros32(rs_u);
2081 *alu_out = get_register(LO);
2083 case MULT: // MULT == D_MUL_MUH.
2084 // TODO(plind) - Unify MULT/DMULT with single set of 64-bit HI/Lo
2086 // TODO(plind) - make the 32-bit MULT ops conform to spec regarding
2087 // checking of 32-bit input values, and un-define operations of HW.
2091 *u64hilo = static_cast<uint64_t>(rs_u) * static_cast<uint64_t>(rt_u);
2093 case DMULT: // DMULT == D_MUL_MUH.
2094 if (kArchVariant != kMips64r6) {
2095 *i128resultH = MultiplyHighSigned(rs, rt);
2096 *i128resultL = rs * rt;
2098 switch (instr->SaValue()) {
2100 *i128resultL = rs * rt;
2103 *i128resultH = MultiplyHighSigned(rs, rt);
2106 UNIMPLEMENTED_MIPS();
2112 UNIMPLEMENTED_MIPS();
2116 if (HaveSameSign(rs, rt)) {
2118 exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue - rt);
2119 } else if (rs < 0) {
2120 exceptions[kIntegerUnderflow] = rs < (Registers::kMinValue - rt);
2126 int32_t alu32_out = rs + rt;
2127 // Sign-extend result of 32bit operation into 64bit register.
2128 *alu_out = static_cast<int64_t>(alu32_out);
2136 if (!HaveSameSign(rs, rt)) {
2138 exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue + rt);
2139 } else if (rs < 0) {
2140 exceptions[kIntegerUnderflow] = rs < (Registers::kMinValue + rt);
2146 int32_t alu32_out = rs - rt;
2147 // Sign-extend result of 32bit operation into 64bit register.
2148 *alu_out = static_cast<int64_t>(alu32_out);
2164 *alu_out = ~(rs | rt);
2167 *alu_out = rs < rt ? 1 : 0;
2170 *alu_out = rs_u < rt_u ? 1 : 0;
2172 // Break and trap instructions.
2175 *do_interrupt = true;
2178 *do_interrupt = rs >= rt;
2181 *do_interrupt = rs_u >= rt_u;
2184 *do_interrupt = rs < rt;
2187 *do_interrupt = rs_u < rt_u;
2190 *do_interrupt = rs == rt;
2193 *do_interrupt = rs != rt;
2198 // No action taken on decode.
2204 // div and divu never raise exceptions.
2211 switch (instr->FunctionFieldRaw()) {
2213 // Only the lower 32 bits are kept.
2214 *alu_out = (int32_t)rs_u * (int32_t)rt_u;
2217 // MIPS32 spec: If no bits were set in GPR rs, the result written to
2219 *alu_out = base::bits::CountLeadingZeros32(rs_u);
2226 switch (instr->FunctionFieldRaw()) {
2227 case INS: { // Mips32r2 instruction.
2228 // Interpret rd field as 5-bit msb of insert.
2229 uint16_t msb = rd_reg;
2230 // Interpret sa field as 5-bit lsb of insert.
2232 uint16_t size = msb - lsb + 1;
2233 uint32_t mask = (1 << size) - 1;
2234 *alu_out = (rt_u & ~(mask << lsb)) | ((rs_u & mask) << lsb);
2237 case EXT: { // Mips32r2 instruction.
2238 // Interpret rd field as 5-bit msb of extract.
2239 uint16_t msb = rd_reg;
2240 // Interpret sa field as 5-bit lsb of extract.
2242 uint16_t size = msb + 1;
2243 uint32_t mask = (1 << size) - 1;
2244 *alu_out = (rs_u & (mask << lsb)) >> lsb;
2257 void Simulator::DecodeTypeRegister(Instruction* instr) {
2258 // Instruction fields.
2259 const Opcode op = instr->OpcodeFieldRaw();
2260 const int64_t rs_reg = instr->RsValue();
2261 const int64_t rs = get_register(rs_reg);
2262 const uint64_t rs_u = static_cast<uint32_t>(rs);
2263 const int64_t rt_reg = instr->RtValue();
2264 const int64_t rt = get_register(rt_reg);
2265 const uint64_t rt_u = static_cast<uint32_t>(rt);
2266 const int64_t rd_reg = instr->RdValue();
2268 const int32_t fr_reg = instr->FrValue();
2269 const int32_t fs_reg = instr->FsValue();
2270 const int32_t ft_reg = instr->FtValue();
2271 const int64_t fd_reg = instr->FdValue();
2272 int64_t i64hilo = 0;
2273 uint64_t u64hilo = 0;
2276 // It should not be used as is. Instructions using it should always
2277 // initialize it first.
2278 int64_t alu_out = 0x12345678;
2280 // For break and trap instructions.
2281 bool do_interrupt = false;
2285 int64_t current_pc = get_pc();
2287 int64_t next_pc = 0;
2288 int64_t return_addr_reg = 31;
2290 int64_t i128resultH;
2291 int64_t i128resultL;
2293 // Set up the variables if needed before executing the instruction.
2294 ConfigureTypeRegister(instr,
2304 // ---------- Raise exceptions triggered.
2307 // ---------- Execution.
2310 switch (instr->RsFieldRaw()) {
2311 case BC1: // Branch on coprocessor condition.
2317 set_register(rt_reg, alu_out);
2322 set_register(rt_reg, alu_out);
2325 // At the moment only FCSR is supported.
2326 DCHECK(fs_reg == kFCSRRegister);
2327 FCSR_ = registers_[rt_reg];
2330 // Hardware writes upper 32-bits to zero on mtc1.
2331 set_fpu_register_hi_word(fs_reg, 0);
2332 set_fpu_register_word(fs_reg, registers_[rt_reg]);
2335 set_fpu_register(fs_reg, registers_[rt_reg]);
2338 set_fpu_register_hi_word(fs_reg, registers_[rt_reg]);
2342 switch (instr->FunctionFieldRaw()) {
2344 f = get_fpu_register_float(fs_reg);
2345 set_fpu_register_double(fd_reg, static_cast<double>(f));
2348 // CVT_W_S CVT_L_S TRUNC_W_S ROUND_W_S ROUND_L_S FLOOR_W_S FLOOR_L_S
2349 // CEIL_W_S CEIL_L_S CVT_PS_S are unimplemented.
2355 uint32_t cc, fcsr_cc;
2357 fs = get_fpu_register_double(fs_reg);
2358 ft = get_fpu_register_double(ft_reg);
2359 cc = instr->FCccValue();
2360 fcsr_cc = get_fcsr_condition_bit(cc);
2361 switch (instr->FunctionFieldRaw()) {
2363 set_fpu_register_double(fd_reg, fs + ft);
2366 set_fpu_register_double(fd_reg, fs - ft);
2369 set_fpu_register_double(fd_reg, fs * ft);
2372 set_fpu_register_double(fd_reg, fs / ft);
2375 set_fpu_register_double(fd_reg, fabs(fs));
2378 set_fpu_register_double(fd_reg, fs);
2381 set_fpu_register_double(fd_reg, -fs);
2384 set_fpu_register_double(fd_reg, sqrt(fs));
2387 set_fcsr_bit(fcsr_cc, std::isnan(fs) || std::isnan(ft));
2390 set_fcsr_bit(fcsr_cc, (fs == ft));
2393 set_fcsr_bit(fcsr_cc,
2394 (fs == ft) || (std::isnan(fs) || std::isnan(ft)));
2397 set_fcsr_bit(fcsr_cc, (fs < ft));
2400 set_fcsr_bit(fcsr_cc,
2401 (fs < ft) || (std::isnan(fs) || std::isnan(ft)));
2404 set_fcsr_bit(fcsr_cc, (fs <= ft));
2407 set_fcsr_bit(fcsr_cc,
2408 (fs <= ft) || (std::isnan(fs) || std::isnan(ft)));
2410 case CVT_W_D: // Convert double to word.
2411 // Rounding modes are not yet supported.
2412 DCHECK((FCSR_ & 3) == 0);
2413 // In rounding mode 0 it should behave like ROUND.
2415 case ROUND_W_D: // Round double to word (round half to even).
2417 double rounded = std::floor(fs + 0.5);
2418 int32_t result = static_cast<int32_t>(rounded);
2419 if ((result & 1) != 0 && result - fs == 0.5) {
2420 // If the number is halfway between two integers,
2421 // round to the even one.
2424 set_fpu_register_word(fd_reg, result);
2425 if (set_fcsr_round_error(fs, rounded)) {
2426 set_fpu_register(fd_reg, kFPUInvalidResult);
2430 case TRUNC_W_D: // Truncate double to word (round towards 0).
2432 double rounded = trunc(fs);
2433 int32_t result = static_cast<int32_t>(rounded);
2434 set_fpu_register_word(fd_reg, result);
2435 if (set_fcsr_round_error(fs, rounded)) {
2436 set_fpu_register(fd_reg, kFPUInvalidResult);
2440 case FLOOR_W_D: // Round double to word towards negative infinity.
2442 double rounded = std::floor(fs);
2443 int32_t result = static_cast<int32_t>(rounded);
2444 set_fpu_register_word(fd_reg, result);
2445 if (set_fcsr_round_error(fs, rounded)) {
2446 set_fpu_register(fd_reg, kFPUInvalidResult);
2450 case CEIL_W_D: // Round double to word towards positive infinity.
2452 double rounded = std::ceil(fs);
2453 int32_t result = static_cast<int32_t>(rounded);
2454 set_fpu_register_word(fd_reg, result);
2455 if (set_fcsr_round_error(fs, rounded)) {
2456 set_fpu_register(fd_reg, kFPUInvalidResult);
2460 case CVT_S_D: // Convert double to float (single).
2461 set_fpu_register_float(fd_reg, static_cast<float>(fs));
2463 case CVT_L_D: // Mips64r2: Truncate double to 64-bit long-word.
2464 // Rounding modes are not yet supported.
2465 DCHECK((FCSR_ & 3) == 0);
2466 // In rounding mode 0 it should behave like ROUND.
2468 case ROUND_L_D: { // Mips64r2 instruction.
2469 // check error cases
2470 double rounded = fs > 0 ? floor(fs + 0.5) : ceil(fs - 0.5);
2471 int64_t result = static_cast<int64_t>(rounded);
2472 set_fpu_register(fd_reg, result);
2473 if (set_fcsr_round64_error(fs, rounded)) {
2474 set_fpu_register(fd_reg, kFPU64InvalidResult);
2478 case TRUNC_L_D: { // Mips64r2 instruction.
2479 double rounded = trunc(fs);
2480 int64_t result = static_cast<int64_t>(rounded);
2481 set_fpu_register(fd_reg, result);
2482 if (set_fcsr_round64_error(fs, rounded)) {
2483 set_fpu_register(fd_reg, kFPU64InvalidResult);
2487 case FLOOR_L_D: { // Mips64r2 instruction.
2488 double rounded = floor(fs);
2489 int64_t result = static_cast<int64_t>(rounded);
2490 set_fpu_register(fd_reg, result);
2491 if (set_fcsr_round64_error(fs, rounded)) {
2492 set_fpu_register(fd_reg, kFPU64InvalidResult);
2496 case CEIL_L_D: { // Mips64r2 instruction.
2497 double rounded = ceil(fs);
2498 int64_t result = static_cast<int64_t>(rounded);
2499 set_fpu_register(fd_reg, result);
2500 if (set_fcsr_round64_error(fs, rounded)) {
2501 set_fpu_register(fd_reg, kFPU64InvalidResult);
2506 UNIMPLEMENTED_MIPS();
2513 switch (instr->FunctionFieldRaw()) {
2514 case CVT_S_W: // Convert word to float (single).
2515 alu_out = get_fpu_register_signed_word(fs_reg);
2516 set_fpu_register_float(fd_reg, static_cast<float>(alu_out));
2518 case CVT_D_W: // Convert word to double.
2519 alu_out = get_fpu_register_signed_word(fs_reg);
2520 set_fpu_register_double(fd_reg, static_cast<double>(alu_out));
2522 default: // Mips64r6 CMP.S instructions unimplemented.
2527 fs = get_fpu_register_double(fs_reg);
2528 ft = get_fpu_register_double(ft_reg);
2529 switch (instr->FunctionFieldRaw()) {
2530 case CVT_D_L: // Mips32r2 instruction.
2531 i64 = get_fpu_register(fs_reg);
2532 set_fpu_register_double(fd_reg, static_cast<double>(i64));
2535 UNIMPLEMENTED_MIPS();
2537 case CMP_AF: // Mips64r6 CMP.D instructions.
2538 UNIMPLEMENTED_MIPS();
2541 if (std::isnan(fs) || std::isnan(ft)) {
2542 set_fpu_register(fd_reg, -1);
2544 set_fpu_register(fd_reg, 0);
2549 set_fpu_register(fd_reg, -1);
2551 set_fpu_register(fd_reg, 0);
2555 if ((fs == ft) || (std::isnan(fs) || std::isnan(ft))) {
2556 set_fpu_register(fd_reg, -1);
2558 set_fpu_register(fd_reg, 0);
2563 set_fpu_register(fd_reg, -1);
2565 set_fpu_register(fd_reg, 0);
2569 if ((fs < ft) || (std::isnan(fs) || std::isnan(ft))) {
2570 set_fpu_register(fd_reg, -1);
2572 set_fpu_register(fd_reg, 0);
2577 set_fpu_register(fd_reg, -1);
2579 set_fpu_register(fd_reg, 0);
2583 if ((fs <= ft) || (std::isnan(fs) || std::isnan(ft))) {
2584 set_fpu_register(fd_reg, -1);
2586 set_fpu_register(fd_reg, 0);
2589 default: // CMP_OR CMP_UNE CMP_NE UNIMPLEMENTED
2598 switch (instr->FunctionFieldRaw()) {
2601 fr = get_fpu_register_double(fr_reg);
2602 fs = get_fpu_register_double(fs_reg);
2603 ft = get_fpu_register_double(ft_reg);
2604 set_fpu_register_double(fd_reg, fs * ft + fr);
2611 switch (instr->FunctionFieldRaw()) {
2613 Instruction* branch_delay_instr = reinterpret_cast<Instruction*>(
2614 current_pc+Instruction::kInstrSize);
2615 BranchDelayInstructionDecode(branch_delay_instr);
2617 pc_modified_ = true;
2621 Instruction* branch_delay_instr = reinterpret_cast<Instruction*>(
2622 current_pc+Instruction::kInstrSize);
2623 BranchDelayInstructionDecode(branch_delay_instr);
2624 set_register(return_addr_reg,
2625 current_pc + 2 * Instruction::kInstrSize);
2627 pc_modified_ = true;
2630 // Instructions using HI and LO registers.
2632 if (kArchVariant != kMips64r6) {
2633 set_register(LO, static_cast<int32_t>(i64hilo & 0xffffffff));
2634 set_register(HI, static_cast<int32_t>(i64hilo >> 32));
2636 switch (instr->SaValue()) {
2638 set_register(rd_reg,
2639 static_cast<int32_t>(i64hilo & 0xffffffff));
2642 set_register(rd_reg, static_cast<int32_t>(i64hilo >> 32));
2645 UNIMPLEMENTED_MIPS();
2651 set_register(LO, static_cast<int32_t>(u64hilo & 0xffffffff));
2652 set_register(HI, static_cast<int32_t>(u64hilo >> 32));
2654 case DMULT: // DMULT == D_MUL_MUH.
2655 if (kArchVariant != kMips64r6) {
2656 set_register(LO, static_cast<int64_t>(i128resultL));
2657 set_register(HI, static_cast<int64_t>(i128resultH));
2659 switch (instr->SaValue()) {
2661 set_register(rd_reg, static_cast<int64_t>(i128resultL));
2664 set_register(rd_reg, static_cast<int64_t>(i128resultH));
2667 UNIMPLEMENTED_MIPS();
2673 UNIMPLEMENTED_MIPS();
2676 set_register(rd_reg, alu_out);
2680 switch (kArchVariant) {
2682 // Divide by zero and overflow was not checked in the
2683 // configuration step - div and divu do not raise exceptions. On
2684 // division by 0 the result will be UNPREDICTABLE. On overflow
2685 // (INT_MIN/-1), return INT_MIN which is what the hardware does.
2686 if (rs == INT_MIN && rt == -1) {
2687 set_register(LO, INT_MIN);
2688 set_register(HI, 0);
2689 } else if (rt != 0) {
2690 set_register(LO, rs / rt);
2691 set_register(HI, rs % rt);
2695 switch (instr->SaValue()) {
2697 if (rs == INT_MIN && rt == -1) {
2698 set_register(rd_reg, INT_MIN);
2699 } else if (rt != 0) {
2700 set_register(rd_reg, rs / rt);
2704 if (rs == INT_MIN && rt == -1) {
2705 set_register(rd_reg, 0);
2706 } else if (rt != 0) {
2707 set_register(rd_reg, rs % rt);
2711 UNIMPLEMENTED_MIPS();
2721 set_register(LO, rs_u / rt_u);
2722 set_register(HI, rs_u % rt_u);
2725 // Break and trap instructions.
2734 SoftwareInterrupt(instr);
2737 // Conditional moves.
2740 set_register(rd_reg, rs);
2745 uint32_t cc = instr->FBccValue();
2746 uint32_t fcsr_cc = get_fcsr_condition_bit(cc);
2747 if (instr->Bit(16)) { // Read Tf bit.
2748 if (test_fcsr_bit(fcsr_cc)) set_register(rd_reg, rs);
2750 if (!test_fcsr_bit(fcsr_cc)) set_register(rd_reg, rs);
2756 set_register(rd_reg, rs);
2760 default: // For other special opcodes we do the default operation.
2761 set_register(rd_reg, alu_out);
2762 TraceRegWr(alu_out);
2766 switch (instr->FunctionFieldRaw()) {
2768 set_register(rd_reg, alu_out);
2769 TraceRegWr(alu_out);
2770 // HI and LO are UNPREDICTABLE after the operation.
2771 set_register(LO, Unpredictable);
2772 set_register(HI, Unpredictable);
2774 default: // For other special2 opcodes we do the default operation.
2775 set_register(rd_reg, alu_out);
2779 switch (instr->FunctionFieldRaw()) {
2781 // Ins instr leaves result in Rt, rather than Rd.
2782 set_register(rt_reg, alu_out);
2783 TraceRegWr(alu_out);
2786 // Ext instr leaves result in Rt, rather than Rd.
2787 set_register(rt_reg, alu_out);
2788 TraceRegWr(alu_out);
2794 // Unimplemented opcodes raised an error in the configuration step before,
2795 // so we can use the default here to set the destination register in common
2798 set_register(rd_reg, alu_out);
2799 TraceRegWr(alu_out);
2804 // Type 2: instructions using a 16 bytes immediate. (e.g. addi, beq).
2805 void Simulator::DecodeTypeImmediate(Instruction* instr) {
2806 // Instruction fields.
2807 Opcode op = instr->OpcodeFieldRaw();
2808 int64_t rs = get_register(instr->RsValue());
2809 uint64_t rs_u = static_cast<uint64_t>(rs);
2810 int64_t rt_reg = instr->RtValue(); // Destination register.
2811 int64_t rt = get_register(rt_reg);
2812 int16_t imm16 = instr->Imm16Value();
2814 int32_t ft_reg = instr->FtValue(); // Destination register.
2815 int64_t ft = get_fpu_register(ft_reg);
2817 // Zero extended immediate.
2818 uint32_t oe_imm16 = 0xffff & imm16;
2819 // Sign extended immediate.
2820 int32_t se_imm16 = imm16;
2823 int64_t current_pc = get_pc();
2825 int64_t next_pc = bad_ra;
2827 // Used for conditional branch instructions.
2828 bool do_branch = false;
2829 bool execute_branch_delay_instruction = false;
2831 // Used for arithmetic instructions.
2832 int64_t alu_out = 0;
2834 double fp_out = 0.0;
2835 uint32_t cc, cc_value, fcsr_cc;
2837 // Used for memory instructions.
2839 // Value to be written in memory.
2840 uint64_t mem_value = 0x0;
2841 // Alignment for 32-bit integers used in LWL, LWR, etc.
2842 const int kInt32AlignmentMask = sizeof(uint32_t) - 1;
2844 // ---------- Configuration (and execution for REGIMM).
2846 // ------------- COP1. Coprocessor instructions.
2848 switch (instr->RsFieldRaw()) {
2849 case BC1: // Branch on coprocessor condition.
2850 cc = instr->FBccValue();
2851 fcsr_cc = get_fcsr_condition_bit(cc);
2852 cc_value = test_fcsr_bit(fcsr_cc);
2853 do_branch = (instr->FBtrueValue()) ? cc_value : !cc_value;
2854 execute_branch_delay_instruction = true;
2857 next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
2859 next_pc = current_pc + kBranchReturnOffset;
2863 do_branch = (ft & 0x1) ? false : true;
2864 execute_branch_delay_instruction = true;
2867 next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
2869 next_pc = current_pc + kBranchReturnOffset;
2873 do_branch = (ft & 0x1) ? true : false;
2874 execute_branch_delay_instruction = true;
2877 next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
2879 next_pc = current_pc + kBranchReturnOffset;
2886 // ------------- REGIMM class.
2888 switch (instr->RtFieldRaw()) {
2890 do_branch = (rs < 0);
2896 do_branch = rs >= 0;
2899 do_branch = rs >= 0;
2904 switch (instr->RtFieldRaw()) {
2909 // Branch instructions common part.
2910 execute_branch_delay_instruction = true;
2913 next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
2914 if (instr->IsLinkingInstruction()) {
2915 set_register(31, current_pc + kBranchReturnOffset);
2918 next_pc = current_pc + kBranchReturnOffset;
2923 break; // case REGIMM.
2924 // ------------- Branch instructions.
2925 // When comparing to zero, the encoding of rt field is always 0, so we don't
2926 // need to replace rt with zero.
2928 do_branch = (rs == rt);
2931 do_branch = rs != rt;
2934 do_branch = rs <= 0;
2939 // ------------- Arithmetic instructions.
2942 if (HaveSameSign(rs, se_imm16)) {
2944 exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue - se_imm16);
2945 } else if (rs < 0) {
2946 exceptions[kIntegerUnderflow] =
2947 rs < (Registers::kMinValue - se_imm16);
2950 alu_out = rs + se_imm16;
2953 int32_t alu32_out = rs + se_imm16;
2954 // Sign-extend result of 32bit operation into 64bit register.
2955 alu_out = static_cast<int64_t>(alu32_out);
2959 alu_out = rs + se_imm16;
2962 alu_out = (rs < se_imm16) ? 1 : 0;
2965 alu_out = (rs_u < static_cast<uint32_t>(se_imm16)) ? 1 : 0;
2968 alu_out = rs & oe_imm16;
2971 alu_out = rs | oe_imm16;
2974 alu_out = rs ^ oe_imm16;
2977 int32_t alu32_out = (oe_imm16 << 16);
2978 // Sign-extend result of 32bit operation into 64bit register.
2979 alu_out = static_cast<int64_t>(alu32_out);
2982 // ------------- Memory instructions.
2984 addr = rs + se_imm16;
2985 alu_out = ReadB(addr);
2988 addr = rs + se_imm16;
2989 alu_out = ReadH(addr, instr);
2992 // al_offset is offset of the effective address within an aligned word.
2993 uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
2994 uint8_t byte_shift = kInt32AlignmentMask - al_offset;
2995 uint32_t mask = (1 << byte_shift * 8) - 1;
2996 addr = rs + se_imm16 - al_offset;
2997 alu_out = ReadW(addr, instr);
2998 alu_out <<= byte_shift * 8;
2999 alu_out |= rt & mask;
3003 addr = rs + se_imm16;
3004 alu_out = ReadW(addr, instr);
3007 addr = rs + se_imm16;
3008 alu_out = ReadWU(addr, instr);
3011 addr = rs + se_imm16;
3012 alu_out = Read2W(addr, instr);
3015 addr = rs + se_imm16;
3016 alu_out = ReadBU(addr);
3019 addr = rs + se_imm16;
3020 alu_out = ReadHU(addr, instr);
3023 // al_offset is offset of the effective address within an aligned word.
3024 uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
3025 uint8_t byte_shift = kInt32AlignmentMask - al_offset;
3026 uint32_t mask = al_offset ? (~0 << (byte_shift + 1) * 8) : 0;
3027 addr = rs + se_imm16 - al_offset;
3028 alu_out = ReadW(addr, instr);
3029 alu_out = static_cast<uint32_t> (alu_out) >> al_offset * 8;
3030 alu_out |= rt & mask;
3034 addr = rs + se_imm16;
3037 addr = rs + se_imm16;
3040 uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
3041 uint8_t byte_shift = kInt32AlignmentMask - al_offset;
3042 uint32_t mask = byte_shift ? (~0 << (al_offset + 1) * 8) : 0;
3043 addr = rs + se_imm16 - al_offset;
3044 mem_value = ReadW(addr, instr) & mask;
3045 mem_value |= static_cast<uint32_t>(rt) >> byte_shift * 8;
3050 addr = rs + se_imm16;
3053 uint8_t al_offset = (rs + se_imm16) & kInt32AlignmentMask;
3054 uint32_t mask = (1 << al_offset * 8) - 1;
3055 addr = rs + se_imm16 - al_offset;
3056 mem_value = ReadW(addr, instr);
3057 mem_value = (rt << al_offset * 8) | (mem_value & mask);
3061 addr = rs + se_imm16;
3062 alu_out = ReadW(addr, instr);
3065 addr = rs + se_imm16;
3066 fp_out = ReadD(addr, instr);
3070 addr = rs + se_imm16;
3076 // ---------- Raise exceptions triggered.
3079 // ---------- Execution.
3081 // ------------- Branch instructions.
3086 // Branch instructions common part.
3087 execute_branch_delay_instruction = true;
3090 next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize;
3091 if (instr->IsLinkingInstruction()) {
3092 set_register(31, current_pc + 2* Instruction::kInstrSize);
3095 next_pc = current_pc + 2 * Instruction::kInstrSize;
3098 // ------------- Arithmetic instructions.
3109 set_register(rt_reg, alu_out);
3110 TraceRegWr(alu_out);
3112 // ------------- Memory instructions.
3122 set_register(rt_reg, alu_out);
3125 WriteB(addr, static_cast<int8_t>(rt));
3128 WriteH(addr, static_cast<uint16_t>(rt), instr);
3131 WriteW(addr, mem_value, instr);
3134 WriteW(addr, rt, instr);
3137 Write2W(addr, rt, instr);
3140 WriteW(addr, mem_value, instr);
3143 set_fpu_register(ft_reg, kFPUInvalidResult); // Trash upper 32 bits.
3144 set_fpu_register_word(ft_reg, static_cast<int32_t>(alu_out));
3147 set_fpu_register_double(ft_reg, fp_out);
3150 addr = rs + se_imm16;
3151 WriteW(addr, get_fpu_register(ft_reg), instr);
3154 addr = rs + se_imm16;
3155 WriteD(addr, get_fpu_register_double(ft_reg), instr);
3162 if (execute_branch_delay_instruction) {
3163 // Execute branch delay slot
3164 // We don't check for end_sim_pc. First it should not be met as the current
3165 // pc is valid. Secondly a jump should always execute its branch delay slot.
3166 Instruction* branch_delay_instr =
3167 reinterpret_cast<Instruction*>(current_pc+Instruction::kInstrSize);
3168 BranchDelayInstructionDecode(branch_delay_instr);
3171 // If needed update pc after the branch delay execution.
3172 if (next_pc != bad_ra) {
3178 // Type 3: instructions using a 26 bytes immediate. (e.g. j, jal).
3179 void Simulator::DecodeTypeJump(Instruction* instr) {
3181 int32_t current_pc = get_pc();
3182 // Get unchanged bits of pc.
3183 int32_t pc_high_bits = current_pc & 0xf0000000;
3185 int32_t next_pc = pc_high_bits | (instr->Imm26Value() << 2);
3187 // Execute branch delay slot.
3188 // We don't check for end_sim_pc. First it should not be met as the current pc
3189 // is valid. Secondly a jump should always execute its branch delay slot.
3190 Instruction* branch_delay_instr =
3191 reinterpret_cast<Instruction*>(current_pc + Instruction::kInstrSize);
3192 BranchDelayInstructionDecode(branch_delay_instr);
3194 // Update pc and ra if necessary.
3195 // Do this after the branch delay execution.
3196 if (instr->IsLinkingInstruction()) {
3197 set_register(31, current_pc + 2 * Instruction::kInstrSize);
3200 pc_modified_ = true;
3204 // Executes the current instruction.
3205 void Simulator::InstructionDecode(Instruction* instr) {
3206 if (v8::internal::FLAG_check_icache) {
3207 CheckICache(isolate_->simulator_i_cache(), instr);
3209 pc_modified_ = false;
3211 v8::internal::EmbeddedVector<char, 256> buffer;
3213 if (::v8::internal::FLAG_trace_sim) {
3214 SNPrintF(trace_buf_, " ");
3215 disasm::NameConverter converter;
3216 disasm::Disassembler dasm(converter);
3217 // Use a reasonably large buffer.
3218 dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(instr));
3221 switch (instr->InstructionType()) {
3222 case Instruction::kRegisterType:
3223 DecodeTypeRegister(instr);
3225 case Instruction::kImmediateType:
3226 DecodeTypeImmediate(instr);
3228 case Instruction::kJumpType:
3229 DecodeTypeJump(instr);
3235 if (::v8::internal::FLAG_trace_sim) {
3236 PrintF(" 0x%08lx %-44s %s\n", reinterpret_cast<intptr_t>(instr),
3237 buffer.start(), trace_buf_.start());
3240 if (!pc_modified_) {
3241 set_register(pc, reinterpret_cast<int64_t>(instr) +
3242 Instruction::kInstrSize);
3248 void Simulator::Execute() {
3249 // Get the PC to simulate. Cannot use the accessor here as we need the
3250 // raw PC value and not the one used as input to arithmetic instructions.
3251 int64_t program_counter = get_pc();
3252 if (::v8::internal::FLAG_stop_sim_at == 0) {
3253 // Fast version of the dispatch loop without checking whether the simulator
3254 // should be stopping at a particular executed instruction.
3255 while (program_counter != end_sim_pc) {
3256 Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
3258 InstructionDecode(instr);
3259 program_counter = get_pc();
3262 // FLAG_stop_sim_at is at the non-default value. Stop in the debugger when
3263 // we reach the particular instuction count.
3264 while (program_counter != end_sim_pc) {
3265 Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
3267 if (icount_ == static_cast<int64_t>(::v8::internal::FLAG_stop_sim_at)) {
3268 MipsDebugger dbg(this);
3271 InstructionDecode(instr);
3273 program_counter = get_pc();
3279 void Simulator::CallInternal(byte* entry) {
3280 // Prepare to execute the code at entry.
3281 set_register(pc, reinterpret_cast<int64_t>(entry));
3282 // Put down marker for end of simulation. The simulator will stop simulation
3283 // when the PC reaches this value. By saving the "end simulation" value into
3284 // the LR the simulation stops when returning to this call point.
3285 set_register(ra, end_sim_pc);
3287 // Remember the values of callee-saved registers.
3288 // The code below assumes that r9 is not used as sb (static base) in
3289 // simulator code and therefore is regarded as a callee-saved register.
3290 int64_t s0_val = get_register(s0);
3291 int64_t s1_val = get_register(s1);
3292 int64_t s2_val = get_register(s2);
3293 int64_t s3_val = get_register(s3);
3294 int64_t s4_val = get_register(s4);
3295 int64_t s5_val = get_register(s5);
3296 int64_t s6_val = get_register(s6);
3297 int64_t s7_val = get_register(s7);
3298 int64_t gp_val = get_register(gp);
3299 int64_t sp_val = get_register(sp);
3300 int64_t fp_val = get_register(fp);
3302 // Set up the callee-saved registers with a known value. To be able to check
3303 // that they are preserved properly across JS execution.
3304 int64_t callee_saved_value = icount_;
3305 set_register(s0, callee_saved_value);
3306 set_register(s1, callee_saved_value);
3307 set_register(s2, callee_saved_value);
3308 set_register(s3, callee_saved_value);
3309 set_register(s4, callee_saved_value);
3310 set_register(s5, callee_saved_value);
3311 set_register(s6, callee_saved_value);
3312 set_register(s7, callee_saved_value);
3313 set_register(gp, callee_saved_value);
3314 set_register(fp, callee_saved_value);
3316 // Start the simulation.
3319 // Check that the callee-saved registers have been preserved.
3320 CHECK_EQ(callee_saved_value, get_register(s0));
3321 CHECK_EQ(callee_saved_value, get_register(s1));
3322 CHECK_EQ(callee_saved_value, get_register(s2));
3323 CHECK_EQ(callee_saved_value, get_register(s3));
3324 CHECK_EQ(callee_saved_value, get_register(s4));
3325 CHECK_EQ(callee_saved_value, get_register(s5));
3326 CHECK_EQ(callee_saved_value, get_register(s6));
3327 CHECK_EQ(callee_saved_value, get_register(s7));
3328 CHECK_EQ(callee_saved_value, get_register(gp));
3329 CHECK_EQ(callee_saved_value, get_register(fp));
3331 // Restore callee-saved registers with the original value.
3332 set_register(s0, s0_val);
3333 set_register(s1, s1_val);
3334 set_register(s2, s2_val);
3335 set_register(s3, s3_val);
3336 set_register(s4, s4_val);
3337 set_register(s5, s5_val);
3338 set_register(s6, s6_val);
3339 set_register(s7, s7_val);
3340 set_register(gp, gp_val);
3341 set_register(sp, sp_val);
3342 set_register(fp, fp_val);
3346 int64_t Simulator::Call(byte* entry, int argument_count, ...) {
3347 const int kRegisterPassedArguments = (kMipsAbi == kN64) ? 8 : 4;
3349 va_start(parameters, argument_count);
3350 // Set up arguments.
3352 // First four arguments passed in registers in both ABI's.
3353 DCHECK(argument_count >= 4);
3354 set_register(a0, va_arg(parameters, int64_t));
3355 set_register(a1, va_arg(parameters, int64_t));
3356 set_register(a2, va_arg(parameters, int64_t));
3357 set_register(a3, va_arg(parameters, int64_t));
3359 if (kMipsAbi == kN64) {
3360 // Up to eight arguments passed in registers in N64 ABI.
3361 // TODO(plind): N64 ABI calls these regs a4 - a7. Clarify this.
3362 if (argument_count >= 5) set_register(a4, va_arg(parameters, int64_t));
3363 if (argument_count >= 6) set_register(a5, va_arg(parameters, int64_t));
3364 if (argument_count >= 7) set_register(a6, va_arg(parameters, int64_t));
3365 if (argument_count >= 8) set_register(a7, va_arg(parameters, int64_t));
3368 // Remaining arguments passed on stack.
3369 int64_t original_stack = get_register(sp);
3370 // Compute position of stack on entry to generated code.
3371 int stack_args_count = (argument_count > kRegisterPassedArguments) ?
3372 (argument_count - kRegisterPassedArguments) : 0;
3373 int stack_args_size = stack_args_count * sizeof(int64_t) + kCArgsSlotsSize;
3374 int64_t entry_stack = original_stack - stack_args_size;
3376 if (base::OS::ActivationFrameAlignment() != 0) {
3377 entry_stack &= -base::OS::ActivationFrameAlignment();
3379 // Store remaining arguments on stack, from low to high memory.
3380 intptr_t* stack_argument = reinterpret_cast<intptr_t*>(entry_stack);
3381 for (int i = kRegisterPassedArguments; i < argument_count; i++) {
3382 int stack_index = i - kRegisterPassedArguments + kCArgSlotCount;
3383 stack_argument[stack_index] = va_arg(parameters, int64_t);
3386 set_register(sp, entry_stack);
3388 CallInternal(entry);
3390 // Pop stack passed arguments.
3391 CHECK_EQ(entry_stack, get_register(sp));
3392 set_register(sp, original_stack);
3394 int64_t result = get_register(v0);
3399 double Simulator::CallFP(byte* entry, double d0, double d1) {
3400 if (!IsMipsSoftFloatABI) {
3401 const FPURegister fparg2 = (kMipsAbi == kN64) ? f13 : f14;
3402 set_fpu_register_double(f12, d0);
3403 set_fpu_register_double(fparg2, d1);
3406 DCHECK(sizeof(buffer[0]) * 2 == sizeof(d0));
3407 memcpy(buffer, &d0, sizeof(d0));
3408 set_dw_register(a0, buffer);
3409 memcpy(buffer, &d1, sizeof(d1));
3410 set_dw_register(a2, buffer);
3412 CallInternal(entry);
3413 if (!IsMipsSoftFloatABI) {
3414 return get_fpu_register_double(f0);
3416 return get_double_from_register_pair(v0);
3421 uintptr_t Simulator::PushAddress(uintptr_t address) {
3422 int64_t new_sp = get_register(sp) - sizeof(uintptr_t);
3423 uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp);
3424 *stack_slot = address;
3425 set_register(sp, new_sp);
3430 uintptr_t Simulator::PopAddress() {
3431 int64_t current_sp = get_register(sp);
3432 uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(current_sp);
3433 uintptr_t address = *stack_slot;
3434 set_register(sp, current_sp + sizeof(uintptr_t));
3441 } } // namespace v8::internal
3443 #endif // USE_SIMULATOR
3445 #endif // V8_TARGET_ARCH_MIPS64