Debian Codegraph @

js/src/jit/riscv64/Simulator-riscv64.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80: */
3 // Copyright 2021 the V8 project authors. All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following
12 // disclaimer in the documentation and/or other materials provided
13 // with the distribution.
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived
16 // from this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #ifdef JS_SIMULATOR_RISCV64
30 # include "jit/riscv64/Simulator-riscv64.h"
31
32 # include "mozilla/Casting.h"
33 # include "mozilla/FloatingPoint.h"
34 # include "mozilla/IntegerPrintfMacros.h"
35 # include "mozilla/Likely.h"
36 # include "mozilla/MathAlgorithms.h"
37
38 # include <float.h>
39 # include <iostream>
40 # include <limits>
41
42 # include "jit/AtomicOperations.h"
43 # include "jit/riscv64/Assembler-riscv64.h"
44 # include "js/Conversions.h"
45 # include "js/UniquePtr.h"
46 # include "js/Utility.h"
47 # include "threading/LockGuard.h"
48 # include "vm/JSContext.h"
49 # include "vm/Runtime.h"
50 # include "wasm/WasmInstance.h"
51 # include "wasm/WasmSignalHandlers.h"
52
53 # define I8(v) static_cast<int8_t>(v)
54 # define I16(v) static_cast<int16_t>(v)
55 # define U16(v) static_cast<uint16_t>(v)
56 # define I32(v) static_cast<int32_t>(v)
57 # define U32(v) static_cast<uint32_t>(v)
58 # define I64(v) static_cast<int64_t>(v)
59 # define U64(v) static_cast<uint64_t>(v)
60 # define I128(v) static_cast<__int128_t>(v)
61 # define U128(v) static_cast<__uint128_t>(v)
62
63 # define REGIx_FORMAT PRIx64
64 # define REGId_FORMAT PRId64
65
66 # define I32_CHECK(v) \
67 ({ \
68 MOZ_ASSERT(I64(I32(v)) == I64(v)); \
69 I32((v)); \
70 })
71
72 namespace js {
73 namespace jit {
74
75 bool Simulator::FLAG_trace_sim = false;
76 bool Simulator::FLAG_debug_sim = false;
77 bool Simulator::FLAG_riscv_trap_to_simulator_debugger = false;
78 bool Simulator::FLAG_riscv_print_watchpoint = false;
79
80 static void UNIMPLEMENTED() {
81 printf("UNIMPLEMENTED instruction.\n");
82 MOZ_CRASH();
83 }
84 static void UNREACHABLE() {
85 printf("UNREACHABLE instruction.\n");
86 MOZ_CRASH();
87 }
88 # define UNSUPPORTED() \
89 std::cout << "Unrecognized instruction [@pc=0x" << std::hex \
90 << registers_[pc] << "]: 0x" << instr_.InstructionBits() \
91 << std::endl; \
92 printf("Unsupported instruction.\n"); \
93 MOZ_CRASH();
94
95 static char* ReadLine(const char* prompt) {
96 UniqueChars result;
97 char lineBuf[256];
98 int offset = 0;
99 bool keepGoing = true;
100 fprintf(stdout, "%s", prompt);
101 fflush(stdout);
102 while (keepGoing) {
103 if (fgets(lineBuf, sizeof(lineBuf), stdin) == nullptr) {
104 // fgets got an error. Just give up.
105 return nullptr;
106 }
107 int len = strlen(lineBuf);
108 if (len > 0 && lineBuf[len - 1] == '\n') {
109 // Since we read a new line we are done reading the line. This
110 // will exit the loop after copying this buffer into the result.
111 keepGoing = false;
112 }
113 if (!result) {
114 // Allocate the initial result and make room for the terminating '\0'
115 result.reset(js_pod_malloc<char>(len + 1));
116 if (!result) {
117 return nullptr;
118 }
119 } else {
120 // Allocate a new result with enough room for the new addition.
121 int new_len = offset + len + 1;
122 char* new_result = js_pod_malloc<char>(new_len);
123 if (!new_result) {
124 return nullptr;
125 }
126 // Copy the existing input into the new array and set the new
127 // array as the result.
128 memcpy(new_result, result.get(), offset * sizeof(char));
129 result.reset(new_result);
130 }
131 // Copy the newly read line into the result.
132 memcpy(result.get() + offset, lineBuf, len * sizeof(char));
133 offset += len;
134 }
135
136 MOZ_ASSERT(result);
137 result[offset] = '\0';
138 return result.release();
139 }
140
141 // -----------------------------------------------------------------------------
142 // Riscv assembly various constants.
143
144 // C/C++ argument slots size.
145 const int kCArgSlotCount = 0;
146 const int kCArgsSlotsSize = kCArgSlotCount * sizeof(uintptr_t);
147 const int kBranchReturnOffset = 2 * kInstrSize;
148
149 class CachePage {
150 public:
151 static const int LINE_VALID = 0;
152 static const int LINE_INVALID = 1;
153
154 static const int kPageShift = 12;
155 static const int kPageSize = 1 << kPageShift;
156 static const int kPageMask = kPageSize - 1;
157 static const int kLineShift = 2; // The cache line is only 4 bytes right now.
158 static const int kLineLength = 1 << kLineShift;
159 static const int kLineMask = kLineLength - 1;
160
161 CachePage() { memset(&validity_map_, LINE_INVALID, sizeof(validity_map_)); }
162
163 char* validityByte(int offset) {
164 return &validity_map_[offset >> kLineShift];
165 }
166
167 char* cachedData(int offset) { return &data_[offset]; }
168
169 private:
170 char data_[kPageSize]; // The cached data.
171 static const int kValidityMapSize = kPageSize >> kLineShift;
172 char validity_map_[kValidityMapSize]; // One byte per line.
173 };
174
175 // Protects the icache() and redirection() properties of the
176 // Simulator.
177 class AutoLockSimulatorCache : public LockGuard<Mutex> {
178 using Base = LockGuard<Mutex>;
179
180 public:
181 explicit AutoLockSimulatorCache()
182 : Base(SimulatorProcess::singleton_->cacheLock_) {}
183 };
184
185 mozilla::Atomic<size_t, mozilla::ReleaseAcquire>
186 SimulatorProcess::ICacheCheckingDisableCount(
187 1); // Checking is disabled by default.
188 SimulatorProcess* SimulatorProcess::singleton_ = nullptr;
189
190 int64_t Simulator::StopSimAt = -1;
191
192 static bool IsFlag(const char* found, const char* flag) {
193 return strlen(found) == strlen(flag) && strcmp(found, flag) == 0;
194 }
195
196 Simulator* Simulator::Create() {
197 auto sim = MakeUnique<Simulator>();
198 if (!sim) {
199 return nullptr;
200 }
201
202 if (!sim->init()) {
203 return nullptr;
204 }
205
206 int64_t stopAt;
207 char* stopAtStr = getenv("RISCV_SIM_STOP_AT");
208 if (stopAtStr && sscanf(stopAtStr, "%" PRIi64, &stopAt) == 1) {
209 fprintf(stderr, "\nStopping simulation at icount %" PRIi64 "\n", stopAt);
210 Simulator::StopSimAt = stopAt;
211 }
212 char* str = getenv("RISCV_TRACE_SIM");
213 if (str != nullptr && IsFlag(str, "true")) {
214 FLAG_trace_sim = true;
215 }
216
217 return sim.release();
218 }
219
220 void Simulator::Destroy(Simulator* sim) { js_delete(sim); }
221
222 # if JS_CODEGEN_RISCV64
223 void Simulator::TraceRegWr(int64_t value, TraceType t) {
224 if (FLAG_trace_sim) {
225 union {
226 int64_t fmt_int64;
227 int32_t fmt_int32[2];
228 float fmt_float[2];
229 double fmt_double;
230 } v;
231 v.fmt_int64 = value;
232
233 switch (t) {
234 case WORD:
235 SNPrintF(trace_buf_,
236 "%016" REGIx_FORMAT " (%" PRId64 ") int32:%" PRId32
237 " uint32:%" PRIu32,
238 v.fmt_int64, icount_, v.fmt_int32[0], v.fmt_int32[0]);
239 break;
240 case DWORD:
241 SNPrintF(trace_buf_,
242 "%016" REGIx_FORMAT " (%" PRId64 ") int64:%" REGId_FORMAT
243 " uint64:%" PRIu64,
244 value, icount_, value, value);
245 break;
246 case FLOAT:
247 SNPrintF(trace_buf_, "%016" REGIx_FORMAT " (%" PRId64 ") flt:%e",
248 v.fmt_int64, icount_, v.fmt_float[0]);
249 break;
250 case DOUBLE:
251 SNPrintF(trace_buf_, "%016" REGIx_FORMAT " (%" PRId64 ") dbl:%e",
252 v.fmt_int64, icount_, v.fmt_double);
253 break;
254 default:
255 UNREACHABLE();
256 }
257 }
258 }
259
260 # elif JS_CODEGEN_RISCV32
261 template <typename T>
262 void Simulator::TraceRegWr(T value, TraceType t) {
263 if (::v8::internal::FLAG_trace_sim) {
264 union {
265 int32_t fmt_int32;
266 float fmt_float;
267 double fmt_double;
268 } v;
269 if (t != DOUBLE) {
270 v.fmt_int32 = value;
271 } else {
272 DCHECK_EQ(sizeof(T), 8);
273 v.fmt_double = value;
274 }
275 switch (t) {
276 case WORD:
277 SNPrintF(trace_buf_,
278 "%016" REGIx_FORMAT " (%" PRId64 ") int32:%" REGId_FORMAT
279 " uint32:%" PRIu32,
280 v.fmt_int32, icount_, v.fmt_int32, v.fmt_int32);
281 break;
282 case FLOAT:
283 SNPrintF(trace_buf_, "%016" REGIx_FORMAT " (%" PRId64 ") flt:%e",
284 v.fmt_int32, icount_, v.fmt_float);
285 break;
286 case DOUBLE:
287 SNPrintF(trace_buf_, "%016" PRIx64 " (%" PRId64 ") dbl:%e",
288 static_cast<int64_t>(v.fmt_double), icount_, v.fmt_double);
289 break;
290 default:
291 UNREACHABLE();
292 }
293 }
294 }
295 # endif
296 // The RiscvDebugger class is used by the simulator while debugging simulated
297 // code.
298 class RiscvDebugger {
299 public:
300 explicit RiscvDebugger(Simulator* sim) : sim_(sim) {}
301
302 void Debug();
303 // Print all registers with a nice formatting.
304 void PrintRegs(char name_prefix, int start_index, int end_index);
305 void printAllRegs();
306 void printAllRegsIncludingFPU();
307
308 static const Instr kNopInstr = 0x0;
309
310 private:
311 Simulator* sim_;
312
313 int64_t GetRegisterValue(int regnum);
314 int64_t GetFPURegisterValue(int regnum);
315 float GetFPURegisterValueFloat(int regnum);
316 double GetFPURegisterValueDouble(int regnum);
317 # ifdef CAN_USE_RVV_INSTRUCTIONS
318 __int128_t GetVRegisterValue(int regnum);
319 # endif
320 bool GetValue(const char* desc, int64_t* value);
321 };
322
323 int64_t RiscvDebugger::GetRegisterValue(int regnum) {
324 if (regnum == Simulator::Register::kNumSimuRegisters) {
325 return sim_->get_pc();
326 } else {
327 return sim_->getRegister(regnum);
328 }
329 }
330
331 int64_t RiscvDebugger::GetFPURegisterValue(int regnum) {
332 if (regnum == Simulator::FPURegister::kNumFPURegisters) {
333 return sim_->get_pc();
334 } else {
335 return sim_->getFpuRegister(regnum);
336 }
337 }
338
339 float RiscvDebugger::GetFPURegisterValueFloat(int regnum) {
340 if (regnum == Simulator::FPURegister::kNumFPURegisters) {
341 return sim_->get_pc();
342 } else {
343 return sim_->getFpuRegisterFloat(regnum);
344 }
345 }
346
347 double RiscvDebugger::GetFPURegisterValueDouble(int regnum) {
348 if (regnum == Simulator::FPURegister::kNumFPURegisters) {
349 return sim_->get_pc();
350 } else {
351 return sim_->getFpuRegisterDouble(regnum);
352 }
353 }
354
355 # ifdef CAN_USE_RVV_INSTRUCTIONS
356 __int128_t RiscvDebugger::GetVRegisterValue(int regnum) {
357 if (regnum == kNumVRegisters) {
358 return sim_->get_pc();
359 } else {
360 return sim_->get_vregister(regnum);
361 }
362 }
363 # endif
364
365 bool RiscvDebugger::GetValue(const char* desc, int64_t* value) {
366 int regnum = Registers::FromName(desc);
367 int fpuregnum = FloatRegisters::FromName(desc);
368
369 if (regnum != Registers::invalid_reg) {
370 *value = GetRegisterValue(regnum);
371 return true;
372 } else if (fpuregnum != FloatRegisters::invalid_reg) {
373 *value = GetFPURegisterValue(fpuregnum);
374 return true;
375 } else if (strncmp(desc, "0x", 2) == 0) {
376 return sscanf(desc + 2, "%" SCNx64, reinterpret_cast<int64_t*>(value)) == 1;
377 } else {
378 return sscanf(desc, "%" SCNu64, reinterpret_cast<int64_t*>(value)) == 1;
379 }
380 }
381
382 # define REG_INFO(name) \
383 name, GetRegisterValue(Registers::FromName(name)), \
384 GetRegisterValue(Registers::FromName(name))
385
386 void RiscvDebugger::PrintRegs(char name_prefix, int start_index,
387 int end_index) {
388 EmbeddedVector<char, 10> name1, name2;
389 MOZ_ASSERT(name_prefix == 'a' || name_prefix == 't' || name_prefix == 's');
390 MOZ_ASSERT(start_index >= 0 && end_index <= 99);
391 int num_registers = (end_index - start_index) + 1;
392 for (int i = 0; i < num_registers / 2; i++) {
393 SNPrintF(name1, "%c%d", name_prefix, start_index + 2 * i);
394 SNPrintF(name2, "%c%d", name_prefix, start_index + 2 * i + 1);
395 printf("%3s: 0x%016" REGIx_FORMAT " %14" REGId_FORMAT
396 " \t%3s: 0x%016" REGIx_FORMAT " %14" REGId_FORMAT " \n",
397 REG_INFO(name1.start()), REG_INFO(name2.start()));
398 }
399 if (num_registers % 2 == 1) {
400 SNPrintF(name1, "%c%d", name_prefix, end_index);
401 printf("%3s: 0x%016" REGIx_FORMAT " %14" REGId_FORMAT " \n",
402 REG_INFO(name1.start()));
403 }
404 }
405
406 void RiscvDebugger::printAllRegs() {
407 printf("\n");
408 // ra, sp, gp
409 printf("%3s: 0x%016" REGIx_FORMAT " %14" REGId_FORMAT
410 "\t%3s: 0x%016" REGIx_FORMAT " %14" REGId_FORMAT
411 "\t%3s: 0x%016" REGIx_FORMAT " %14" REGId_FORMAT "\n",
412 REG_INFO("ra"), REG_INFO("sp"), REG_INFO("gp"));
413
414 // tp, fp, pc
415 printf("%3s: 0x%016" REGIx_FORMAT " %14" REGId_FORMAT
416 "\t%3s: 0x%016" REGIx_FORMAT " %14" REGId_FORMAT
417 "\t%3s: 0x%016" REGIx_FORMAT " %14" REGId_FORMAT "\n",
418 REG_INFO("tp"), REG_INFO("fp"), REG_INFO("pc"));
419
420 // print register a0, .., a7
421 PrintRegs('a', 0, 7);
422 // print registers s1, ..., s11
423 PrintRegs('s', 1, 11);
424 // print registers t0, ..., t6
425 PrintRegs('t', 0, 6);
426 }
427
428 # undef REG_INFO
429
430 void RiscvDebugger::printAllRegsIncludingFPU() {
431 # define FPU_REG_INFO(n) \
432 FloatRegisters::GetName(n), GetFPURegisterValue(n), \
433 GetFPURegisterValueDouble(n)
434
435 printAllRegs();
436
437 printf("\n\n");
438 // f0, f1, f2, ... f31.
439 MOZ_ASSERT(kNumFPURegisters % 2 == 0);
440 for (int i = 0; i < kNumFPURegisters; i += 2)
441 printf("%3s: 0x%016" PRIx64 " %16.4e \t%3s: 0x%016" PRIx64 " %16.4e\n",
442 FPU_REG_INFO(i), FPU_REG_INFO(i + 1));
443 # undef FPU_REG_INFO
444 }
445
446 void RiscvDebugger::Debug() {
447 intptr_t last_pc = -1;
448 bool done = false;
449
450 # define COMMAND_SIZE 63
451 # define ARG_SIZE 255
452
453 # define STR(a) #a
454 # define XSTR(a) STR(a)
455
456 char cmd[COMMAND_SIZE + 1];
457 char arg1[ARG_SIZE + 1];
458 char arg2[ARG_SIZE + 1];
459 char* argv[3] = {cmd, arg1, arg2};
460
461 // Make sure to have a proper terminating character if reaching the limit.
462 cmd[COMMAND_SIZE] = 0;
463 arg1[ARG_SIZE] = 0;
464 arg2[ARG_SIZE] = 0;
465
466 while (!done && (sim_->get_pc() != Simulator::end_sim_pc)) {
467 if (last_pc != sim_->get_pc()) {
468 disasm::NameConverter converter;
469 disasm::Disassembler dasm(converter);
470 // Use a reasonably large buffer.
471 EmbeddedVector<char, 256> buffer;
472 dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(sim_->get_pc()));
473 printf(" 0x%016" REGIx_FORMAT " %s\n", sim_->get_pc(), buffer.start());
474 last_pc = sim_->get_pc();
475 }
476 char* line = ReadLine("sim> ");
477 if (line == nullptr) {
478 break;
479 } else {
480 char* last_input = sim_->lastDebuggerInput();
481 if (strcmp(line, "\n") == 0 && last_input != nullptr) {
482 line = last_input;
483 } else {
484 // Ownership is transferred to sim_;
485 sim_->setLastDebuggerInput(line);
486 }
487 // Use sscanf to parse the individual parts of the command line. At the
488 // moment no command expects more than two parameters.
489 int argc = sscanf(
490 line,
491 "%" XSTR(COMMAND_SIZE) "s "
492 "%" XSTR(ARG_SIZE) "s "
493 "%" XSTR(ARG_SIZE) "s",
494 cmd, arg1, arg2);
495 if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) {
496 SimInstruction* instr =
497 reinterpret_cast<SimInstruction*>(sim_->get_pc());
498 if (!(instr->IsTrap()) ||
499 instr->InstructionBits() == rtCallRedirInstr) {
500 sim_->icount_++;
501 sim_->InstructionDecode(
502 reinterpret_cast<Instruction*>(sim_->get_pc()));
503 } else {
504 // Allow si to jump over generated breakpoints.
505 printf("/!\\ Jumping over generated breakpoint.\n");
506 sim_->set_pc(sim_->get_pc() + kInstrSize);
507 }
508 } else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) {
509 // Leave the debugger shell.
510 done = true;
511 } else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) {
512 if (argc == 2) {
513 int64_t value;
514 int64_t fvalue;
515 double dvalue;
516 if (strcmp(arg1, "all") == 0) {
517 printAllRegs();
518 } else if (strcmp(arg1, "allf") == 0) {
519 printAllRegsIncludingFPU();
520 } else {
521 int regnum = Registers::FromName(arg1);
522 int fpuregnum = FloatRegisters::FromName(arg1);
523 # ifdef CAN_USE_RVV_INSTRUCTIONS
524 int vregnum = VRegisters::FromName(arg1);
525 # endif
526 if (regnum != Registers::invalid_reg) {
527 value = GetRegisterValue(regnum);
528 printf("%s: 0x%08" REGIx_FORMAT " %" REGId_FORMAT " \n", arg1,
529 value, value);
530 } else if (fpuregnum != FloatRegisters::invalid_reg) {
531 fvalue = GetFPURegisterValue(fpuregnum);
532 dvalue = GetFPURegisterValueDouble(fpuregnum);
533 printf("%3s: 0x%016" PRIx64 " %16.4e\n",
534 FloatRegisters::GetName(fpuregnum), fvalue, dvalue);
535 # ifdef CAN_USE_RVV_INSTRUCTIONS
536 } else if (vregnum != kInvalidVRegister) {
537 __int128_t v = GetVRegisterValue(vregnum);
538 printf("\t%s:0x%016" REGIx_FORMAT "%016" REGIx_FORMAT "\n",
539 VRegisters::GetName(vregnum), (uint64_t)(v >> 64),
540 (uint64_t)v);
541 # endif
542 } else {
543 printf("%s unrecognized\n", arg1);
544 }
545 }
546 } else {
547 if (argc == 3) {
548 if (strcmp(arg2, "single") == 0) {
549 int64_t value;
550 float fvalue;
551 int fpuregnum = FloatRegisters::FromName(arg1);
552
553 if (fpuregnum != FloatRegisters::invalid_reg) {
554 value = GetFPURegisterValue(fpuregnum);
555 value &= 0xFFFFFFFFUL;
556 fvalue = GetFPURegisterValueFloat(fpuregnum);
557 printf("%s: 0x%08" PRIx64 " %11.4e\n", arg1, value, fvalue);
558 } else {
559 printf("%s unrecognized\n", arg1);
560 }
561 } else {
562 printf("print <fpu register> single\n");
563 }
564 } else {
565 printf("print <register> or print <fpu register> single\n");
566 }
567 }
568 } else if ((strcmp(cmd, "po") == 0) ||
569 (strcmp(cmd, "printobject") == 0)) {
570 UNIMPLEMENTED();
571 } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) {
572 int64_t* cur = nullptr;
573 int64_t* end = nullptr;
574 int next_arg = 1;
575 if (argc < 2) {
576 printf("Need to specify <address> to memhex command\n");
577 continue;
578 }
579 int64_t value;
580 if (!GetValue(arg1, &value)) {
581 printf("%s unrecognized\n", arg1);
582 continue;
583 }
584 cur = reinterpret_cast<int64_t*>(value);
585 next_arg++;
586
587 int64_t words;
588 if (argc == next_arg) {
589 words = 10;
590 } else {
591 if (!GetValue(argv[next_arg], &words)) {
592 words = 10;
593 }
594 }
595 end = cur + words;
596
597 while (cur < end) {
598 printf(" 0x%012" PRIxPTR " : 0x%016" REGIx_FORMAT
599 " %14" REGId_FORMAT " ",
600 reinterpret_cast<intptr_t>(cur), *cur, *cur);
601 printf("\n");
602 cur++;
603 }
604 } else if ((strcmp(cmd, "watch") == 0)) {
605 if (argc < 2) {
606 printf("Need to specify <address> to mem command\n");
607 continue;
608 }
609 int64_t value;
610 if (!GetValue(arg1, &value)) {
611 printf("%s unrecognized\n", arg1);
612 continue;
613 }
614 sim_->watch_address_ = reinterpret_cast<intptr_t*>(value);
615 sim_->watch_value_ = *(sim_->watch_address_);
616 } else if ((strcmp(cmd, "disasm") == 0) || (strcmp(cmd, "dpc") == 0) ||
617 (strcmp(cmd, "di") == 0)) {
618 disasm::NameConverter converter;
619 disasm::Disassembler dasm(converter);
620 // Use a reasonably large buffer.
621 EmbeddedVector<char, 256> buffer;
622
623 byte* cur = nullptr;
624 byte* end = nullptr;
625
626 if (argc == 1) {
627 cur = reinterpret_cast<byte*>(sim_->get_pc());
628 end = cur + (10 * kInstrSize);
629 } else if (argc == 2) {
630 auto regnum = Registers::FromName(arg1);
631 if (regnum != Registers::invalid_reg || strncmp(arg1, "0x", 2) == 0) {
632 // The argument is an address or a register name.
633 sreg_t value;
634 if (GetValue(arg1, &value)) {
635 cur = reinterpret_cast<byte*>(value);
636 // Disassemble 10 instructions at <arg1>.
637 end = cur + (10 * kInstrSize);
638 }
639 } else {
640 // The argument is the number of instructions.
641 sreg_t value;
642 if (GetValue(arg1, &value)) {
643 cur = reinterpret_cast<byte*>(sim_->get_pc());
644 // Disassemble <arg1> instructions.
645 end = cur + (value * kInstrSize);
646 }
647 }
648 } else {
649 sreg_t value1;
650 sreg_t value2;
651 if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
652 cur = reinterpret_cast<byte*>(value1);
653 end = cur + (value2 * kInstrSize);
654 }
655 }
656 while (cur < end) {
657 dasm.InstructionDecode(buffer, cur);
658 printf(" 0x%08" PRIxPTR " %s\n", reinterpret_cast<intptr_t>(cur),
659 buffer.start());
660 cur += kInstrSize;
661 }
662 } else if (strcmp(cmd, "trace") == 0) {
663 Simulator::FLAG_trace_sim = true;
664 Simulator::FLAG_riscv_print_watchpoint = true;
665 } else if (strcmp(cmd, "break") == 0 || strcmp(cmd, "b") == 0 ||
666 strcmp(cmd, "tbreak") == 0) {
667 bool is_tbreak = strcmp(cmd, "tbreak") == 0;
668 if (argc == 2) {
669 int64_t value;
670 if (GetValue(arg1, &value)) {
671 sim_->SetBreakpoint(reinterpret_cast<SimInstruction*>(value),
672 is_tbreak);
673 } else {
674 printf("%s unrecognized\n", arg1);
675 }
676 } else {
677 sim_->ListBreakpoints();
678 printf("Use `break <address>` to set or disable a breakpoint\n");
679 printf(
680 "Use `tbreak <address>` to set or disable a temporary "
681 "breakpoint\n");
682 }
683 } else if (strcmp(cmd, "flags") == 0) {
684 printf("No flags on RISC-V !\n");
685 } else if (strcmp(cmd, "stop") == 0) {
686 int64_t value;
687 if (argc == 3) {
688 // Print information about all/the specified breakpoint(s).
689 if (strcmp(arg1, "info") == 0) {
690 if (strcmp(arg2, "all") == 0) {
691 printf("Stop information:\n");
692 for (uint32_t i = kMaxWatchpointCode + 1; i <= kMaxStopCode;
693 i++) {
694 sim_->printStopInfo(i);
695 }
696 } else if (GetValue(arg2, &value)) {
697 sim_->printStopInfo(value);
698 } else {
699 printf("Unrecognized argument.\n");
700 }
701 } else if (strcmp(arg1, "enable") == 0) {
702 // Enable all/the specified breakpoint(s).
703 if (strcmp(arg2, "all") == 0) {
704 for (uint32_t i = kMaxWatchpointCode + 1; i <= kMaxStopCode;
705 i++) {
706 sim_->enableStop(i);
707 }
708 } else if (GetValue(arg2, &value)) {
709 sim_->enableStop(value);
710 } else {
711 printf("Unrecognized argument.\n");
712 }
713 } else if (strcmp(arg1, "disable") == 0) {
714 // Disable all/the specified breakpoint(s).
715 if (strcmp(arg2, "all") == 0) {
716 for (uint32_t i = kMaxWatchpointCode + 1; i <= kMaxStopCode;
717 i++) {
718 sim_->disableStop(i);
719 }
720 } else if (GetValue(arg2, &value)) {
721 sim_->disableStop(value);
722 } else {
723 printf("Unrecognized argument.\n");
724 }
725 }
726 } else {
727 printf("Wrong usage. Use help command for more information.\n");
728 }
729 } else if ((strcmp(cmd, "stat") == 0) || (strcmp(cmd, "st") == 0)) {
730 UNIMPLEMENTED();
731 } else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) {
732 printf("cont (alias 'c')\n");
733 printf(" Continue execution\n");
734 printf("stepi (alias 'si')\n");
735 printf(" Step one instruction\n");
736 printf("print (alias 'p')\n");
737 printf(" print <register>\n");
738 printf(" Print register content\n");
739 printf(" Use register name 'all' to print all GPRs\n");
740 printf(" Use register name 'allf' to print all GPRs and FPRs\n");
741 printf("printobject (alias 'po')\n");
742 printf(" printobject <register>\n");
743 printf(" Print an object from a register\n");
744 printf("stack\n");
745 printf(" stack [<words>]\n");
746 printf(" Dump stack content, default dump 10 words)\n");
747 printf("mem\n");
748 printf(" mem <address> [<words>]\n");
749 printf(" Dump memory content, default dump 10 words)\n");
750 printf("watch\n");
751 printf(" watch <address> \n");
752 printf(" watch memory content.)\n");
753 printf("flags\n");
754 printf(" print flags\n");
755 printf("disasm (alias 'di')\n");
756 printf(" disasm [<instructions>]\n");
757 printf(" disasm [<address/register>] (e.g., disasm pc) \n");
758 printf(" disasm [[<address/register>] <instructions>]\n");
759 printf(" Disassemble code, default is 10 instructions\n");
760 printf(" from pc\n");
761 printf("gdb \n");
762 printf(" Return to gdb if the simulator was started with gdb\n");
763 printf("break (alias 'b')\n");
764 printf(" break : list all breakpoints\n");
765 printf(" break <address> : set / enable / disable a breakpoint.\n");
766 printf("tbreak\n");
767 printf(" tbreak : list all breakpoints\n");
768 printf(
769 " tbreak <address> : set / enable / disable a temporary "
770 "breakpoint.\n");
771 printf(" Set a breakpoint enabled only for one stop. \n");
772 printf("stop feature:\n");
773 printf(" Description:\n");
774 printf(" Stops are debug instructions inserted by\n");
775 printf(" the Assembler::stop() function.\n");
776 printf(" When hitting a stop, the Simulator will\n");
777 printf(" stop and give control to the Debugger.\n");
778 printf(" All stop codes are watched:\n");
779 printf(" - They can be enabled / disabled: the Simulator\n");
780 printf(" will / won't stop when hitting them.\n");
781 printf(" - The Simulator keeps track of how many times they \n");
782 printf(" are met. (See the info command.) Going over a\n");
783 printf(" disabled stop still increases its counter. \n");
784 printf(" Commands:\n");
785 printf(" stop info all/<code> : print infos about number <code>\n");
786 printf(" or all stop(s).\n");
787 printf(" stop enable/disable all/<code> : enables / disables\n");
788 printf(" all or number <code> stop(s)\n");
789 } else {
790 printf("Unknown command: %s\n", cmd);
791 }
792 }
793 }
794
795 # undef COMMAND_SIZE
796 # undef ARG_SIZE
797
798 # undef STR
799 # undef XSTR
800 }
801
802 void Simulator::SetBreakpoint(SimInstruction* location, bool is_tbreak) {
803 for (unsigned i = 0; i < breakpoints_.size(); i++) {
804 if (breakpoints_.at(i).location == location) {
805 if (breakpoints_.at(i).is_tbreak != is_tbreak) {
806 printf("Change breakpoint at %p to %s breakpoint\n",
807 reinterpret_cast<void*>(location),
808 is_tbreak ? "temporary" : "regular");
809 breakpoints_.at(i).is_tbreak = is_tbreak;
810 return;
811 }
812 printf("Existing breakpoint at %p was %s\n",
813 reinterpret_cast<void*>(location),
814 breakpoints_.at(i).enabled ? "disabled" : "enabled");
815 breakpoints_.at(i).enabled = !breakpoints_.at(i).enabled;
816 return;
817 }
818 }
819 Breakpoint new_breakpoint = {location, true, is_tbreak};
820 breakpoints_.push_back(new_breakpoint);
821 printf("Set a %sbreakpoint at %p\n", is_tbreak ? "temporary " : "",
822 reinterpret_cast<void*>(location));
823 }
824
825 void Simulator::ListBreakpoints() {
826 printf("Breakpoints:\n");
827 for (unsigned i = 0; i < breakpoints_.size(); i++) {
828 printf("%p : %s %s\n",
829 reinterpret_cast<void*>(breakpoints_.at(i).location),
830 breakpoints_.at(i).enabled ? "enabled" : "disabled",
831 breakpoints_.at(i).is_tbreak ? ": temporary" : "");
832 }
833 }
834
835 void Simulator::CheckBreakpoints() {
836 bool hit_a_breakpoint = false;
837 bool is_tbreak = false;
838 SimInstruction* pc_ = reinterpret_cast<SimInstruction*>(get_pc());
839 for (unsigned i = 0; i < breakpoints_.size(); i++) {
840 if ((breakpoints_.at(i).location == pc_) && breakpoints_.at(i).enabled) {
841 hit_a_breakpoint = true;
842 if (breakpoints_.at(i).is_tbreak) {
843 // Disable a temporary breakpoint.
844 is_tbreak = true;
845 breakpoints_.at(i).enabled = false;
846 }
847 break;
848 }
849 }
850 if (hit_a_breakpoint) {
851 printf("Hit %sa breakpoint at %p.\n", is_tbreak ? "and disabled " : "",
852 reinterpret_cast<void*>(pc_));
853 RiscvDebugger dbg(this);
854 dbg.Debug();
855 }
856 }
857
858 static bool AllOnOnePage(uintptr_t start, int size) {
859 intptr_t start_page = (start & ~CachePage::kPageMask);
860 intptr_t end_page = ((start + size) & ~CachePage::kPageMask);
861 return start_page == end_page;
862 }
863
864 void Simulator::setLastDebuggerInput(char* input) {
865 js_free(lastDebuggerInput_);
866 lastDebuggerInput_ = input;
867 }
868
869 static CachePage* GetCachePageLocked(SimulatorProcess::ICacheMap& i_cache,
870 void* page) {
871 SimulatorProcess::ICacheMap::AddPtr p = i_cache.lookupForAdd(page);
872 if (p) {
873 return p->value();
874 }
875 AutoEnterOOMUnsafeRegion oomUnsafe;
876 CachePage* new_page = js_new<CachePage>();
877 if (!new_page || !i_cache.add(p, page, new_page)) {
878 oomUnsafe.crash("Simulator CachePage");
879 }
880 return new_page;
881 }
882
883 // Flush from start up to and not including start + size.
884 static void FlushOnePageLocked(SimulatorProcess::ICacheMap& i_cache,
885 intptr_t start, int size) {
886 MOZ_ASSERT(size <= CachePage::kPageSize);
887 MOZ_ASSERT(AllOnOnePage(start, size - 1));
888 MOZ_ASSERT((start & CachePage::kLineMask) == 0);
889 MOZ_ASSERT((size & CachePage::kLineMask) == 0);
890 void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask));
891 int offset = (start & CachePage::kPageMask);
892 CachePage* cache_page = GetCachePageLocked(i_cache, page);
893 char* valid_bytemap = cache_page->validityByte(offset);
894 memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift);
895 }
896
897 static void FlushICacheLocked(SimulatorProcess::ICacheMap& i_cache,
898 void* start_addr, size_t size) {
899 intptr_t start = reinterpret_cast<intptr_t>(start_addr);
900 int intra_line = (start & CachePage::kLineMask);
901 start -= intra_line;
902 size += intra_line;
903 size = ((size - 1) | CachePage::kLineMask) + 1;
904 int offset = (start & CachePage::kPageMask);
905 while (!AllOnOnePage(start, size - 1)) {
906 int bytes_to_flush = CachePage::kPageSize - offset;
907 FlushOnePageLocked(i_cache, start, bytes_to_flush);
908 start += bytes_to_flush;
909 size -= bytes_to_flush;
910 MOZ_ASSERT((start & CachePage::kPageMask) == 0);
911 offset = 0;
912 }
913 if (size != 0) {
914 FlushOnePageLocked(i_cache, start, size);
915 }
916 }
917
918 /* static */
919 void SimulatorProcess::checkICacheLocked(SimInstruction* instr) {
920 intptr_t address = reinterpret_cast<intptr_t>(instr);
921 void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask));
922 void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask));
923 int offset = (address & CachePage::kPageMask);
924 CachePage* cache_page = GetCachePageLocked(icache(), page);
925 char* cache_valid_byte = cache_page->validityByte(offset);
926 bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID);
927 char* cached_line = cache_page->cachedData(offset & ~CachePage::kLineMask);
928
929 if (cache_hit) {
930 // Check that the data in memory matches the contents of the I-cache.
931 int cmpret = memcmp(reinterpret_cast<void*>(instr),
932 cache_page->cachedData(offset), kInstrSize);
933 MOZ_ASSERT(cmpret == 0);
934 } else {
935 // Cache miss. Load memory into the cache.
936 memcpy(cached_line, line, CachePage::kLineLength);
937 *cache_valid_byte = CachePage::LINE_VALID;
938 }
939 }
940
941 HashNumber SimulatorProcess::ICacheHasher::hash(const Lookup& l) {
942 return U32(reinterpret_cast<uintptr_t>(l)) >> 2;
943 }
944
945 bool SimulatorProcess::ICacheHasher::match(const Key& k, const Lookup& l) {
946 MOZ_ASSERT((reinterpret_cast<intptr_t>(k) & CachePage::kPageMask) == 0);
947 MOZ_ASSERT((reinterpret_cast<intptr_t>(l) & CachePage::kPageMask) == 0);
948 return k == l;
949 }
950
951 /* static */
952 void SimulatorProcess::FlushICache(void* start_addr, size_t size) {
953 if (!ICacheCheckingDisableCount) {
954 AutoLockSimulatorCache als;
955 js::jit::FlushICacheLocked(icache(), start_addr, size);
956 }
957 }
958
959 Simulator::Simulator() {
960 // Set up simulator support first. Some of this information is needed to
961 // setup the architecture state.
962
963 // Note, allocation and anything that depends on allocated memory is
964 // deferred until init(), in order to handle OOM properly.
965
966 stack_ = nullptr;
967 stackLimit_ = 0;
968 pc_modified_ = false;
969 icount_ = 0;
970 break_count_ = 0;
971 break_pc_ = nullptr;
972 break_instr_ = 0;
973 single_stepping_ = false;
974 single_step_callback_ = nullptr;
975 single_step_callback_arg_ = nullptr;
976
977 // Set up architecture state.
978 // All registers are initialized to zero to start with.
979 for (int i = 0; i < Simulator::Register::kNumSimuRegisters; i++) {
980 registers_[i] = 0;
981 }
982 for (int i = 0; i < Simulator::FPURegister::kNumFPURegisters; i++) {
983 FPUregisters_[i] = 0;
984 }
985 FCSR_ = 0;
986 LLBit_ = false;
987 LLAddr_ = 0;
988 lastLLValue_ = 0;
989
990 // The ra and pc are initialized to a known bad value that will cause an
991 // access violation if the simulator ever tries to execute it.
992 registers_[pc] = bad_ra;
993 registers_[ra] = bad_ra;
994
995 for (int i = 0; i < kNumExceptions; i++) {
996 exceptions[i] = 0;
997 }
998
999 lastDebuggerInput_ = nullptr;
1000 }
1001
1002 bool Simulator::init() {
1003 // Allocate 2MB for the stack. Note that we will only use 1MB, see below.
1004 static const size_t stackSize = 2 * 1024 * 1024;
1005 stack_ = js_pod_malloc<char>(stackSize);
1006 if (!stack_) {
1007 return false;
1008 }
1009
1010 // Leave a safety margin of 1MB to prevent overrunning the stack when
1011 // pushing values (total stack size is 2MB).
1012 stackLimit_ = reinterpret_cast<uintptr_t>(stack_) + 1024 * 1024;
1013
1014 // The sp is initialized to point to the bottom (high address) of the
1015 // allocated stack area. To be safe in potential stack underflows we leave
1016 // some buffer below.
1017 registers_[sp] = reinterpret_cast<int64_t>(stack_) + stackSize - 64;
1018
1019 return true;
1020 }
1021
1022 // When the generated code calls an external reference we need to catch that in
1023 // the simulator. The external reference will be a function compiled for the
1024 // host architecture. We need to call that function instead of trying to
1025 // execute it with the simulator. We do that by redirecting the external
1026 // reference to a swi (software-interrupt) instruction that is handled by
1027 // the simulator. We write the original destination of the jump just at a known
1028 // offset from the swi instruction so the simulator knows what to call.
1029 class Redirection {
1030 friend class SimulatorProcess;
1031
1032 // sim's lock must already be held.
1033 Redirection(void* nativeFunction, ABIFunctionType type)
1034 : nativeFunction_(nativeFunction),
1035 swiInstruction_(rtCallRedirInstr),
1036 type_(type),
1037 next_(nullptr) {
1038 next_ = SimulatorProcess::redirection();
1039 if (!SimulatorProcess::ICacheCheckingDisableCount) {
1040 FlushICacheLocked(SimulatorProcess::icache(), addressOfSwiInstruction(),
1041 kInstrSize);
1042 }
1043 SimulatorProcess::setRedirection(this);
1044 }
1045
1046 public:
1047 void* addressOfSwiInstruction() { return &swiInstruction_; }
1048 void* nativeFunction() const { return nativeFunction_; }
1049 ABIFunctionType type() const { return type_; }
1050
1051 static Redirection* Get(void* nativeFunction, ABIFunctionType type) {
1052 AutoLockSimulatorCache als;
1053
1054 Redirection* current = SimulatorProcess::redirection();
1055 for (; current != nullptr; current = current->next_) {
1056 if (current->nativeFunction_ == nativeFunction) {
1057 MOZ_ASSERT(current->type() == type);
1058 return current;
1059 }
1060 }
1061
1062 // Note: we can't use js_new here because the constructor is private.
1063 AutoEnterOOMUnsafeRegion oomUnsafe;
1064 Redirection* redir = js_pod_malloc<Redirection>(1);
1065 if (!redir) {
1066 oomUnsafe.crash("Simulator redirection");
1067 }
1068 new (redir) Redirection(nativeFunction, type);
1069 return redir;
1070 }
1071
1072 static Redirection* FromSwiInstruction(Instruction* swiInstruction) {
1073 uint8_t* addrOfSwi = reinterpret_cast<uint8_t*>(swiInstruction);
1074 uint8_t* addrOfRedirection =
1075 addrOfSwi - offsetof(Redirection, swiInstruction_);
1076 return reinterpret_cast<Redirection*>(addrOfRedirection);
1077 }
1078
1079 private:
1080 void* nativeFunction_;
1081 uint32_t swiInstruction_;
1082 ABIFunctionType type_;
1083 Redirection* next_;
1084 };
1085
1086 Simulator::~Simulator() { js_free(stack_); }
1087
1088 SimulatorProcess::SimulatorProcess()
1089 : cacheLock_(mutexid::SimulatorCacheLock), redirection_(nullptr) {
1090 if (getenv("MIPS_SIM_ICACHE_CHECKS")) {
1091 ICacheCheckingDisableCount = 0;
1092 }
1093 }
1094
1095 SimulatorProcess::~SimulatorProcess() {
1096 Redirection* r = redirection_;
1097 while (r) {
1098 Redirection* next = r->next_;
1099 js_delete(r);
1100 r = next;
1101 }
1102 }
1103
1104 /* static */
1105 void* Simulator::RedirectNativeFunction(void* nativeFunction,
1106 ABIFunctionType type) {
1107 Redirection* redirection = Redirection::Get(nativeFunction, type);
1108 return redirection->addressOfSwiInstruction();
1109 }
1110
1111 // Get the active Simulator for the current thread.
1112 Simulator* Simulator::Current() {
1113 JSContext* cx = TlsContext.get();
1114 MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
1115 return cx->simulator();
1116 }
1117
1118 // Sets the register in the architecture state. It will also deal with updating
1119 // Simulator internal state for special registers such as PC.
1120 void Simulator::setRegister(int reg, int64_t value) {
1121 MOZ_ASSERT((reg >= 0) && (reg < Simulator::Register::kNumSimuRegisters));
1122 if (reg == pc) {
1123 pc_modified_ = true;
1124 }
1125
1126 // Zero register always holds 0.
1127 registers_[reg] = (reg == 0) ? 0 : value;
1128 }
1129
1130 void Simulator::setFpuRegister(int fpureg, int64_t value) {
1131 MOZ_ASSERT((fpureg >= 0) &&
1132 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1133 FPUregisters_[fpureg] = value;
1134 }
1135
1136 void Simulator::setFpuRegisterLo(int fpureg, int32_t value) {
1137 MOZ_ASSERT((fpureg >= 0) &&
1138 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1139 *mozilla::BitwiseCast<int32_t*>(&FPUregisters_[fpureg]) = value;
1140 }
1141
1142 void Simulator::setFpuRegisterHi(int fpureg, int32_t value) {
1143 MOZ_ASSERT((fpureg >= 0) &&
1144 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1145 *((mozilla::BitwiseCast<int32_t*>(&FPUregisters_[fpureg])) + 1) = value;
1146 }
1147
1148 void Simulator::setFpuRegisterFloat(int fpureg, float value) {
1149 MOZ_ASSERT((fpureg >= 0) &&
1150 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1151 *mozilla::BitwiseCast<int64_t*>(&FPUregisters_[fpureg]) = box_float(value);
1152 }
1153
1154 void Simulator::setFpuRegisterFloat(int fpureg, Float32 value) {
1155 MOZ_ASSERT((fpureg >= 0) && (fpureg < kNumFPURegisters));
1156 Float64 t = Float64::FromBits(box_float(value.get_bits()));
1157 memcpy(&FPUregisters_[fpureg], &t, 8);
1158 }
1159
1160 void Simulator::setFpuRegisterDouble(int fpureg, double value) {
1161 MOZ_ASSERT((fpureg >= 0) &&
1162 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1163 *mozilla::BitwiseCast<double*>(&FPUregisters_[fpureg]) = value;
1164 }
1165
1166 void Simulator::setFpuRegisterDouble(int fpureg, Float64 value) {
1167 MOZ_ASSERT((fpureg >= 0) && (fpureg < kNumFPURegisters));
1168 memcpy(&FPUregisters_[fpureg], &value, 8);
1169 }
1170
1171 // Get the register from the architecture state. This function does handle
1172 // the special case of accessing the PC register.
1173 int64_t Simulator::getRegister(int reg) const {
1174 MOZ_ASSERT((reg >= 0) && (reg < Simulator::Register::kNumSimuRegisters));
1175 if (reg == 0) {
1176 return 0;
1177 }
1178 return registers_[reg] + ((reg == pc) ? SimInstruction::kPCReadOffset : 0);
1179 }
1180
1181 int64_t Simulator::getFpuRegister(int fpureg) const {
1182 MOZ_ASSERT((fpureg >= 0) &&
1183 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1184 return FPUregisters_[fpureg];
1185 }
1186
1187 int32_t Simulator::getFpuRegisterLo(int fpureg) const {
1188 MOZ_ASSERT((fpureg >= 0) &&
1189 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1190 return *mozilla::BitwiseCast<int32_t*>(&FPUregisters_[fpureg]);
1191 }
1192
1193 int32_t Simulator::getFpuRegisterHi(int fpureg) const {
1194 MOZ_ASSERT((fpureg >= 0) &&
1195 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1196 return *((mozilla::BitwiseCast<int32_t*>(&FPUregisters_[fpureg])) + 1);
1197 }
1198
1199 float Simulator::getFpuRegisterFloat(int fpureg) const {
1200 MOZ_ASSERT((fpureg >= 0) &&
1201 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1202 return *mozilla::BitwiseCast<float*>(&FPUregisters_[fpureg]);
1203 }
1204
1205 Float32 Simulator::getFpuRegisterFloat32(int fpureg) const {
1206 MOZ_ASSERT((fpureg >= 0) && (fpureg < kNumFPURegisters));
1207 if (!is_boxed_float(FPUregisters_[fpureg])) {
1208 return Float32::FromBits(0x7ffc0000);
1209 }
1210 return Float32::FromBits(
1211 *bit_cast<uint32_t*>(const_cast<int64_t*>(&FPUregisters_[fpureg])));
1212 }
1213
1214 double Simulator::getFpuRegisterDouble(int fpureg) const {
1215 MOZ_ASSERT((fpureg >= 0) &&
1216 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1217 return *mozilla::BitwiseCast<double*>(&FPUregisters_[fpureg]);
1218 }
1219
1220 Float64 Simulator::getFpuRegisterFloat64(int fpureg) const {
1221 MOZ_ASSERT((fpureg >= 0) && (fpureg < kNumFPURegisters));
1222 return Float64::FromBits(FPUregisters_[fpureg]);
1223 }
1224
1225 void Simulator::setCallResultDouble(double result) {
1226 setFpuRegisterDouble(fa0, result);
1227 }
1228
1229 void Simulator::setCallResultFloat(float result) {
1230 setFpuRegisterFloat(fa0, result);
1231 }
1232
1233 void Simulator::setCallResult(int64_t res) { setRegister(a0, res); }
1234
1235 void Simulator::setCallResult(__int128_t res) {
1236 setRegister(a0, I64(res));
1237 setRegister(a1, I64(res >> 64));
1238 }
1239
1240 // Raw access to the PC register.
1241 void Simulator::set_pc(int64_t value) {
1242 pc_modified_ = true;
1243 registers_[pc] = value;
1244 }
1245
1246 bool Simulator::has_bad_pc() const {
1247 return ((registers_[pc] == bad_ra) || (registers_[pc] == end_sim_pc));
1248 }
1249
1250 // Raw access to the PC register without the special adjustment when reading.
1251 int64_t Simulator::get_pc() const { return registers_[pc]; }
1252
1253 JS::ProfilingFrameIterator::RegisterState Simulator::registerState() {
1254 wasm::RegisterState state;
1255 state.pc = (void*)get_pc();
1256 state.fp = (void*)getRegister(fp);
1257 state.sp = (void*)getRegister(sp);
1258 state.lr = (void*)getRegister(ra);
1259 return state;
1260 }
1261
1262 void Simulator::HandleWasmTrap() {
1263 uint8_t* newPC;
1264 if (wasm::HandleIllegalInstruction(registerState(), &newPC)) {
1265 set_pc(int64_t(newPC));
1266 return;
1267 }
1268 }
1269
1270 // TODO(plind): consider making icount_ printing a flag option.
1271 template <typename T>
1272 void Simulator::TraceMemRd(sreg_t addr, T value, sreg_t reg_value) {
1273 if (FLAG_trace_sim) {
1274 if (std::is_integral<T>::value) {
1275 switch (sizeof(T)) {
1276 case 1:
1277 SNPrintF(trace_buf_,
1278 "%016" REGIx_FORMAT " (%" PRId64 ") int8:%" PRId8
1279 " uint8:%" PRIu8 " <-- [addr: %" REGIx_FORMAT "]",
1280 reg_value, icount_, static_cast<int8_t>(value),
1281 static_cast<uint8_t>(value), addr);
1282 break;
1283 case 2:
1284 SNPrintF(trace_buf_,
1285 "%016" REGIx_FORMAT " (%" PRId64 ") int16:%" PRId16
1286 " uint16:%" PRIu16 " <-- [addr: %" REGIx_FORMAT "]",
1287 reg_value, icount_, static_cast<int16_t>(value),
1288 static_cast<uint16_t>(value), addr);
1289 break;
1290 case 4:
1291 SNPrintF(trace_buf_,
1292 "%016" REGIx_FORMAT " (%" PRId64 ") int32:%" PRId32
1293 " uint32:%" PRIu32 " <-- [addr: %" REGIx_FORMAT "]",
1294 reg_value, icount_, static_cast<int32_t>(value),
1295 static_cast<uint32_t>(value), addr);
1296 break;
1297 case 8:
1298 SNPrintF(trace_buf_,
1299 "%016" REGIx_FORMAT " (%" PRId64 ") int64:%" PRId64
1300 " uint64:%" PRIu64 " <-- [addr: %" REGIx_FORMAT "]",
1301 reg_value, icount_, static_cast<int64_t>(value),
1302 static_cast<uint64_t>(value), addr);
1303 break;
1304 default:
1305 UNREACHABLE();
1306 }
1307 } else if (std::is_same<float, T>::value) {
1308 SNPrintF(trace_buf_,
1309 "%016" REGIx_FORMAT " (%" PRId64
1310 ") flt:%e <-- [addr: %" REGIx_FORMAT "]",
1311 reg_value, icount_, static_cast<float>(value), addr);
1312 } else if (std::is_same<double, T>::value) {
1313 SNPrintF(trace_buf_,
1314 "%016" REGIx_FORMAT " (%" PRId64
1315 ") dbl:%e <-- [addr: %" REGIx_FORMAT "]",
1316 reg_value, icount_, static_cast<double>(value), addr);
1317 } else {
1318 UNREACHABLE();
1319 }
1320 }
1321 }
1322
1323 void Simulator::TraceMemRdFloat(sreg_t addr, Float32 value, int64_t reg_value) {
1324 if (FLAG_trace_sim) {
1325 SNPrintF(trace_buf_,
1326 "%016" PRIx64 " (%" PRId64
1327 ") flt:%e <-- [addr: %" REGIx_FORMAT "]",
1328 reg_value, icount_, static_cast<float>(value.get_scalar()), addr);
1329 }
1330 }
1331
1332 void Simulator::TraceMemRdDouble(sreg_t addr, double value, int64_t reg_value) {
1333 if (FLAG_trace_sim) {
1334 SNPrintF(trace_buf_,
1335 "%016" PRIx64 " (%" PRId64
1336 ") dbl:%e <-- [addr: %" REGIx_FORMAT "]",
1337 reg_value, icount_, static_cast<double>(value), addr);
1338 }
1339 }
1340
1341 void Simulator::TraceMemRdDouble(sreg_t addr, Float64 value,
1342 int64_t reg_value) {
1343 if (FLAG_trace_sim) {
1344 SNPrintF(trace_buf_,
1345 "%016" PRIx64 " (%" PRId64
1346 ") dbl:%e <-- [addr: %" REGIx_FORMAT "]",
1347 reg_value, icount_, static_cast<double>(value.get_scalar()), addr);
1348 }
1349 }
1350
1351 template <typename T>
1352 void Simulator::TraceMemWr(sreg_t addr, T value) {
1353 if (FLAG_trace_sim) {
1354 switch (sizeof(T)) {
1355 case 1:
1356 SNPrintF(trace_buf_,
1357 " (%" PRIu64 ") int8:%" PRId8
1358 " uint8:%" PRIu8 " --> [addr: %" REGIx_FORMAT "]",
1359 icount_, static_cast<int8_t>(value),
1360 static_cast<uint8_t>(value), addr);
1361 break;
1362 case 2:
1363 SNPrintF(trace_buf_,
1364 " (%" PRIu64 ") int16:%" PRId16
1365 " uint16:%" PRIu16 " --> [addr: %" REGIx_FORMAT "]",
1366 icount_, static_cast<int16_t>(value),
1367 static_cast<uint16_t>(value), addr);
1368 break;
1369 case 4:
1370 if (std::is_integral<T>::value) {
1371 SNPrintF(trace_buf_,
1372 " (%" PRIu64 ") int32:%" PRId32
1373 " uint32:%" PRIu32 " --> [addr: %" REGIx_FORMAT "]",
1374 icount_, static_cast<int32_t>(value),
1375 static_cast<uint32_t>(value), addr);
1376 } else {
1377 SNPrintF(trace_buf_,
1378 " (%" PRIu64
1379 ") flt:%e --> [addr: %" REGIx_FORMAT "]",
1380 icount_, static_cast<float>(value), addr);
1381 }
1382 break;
1383 case 8:
1384 if (std::is_integral<T>::value) {
1385 SNPrintF(trace_buf_,
1386 " (%" PRIu64 ") int64:%" PRId64
1387 " uint64:%" PRIu64 " --> [addr: %" REGIx_FORMAT "]",
1388 icount_, static_cast<int64_t>(value),
1389 static_cast<uint64_t>(value), addr);
1390 } else {
1391 SNPrintF(trace_buf_,
1392 " (%" PRIu64
1393 ") dbl:%e --> [addr: %" REGIx_FORMAT "]",
1394 icount_, static_cast<double>(value), addr);
1395 }
1396 break;
1397 default:
1398 UNREACHABLE();
1399 }
1400 }
1401 }
1402
1403 void Simulator::TraceMemWrDouble(sreg_t addr, double value) {
1404 if (FLAG_trace_sim) {
1405 SNPrintF(trace_buf_,
1406 " (%" PRIu64
1407 ") dbl:%e --> [addr: %" REGIx_FORMAT "]",
1408 icount_, value, addr);
1409 }
1410 }
1411
1412 template <typename T>
1413 void Simulator::TraceLr(sreg_t addr, T value, sreg_t reg_value) {
1414 if (FLAG_trace_sim) {
1415 if (std::is_integral<T>::value) {
1416 switch (sizeof(T)) {
1417 case 4:
1418 SNPrintF(trace_buf_,
1419 "%016" REGIx_FORMAT " (%" PRId64 ") int32:%" PRId32
1420 " uint32:%" PRIu32 " <-- [addr: %" REGIx_FORMAT "]",
1421 reg_value, icount_, static_cast<int32_t>(value),
1422 static_cast<uint32_t>(value), addr);
1423 break;
1424 case 8:
1425 SNPrintF(trace_buf_,
1426 "%016" REGIx_FORMAT " (%" PRId64 ") int64:%" PRId64
1427 " uint64:%" PRIu64 " <-- [addr: %" REGIx_FORMAT "]",
1428 reg_value, icount_, static_cast<int64_t>(value),
1429 static_cast<uint64_t>(value), addr);
1430 break;
1431 default:
1432 UNREACHABLE();
1433 }
1434 } else {
1435 UNREACHABLE();
1436 }
1437 }
1438 }
1439
1440 template <typename T>
1441 void Simulator::TraceSc(sreg_t addr, T value) {
1442 if (FLAG_trace_sim) {
1443 switch (sizeof(T)) {
1444 case 4:
1445 SNPrintF(trace_buf_,
1446 "%016" REGIx_FORMAT " (%" PRIu64 ") int32:%" PRId32
1447 " uint32:%" PRIu32 " --> [addr: %" REGIx_FORMAT "]",
1448 getRegister(rd_reg()), icount_, static_cast<int32_t>(value),
1449 static_cast<uint32_t>(value), addr);
1450 break;
1451 case 8:
1452 SNPrintF(trace_buf_,
1453 "%016" REGIx_FORMAT " (%" PRIu64 ") int64:%" PRId64
1454 " uint64:%" PRIu64 " --> [addr: %" REGIx_FORMAT "]",
1455 getRegister(rd_reg()), icount_, static_cast<int64_t>(value),
1456 static_cast<uint64_t>(value), addr);
1457 break;
1458 default:
1459 UNREACHABLE();
1460 }
1461 }
1462 }
1463
1464 // TODO(RISCV): check whether the specific board supports unaligned load/store
1465 // (determined by EEI). For now, we assume the board does not support unaligned
1466 // load/store (e.g., trapping)
1467 template <typename T>
1468 T Simulator::ReadMem(sreg_t addr, Instruction* instr) {
1469 if (handleWasmSegFault(addr, sizeof(T))) {
1470 return -1;
1471 }
1472 if (addr >= 0 && addr < 0x400) {
1473 // This has to be a nullptr-dereference, drop into debugger.
1474 printf("Memory read from bad address: 0x%08" REGIx_FORMAT
1475 " , pc=0x%08" PRIxPTR " \n",
1476 addr, reinterpret_cast<intptr_t>(instr));
1477 DieOrDebug();
1478 }
1479 T* ptr = reinterpret_cast<T*>(addr);
1480 T value = *ptr;
1481 return value;
1482 }
1483
1484 template <typename T>
1485 void Simulator::WriteMem(sreg_t addr, T value, Instruction* instr) {
1486 if (handleWasmSegFault(addr, sizeof(T))) {
1487 value = -1;
1488 return;
1489 }
1490 if (addr >= 0 && addr < 0x400) {
1491 // This has to be a nullptr-dereference, drop into debugger.
1492 printf("Memory write to bad address: 0x%08" REGIx_FORMAT
1493 " , pc=0x%08" PRIxPTR " \n",
1494 addr, reinterpret_cast<intptr_t>(instr));
1495 DieOrDebug();
1496 }
1497 T* ptr = reinterpret_cast<T*>(addr);
1498 if (!std::is_same<double, T>::value) {
1499 TraceMemWr(addr, value);
1500 } else {
1501 TraceMemWrDouble(addr, value);
1502 }
1503 *ptr = value;
1504 }
1505
1506 template <>
1507 void Simulator::WriteMem(sreg_t addr, Float32 value, Instruction* instr) {
1508 if (handleWasmSegFault(addr, 4)) {
1509 value = Float32(-1.0f);
1510 return;
1511 }
1512 if (addr >= 0 && addr < 0x400) {
1513 // This has to be a nullptr-dereference, drop into debugger.
1514 printf("Memory write to bad address: 0x%08" REGIx_FORMAT
1515 " , pc=0x%08" PRIxPTR " \n",
1516 addr, reinterpret_cast<intptr_t>(instr));
1517 DieOrDebug();
1518 }
1519 float* ptr = reinterpret_cast<float*>(addr);
1520 TraceMemWr(addr, value.get_scalar());
1521 memcpy(ptr, &value, 4);
1522 }
1523
1524 template <>
1525 void Simulator::WriteMem(sreg_t addr, Float64 value, Instruction* instr) {
1526 if (handleWasmSegFault(addr, 8)) {
1527 value = Float64(-1.0);
1528 return;
1529 }
1530 if (addr >= 0 && addr < 0x400) {
1531 // This has to be a nullptr-dereference, drop into debugger.
1532 printf("Memory write to bad address: 0x%08" REGIx_FORMAT
1533 " , pc=0x%08" PRIxPTR " \n",
1534 addr, reinterpret_cast<intptr_t>(instr));
1535 DieOrDebug();
1536 }
1537 double* ptr = reinterpret_cast<double*>(addr);
1538 TraceMemWrDouble(addr, value.get_scalar());
1539 memcpy(ptr, &value, 8);
1540 }
1541
1542 uintptr_t Simulator::stackLimit() const { return stackLimit_; }
1543
1544 uintptr_t* Simulator::addressOfStackLimit() { return &stackLimit_; }
1545
1546 bool Simulator::overRecursed(uintptr_t newsp) const {
1547 if (newsp == 0) {
1548 newsp = getRegister(sp);
1549 }
1550 return newsp <= stackLimit();
1551 }
1552
1553 bool Simulator::overRecursedWithExtra(uint32_t extra) const {
1554 uintptr_t newsp = getRegister(sp) - extra;
1555 return newsp <= stackLimit();
1556 }
1557
1558 // Unsupported instructions use format to print an error and stop execution.
1559 void Simulator::format(SimInstruction* instr, const char* format) {
1560 printf("Simulator found unsupported instruction:\n 0x%016lx: %s\n",
1561 reinterpret_cast<intptr_t>(instr), format);
1562 MOZ_CRASH();
1563 }
1564
1565 // Note: With the code below we assume that all runtime calls return a 64 bits
1566 // result. If they don't, the v1 result register contains a bogus value, which
1567 // is fine because it is caller-saved.
1568 typedef int64_t (*Prototype_General0)();
1569 typedef int64_t (*Prototype_General1)(int64_t arg0);
1570 typedef int64_t (*Prototype_General2)(int64_t arg0, int64_t arg1);
1571 typedef int64_t (*Prototype_General3)(int64_t arg0, int64_t arg1, int64_t arg2);
1572 typedef int64_t (*Prototype_General4)(int64_t arg0, int64_t arg1, int64_t arg2,
1573 int64_t arg3);
1574 typedef int64_t (*Prototype_General5)(int64_t arg0, int64_t arg1, int64_t arg2,
1575 int64_t arg3, int64_t arg4);
1576 typedef int64_t (*Prototype_General6)(int64_t arg0, int64_t arg1, int64_t arg2,
1577 int64_t arg3, int64_t arg4, int64_t arg5);
1578 typedef int64_t (*Prototype_General7)(int64_t arg0, int64_t arg1, int64_t arg2,
1579 int64_t arg3, int64_t arg4, int64_t arg5,
1580 int64_t arg6);
1581 typedef int64_t (*Prototype_General8)(int64_t arg0, int64_t arg1, int64_t arg2,
1582 int64_t arg3, int64_t arg4, int64_t arg5,
1583 int64_t arg6, int64_t arg7);
1584 typedef int64_t (*Prototype_GeneralGeneralGeneralInt64)(int64_t arg0,
1585 int64_t arg1,
1586 int64_t arg2,
1587 int64_t arg3);
1588 typedef int64_t (*Prototype_GeneralGeneralInt64Int64)(int64_t arg0,
1589 int64_t arg1,
1590 int64_t arg2,
1591 int64_t arg3);
1592
1593 typedef int64_t (*Prototype_Int_Double)(double arg0);
1594 typedef int64_t (*Prototype_Int_IntDouble)(int64_t arg0, double arg1);
1595 typedef int64_t (*Prototype_Int_DoubleInt)(double arg0, int64_t arg1);
1596 typedef int64_t (*Prototype_Int_DoubleIntInt)(double arg0, int64_t arg1,
1597 int64_t arg2);
1598 typedef int64_t (*Prototype_Int_IntDoubleIntInt)(int64_t arg0, double arg1,
1599 int64_t arg2, int64_t arg3);
1600
1601 typedef float (*Prototype_Float32_Float32)(float arg0);
1602 typedef int64_t (*Prototype_Int_Float32)(float arg0);
1603 typedef float (*Prototype_Float32_Float32Float32)(float arg0, float arg1);
1604
1605 typedef double (*Prototype_Double_None)();
1606 typedef double (*Prototype_Double_Double)(double arg0);
1607 typedef double (*Prototype_Double_Int)(int64_t arg0);
1608 typedef double (*Prototype_Double_DoubleInt)(double arg0, int64_t arg1);
1609 typedef double (*Prototype_Double_IntDouble)(int64_t arg0, double arg1);
1610 typedef double (*Prototype_Double_DoubleDouble)(double arg0, double arg1);
1611 typedef double (*Prototype_Double_DoubleDoubleDouble)(double arg0, double arg1,
1612 double arg2);
1613 typedef double (*Prototype_Double_DoubleDoubleDoubleDouble)(double arg0,
1614 double arg1,
1615 double arg2,
1616 double arg3);
1617
1618 typedef int32_t (*Prototype_Int32_General)(int64_t);
1619 typedef int32_t (*Prototype_Int32_GeneralInt32)(int64_t, int32_t);
1620 typedef int32_t (*Prototype_Int32_GeneralInt32Int32)(int64_t, int32_t, int32_t);
1621 typedef int32_t (*Prototype_Int32_GeneralInt32Int32Int32)(int64_t, int32_t,
1622 int32_t, int32_t);
1623 typedef int32_t (*Prototype_Int32_GeneralInt32Int32Int32Int32)(int64_t, int32_t,
1624 int32_t, int32_t,
1625 int32_t);
1626 typedef int32_t (*Prototype_Int32_GeneralInt32Int32Int32Int32Int32)(
1627 int64_t, int32_t, int32_t, int32_t, int32_t, int32_t);
1628 typedef int32_t (*Prototype_Int32_GeneralInt32Int32Int32Int32General)(
1629 int64_t, int32_t, int32_t, int32_t, int32_t, int64_t);
1630 typedef int32_t (*Prototype_Int32_GeneralInt32Int32Int32General)(
1631 int64_t, int32_t, int32_t, int32_t, int64_t);
1632 typedef int32_t (*Prototype_Int32_GeneralInt32Int32General)(int64_t, int32_t,
1633 int32_t, int64_t);
1634 typedef int32_t (*Prototype_Int32_GeneralInt32Int32Int64Int32)(int64_t, int32_t,
1635 int32_t, int64_t,
1636 int32_t);
1637 typedef int32_t (*Prototype_Int32_GeneralInt32GeneralInt32)(int64_t, int32_t,
1638 int64_t, int32_t);
1639 typedef int32_t (*Prototype_Int32_GeneralInt32GeneralInt32Int32)(
1640 int64_t, int32_t, int64_t, int32_t, int32_t);
1641 typedef int32_t (*Prototype_Int32_GeneralInt32Int64Int64Int32)(int64_t, int32_t,
1642 int64_t, int64_t,
1643 int32_t);
1644 typedef int32_t (*Prototype_Int32_GeneralGeneral)(int64_t, int64_t);
1645 typedef int32_t (*Prototype_Int32_GeneralGeneralGeneral)(int64_t, int64_t,
1646 int64_t);
1647 typedef int32_t (*Prototype_Int32_GeneralGeneralInt32Int32)(int64_t, int64_t,
1648 int32_t, int32_t);
1649 typedef int32_t (*Prototype_Int32_GeneralInt64Int32Int32)(int64_t, int64_t,
1650 int32_t, int32_t);
1651 typedef int32_t (*Prototype_Int32_GeneralInt64Int32Int32Int32Int32)(
1652 int64_t, int64_t, int32_t, int32_t, int32_t, int32_t);
1653 typedef int32_t (*Prototype_Int32_GeneralInt64Int32Int64Int32)(int64_t, int64_t,
1654 int32_t, int64_t,
1655 int32_t);
1656 typedef int32_t (*Prototype_Int32_GeneralInt64Int32Int32Int32)(int64_t, int64_t,
1657 int32_t, int32_t,
1658 int32_t);
1659 typedef int32_t (*Prototype_Int32_GeneralGeneralInt32Int32Int32GeneralInt32)(
1660 int64_t, int64_t, int32_t, int32_t, int32_t, int64_t, int32_t);
1661 typedef int32_t (*Prototype_Int32_GeneralGeneralInt32General)(int32_t, int32_t,
1662 int32_t, int32_t);
1663 typedef int32_t (*Prototype_Int32_GeneralInt64Int32Int64General)(
1664 int64_t, int64_t, int32_t, int64_t, int64_t);
1665 typedef int32_t (*Prototype_Int32_GeneralInt64Int64Int64)(int64_t, int64_t,
1666 int64_t, int64_t);
1667 typedef int32_t (*Prototype_Int32_GeneralInt64Int64Int64Int32)(int64_t, int64_t,
1668 int64_t, int64_t,
1669 int32_t);
1670 typedef int32_t (*Prototype_Int32_GeneralInt64Int64General)(int64_t, int64_t,
1671 int64_t, int64_t);
1672 typedef int32_t (*Prototype_Int32_GeneralInt64Int64Int64General)(
1673 int64_t, int64_t, int64_t, int64_t, int64_t);
1674 typedef int32_t (*Prototype_Int32_GeneralInt64Int64Int64Int32Int32)(
1675 int64_t, int64_t, int64_t, int64_t, int32_t, int32_t);
1676 typedef int64_t (*Prototype_General_GeneralInt32)(int64_t, int32_t);
1677 typedef int64_t (*Prototype_General_GeneralInt32Int32)(int64_t, int32_t,
1678 int32_t);
1679 typedef int64_t (*Prototype_General_GeneralInt32General)(int64_t, int32_t,
1680 int64_t);
1681 typedef int64_t (*Prototype_General_GeneralInt32Int32GeneralInt32)(
1682 int64_t, int32_t, int32_t, int64_t, int32_t);
1683 typedef int32_t (*Prototype_Int32_GeneralGeneralInt32GeneralInt32Int32Int32)(
1684 int64_t, int64_t, int32_t, int64_t, int32_t, int32_t, int32_t);
1685 typedef int64_t (*Prototype_Int64_General)(int64_t);
1686 typedef int64_t (*Prototype_Int64_GeneralInt32)(int64_t, int32_t);
1687 typedef int64_t (*Prototype_Int64_GeneralInt64)(int64_t, int64_t);
1688 typedef int64_t (*Prototype_Int64_GeneralInt64Int32)(int64_t, int64_t, int32_t);
1689 typedef int32_t (*Prototype_Int32_GeneralInt64Int64General)(int64_t, int64_t,
1690 int64_t, int64_t);
1691 // Generated by Assembler::break_()/stop(), ebreak code is passed as immediate
1692 // field of a subsequent LUI instruction; otherwise returns -1
1693 static inline uint32_t get_ebreak_code(Instruction* instr) {
1694 MOZ_ASSERT(instr->InstructionBits() == kBreakInstr);
1695 uint8_t* cur = reinterpret_cast<uint8_t*>(instr);
1696 Instruction* next_instr = reinterpret_cast<Instruction*>(cur + kInstrSize);
1697 if (next_instr->BaseOpcodeFieldRaw() == LUI)
1698 return (next_instr->Imm20UValue());
1699 else
1700 return -1;
1701 }
1702
1703 // Software interrupt instructions are used by the simulator to call into C++.
1704 void Simulator::SoftwareInterrupt() {
1705 // There are two instructions that could get us here, the ebreak or ecall
1706 // instructions are "SYSTEM" class opcode distinuished by Imm12Value field w/
1707 // the rest of instruction fields being zero
1708 // We first check if we met a call_rt_redirected.
1709 if (instr_.InstructionBits() == rtCallRedirInstr) {
1710 Redirection* redirection = Redirection::FromSwiInstruction(instr_.instr());
1711 uintptr_t nativeFn =
1712 reinterpret_cast<uintptr_t>(redirection->nativeFunction());
1713
1714 intptr_t arg0 = getRegister(a0);
1715 intptr_t arg1 = getRegister(a1);
1716 intptr_t arg2 = getRegister(a2);
1717 intptr_t arg3 = getRegister(a3);
1718 intptr_t arg4 = getRegister(a4);
1719 intptr_t arg5 = getRegister(a5);
1720 intptr_t arg6 = getRegister(a6);
1721 intptr_t arg7 = getRegister(a7);
1722
1723 // This is dodgy but it works because the C entry stubs are never moved.
1724 // See comment in codegen-arm.cc and bug 1242173.
1725 intptr_t saved_ra = getRegister(ra);
1726
1727 intptr_t external =
1728 reinterpret_cast<intptr_t>(redirection->nativeFunction());
1729
1730 bool stack_aligned = (getRegister(sp) & (ABIStackAlignment - 1)) == 0;
1731 if (!stack_aligned) {
1732 fprintf(stderr, "Runtime call with unaligned stack!\n");
1733 MOZ_CRASH();
1734 }
1735
1736 if (single_stepping_) {
1737 single_step_callback_(single_step_callback_arg_, this, nullptr);
1738 }
1739 if (FLAG_trace_sim) {
1740 printf(
1741 "Call to host function at %p with args %ld, %ld, %ld, %ld, %ld, %ld, "
1742 "%ld, %ld\n",
1743 reinterpret_cast<void*>(external), arg0, arg1, arg2, arg3, arg4, arg5,
1744 arg6, arg7);
1745 }
1746 switch (redirection->type()) {
1747 case Args_General0: {
1748 Prototype_General0 target =
1749 reinterpret_cast<Prototype_General0>(external);
1750 int64_t result = target();
1751 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1752 setCallResult(result);
1753 break;
1754 }
1755 case Args_General1: {
1756 Prototype_General1 target =
1757 reinterpret_cast<Prototype_General1>(external);
1758 int64_t result = target(arg0);
1759 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1760 setCallResult(result);
1761 break;
1762 }
1763 case Args_General2: {
1764 Prototype_General2 target =
1765 reinterpret_cast<Prototype_General2>(external);
1766 int64_t result = target(arg0, arg1);
1767 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1768 setCallResult(result);
1769 break;
1770 }
1771 case Args_General3: {
1772 Prototype_General3 target =
1773 reinterpret_cast<Prototype_General3>(external);
1774 int64_t result = target(arg0, arg1, arg2);
1775 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1776 if (external == intptr_t(&js::wasm::Instance::wake_m32)) {
1777 result = int32_t(result);
1778 }
1779 setCallResult(result);
1780 break;
1781 }
1782 case Args_General4: {
1783 Prototype_General4 target =
1784 reinterpret_cast<Prototype_General4>(external);
1785 int64_t result = target(arg0, arg1, arg2, arg3);
1786 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1787 setCallResult(result);
1788 break;
1789 }
1790 case Args_General5: {
1791 Prototype_General5 target =
1792 reinterpret_cast<Prototype_General5>(external);
1793 int64_t result = target(arg0, arg1, arg2, arg3, arg4);
1794 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1795 setCallResult(result);
1796 break;
1797 }
1798 case Args_General6: {
1799 Prototype_General6 target =
1800 reinterpret_cast<Prototype_General6>(external);
1801 int64_t result = target(arg0, arg1, arg2, arg3, arg4, arg5);
1802 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1803 setCallResult(result);
1804 break;
1805 }
1806 case Args_General7: {
1807 Prototype_General7 target =
1808 reinterpret_cast<Prototype_General7>(external);
1809 int64_t result = target(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
1810 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1811 setCallResult(result);
1812 break;
1813 }
1814 case Args_General8: {
1815 Prototype_General8 target =
1816 reinterpret_cast<Prototype_General8>(external);
1817 int64_t result = target(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
1818 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1819 setCallResult(result);
1820 break;
1821 }
1822 case Args_Double_None: {
1823 Prototype_Double_None target =
1824 reinterpret_cast<Prototype_Double_None>(external);
1825 double dresult = target();
1826 if (FLAG_trace_sim) printf("ret %f\n", dresult);
1827 setCallResultDouble(dresult);
1828 break;
1829 }
1830 case Args_Int_Double: {
1831 double dval0 = getFpuRegisterDouble(fa0);
1832 Prototype_Int_Double target =
1833 reinterpret_cast<Prototype_Int_Double>(external);
1834 int64_t result = target(dval0);
1835 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1836 if (external == intptr_t((int32_t (*)(double))JS::ToInt32)) {
1837 result = int32_t(result);
1838 }
1839 setRegister(a0, result);
1840 break;
1841 }
1842 case Args_Int_GeneralGeneralGeneralInt64: {
1843 Prototype_GeneralGeneralGeneralInt64 target =
1844 reinterpret_cast<Prototype_GeneralGeneralGeneralInt64>(external);
1845 int64_t result = target(arg0, arg1, arg2, arg3);
1846 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1847 if (external == intptr_t(&js::wasm::Instance::wait_i32_m32)) {
1848 result = int32_t(result);
1849 }
1850 setRegister(a0, result);
1851 break;
1852 }
1853 case Args_Int_GeneralGeneralInt64Int64: {
1854 Prototype_GeneralGeneralInt64Int64 target =
1855 reinterpret_cast<Prototype_GeneralGeneralInt64Int64>(external);
1856 int64_t result = target(arg0, arg1, arg2, arg3);
1857 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1858 if (external == intptr_t(&js::wasm::Instance::wait_i64_m32)) {
1859 result = int32_t(result);
1860 }
1861 setRegister(a0, result);
1862 break;
1863 }
1864 case Args_Int_DoubleInt: {
1865 double dval = getFpuRegisterDouble(fa0);
1866 Prototype_Int_DoubleInt target =
1867 reinterpret_cast<Prototype_Int_DoubleInt>(external);
1868 int64_t result = target(dval, arg0);
1869 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1870 setRegister(a0, result);
1871 break;
1872 }
1873 case Args_Int_DoubleIntInt: {
1874 double dval = getFpuRegisterDouble(fa0);
1875 Prototype_Int_DoubleIntInt target =
1876 reinterpret_cast<Prototype_Int_DoubleIntInt>(external);
1877 int64_t result = target(dval, arg1, arg2);
1878 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1879 setRegister(a0, result);
1880 break;
1881 }
1882 case Args_Int_IntDoubleIntInt: {
1883 double dval = getFpuRegisterDouble(fa0);
1884 Prototype_Int_IntDoubleIntInt target =
1885 reinterpret_cast<Prototype_Int_IntDoubleIntInt>(external);
1886 int64_t result = target(arg0, dval, arg2, arg3);
1887 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1888 setRegister(a0, result);
1889 break;
1890 }
1891 case Args_Double_Double: {
1892 double dval0 = getFpuRegisterDouble(fa0);
1893 Prototype_Double_Double target =
1894 reinterpret_cast<Prototype_Double_Double>(external);
1895 double dresult = target(dval0);
1896 if (FLAG_trace_sim) printf("ret %f\n", dresult);
1897 setCallResultDouble(dresult);
1898 break;
1899 }
1900 case Args_Float32_Float32: {
1901 float fval0;
1902 fval0 = getFpuRegisterFloat(fa0);
1903 Prototype_Float32_Float32 target =
1904 reinterpret_cast<Prototype_Float32_Float32>(external);
1905 float fresult = target(fval0);
1906 if (FLAG_trace_sim) printf("ret %f\n", fresult);
1907 setCallResultFloat(fresult);
1908 break;
1909 }
1910 case Args_Int_Float32: {
1911 float fval0;
1912 fval0 = getFpuRegisterFloat(fa0);
1913 Prototype_Int_Float32 target =
1914 reinterpret_cast<Prototype_Int_Float32>(external);
1915 int64_t result = target(fval0);
1916 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1917 setRegister(a0, result);
1918 break;
1919 }
1920 case Args_Float32_Float32Float32: {
1921 float fval0;
1922 float fval1;
1923 fval0 = getFpuRegisterFloat(fa0);
1924 fval1 = getFpuRegisterFloat(fa1);
1925 Prototype_Float32_Float32Float32 target =
1926 reinterpret_cast<Prototype_Float32_Float32Float32>(external);
1927 float fresult = target(fval0, fval1);
1928 if (FLAG_trace_sim) printf("ret %f\n", fresult);
1929 setCallResultFloat(fresult);
1930 break;
1931 }
1932 case Args_Double_Int: {
1933 Prototype_Double_Int target =
1934 reinterpret_cast<Prototype_Double_Int>(external);
1935 double dresult = target(arg0);
1936 if (FLAG_trace_sim) printf("ret %f\n", dresult);
1937 setCallResultDouble(dresult);
1938 break;
1939 }
1940 case Args_Double_DoubleInt: {
1941 double dval0 = getFpuRegisterDouble(fa0);
1942 Prototype_Double_DoubleInt target =
1943 reinterpret_cast<Prototype_Double_DoubleInt>(external);
1944 double dresult = target(dval0, arg0);
1945 if (FLAG_trace_sim) printf("ret %f\n", dresult);
1946 setCallResultDouble(dresult);
1947 break;
1948 }
1949 case Args_Double_DoubleDouble: {
1950 double dval0 = getFpuRegisterDouble(fa0);
1951 double dval1 = getFpuRegisterDouble(fa1);
1952 Prototype_Double_DoubleDouble target =
1953 reinterpret_cast<Prototype_Double_DoubleDouble>(external);
1954 double dresult = target(dval0, dval1);
1955 if (FLAG_trace_sim) printf("ret %f\n", dresult);
1956 setCallResultDouble(dresult);
1957 break;
1958 }
1959 case Args_Double_IntDouble: {
1960 double dval0 = getFpuRegisterDouble(fa0);
1961 Prototype_Double_IntDouble target =
1962 reinterpret_cast<Prototype_Double_IntDouble>(external);
1963 double dresult = target(arg0, dval0);
1964 if (FLAG_trace_sim) printf("ret %f\n", dresult);
1965 setCallResultDouble(dresult);
1966 break;
1967 }
1968 case Args_Int_IntDouble: {
1969 double dval0 = getFpuRegisterDouble(fa0);
1970 Prototype_Int_IntDouble target =
1971 reinterpret_cast<Prototype_Int_IntDouble>(external);
1972 int64_t result = target(arg0, dval0);
1973 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", result);
1974 setRegister(a0, result);
1975 break;
1976 }
1977 case Args_Double_DoubleDoubleDouble: {
1978 double dval0 = getFpuRegisterDouble(fa0);
1979 double dval1 = getFpuRegisterDouble(fa1);
1980 double dval2 = getFpuRegisterDouble(fa2);
1981 Prototype_Double_DoubleDoubleDouble target =
1982 reinterpret_cast<Prototype_Double_DoubleDoubleDouble>(external);
1983 double dresult = target(dval0, dval1, dval2);
1984 if (FLAG_trace_sim) printf("ret %f\n", dresult);
1985 setCallResultDouble(dresult);
1986 break;
1987 }
1988 case Args_Double_DoubleDoubleDoubleDouble: {
1989 double dval0 = getFpuRegisterDouble(fa0);
1990 double dval1 = getFpuRegisterDouble(fa1);
1991 double dval2 = getFpuRegisterDouble(fa2);
1992 double dval3 = getFpuRegisterDouble(fa3);
1993 Prototype_Double_DoubleDoubleDoubleDouble target =
1994 reinterpret_cast<Prototype_Double_DoubleDoubleDoubleDouble>(
1995 external);
1996 double dresult = target(dval0, dval1, dval2, dval3);
1997 if (FLAG_trace_sim) printf("ret %f\n", dresult);
1998 setCallResultDouble(dresult);
1999 break;
2000 }
2001 case Args_Int32_General: {
2002 int32_t ret = reinterpret_cast<Prototype_Int32_General>(nativeFn)(arg0);
2003 if (FLAG_trace_sim) printf("ret %d\n", ret);
2004 setRegister(a0, I64(ret));
2005 break;
2006 }
2007 case Args_Int32_GeneralInt32: {
2008 int32_t ret = reinterpret_cast<Prototype_Int32_GeneralInt32>(nativeFn)(
2009 arg0, I32(arg1));
2010 if (FLAG_trace_sim) printf("ret %d\n", ret);
2011 setRegister(a0, I64(ret));
2012 break;
2013 }
2014 case Args_Int32_GeneralInt32Int32: {
2015 int32_t ret = reinterpret_cast<Prototype_Int32_GeneralInt32Int32>(
2016 nativeFn)(arg0, I32(arg1), I32(arg2));
2017 if (FLAG_trace_sim) printf("ret %d\n", ret);
2018 setRegister(a0, I64(ret));
2019 break;
2020 }
2021 case Args_Int32_GeneralInt32Int32Int32: {
2022 int32_t ret = reinterpret_cast<Prototype_Int32_GeneralInt32Int32Int32>(
2023 nativeFn)(arg0, I32(arg1), I32(arg2), I32(arg3));
2024 setRegister(a0, I64(ret));
2025 break;
2026 }
2027 case Args_Int32_GeneralInt32Int32Int32Int32: {
2028 int32_t ret =
2029 reinterpret_cast<Prototype_Int32_GeneralInt32Int32Int32Int32>(
2030 nativeFn)(arg0, I32(arg1), I32(arg2), I32(arg3), I32(arg4));
2031 if (FLAG_trace_sim) printf("ret %d\n", ret);
2032 setRegister(a0, I64(ret));
2033 break;
2034 }
2035 case Args_Int32_GeneralInt32Int32Int32Int32Int32: {
2036 int32_t ret =
2037 reinterpret_cast<Prototype_Int32_GeneralInt32Int32Int32Int32Int32>(
2038 nativeFn)(arg0, I32(arg1), I32(arg2), I32(arg3), I32(arg4),
2039 I32(arg5));
2040 if (FLAG_trace_sim) printf("ret %d\n", ret);
2041 setRegister(a0, I64(ret));
2042 break;
2043 }
2044 case Args_Int32_GeneralInt32Int32Int32Int32General: {
2045 int32_t ret = reinterpret_cast<
2046 Prototype_Int32_GeneralInt32Int32Int32Int32General>(nativeFn)(
2047 arg0, I32(arg1), I32(arg2), I32(arg3), I32(arg4), arg5);
2048 if (FLAG_trace_sim) printf("ret %d\n", ret);
2049 setRegister(a0, I64(ret));
2050 break;
2051 }
2052 case Args_Int32_GeneralInt32Int32Int32General: {
2053 int32_t ret =
2054 reinterpret_cast<Prototype_Int32_GeneralInt32Int32Int32General>(
2055 nativeFn)(arg0, I32(arg1), I32(arg2), I32(arg3), arg4);
2056 if (FLAG_trace_sim) printf("ret %d\n", ret);
2057 setRegister(a0, I64(ret));
2058 break;
2059 }
2060 case Args_Int32_GeneralInt32Int32General: {
2061 int32_t ret =
2062 reinterpret_cast<Prototype_Int32_GeneralInt32Int32General>(
2063 nativeFn)(arg0, I32(arg1), I32(arg2), arg3);
2064 if (FLAG_trace_sim) printf("ret %d\n", ret);
2065 setRegister(a0, I64(ret));
2066 break;
2067 }
2068 case Args_Int32_GeneralInt32Int32Int64Int32: {
2069 int32_t ret =
2070 reinterpret_cast<Prototype_Int32_GeneralInt32Int32Int64Int32>(
2071 nativeFn)(arg0, I32(arg1), I32(arg2), arg3, I32(arg4));
2072 setRegister(a0, I64(ret));
2073 break;
2074 }
2075 case Args_Int32_GeneralInt32GeneralInt32: {
2076 int32_t ret =
2077 reinterpret_cast<Prototype_Int32_GeneralInt32GeneralInt32>(
2078 nativeFn)(arg0, I32(arg1), arg2, I32(arg3));
2079 if (FLAG_trace_sim) printf("ret %d\n", ret);
2080 setRegister(a0, I64(ret));
2081 break;
2082 }
2083 case Args_Int32_GeneralInt32GeneralInt32Int32: {
2084 int32_t ret =
2085 reinterpret_cast<Prototype_Int32_GeneralInt32GeneralInt32Int32>(
2086 nativeFn)(arg0, I32(arg1), arg2, I32(arg3), I32(arg4));
2087 if (FLAG_trace_sim) printf("ret %d\n", ret);
2088 setRegister(a0, I64(ret));
2089 break;
2090 }
2091 case Args_Int32_GeneralGeneral: {
2092 int32_t ret = reinterpret_cast<Prototype_Int32_GeneralGeneral>(
2093 nativeFn)(arg0, arg1);
2094 if (FLAG_trace_sim) printf("ret %d\n", ret);
2095 setRegister(a0, I64(ret));
2096 break;
2097 }
2098 case Args_Int32_GeneralInt32Int64Int64Int32: {
2099 int32_t ret =
2100 reinterpret_cast<Prototype_Int32_GeneralInt32Int64Int64Int32>(
2101 nativeFn)(arg0, I32(arg1), arg2, arg3, I32(arg4));
2102 setRegister(a0, I64(ret));
2103 break;
2104 }
2105 case Args_Int32_GeneralGeneralGeneral: {
2106 int32_t ret = reinterpret_cast<Prototype_Int32_GeneralGeneralGeneral>(
2107 nativeFn)(arg0, arg1, arg2);
2108 if (FLAG_trace_sim) printf("ret %d\n", ret);
2109 setRegister(a0, I64(ret));
2110 break;
2111 }
2112 case Args_Int32_GeneralGeneralInt32Int32: {
2113 int32_t ret =
2114 reinterpret_cast<Prototype_Int32_GeneralGeneralInt32Int32>(
2115 nativeFn)(arg0, arg1, I32(arg2), I32(arg3));
2116 if (FLAG_trace_sim) printf("ret %d\n", ret);
2117 setRegister(a0, I64(ret));
2118 break;
2119 }
2120 case js::jit::Args_Int32_GeneralInt64Int32Int32: {
2121 int32_t ret = reinterpret_cast<Prototype_Int32_GeneralInt64Int32Int32>(
2122 nativeFn)(arg0, arg1, I32(arg2), I32(arg3));
2123 setRegister(a0, I64(ret));
2124 break;
2125 }
2126 case js::jit::Args_Int32_GeneralInt64Int32Int32Int32Int32: {
2127 int32_t ret =
2128 reinterpret_cast<Prototype_Int32_GeneralInt64Int32Int32Int32Int32>(
2129 nativeFn)(arg0, arg1, I32(arg2), I32(arg3), I32(arg4),
2130 I32(arg5));
2131 setRegister(a0, I64(ret));
2132 break;
2133 }
2134 case js::jit::Args_Int32_GeneralInt64Int32Int64Int32: {
2135 int32_t ret =
2136 reinterpret_cast<Prototype_Int32_GeneralInt64Int32Int64Int32>(
2137 nativeFn)(arg0, arg1, I32(arg2), arg3, I32(arg4));
2138 setRegister(a0, I64(ret));
2139 break;
2140 }
2141 case js::jit::Args_Int32_GeneralInt64Int32Int64General: {
2142 int32_t ret =
2143 reinterpret_cast<Prototype_Int32_GeneralInt64Int32Int64General>(
2144 nativeFn)(arg0, arg1, I32(arg2), arg3, arg4);
2145 if (FLAG_trace_sim) printf("ret %d\n", ret);
2146 setRegister(a0, I64(ret));
2147 break;
2148 }
2149 case js::jit::Args_Int32_GeneralInt64Int64Int64: {
2150 int32_t ret = reinterpret_cast<Prototype_Int32_GeneralInt64Int64Int64>(
2151 nativeFn)(arg0, arg1, arg2, arg3);
2152 if (FLAG_trace_sim) printf("ret %d\n", ret);
2153 setRegister(a0, I64(ret));
2154 break;
2155 }
2156 case js::jit::Args_Int32_GeneralInt64Int64Int64Int32: {
2157 int32_t ret =
2158 reinterpret_cast<Prototype_Int32_GeneralInt64Int64Int64Int32>(
2159 nativeFn)(arg0, arg1, arg2, arg3, I32(arg4));
2160 setRegister(a0, I64(ret));
2161 break;
2162 }
2163 case js::jit::Args_Int32_GeneralInt64Int64General: {
2164 int32_t ret =
2165 reinterpret_cast<Prototype_Int32_GeneralInt64Int64General>(
2166 nativeFn)(arg0, arg1, arg2, arg3);
2167 if (FLAG_trace_sim) printf("ret %d\n", ret);
2168 setRegister(a0, I64(ret));
2169 break;
2170 }
2171 case js::jit::Args_Int32_GeneralInt64Int64Int64General: {
2172 int32_t ret =
2173 reinterpret_cast<Prototype_Int32_GeneralInt64Int64Int64General>(
2174 nativeFn)(arg0, arg1, arg2, arg3, arg4);
2175 if (FLAG_trace_sim) printf("ret %d\n", ret);
2176 setRegister(a0, I64(ret));
2177 break;
2178 }
2179 case Args_General_GeneralInt32: {
2180 int64_t ret = reinterpret_cast<Prototype_General_GeneralInt32>(
2181 nativeFn)(arg0, I32(arg1));
2182 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", ret);
2183 setRegister(a0, ret);
2184 break;
2185 }
2186 case js::jit::Args_Int32_GeneralInt64Int64Int64Int32Int32: {
2187 int32_t ret =
2188 reinterpret_cast<Prototype_Int32_GeneralInt64Int64Int64Int32Int32>(
2189 nativeFn)(arg0, arg1, arg2, arg3, I32(arg4), I32(arg5));
2190 setRegister(a0, I64(ret));
2191 break;
2192 }
2193 case Args_General_GeneralInt32Int32: {
2194 int64_t ret = reinterpret_cast<Prototype_General_GeneralInt32Int32>(
2195 nativeFn)(arg0, I32(arg1), I32(arg2));
2196 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", ret);
2197 setRegister(a0, ret);
2198 break;
2199 }
2200 case Args_General_GeneralInt32General: {
2201 int64_t ret = reinterpret_cast<Prototype_General_GeneralInt32General>(
2202 nativeFn)(arg0, I32(arg1), arg2);
2203 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", ret);
2204 setRegister(a0, ret);
2205 break;
2206 }
2207 case js::jit::Args_General_GeneralInt32Int32GeneralInt32: {
2208 int64_t ret =
2209 reinterpret_cast<Prototype_General_GeneralInt32Int32GeneralInt32>(
2210 nativeFn)(arg0, I32(arg1), I32(arg2), arg3, I32(arg4));
2211 setRegister(a0, ret);
2212 break;
2213 }
2214 case js::jit::Args_Int32_GeneralGeneralInt32Int32Int32GeneralInt32: {
2215 int32_t ret = reinterpret_cast<
2216 Prototype_Int32_GeneralGeneralInt32Int32Int32GeneralInt32>(
2217 nativeFn)(arg0, arg1, I32(arg2), I32(arg3), I32(arg4), arg5,
2218 I32(arg6));
2219 setRegister(a0, I64(ret));
2220 break;
2221 }
2222 case js::jit::Args_Int32_GeneralGeneralInt32General: {
2223 Prototype_Int32_GeneralGeneralInt32General target =
2224 reinterpret_cast<Prototype_Int32_GeneralGeneralInt32General>(
2225 external);
2226 int64_t result = target(I32(arg0), I32(arg1), I32(arg2), I32(arg3));
2227 setRegister(a0, I64(result));
2228 break;
2229 }
2230 case js::jit::Args_Int32_GeneralGeneralInt32GeneralInt32Int32Int32: {
2231 int64_t arg6 = getRegister(a6);
2232 int32_t ret = reinterpret_cast<
2233 Prototype_Int32_GeneralGeneralInt32GeneralInt32Int32Int32>(
2234 nativeFn)(arg0, arg1, I32(arg2), arg3, I32(arg4), I32(arg5),
2235 I32(arg6));
2236 setRegister(a0, I64(ret));
2237 break;
2238 }
2239 case js::jit::Args_Int64_General: {
2240 int64_t ret = reinterpret_cast<Prototype_Int64_General>(nativeFn)(arg0);
2241 if (FLAG_trace_sim) printf("ret %" PRId64 "\n", ret);
2242 setRegister(a0, ret);
2243 break;
2244 }
2245 case js::jit::Args_Int64_GeneralInt32: {
2246 int64_t ret = reinterpret_cast<Prototype_Int64_GeneralInt32>(nativeFn)(
2247 arg0, I32(arg1));
2248 setRegister(a0, ret);
2249 break;
2250 }
2251 case js::jit::Args_Int64_GeneralInt64: {
2252 int64_t ret = reinterpret_cast<Prototype_Int64_GeneralInt64>(nativeFn)(
2253 arg0, arg1);
2254 setRegister(a0, ret);
2255 break;
2256 }
2257 case js::jit::Args_Int64_GeneralInt64Int32: {
2258 int64_t ret = reinterpret_cast<Prototype_Int64_GeneralInt64Int32>(
2259 nativeFn)(arg0, arg1, I32(arg2));
2260 setRegister(a0, ret);
2261 break;
2262 }
2263 default:
2264 MOZ_CRASH("Unknown function type.");
2265 }
2266
2267 if (single_stepping_) {
2268 single_step_callback_(single_step_callback_arg_, this, nullptr);
2269 }
2270
2271 setRegister(ra, saved_ra);
2272 set_pc(getRegister(ra));
2273
2274 } else if (instr_.InstructionBits() == kBreakInstr &&
2275 (get_ebreak_code(instr_.instr()) <= kMaxStopCode)) {
2276 uint32_t code = get_ebreak_code(instr_.instr());
2277 if (isWatchpoint(code)) {
2278 printWatchpoint(code);
2279 } else if (IsTracepoint(code)) {
2280 if (!FLAG_debug_sim) {
2281 MOZ_CRASH("Add --debug-sim when tracepoint instruction is used.\n");
2282 }
2283 // printf("%d %d %d %d %d %d %d\n", code, code & LOG_TRACE, code &
2284 // LOG_REGS,
2285 // code & kDebuggerTracingDirectivesMask, TRACE_ENABLE,
2286 // TRACE_DISABLE, kDebuggerTracingDirectivesMask);
2287 switch (code & kDebuggerTracingDirectivesMask) {
2288 case TRACE_ENABLE:
2289 if (code & LOG_TRACE) {
2290 FLAG_trace_sim = true;
2291 }
2292 if (code & LOG_REGS) {
2293 RiscvDebugger dbg(this);
2294 dbg.printAllRegs();
2295 }
2296 break;
2297 case TRACE_DISABLE:
2298 if (code & LOG_TRACE) {
2299 FLAG_trace_sim = false;
2300 }
2301 break;
2302 default:
2303 UNREACHABLE();
2304 }
2305 } else {
2306 increaseStopCounter(code);
2307 handleStop(code);
2308 }
2309 } else {
2310 // uint8_t code = get_ebreak_code(instr_.instr()) - kMaxStopCode - 1;
2311 // switch (LNode::Opcode(code)) {
2312 // #define EMIT_OP(OP, ...) \
2313 // case LNode::Opcode::OP:\
2314 // std::cout << #OP << std::endl; \
2315 // break;
2316 // LIR_OPCODE_LIST(EMIT_OP);
2317 // #undef EMIT_OP
2318 // }
2319 DieOrDebug();
2320 }
2321 }
2322
2323 // Stop helper functions.
2324 bool Simulator::isWatchpoint(uint32_t code) {
2325 return (code <= kMaxWatchpointCode);
2326 }
2327
2328 bool Simulator::IsTracepoint(uint32_t code) {
2329 return (code <= kMaxTracepointCode && code > kMaxWatchpointCode);
2330 }
2331
2332 void Simulator::printWatchpoint(uint32_t code) {
2333 RiscvDebugger dbg(this);
2334 ++break_count_;
2335 if (FLAG_riscv_print_watchpoint) {
2336 printf("\n---- break %d marker: %20" PRIi64 " (instr count: %20" PRIi64
2337 ") ----\n",
2338 code, break_count_, icount_);
2339 dbg.printAllRegs(); // Print registers and continue running.
2340 }
2341 }
2342
2343 void Simulator::handleStop(uint32_t code) {
2344 // Stop if it is enabled, otherwise go on jumping over the stop
2345 // and the message address.
2346 if (isEnabledStop(code)) {
2347 RiscvDebugger dbg(this);
2348 dbg.Debug();
2349 } else {
2350 set_pc(get_pc() + 2 * kInstrSize);
2351 }
2352 }
2353
2354 bool Simulator::isStopInstruction(SimInstruction* instr) {
2355 if (instr->InstructionBits() != kBreakInstr) return false;
2356 int32_t code = get_ebreak_code(instr->instr());
2357 return code != -1 && static_cast<uint32_t>(code) > kMaxWatchpointCode &&
2358 static_cast<uint32_t>(code) <= kMaxStopCode;
2359 }
2360
2361 bool Simulator::isEnabledStop(uint32_t code) {
2362 MOZ_ASSERT(code <= kMaxStopCode);
2363 MOZ_ASSERT(code > kMaxWatchpointCode);
2364 return !(watchedStops_[code].count_ & kStopDisabledBit);
2365 }
2366
2367 void Simulator::enableStop(uint32_t code) {
2368 if (!isEnabledStop(code)) {
2369 watchedStops_[code].count_ &= ~kStopDisabledBit;
2370 }
2371 }
2372
2373 void Simulator::disableStop(uint32_t code) {
2374 if (isEnabledStop(code)) {
2375 watchedStops_[code].count_ |= kStopDisabledBit;
2376 }
2377 }
2378
2379 void Simulator::increaseStopCounter(uint32_t code) {
2380 MOZ_ASSERT(code <= kMaxStopCode);
2381 if ((watchedStops_[code].count_ & ~(1 << 31)) == 0x7fffffff) {
2382 printf(
2383 "Stop counter for code %i has overflowed.\n"
2384 "Enabling this code and reseting the counter to 0.\n",
2385 code);
2386 watchedStops_[code].count_ = 0;
2387 enableStop(code);
2388 } else {
2389 watchedStops_[code].count_++;
2390 }
2391 }
2392
2393 // Print a stop status.
2394 void Simulator::printStopInfo(uint32_t code) {
2395 if (code <= kMaxWatchpointCode) {
2396 printf("That is a watchpoint, not a stop.\n");
2397 return;
2398 } else if (code > kMaxStopCode) {
2399 printf("Code too large, only %u stops can be used\n", kMaxStopCode + 1);
2400 return;
2401 }
2402 const char* state = isEnabledStop(code) ? "Enabled" : "Disabled";
2403 int32_t count = watchedStops_[code].count_ & ~kStopDisabledBit;
2404 // Don't print the state of unused breakpoints.
2405 if (count != 0) {
2406 if (watchedStops_[code].desc_) {
2407 printf("stop %i - 0x%x: \t%s, \tcounter = %i, \t%s\n", code, code, state,
2408 count, watchedStops_[code].desc_);
2409 } else {
2410 printf("stop %i - 0x%x: \t%s, \tcounter = %i\n", code, code, state,
2411 count);
2412 }
2413 }
2414 }
2415
2416 void Simulator::SignalException(Exception e) {
2417 printf("Error: Exception %i raised.", static_cast<int>(e));
2418 MOZ_CRASH();
2419 }
2420
2421 // TODO(plind): refactor this messy debug code when we do unaligned access.
2422 void Simulator::DieOrDebug() {
2423 if (FLAG_riscv_trap_to_simulator_debugger) {
2424 RiscvDebugger dbg(this);
2425 dbg.Debug();
2426 } else {
2427 MOZ_CRASH("Die");
2428 }
2429 }
2430
2431 // Executes the current instruction.
2432 void Simulator::InstructionDecode(Instruction* instr) {
2433 // if (FLAG_check_icache) {
2434 // CheckICache(SimulatorProcess::icache(), instr);
2435 // }
2436 pc_modified_ = false;
2437
2438 EmbeddedVector<char, 256> buffer;
2439
2440 if (FLAG_trace_sim || FLAG_debug_sim) {
2441 SNPrintF(trace_buf_, " ");
2442 disasm::NameConverter converter;
2443 disasm::Disassembler dasm(converter);
2444 // Use a reasonably large buffer.
2445 dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(instr));
2446
2447 // printf("EXECUTING 0x%08" PRIxPTR " %-44s\n",
2448 // reinterpret_cast<intptr_t>(instr), buffer.begin());
2449 }
2450
2451 instr_ = instr;
2452 switch (instr_.InstructionType()) {
2453 case Instruction::kRType:
2454 DecodeRVRType();
2455 break;
2456 case Instruction::kR4Type:
2457 DecodeRVR4Type();
2458 break;
2459 case Instruction::kIType:
2460 DecodeRVIType();
2461 break;
2462 case Instruction::kSType:
2463 DecodeRVSType();
2464 break;
2465 case Instruction::kBType:
2466 DecodeRVBType();
2467 break;
2468 case Instruction::kUType:
2469 DecodeRVUType();
2470 break;
2471 case Instruction::kJType:
2472 DecodeRVJType();
2473 break;
2474 case Instruction::kCRType:
2475 DecodeCRType();
2476 break;
2477 case Instruction::kCAType:
2478 DecodeCAType();
2479 break;
2480 case Instruction::kCJType:
2481 DecodeCJType();
2482 break;
2483 case Instruction::kCBType:
2484 DecodeCBType();
2485 break;
2486 case Instruction::kCIType:
2487 DecodeCIType();
2488 break;
2489 case Instruction::kCIWType:
2490 DecodeCIWType();
2491 break;
2492 case Instruction::kCSSType:
2493 DecodeCSSType();
2494 break;
2495 case Instruction::kCLType:
2496 DecodeCLType();
2497 break;
2498 case Instruction::kCSType:
2499 DecodeCSType();
2500 break;
2501 # ifdef CAN_USE_RVV_INSTRUCTIONS
2502 case Instruction::kVType:
2503 DecodeVType();
2504 break;
2505 # endif
2506 default:
2507 UNSUPPORTED();
2508 }
2509
2510 if (FLAG_trace_sim) {
2511 printf(" 0x%012" PRIxPTR " %-44s\t%s\n",
2512 reinterpret_cast<intptr_t>(instr), buffer.start(),
2513 trace_buf_.start());
2514 }
2515
2516 if (!pc_modified_) {
2517 setRegister(pc, reinterpret_cast<sreg_t>(instr) + instr->InstructionSize());
2518 }
2519
2520 if (watch_address_ != nullptr) {
2521 printf(" 0x%012" PRIxPTR " : 0x%016" REGIx_FORMAT " %14" REGId_FORMAT
2522 " \n",
2523 reinterpret_cast<intptr_t>(watch_address_), I64(*watch_address_),
2524 I64(*watch_address_));
2525 if (watch_value_ != *watch_address_) {
2526 RiscvDebugger dbg(this);
2527 dbg.Debug();
2528 watch_value_ = *watch_address_;
2529 }
2530 }
2531 }
2532
2533 void Simulator::enable_single_stepping(SingleStepCallback cb, void* arg) {
2534 single_stepping_ = true;
2535 single_step_callback_ = cb;
2536 single_step_callback_arg_ = arg;
2537 single_step_callback_(single_step_callback_arg_, this, (void*)get_pc());
2538 }
2539
2540 void Simulator::disable_single_stepping() {
2541 if (!single_stepping_) {
2542 return;
2543 }
2544 single_step_callback_(single_step_callback_arg_, this, (void*)get_pc());
2545 single_stepping_ = false;
2546 single_step_callback_ = nullptr;
2547 single_step_callback_arg_ = nullptr;
2548 }
2549
2550 template <bool enableStopSimAt>
2551 void Simulator::execute() {
2552 if (single_stepping_) {
2553 single_step_callback_(single_step_callback_arg_, this, nullptr);
2554 }
2555
2556 // Get the PC to simulate. Cannot use the accessor here as we need the
2557 // raw PC value and not the one used as input to arithmetic instructions.
2558 int64_t program_counter = get_pc();
2559
2560 while (program_counter != end_sim_pc) {
2561 if (enableStopSimAt && (icount_ == Simulator::StopSimAt)) {
2562 RiscvDebugger dbg(this);
2563 dbg.Debug();
2564 }
2565 if (single_stepping_) {
2566 single_step_callback_(single_step_callback_arg_, this,
2567 (void*)program_counter);
2568 }
2569 Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
2570 InstructionDecode(instr);
2571 icount_++;
2572 program_counter = get_pc();
2573 }
2574
2575 if (single_stepping_) {
2576 single_step_callback_(single_step_callback_arg_, this, nullptr);
2577 }
2578 }
2579
2580 // RISCV Instruction Decode Routine
2581 void Simulator::DecodeRVRType() {
2582 switch (instr_.InstructionBits() & kRTypeMask) {
2583 case RO_ADD: {
2584 set_rd(sext_xlen(rs1() + rs2()));
2585 break;
2586 }
2587 case RO_SUB: {
2588 set_rd(sext_xlen(rs1() - rs2()));
2589 break;
2590 }
2591 case RO_SLL: {
2592 set_rd(sext_xlen(rs1() << (rs2() & (xlen - 1))));
2593 break;
2594 }
2595 case RO_SLT: {
2596 set_rd(sreg_t(rs1()) < sreg_t(rs2()));
2597 break;
2598 }
2599 case RO_SLTU: {
2600 set_rd(reg_t(rs1()) < reg_t(rs2()));
2601 break;
2602 }
2603 case RO_XOR: {
2604 set_rd(rs1() ^ rs2());
2605 break;
2606 }
2607 case RO_SRL: {
2608 set_rd(sext_xlen(zext_xlen(rs1()) >> (rs2() & (xlen - 1))));
2609 break;
2610 }
2611 case RO_SRA: {
2612 set_rd(sext_xlen(sext_xlen(rs1()) >> (rs2() & (xlen - 1))));
2613 break;
2614 }
2615 case RO_OR: {
2616 set_rd(rs1() | rs2());
2617 break;
2618 }
2619 case RO_AND: {
2620 set_rd(rs1() & rs2());
2621 break;
2622 }
2623 # ifdef JS_CODEGEN_RISCV64
2624 case RO_ADDW: {
2625 set_rd(sext32(rs1() + rs2()));
2626 break;
2627 }
2628 case RO_SUBW: {
2629 set_rd(sext32(rs1() - rs2()));
2630 break;
2631 }
2632 case RO_SLLW: {
2633 set_rd(sext32(rs1() << (rs2() & 0x1F)));
2634 break;
2635 }
2636 case RO_SRLW: {
2637 set_rd(sext32(uint32_t(rs1()) >> (rs2() & 0x1F)));
2638 break;
2639 }
2640 case RO_SRAW: {
2641 set_rd(sext32(int32_t(rs1()) >> (rs2() & 0x1F)));
2642 break;
2643 }
2644 # endif /* JS_CODEGEN_RISCV64 */
2645 // TODO(riscv): Add RISCV M extension macro
2646 case RO_MUL: {
2647 set_rd(rs1() * rs2());
2648 break;
2649 }
2650 case RO_MULH: {
2651 set_rd(mulh(rs1(), rs2()));
2652 break;
2653 }
2654 case RO_MULHSU: {
2655 set_rd(mulhsu(rs1(), rs2()));
2656 break;
2657 }
2658 case RO_MULHU: {
2659 set_rd(mulhu(rs1(), rs2()));
2660 break;
2661 }
2662 case RO_DIV: {
2663 sreg_t lhs = sext_xlen(rs1());
2664 sreg_t rhs = sext_xlen(rs2());
2665 if (rhs == 0) {
2666 set_rd(-1);
2667 } else if (lhs == INTPTR_MIN && rhs == -1) {
2668 set_rd(lhs);
2669 } else {
2670 set_rd(sext_xlen(lhs / rhs));
2671 }
2672 break;
2673 }
2674 case RO_DIVU: {
2675 reg_t lhs = zext_xlen(rs1());
2676 reg_t rhs = zext_xlen(rs2());
2677 if (rhs == 0) {
2678 set_rd(UINTPTR_MAX);
2679 } else {
2680 set_rd(zext_xlen(lhs / rhs));
2681 }
2682 break;
2683 }
2684 case RO_REM: {
2685 sreg_t lhs = sext_xlen(rs1());
2686 sreg_t rhs = sext_xlen(rs2());
2687 if (rhs == 0) {
2688 set_rd(lhs);
2689 } else if (lhs == INTPTR_MIN && rhs == -1) {
2690 set_rd(0);
2691 } else {
2692 set_rd(sext_xlen(lhs % rhs));
2693 }
2694 break;
2695 }
2696 case RO_REMU: {
2697 reg_t lhs = zext_xlen(rs1());
2698 reg_t rhs = zext_xlen(rs2());
2699 if (rhs == 0) {
2700 set_rd(lhs);
2701 } else {
2702 set_rd(zext_xlen(lhs % rhs));
2703 }
2704 break;
2705 }
2706 # ifdef JS_CODEGEN_RISCV64
2707 case RO_MULW: {
2708 set_rd(sext32(sext32(rs1()) * sext32(rs2())));
2709 break;
2710 }
2711 case RO_DIVW: {
2712 sreg_t lhs = sext32(rs1());
2713 sreg_t rhs = sext32(rs2());
2714 if (rhs == 0) {
2715 set_rd(-1);
2716 } else if (lhs == INT32_MIN && rhs == -1) {
2717 set_rd(lhs);
2718 } else {
2719 set_rd(sext32(lhs / rhs));
2720 }
2721 break;
2722 }
2723 case RO_DIVUW: {
2724 reg_t lhs = zext32(rs1());
2725 reg_t rhs = zext32(rs2());
2726 if (rhs == 0) {
2727 set_rd(UINT32_MAX);
2728 } else {
2729 set_rd(zext32(lhs / rhs));
2730 }
2731 break;
2732 }
2733 case RO_REMW: {
2734 sreg_t lhs = sext32(rs1());
2735 sreg_t rhs = sext32(rs2());
2736 if (rhs == 0) {
2737 set_rd(lhs);
2738 } else if (lhs == INT32_MIN && rhs == -1) {
2739 set_rd(0);
2740 } else {
2741 set_rd(sext32(lhs % rhs));
2742 }
2743 break;
2744 }
2745 case RO_REMUW: {
2746 reg_t lhs = zext32(rs1());
2747 reg_t rhs = zext32(rs2());
2748 if (rhs == 0) {
2749 set_rd(zext32(lhs));
2750 } else {
2751 set_rd(zext32(lhs % rhs));
2752 }
2753 break;
2754 }
2755 # endif /*JS_CODEGEN_RISCV64*/
2756 // TODO(riscv): End Add RISCV M extension macro
2757 default: {
2758 switch (instr_.BaseOpcode()) {
2759 case AMO:
2760 DecodeRVRAType();
2761 break;
2762 case OP_FP:
2763 DecodeRVRFPType();
2764 break;
2765 default:
2766 UNSUPPORTED();
2767 }
2768 }
2769 }
2770 }
2771
2772 template <typename T>
2773 T Simulator::FMaxMinHelper(T a, T b, MaxMinKind kind) {
2774 // set invalid bit for signaling nan
2775 if ((a == std::numeric_limits<T>::signaling_NaN()) ||
2776 (b == std::numeric_limits<T>::signaling_NaN())) {
2777 set_csr_bits(csr_fflags, kInvalidOperation);
2778 }
2779
2780 T result = 0;
2781 if (std::isnan(a) && std::isnan(b)) {
2782 result = std::numeric_limits<float>::quiet_NaN();
2783 } else if (std::isnan(a)) {
2784 result = b;
2785 } else if (std::isnan(b)) {
2786 result = a;
2787 } else if (b == a) { // Handle -0.0 == 0.0 case.
2788 if (kind == MaxMinKind::kMax) {
2789 result = std::signbit(b) ? a : b;
2790 } else {
2791 result = std::signbit(b) ? b : a;
2792 }
2793 } else {
2794 result = (kind == MaxMinKind::kMax) ? fmax(a, b) : fmin(a, b);
2795 }
2796
2797 return result;
2798 }
2799
2800 float Simulator::RoundF2FHelper(float input_val, int rmode) {
2801 if (rmode == DYN) rmode = get_dynamic_rounding_mode();
2802
2803 float rounded = 0;
2804 switch (rmode) {
2805 case RNE: { // Round to Nearest, tiest to Even
2806 rounded = floorf(input_val);
2807 float error = input_val - rounded;
2808
2809 // Take care of correctly handling the range [-0.5, -0.0], which must
2810 // yield -0.0.
2811 if ((-0.5 <= input_val) && (input_val < 0.0)) {
2812 rounded = -0.0;
2813
2814 // If the error is greater than 0.5, or is equal to 0.5 and the integer
2815 // result is odd, round up.
2816 } else if ((error > 0.5) ||
2817 ((error == 0.5) && (std::fmod(rounded, 2) != 0))) {
2818 rounded++;
2819 }
2820 break;
2821 }
2822 case RTZ: // Round towards Zero
2823 rounded = std::truncf(input_val);
2824 break;
2825 case RDN: // Round Down (towards -infinity)
2826 rounded = floorf(input_val);
2827 break;
2828 case RUP: // Round Up (towards +infinity)
2829 rounded = ceilf(input_val);
2830 break;
2831 case RMM: // Round to Nearest, tiest to Max Magnitude
2832 rounded = std::roundf(input_val);
2833 break;
2834 default:
2835 UNREACHABLE();
2836 }
2837
2838 return rounded;
2839 }
2840
2841 double Simulator::RoundF2FHelper(double input_val, int rmode) {
2842 if (rmode == DYN) rmode = get_dynamic_rounding_mode();
2843
2844 double rounded = 0;
2845 switch (rmode) {
2846 case RNE: { // Round to Nearest, tiest to Even
2847 rounded = std::floor(input_val);
2848 double error = input_val - rounded;
2849
2850 // Take care of correctly handling the range [-0.5, -0.0], which must
2851 // yield -0.0.
2852 if ((-0.5 <= input_val) && (input_val < 0.0)) {
2853 rounded = -0.0;
2854
2855 // If the error is greater than 0.5, or is equal to 0.5 and the integer
2856 // result is odd, round up.
2857 } else if ((error > 0.5) ||
2858 ((error == 0.5) && (std::fmod(rounded, 2) != 0))) {
2859 rounded++;
2860 }
2861 break;
2862 }
2863 case RTZ: // Round towards Zero
2864 rounded = std::trunc(input_val);
2865 break;
2866 case RDN: // Round Down (towards -infinity)
2867 rounded = std::floor(input_val);
2868 break;
2869 case RUP: // Round Up (towards +infinity)
2870 rounded = std::ceil(input_val);
2871 break;
2872 case RMM: // Round to Nearest, tiest to Max Magnitude
2873 rounded = std::round(input_val);
2874 break;
2875 default:
2876 UNREACHABLE();
2877 }
2878 return rounded;
2879 }
2880
2881 // convert rounded floating-point to integer types, handle input values that
2882 // are out-of-range, underflow, or NaN, and set appropriate fflags
2883 template <typename I_TYPE, typename F_TYPE>
2884 I_TYPE Simulator::RoundF2IHelper(F_TYPE original, int rmode) {
2885 MOZ_ASSERT(std::is_integral<I_TYPE>::value);
2886
2887 MOZ_ASSERT((std::is_same<F_TYPE, float>::value ||
2888 std::is_same<F_TYPE, double>::value));
2889
2890 I_TYPE max_i = std::numeric_limits<I_TYPE>::max();
2891 I_TYPE min_i = std::numeric_limits<I_TYPE>::min();
2892
2893 if (!std::isfinite(original)) {
2894 set_fflags(kInvalidOperation);
2895 if (std::isnan(original) ||
2896 original == std::numeric_limits<F_TYPE>::infinity()) {
2897 return max_i;
2898 } else {
2899 MOZ_ASSERT(original == -std::numeric_limits<F_TYPE>::infinity());
2900 return min_i;
2901 }
2902 }
2903
2904 F_TYPE rounded = RoundF2FHelper(original, rmode);
2905 if (original != rounded) set_fflags(kInexact);
2906
2907 if (!std::isfinite(rounded)) {
2908 set_fflags(kInvalidOperation);
2909 if (std::isnan(rounded) ||
2910 rounded == std::numeric_limits<F_TYPE>::infinity()) {
2911 return max_i;
2912 } else {
2913 MOZ_ASSERT(rounded == -std::numeric_limits<F_TYPE>::infinity());
2914 return min_i;
2915 }
2916 }
2917
2918 // Since integer max values are either all 1s (for unsigned) or all 1s
2919 // except for sign-bit (for signed), they cannot be represented precisely in
2920 // floating point, in order to precisely tell whether the rounded floating
2921 // point is within the max range, we compare against (max_i+1) which would
2922 // have a single 1 w/ many trailing zeros
2923 float max_i_plus_1 =
2924 std::is_same<uint64_t, I_TYPE>::value
2925 ? 0x1p64f // uint64_t::max + 1 cannot be represented in integers,
2926 // so use its float representation directly
2927 : static_cast<float>(static_cast<uint64_t>(max_i) + 1);
2928 if (rounded >= max_i_plus_1) {
2929 set_fflags(kOverflow | kInvalidOperation);
2930 return max_i;
2931 }
2932
2933 // Since min_i (either 0 for unsigned, or for signed) is represented
2934 // precisely in floating-point, comparing rounded directly against min_i
2935 if (rounded <= min_i) {
2936 if (rounded < min_i) set_fflags(kOverflow | kInvalidOperation);
2937 return min_i;
2938 }
2939
2940 F_TYPE underflow_fval =
2941 std::is_same<F_TYPE, float>::value ? FLT_MIN : DBL_MIN;
2942 if (rounded < underflow_fval && rounded > -underflow_fval && rounded != 0) {
2943 set_fflags(kUnderflow);
2944 }
2945
2946 return static_cast<I_TYPE>(rounded);
2947 }
2948
2949 template <typename T>
2950 static int64_t FclassHelper(T value) {
2951 switch (std::fpclassify(value)) {
2952 case FP_INFINITE:
2953 return (std::signbit(value) ? kNegativeInfinity : kPositiveInfinity);
2954 case FP_NAN:
2955 return (isSnan(value) ? kSignalingNaN : kQuietNaN);
2956 case FP_NORMAL:
2957 return (std::signbit(value) ? kNegativeNormalNumber
2958 : kPositiveNormalNumber);
2959 case FP_SUBNORMAL:
2960 return (std::signbit(value) ? kNegativeSubnormalNumber
2961 : kPositiveSubnormalNumber);
2962 case FP_ZERO:
2963 return (std::signbit(value) ? kNegativeZero : kPositiveZero);
2964 default:
2965 UNREACHABLE();
2966 }
2967 UNREACHABLE();
2968 return FP_ZERO;
2969 }
2970
2971 template <typename T>
2972 bool Simulator::CompareFHelper(T input1, T input2, FPUCondition cc) {
2973 MOZ_ASSERT(std::is_floating_point<T>::value);
2974 bool result = false;
2975 switch (cc) {
2976 case LT:
2977 case LE:
2978 // FLT, FLE are signaling compares
2979 if (std::isnan(input1) || std::isnan(input2)) {
2980 set_fflags(kInvalidOperation);
2981 result = false;
2982 } else {
2983 result = (cc == LT) ? (input1 < input2) : (input1 <= input2);
2984 }
2985 break;
2986 case EQ:
2987 if (std::numeric_limits<T>::signaling_NaN() == input1 ||
2988 std::numeric_limits<T>::signaling_NaN() == input2) {
2989 set_fflags(kInvalidOperation);
2990 }
2991 if (std::isnan(input1) || std::isnan(input2)) {
2992 result = false;
2993 } else {
2994 result = (input1 == input2);
2995 }
2996 break;
2997 case NE:
2998 if (std::numeric_limits<T>::signaling_NaN() == input1 ||
2999 std::numeric_limits<T>::signaling_NaN() == input2) {
3000 set_fflags(kInvalidOperation);
3001 }
3002 if (std::isnan(input1) || std::isnan(input2)) {
3003 result = true;
3004 } else {
3005 result = (input1 != input2);
3006 }
3007 break;
3008 default:
3009 UNREACHABLE();
3010 }
3011 return result;
3012 }
3013
3014 template <typename T>
3015 static inline bool is_invalid_fmul(T src1, T src2) {
3016 return (isinf(src1) && src2 == static_cast<T>(0.0)) ||
3017 (src1 == static_cast<T>(0.0) && isinf(src2));
3018 }
3019
3020 template <typename T>
3021 static inline bool is_invalid_fadd(T src1, T src2) {
3022 return (isinf(src1) && isinf(src2) &&
3023 std::signbit(src1) != std::signbit(src2));
3024 }
3025
3026 template <typename T>
3027 static inline bool is_invalid_fsub(T src1, T src2) {
3028 return (isinf(src1) && isinf(src2) &&
3029 std::signbit(src1) == std::signbit(src2));
3030 }
3031
3032 template <typename T>
3033 static inline bool is_invalid_fdiv(T src1, T src2) {
3034 return ((src1 == 0 && src2 == 0) || (isinf(src1) && isinf(src2)));
3035 }
3036
3037 template <typename T>
3038 static inline bool is_invalid_fsqrt(T src1) {
3039 return (src1 < 0);
3040 }
3041
3042 int Simulator::loadLinkedW(uint64_t addr, SimInstruction* instr) {
3043 if ((addr & 3) == 0) {
3044 if (handleWasmSegFault(addr, 4)) {
3045 return -1;
3046 }
3047
3048 volatile int32_t* ptr = reinterpret_cast<volatile int32_t*>(addr);
3049 int32_t value = *ptr;
3050 lastLLValue_ = value;
3051 LLAddr_ = addr;
3052 // Note that any memory write or "external" interrupt should reset this
3053 // value to false.
3054 LLBit_ = true;
3055 return value;
3056 }
3057 printf("Unaligned write at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
3058 reinterpret_cast<intptr_t>(instr));
3059 MOZ_CRASH();
3060 return 0;
3061 }
3062
3063 int Simulator::storeConditionalW(uint64_t addr, int value,
3064 SimInstruction* instr) {
3065 // Correct behavior in this case, as defined by architecture, is to just
3066 // return 0, but there is no point at allowing that. It is certainly an
3067 // indicator of a bug.
3068 if (addr != LLAddr_) {
3069 printf("SC to bad address: 0x%016" PRIx64 ", pc=0x%016" PRIxPTR
3070 ", expected: 0x%016" PRIxPTR "\n",
3071 addr, reinterpret_cast<intptr_t>(instr), LLAddr_);
3072 MOZ_CRASH();
3073 }
3074
3075 if ((addr & 3) == 0) {
3076 SharedMem<int32_t*> ptr =
3077 SharedMem<int32_t*>::shared(reinterpret_cast<int32_t*>(addr));
3078
3079 if (!LLBit_) {
3080 return 1;
3081 }
3082
3083 LLBit_ = false;
3084 LLAddr_ = 0;
3085 int32_t expected = int32_t(lastLLValue_);
3086 int32_t old =
3087 AtomicOperations::compareExchangeSeqCst(ptr, expected, int32_t(value));
3088 return (old == expected) ? 0 : 1;
3089 }
3090 printf("Unaligned SC at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
3091 reinterpret_cast<intptr_t>(instr));
3092 MOZ_CRASH();
3093 return 0;
3094 }
3095
3096 int64_t Simulator::loadLinkedD(uint64_t addr, SimInstruction* instr) {
3097 if ((addr & kPointerAlignmentMask) == 0) {
3098 if (handleWasmSegFault(addr, 8)) {
3099 return -1;
3100 }
3101
3102 volatile int64_t* ptr = reinterpret_cast<volatile int64_t*>(addr);
3103 int64_t value = *ptr;
3104 lastLLValue_ = value;
3105 LLAddr_ = addr;
3106 // Note that any memory write or "external" interrupt should reset this
3107 // value to false.
3108 LLBit_ = true;
3109 return value;
3110 }
3111 printf("Unaligned write at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
3112 reinterpret_cast<intptr_t>(instr));
3113 MOZ_CRASH();
3114 return 0;
3115 }
3116
3117 int Simulator::storeConditionalD(uint64_t addr, int64_t value,
3118 SimInstruction* instr) {
3119 // Correct behavior in this case, as defined by architecture, is to just
3120 // return 0, but there is no point at allowing that. It is certainly an
3121 // indicator of a bug.
3122 if (addr != LLAddr_) {
3123 printf("SC to bad address: 0x%016" PRIx64 ", pc=0x%016" PRIxPTR
3124 ", expected: 0x%016" PRIxPTR "\n",
3125 addr, reinterpret_cast<intptr_t>(instr), LLAddr_);
3126 MOZ_CRASH();
3127 }
3128
3129 if ((addr & kPointerAlignmentMask) == 0) {
3130 SharedMem<int64_t*> ptr =
3131 SharedMem<int64_t*>::shared(reinterpret_cast<int64_t*>(addr));
3132
3133 if (!LLBit_) {
3134 return 1;
3135 }
3136
3137 LLBit_ = false;
3138 LLAddr_ = 0;
3139 int64_t expected = lastLLValue_;
3140 int64_t old =
3141 AtomicOperations::compareExchangeSeqCst(ptr, expected, int64_t(value));
3142 return (old == expected) ? 0 : 1;
3143 }
3144 printf("Unaligned SC at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
3145 reinterpret_cast<intptr_t>(instr));
3146 MOZ_CRASH();
3147 return 0;
3148 }
3149
3150 void Simulator::DecodeRVRAType() {
3151 // TODO(riscv): Add macro for RISCV A extension
3152 // Special handling for A extension instructions because it uses func5
3153 // For all A extension instruction, V8 simulator is pure sequential. No
3154 // Memory address lock or other synchronizaiton behaviors.
3155 switch (instr_.InstructionBits() & kRATypeMask) {
3156 case RO_LR_W: {
3157 sreg_t addr = rs1();
3158 set_rd(loadLinkedW(addr, &instr_));
3159 TraceLr(addr, getRegister(rd_reg()), getRegister(rd_reg()));
3160 break;
3161 }
3162 case RO_SC_W: {
3163 sreg_t addr = rs1();
3164 auto value = static_cast<int32_t>(rs2());
3165 auto result =
3166 storeConditionalW(addr, static_cast<int32_t>(rs2()), &instr_);
3167 set_rd(result);
3168 if (!result) {
3169 TraceSc(addr, value);
3170 }
3171 break;
3172 }
3173 case RO_AMOSWAP_W: {
3174 if ((rs1() & 0x3) != 0) {
3175 DieOrDebug();
3176 }
3177 set_rd(sext32(amo<uint32_t>(
3178 rs1(), [&](uint32_t lhs) { return (uint32_t)rs2(); }, instr_.instr(),
3179 WORD)));
3180 break;
3181 }
3182 case RO_AMOADD_W: {
3183 if ((rs1() & 0x3) != 0) {
3184 DieOrDebug();
3185 }
3186 set_rd(sext32(amo<uint32_t>(
3187 rs1(), [&](uint32_t lhs) { return lhs + (uint32_t)rs2(); },
3188 instr_.instr(), WORD)));
3189 break;
3190 }
3191 case RO_AMOXOR_W: {
3192 if ((rs1() & 0x3) != 0) {
3193 DieOrDebug();
3194 }
3195 set_rd(sext32(amo<uint32_t>(
3196 rs1(), [&](uint32_t lhs) { return lhs ^ (uint32_t)rs2(); },
3197 instr_.instr(), WORD)));
3198 break;
3199 }
3200 case RO_AMOAND_W: {
3201 if ((rs1() & 0x3) != 0) {
3202 DieOrDebug();
3203 }
3204 set_rd(sext32(amo<uint32_t>(
3205 rs1(), [&](uint32_t lhs) { return lhs & (uint32_t)rs2(); },
3206 instr_.instr(), WORD)));
3207 break;
3208 }
3209 case RO_AMOOR_W: {
3210 if ((rs1() & 0x3) != 0) {
3211 DieOrDebug();
3212 }
3213 set_rd(sext32(amo<uint32_t>(
3214 rs1(), [&](uint32_t lhs) { return lhs | (uint32_t)rs2(); },
3215 instr_.instr(), WORD)));
3216 break;
3217 }
3218 case RO_AMOMIN_W: {
3219 if ((rs1() & 0x3) != 0) {
3220 DieOrDebug();
3221 }
3222 set_rd(sext32(amo<int32_t>(
3223 rs1(), [&](int32_t lhs) { return std::min(lhs, (int32_t)rs2()); },
3224 instr_.instr(), WORD)));
3225 break;
3226 }
3227 case RO_AMOMAX_W: {
3228 if ((rs1() & 0x3) != 0) {
3229 DieOrDebug();
3230 }
3231 set_rd(sext32(amo<int32_t>(
3232 rs1(), [&](int32_t lhs) { return std::max(lhs, (int32_t)rs2()); },
3233 instr_.instr(), WORD)));
3234 break;
3235 }
3236 case RO_AMOMINU_W: {
3237 if ((rs1() & 0x3) != 0) {
3238 DieOrDebug();
3239 }
3240 set_rd(sext32(amo<uint32_t>(
3241 rs1(), [&](uint32_t lhs) { return std::min(lhs, (uint32_t)rs2()); },
3242 instr_.instr(), WORD)));
3243 break;
3244 }
3245 case RO_AMOMAXU_W: {
3246 if ((rs1() & 0x3) != 0) {
3247 DieOrDebug();
3248 }
3249 set_rd(sext32(amo<uint32_t>(
3250 rs1(), [&](uint32_t lhs) { return std::max(lhs, (uint32_t)rs2()); },
3251 instr_.instr(), WORD)));
3252 break;
3253 }
3254 # ifdef JS_CODEGEN_RISCV64
3255 case RO_LR_D: {
3256 sreg_t addr = rs1();
3257 set_rd(loadLinkedD(addr, &instr_));
3258 TraceLr(addr, getRegister(rd_reg()), getRegister(rd_reg()));
3259 break;
3260 }
3261 case RO_SC_D: {
3262 sreg_t addr = rs1();
3263 auto value = static_cast<int64_t>(rs2());
3264 auto result =
3265 storeConditionalD(addr, static_cast<int64_t>(rs2()), &instr_);
3266 set_rd(result);
3267 if (!result) {
3268 TraceSc(addr, value);
3269 }
3270 break;
3271 }
3272 case RO_AMOSWAP_D: {
3273 set_rd(amo<int64_t>(
3274 rs1(), [&](int64_t lhs) { return rs2(); }, instr_.instr(), DWORD));
3275 break;
3276 }
3277 case RO_AMOADD_D: {
3278 set_rd(amo<int64_t>(
3279 rs1(), [&](int64_t lhs) { return lhs + rs2(); }, instr_.instr(),
3280 DWORD));
3281 break;
3282 }
3283 case RO_AMOXOR_D: {
3284 set_rd(amo<int64_t>(
3285 rs1(), [&](int64_t lhs) { return lhs ^ rs2(); }, instr_.instr(),
3286 DWORD));
3287 break;
3288 }
3289 case RO_AMOAND_D: {
3290 set_rd(amo<int64_t>(
3291 rs1(), [&](int64_t lhs) { return lhs & rs2(); }, instr_.instr(),
3292 DWORD));
3293 break;
3294 }
3295 case RO_AMOOR_D: {
3296 set_rd(amo<int64_t>(
3297 rs1(), [&](int64_t lhs) { return lhs | rs2(); }, instr_.instr(),
3298 DWORD));
3299 break;
3300 }
3301 case RO_AMOMIN_D: {
3302 set_rd(amo<int64_t>(
3303 rs1(), [&](int64_t lhs) { return std::min(lhs, rs2()); },
3304 instr_.instr(), DWORD));
3305 break;
3306 }
3307 case RO_AMOMAX_D: {
3308 set_rd(amo<int64_t>(
3309 rs1(), [&](int64_t lhs) { return std::max(lhs, rs2()); },
3310 instr_.instr(), DWORD));
3311 break;
3312 }
3313 case RO_AMOMINU_D: {
3314 set_rd(amo<uint64_t>(
3315 rs1(), [&](uint64_t lhs) { return std::min(lhs, (uint64_t)rs2()); },
3316 instr_.instr(), DWORD));
3317 break;
3318 }
3319 case RO_AMOMAXU_D: {
3320 set_rd(amo<uint64_t>(
3321 rs1(), [&](uint64_t lhs) { return std::max(lhs, (uint64_t)rs2()); },
3322 instr_.instr(), DWORD));
3323 break;
3324 }
3325 # endif /*JS_CODEGEN_RISCV64*/
3326 // TODO(riscv): End Add macro for RISCV A extension
3327 default: {
3328 UNSUPPORTED();
3329 }
3330 }
3331 }
3332
3333 void Simulator::DecodeRVRFPType() {
3334 // OP_FP instructions (F/D) uses func7 first. Some further uses func3 and
3335 // rs2()
3336
3337 // kRATypeMask is only for func7
3338 switch (instr_.InstructionBits() & kRFPTypeMask) {
3339 // TODO(riscv): Add macro for RISCV F extension
3340 case RO_FADD_S: {
3341 // TODO(riscv): use rm value (round mode)
3342 auto fn = [this](float frs1, float frs2) {
3343 if (is_invalid_fadd(frs1, frs2)) {
3344 this->set_fflags(kInvalidOperation);
3345 return std::numeric_limits<float>::quiet_NaN();
3346 } else {
3347 return frs1 + frs2;
3348 }
3349 };
3350 set_frd(CanonicalizeFPUOp2<float>(fn));
3351 break;
3352 }
3353 case RO_FSUB_S: {
3354 // TODO(riscv): use rm value (round mode)
3355 auto fn = [this](float frs1, float frs2) {
3356 if (is_invalid_fsub(frs1, frs2)) {
3357 this->set_fflags(kInvalidOperation);
3358 return std::numeric_limits<float>::quiet_NaN();
3359 } else {
3360 return frs1 - frs2;
3361 }
3362 };
3363 set_frd(CanonicalizeFPUOp2<float>(fn));
3364 break;
3365 }
3366 case RO_FMUL_S: {
3367 // TODO(riscv): use rm value (round mode)
3368 auto fn = [this](float frs1, float frs2) {
3369 if (is_invalid_fmul(frs1, frs2)) {
3370 this->set_fflags(kInvalidOperation);
3371 return std::numeric_limits<float>::quiet_NaN();
3372 } else {
3373 return frs1 * frs2;
3374 }
3375 };
3376 set_frd(CanonicalizeFPUOp2<float>(fn));
3377 break;
3378 }
3379 case RO_FDIV_S: {
3380 // TODO(riscv): use rm value (round mode)
3381 auto fn = [this](float frs1, float frs2) {
3382 if (is_invalid_fdiv(frs1, frs2)) {
3383 this->set_fflags(kInvalidOperation);
3384 return std::numeric_limits<float>::quiet_NaN();
3385 } else if (frs2 == 0.0f) {
3386 this->set_fflags(kDivideByZero);
3387 return (std::signbit(frs1) == std::signbit(frs2)
3388 ? std::numeric_limits<float>::infinity()
3389 : -std::numeric_limits<float>::infinity());
3390 } else {
3391 return frs1 / frs2;
3392 }
3393 };
3394 set_frd(CanonicalizeFPUOp2<float>(fn));
3395 break;
3396 }
3397 case RO_FSQRT_S: {
3398 if (instr_.Rs2Value() == 0b00000) {
3399 // TODO(riscv): use rm value (round mode)
3400 auto fn = [this](float frs) {
3401 if (is_invalid_fsqrt(frs)) {
3402 this->set_fflags(kInvalidOperation);
3403 return std::numeric_limits<float>::quiet_NaN();
3404 } else {
3405 return std::sqrt(frs);
3406 }
3407 };
3408 set_frd(CanonicalizeFPUOp1<float>(fn));
3409 } else {
3410 UNSUPPORTED();
3411 }
3412 break;
3413 }
3414 case RO_FSGNJ_S: { // RO_FSGNJN_S RO_FSQNJX_S
3415 switch (instr_.Funct3Value()) {
3416 case 0b000: { // RO_FSGNJ_S
3417 set_frd(fsgnj32(frs1_boxed(), frs2_boxed(), false, false));
3418 break;
3419 }
3420 case 0b001: { // RO_FSGNJN_S
3421 set_frd(fsgnj32(frs1_boxed(), frs2_boxed(), true, false));
3422 break;
3423 }
3424 case 0b010: { // RO_FSQNJX_S
3425 set_frd(fsgnj32(frs1_boxed(), frs2_boxed(), false, true));
3426 break;
3427 }
3428 default: {
3429 UNSUPPORTED();
3430 }
3431 }
3432 break;
3433 }
3434 case RO_FMIN_S: { // RO_FMAX_S
3435 switch (instr_.Funct3Value()) {
3436 case 0b000: { // RO_FMIN_S
3437 set_frd(FMaxMinHelper(frs1(), frs2(), MaxMinKind::kMin));
3438 break;
3439 }
3440 case 0b001: { // RO_FMAX_S
3441 set_frd(FMaxMinHelper(frs1(), frs2(), MaxMinKind::kMax));
3442 break;
3443 }
3444 default: {
3445 UNSUPPORTED();
3446 }
3447 }
3448 break;
3449 }
3450 case RO_FCVT_W_S: { // RO_FCVT_WU_S , 64F RO_FCVT_L_S RO_FCVT_LU_S
3451 float original_val = frs1();
3452 switch (instr_.Rs2Value()) {
3453 case 0b00000: { // RO_FCVT_W_S
3454 set_rd(RoundF2IHelper<int32_t>(original_val, instr_.RoundMode()));
3455 break;
3456 }
3457 case 0b00001: { // RO_FCVT_WU_S
3458 set_rd(sext32(
3459 RoundF2IHelper<uint32_t>(original_val, instr_.RoundMode())));
3460 break;
3461 }
3462 # ifdef JS_CODEGEN_RISCV64
3463 case 0b00010: { // RO_FCVT_L_S
3464 set_rd(RoundF2IHelper<int64_t>(original_val, instr_.RoundMode()));
3465 break;
3466 }
3467 case 0b00011: { // RO_FCVT_LU_S
3468 set_rd(RoundF2IHelper<uint64_t>(original_val, instr_.RoundMode()));
3469 break;
3470 }
3471 # endif /* JS_CODEGEN_RISCV64 */
3472 default: {
3473 UNSUPPORTED();
3474 }
3475 }
3476 break;
3477 }
3478 case RO_FMV: { // RO_FCLASS_S
3479 switch (instr_.Funct3Value()) {
3480 case 0b000: {
3481 if (instr_.Rs2Value() == 0b00000) {
3482 // RO_FMV_X_W
3483 set_rd(sext32(getFpuRegister(rs1_reg())));
3484 } else {
3485 UNSUPPORTED();
3486 }
3487 break;
3488 }
3489 case 0b001: { // RO_FCLASS_S
3490 set_rd(FclassHelper(frs1()));
3491 break;
3492 }
3493 default: {
3494 UNSUPPORTED();
3495 }
3496 }
3497 break;
3498 }
3499 case RO_FLE_S: { // RO_FEQ_S RO_FLT_S RO_FLE_S
3500 switch (instr_.Funct3Value()) {
3501 case 0b010: { // RO_FEQ_S
3502 set_rd(CompareFHelper(frs1(), frs2(), EQ));
3503 break;
3504 }
3505 case 0b001: { // RO_FLT_S
3506 set_rd(CompareFHelper(frs1(), frs2(), LT));
3507 break;
3508 }
3509 case 0b000: { // RO_FLE_S
3510 set_rd(CompareFHelper(frs1(), frs2(), LE));
3511 break;
3512 }
3513 default: {
3514 UNSUPPORTED();
3515 }
3516 }
3517 break;
3518 }
3519 case RO_FCVT_S_W: { // RO_FCVT_S_WU , 64F RO_FCVT_S_L RO_FCVT_S_LU
3520 switch (instr_.Rs2Value()) {
3521 case 0b00000: { // RO_FCVT_S_W
3522 set_frd(static_cast<float>((int32_t)rs1()));
3523 break;
3524 }
3525 case 0b00001: { // RO_FCVT_S_WU
3526 set_frd(static_cast<float>((uint32_t)rs1()));
3527 break;
3528 }
3529 # ifdef JS_CODEGEN_RISCV64
3530 case 0b00010: { // RO_FCVT_S_L
3531 set_frd(static_cast<float>((int64_t)rs1()));
3532 break;
3533 }
3534 case 0b00011: { // RO_FCVT_S_LU
3535 set_frd(static_cast<float>((uint64_t)rs1()));
3536 break;
3537 }
3538 # endif /* JS_CODEGEN_RISCV64 */
3539 default: {
3540 UNSUPPORTED();
3541 }
3542 }
3543 break;
3544 }
3545 case RO_FMV_W_X: {
3546 if (instr_.Funct3Value() == 0b000) {
3547 // since FMV preserves source bit-pattern, no need to canonize
3548 Float32 result = Float32::FromBits((uint32_t)rs1());
3549 set_frd(result);
3550 } else {
3551 UNSUPPORTED();
3552 }
3553 break;
3554 }
3555 // TODO(riscv): Add macro for RISCV D extension
3556 case RO_FADD_D: {
3557 // TODO(riscv): use rm value (round mode)
3558 auto fn = [this](double drs1, double drs2) {
3559 if (is_invalid_fadd(drs1, drs2)) {
3560 this->set_fflags(kInvalidOperation);
3561 return std::numeric_limits<double>::quiet_NaN();
3562 } else {
3563 return drs1 + drs2;
3564 }
3565 };
3566 set_drd(CanonicalizeFPUOp2<double>(fn));
3567 break;
3568 }
3569 case RO_FSUB_D: {
3570 // TODO(riscv): use rm value (round mode)
3571 auto fn = [this](double drs1, double drs2) {
3572 if (is_invalid_fsub(drs1, drs2)) {
3573 this->set_fflags(kInvalidOperation);
3574 return std::numeric_limits<double>::quiet_NaN();
3575 } else {
3576 return drs1 - drs2;
3577 }
3578 };
3579 set_drd(CanonicalizeFPUOp2<double>(fn));
3580 break;
3581 }
3582 case RO_FMUL_D: {
3583 // TODO(riscv): use rm value (round mode)
3584 auto fn = [this](double drs1, double drs2) {
3585 if (is_invalid_fmul(drs1, drs2)) {
3586 this->set_fflags(kInvalidOperation);
3587 return std::numeric_limits<double>::quiet_NaN();
3588 } else {
3589 return drs1 * drs2;
3590 }
3591 };
3592 set_drd(CanonicalizeFPUOp2<double>(fn));
3593 break;
3594 }
3595 case RO_FDIV_D: {
3596 // TODO(riscv): use rm value (round mode)
3597 auto fn = [this](double drs1, double drs2) {
3598 if (is_invalid_fdiv(drs1, drs2)) {
3599 this->set_fflags(kInvalidOperation);
3600 return std::numeric_limits<double>::quiet_NaN();
3601 } else if (drs2 == 0.0) {
3602 this->set_fflags(kDivideByZero);
3603 return (std::signbit(drs1) == std::signbit(drs2)
3604 ? std::numeric_limits<double>::infinity()
3605 : -std::numeric_limits<double>::infinity());
3606 } else {
3607 return drs1 / drs2;
3608 }
3609 };
3610 set_drd(CanonicalizeFPUOp2<double>(fn));
3611 break;
3612 }
3613 case RO_FSQRT_D: {
3614 if (instr_.Rs2Value() == 0b00000) {
3615 // TODO(riscv): use rm value (round mode)
3616 auto fn = [this](double drs) {
3617 if (is_invalid_fsqrt(drs)) {
3618 this->set_fflags(kInvalidOperation);
3619 return std::numeric_limits<double>::quiet_NaN();
3620 } else {
3621 return std::sqrt(drs);
3622 }
3623 };
3624 set_drd(CanonicalizeFPUOp1<double>(fn));
3625 } else {
3626 UNSUPPORTED();
3627 }
3628 break;
3629 }
3630 case RO_FSGNJ_D: { // RO_FSGNJN_D RO_FSQNJX_D
3631 switch (instr_.Funct3Value()) {
3632 case 0b000: { // RO_FSGNJ_D
3633 set_drd(fsgnj64(drs1_boxed(), drs2_boxed(), false, false));
3634 break;
3635 }
3636 case 0b001: { // RO_FSGNJN_D
3637 set_drd(fsgnj64(drs1_boxed(), drs2_boxed(), true, false));
3638 break;
3639 }
3640 case 0b010: { // RO_FSQNJX_D
3641 set_drd(fsgnj64(drs1_boxed(), drs2_boxed(), false, true));
3642 break;
3643 }
3644 default: {
3645 UNSUPPORTED();
3646 }
3647 }
3648 break;
3649 }
3650 case RO_FMIN_D: { // RO_FMAX_D
3651 switch (instr_.Funct3Value()) {
3652 case 0b000: { // RO_FMIN_D
3653 set_drd(FMaxMinHelper(drs1(), drs2(), MaxMinKind::kMin));
3654 break;
3655 }
3656 case 0b001: { // RO_FMAX_D
3657 set_drd(FMaxMinHelper(drs1(), drs2(), MaxMinKind::kMax));
3658 break;
3659 }
3660 default: {
3661 UNSUPPORTED();
3662 }
3663 }
3664 break;
3665 }
3666 case (RO_FCVT_S_D & kRFPTypeMask): {
3667 if (instr_.Rs2Value() == 0b00001) {
3668 auto fn = [](double drs) { return static_cast<float>(drs); };
3669 set_frd(CanonicalizeDoubleToFloatOperation(fn));
3670 } else {
3671 UNSUPPORTED();
3672 }
3673 break;
3674 }
3675 case RO_FCVT_D_S: {
3676 if (instr_.Rs2Value() == 0b00000) {
3677 auto fn = [](float frs) { return static_cast<double>(frs); };
3678 set_drd(CanonicalizeFloatToDoubleOperation(fn));
3679 } else {
3680 UNSUPPORTED();
3681 }
3682 break;
3683 }
3684 case RO_FLE_D: { // RO_FEQ_D RO_FLT_D RO_FLE_D
3685 switch (instr_.Funct3Value()) {
3686 case 0b010: { // RO_FEQ_S
3687 set_rd(CompareFHelper(drs1(), drs2(), EQ));
3688 break;
3689 }
3690 case 0b001: { // RO_FLT_D
3691 set_rd(CompareFHelper(drs1(), drs2(), LT));
3692 break;
3693 }
3694 case 0b000: { // RO_FLE_D
3695 set_rd(CompareFHelper(drs1(), drs2(), LE));
3696 break;
3697 }
3698 default: {
3699 UNSUPPORTED();
3700 }
3701 }
3702 break;
3703 }
3704 case (RO_FCLASS_D & kRFPTypeMask): { // RO_FCLASS_D , 64D RO_FMV_X_D
3705 if (instr_.Rs2Value() != 0b00000) {
3706 UNSUPPORTED();
3707 }
3708 switch (instr_.Funct3Value()) {
3709 case 0b001: { // RO_FCLASS_D
3710 set_rd(FclassHelper(drs1()));
3711 break;
3712 }
3713 # ifdef JS_CODEGEN_RISCV64
3714 case 0b000: { // RO_FMV_X_D
3715 set_rd(bit_cast<int64_t>(drs1()));
3716 break;
3717 }
3718 # endif /* JS_CODEGEN_RISCV64 */
3719 default: {
3720 UNSUPPORTED();
3721 }
3722 }
3723 break;
3724 }
3725 case RO_FCVT_W_D: { // RO_FCVT_WU_D , 64F RO_FCVT_L_D RO_FCVT_LU_D
3726 double original_val = drs1();
3727 switch (instr_.Rs2Value()) {
3728 case 0b00000: { // RO_FCVT_W_D
3729 set_rd(RoundF2IHelper<int32_t>(original_val, instr_.RoundMode()));
3730 break;
3731 }
3732 case 0b00001: { // RO_FCVT_WU_D
3733 set_rd(sext32(
3734 RoundF2IHelper<uint32_t>(original_val, instr_.RoundMode())));
3735 break;
3736 }
3737 # ifdef JS_CODEGEN_RISCV64
3738 case 0b00010: { // RO_FCVT_L_D
3739 set_rd(RoundF2IHelper<int64_t>(original_val, instr_.RoundMode()));
3740 break;
3741 }
3742 case 0b00011: { // RO_FCVT_LU_D
3743 set_rd(RoundF2IHelper<uint64_t>(original_val, instr_.RoundMode()));
3744 break;
3745 }
3746 # endif /* JS_CODEGEN_RISCV64 */
3747 default: {
3748 UNSUPPORTED();
3749 }
3750 }
3751 break;
3752 }
3753 case RO_FCVT_D_W: { // RO_FCVT_D_WU , 64F RO_FCVT_D_L RO_FCVT_D_LU
3754 switch (instr_.Rs2Value()) {
3755 case 0b00000: { // RO_FCVT_D_W
3756 set_drd((int32_t)rs1());
3757 break;
3758 }
3759 case 0b00001: { // RO_FCVT_D_WU
3760 set_drd((uint32_t)rs1());
3761 break;
3762 }
3763 # ifdef JS_CODEGEN_RISCV64
3764 case 0b00010: { // RO_FCVT_D_L
3765 set_drd((int64_t)rs1());
3766 break;
3767 }
3768 case 0b00011: { // RO_FCVT_D_LU
3769 set_drd((uint64_t)rs1());
3770 break;
3771 }
3772 # endif /* JS_CODEGEN_RISCV64 */
3773 default: {
3774 UNSUPPORTED();
3775 }
3776 }
3777 break;
3778 }
3779 # ifdef JS_CODEGEN_RISCV64
3780 case RO_FMV_D_X: {
3781 if (instr_.Funct3Value() == 0b000 && instr_.Rs2Value() == 0b00000) {
3782 // Since FMV preserves source bit-pattern, no need to canonize
3783 set_drd(bit_cast<double>(rs1()));
3784 } else {
3785 UNSUPPORTED();
3786 }
3787 break;
3788 }
3789 # endif /* JS_CODEGEN_RISCV64 */
3790 default: {
3791 UNSUPPORTED();
3792 }
3793 }
3794 }
3795
3796 void Simulator::DecodeRVR4Type() {
3797 switch (instr_.InstructionBits() & kR4TypeMask) {
3798 // TODO(riscv): use F Extension macro block
3799 case RO_FMADD_S: {
3800 // TODO(riscv): use rm value (round mode)
3801 auto fn = [this](float frs1, float frs2, float frs3) {
3802 if (is_invalid_fmul(frs1, frs2) || is_invalid_fadd(frs1 * frs2, frs3)) {
3803 this->set_fflags(kInvalidOperation);
3804 return std::numeric_limits<float>::quiet_NaN();
3805 } else {
3806 return std::fma(frs1, frs2, frs3);
3807 }
3808 };
3809 set_frd(CanonicalizeFPUOp3<float>(fn));
3810 break;
3811 }
3812 case RO_FMSUB_S: {
3813 // TODO(riscv): use rm value (round mode)
3814 auto fn = [this](float frs1, float frs2, float frs3) {
3815 if (is_invalid_fmul(frs1, frs2) || is_invalid_fsub(frs1 * frs2, frs3)) {
3816 this->set_fflags(kInvalidOperation);
3817 return std::numeric_limits<float>::quiet_NaN();
3818 } else {
3819 return std::fma(frs1, frs2, -frs3);
3820 }
3821 };
3822 set_frd(CanonicalizeFPUOp3<float>(fn));
3823 break;
3824 }
3825 case RO_FNMSUB_S: {
3826 // TODO(riscv): use rm value (round mode)
3827 auto fn = [this](float frs1, float frs2, float frs3) {
3828 if (is_invalid_fmul(frs1, frs2) || is_invalid_fsub(frs3, frs1 * frs2)) {
3829 this->set_fflags(kInvalidOperation);
3830 return std::numeric_limits<float>::quiet_NaN();
3831 } else {
3832 return -std::fma(frs1, frs2, -frs3);
3833 }
3834 };
3835 set_frd(CanonicalizeFPUOp3<float>(fn));
3836 break;
3837 }
3838 case RO_FNMADD_S: {
3839 // TODO(riscv): use rm value (round mode)
3840 auto fn = [this](float frs1, float frs2, float frs3) {
3841 if (is_invalid_fmul(frs1, frs2) || is_invalid_fadd(frs1 * frs2, frs3)) {
3842 this->set_fflags(kInvalidOperation);
3843 return std::numeric_limits<float>::quiet_NaN();
3844 } else {
3845 return -std::fma(frs1, frs2, frs3);
3846 }
3847 };
3848 set_frd(CanonicalizeFPUOp3<float>(fn));
3849 break;
3850 }
3851 // TODO(riscv): use F Extension macro block
3852 case RO_FMADD_D: {
3853 // TODO(riscv): use rm value (round mode)
3854 auto fn = [this](double drs1, double drs2, double drs3) {
3855 if (is_invalid_fmul(drs1, drs2) || is_invalid_fadd(drs1 * drs2, drs3)) {
3856 this->set_fflags(kInvalidOperation);
3857 return std::numeric_limits<double>::quiet_NaN();
3858 } else {
3859 return std::fma(drs1, drs2, drs3);
3860 }
3861 };
3862 set_drd(CanonicalizeFPUOp3<double>(fn));
3863 break;
3864 }
3865 case RO_FMSUB_D: {
3866 // TODO(riscv): use rm value (round mode)
3867 auto fn = [this](double drs1, double drs2, double drs3) {
3868 if (is_invalid_fmul(drs1, drs2) || is_invalid_fsub(drs1 * drs2, drs3)) {
3869 this->set_fflags(kInvalidOperation);
3870 return std::numeric_limits<double>::quiet_NaN();
3871 } else {
3872 return std::fma(drs1, drs2, -drs3);
3873 }
3874 };
3875 set_drd(CanonicalizeFPUOp3<double>(fn));
3876 break;
3877 }
3878 case RO_FNMSUB_D: {
3879 // TODO(riscv): use rm value (round mode)
3880 auto fn = [this](double drs1, double drs2, double drs3) {
3881 if (is_invalid_fmul(drs1, drs2) || is_invalid_fsub(drs3, drs1 * drs2)) {
3882 this->set_fflags(kInvalidOperation);
3883 return std::numeric_limits<double>::quiet_NaN();
3884 } else {
3885 return -std::fma(drs1, drs2, -drs3);
3886 }
3887 };
3888 set_drd(CanonicalizeFPUOp3<double>(fn));
3889 break;
3890 }
3891 case RO_FNMADD_D: {
3892 // TODO(riscv): use rm value (round mode)
3893 auto fn = [this](double drs1, double drs2, double drs3) {
3894 if (is_invalid_fmul(drs1, drs2) || is_invalid_fadd(drs1 * drs2, drs3)) {
3895 this->set_fflags(kInvalidOperation);
3896 return std::numeric_limits<double>::quiet_NaN();
3897 } else {
3898 return -std::fma(drs1, drs2, drs3);
3899 }
3900 };
3901 set_drd(CanonicalizeFPUOp3<double>(fn));
3902 break;
3903 }
3904 default:
3905 UNSUPPORTED();
3906 }
3907 }
3908
3909 # ifdef CAN_USE_RVV_INSTRUCTIONS
3910 bool Simulator::DecodeRvvVL() {
3911 uint32_t instr_temp =
3912 instr_.InstructionBits() & (kRvvMopMask | kRvvNfMask | kBaseOpcodeMask);
3913 if (RO_V_VL == instr_temp) {
3914 if (!(instr_.InstructionBits() & (kRvvRs2Mask))) {
3915 switch (instr_.vl_vs_width()) {
3916 case 8: {
3917 RVV_VI_LD(0, (i * nf + fn), int8, false);
3918 break;
3919 }
3920 case 16: {
3921 RVV_VI_LD(0, (i * nf + fn), int16, false);
3922 break;
3923 }
3924 case 32: {
3925 RVV_VI_LD(0, (i * nf + fn), int32, false);
3926 break;
3927 }
3928 case 64: {
3929 RVV_VI_LD(0, (i * nf + fn), int64, false);
3930 break;
3931 }
3932 default:
3933 UNIMPLEMENTED_RISCV();
3934 break;
3935 }
3936 return true;
3937 } else {
3938 UNIMPLEMENTED_RISCV();
3939 return true;
3940 }
3941 } else if (RO_V_VLS == instr_temp) {
3942 UNIMPLEMENTED_RISCV();
3943 return true;
3944 } else if (RO_V_VLX == instr_temp) {
3945 UNIMPLEMENTED_RISCV();
3946 return true;
3947 } else if (RO_V_VLSEG2 == instr_temp || RO_V_VLSEG3 == instr_temp ||
3948 RO_V_VLSEG4 == instr_temp || RO_V_VLSEG5 == instr_temp ||
3949 RO_V_VLSEG6 == instr_temp || RO_V_VLSEG7 == instr_temp ||
3950 RO_V_VLSEG8 == instr_temp) {
3951 if (!(instr_.InstructionBits() & (kRvvRs2Mask))) {
3952 UNIMPLEMENTED_RISCV();
3953 return true;
3954 } else {
3955 UNIMPLEMENTED_RISCV();
3956 return true;
3957 }
3958 } else if (RO_V_VLSSEG2 == instr_temp || RO_V_VLSSEG3 == instr_temp ||
3959 RO_V_VLSSEG4 == instr_temp || RO_V_VLSSEG5 == instr_temp ||
3960 RO_V_VLSSEG6 == instr_temp || RO_V_VLSSEG7 == instr_temp ||
3961 RO_V_VLSSEG8 == instr_temp) {
3962 UNIMPLEMENTED_RISCV();
3963 return true;
3964 } else if (RO_V_VLXSEG2 == instr_temp || RO_V_VLXSEG3 == instr_temp ||
3965 RO_V_VLXSEG4 == instr_temp || RO_V_VLXSEG5 == instr_temp ||
3966 RO_V_VLXSEG6 == instr_temp || RO_V_VLXSEG7 == instr_temp ||
3967 RO_V_VLXSEG8 == instr_temp) {
3968 UNIMPLEMENTED_RISCV();
3969 return true;
3970 } else {
3971 return false;
3972 }
3973 }
3974
3975 bool Simulator::DecodeRvvVS() {
3976 uint32_t instr_temp =
3977 instr_.InstructionBits() & (kRvvMopMask | kRvvNfMask | kBaseOpcodeMask);
3978 if (RO_V_VS == instr_temp) {
3979 if (!(instr_.InstructionBits() & (kRvvRs2Mask))) {
3980 switch (instr_.vl_vs_width()) {
3981 case 8: {
3982 RVV_VI_ST(0, (i * nf + fn), uint8, false);
3983 break;
3984 }
3985 case 16: {
3986 RVV_VI_ST(0, (i * nf + fn), uint16, false);
3987 break;
3988 }
3989 case 32: {
3990 RVV_VI_ST(0, (i * nf + fn), uint32, false);
3991 break;
3992 }
3993 case 64: {
3994 RVV_VI_ST(0, (i * nf + fn), uint64, false);
3995 break;
3996 }
3997 default:
3998 UNIMPLEMENTED_RISCV();
3999 break;
4000 }
4001 } else {
4002 UNIMPLEMENTED_RISCV();
4003 }
4004 return true;
4005 } else if (RO_V_VSS == instr_temp) {
4006 UNIMPLEMENTED_RISCV();
4007 return true;
4008 } else if (RO_V_VSX == instr_temp) {
4009 UNIMPLEMENTED_RISCV();
4010 return true;
4011 } else if (RO_V_VSU == instr_temp) {
4012 UNIMPLEMENTED_RISCV();
4013 return true;
4014 } else if (RO_V_VSSEG2 == instr_temp || RO_V_VSSEG3 == instr_temp ||
4015 RO_V_VSSEG4 == instr_temp || RO_V_VSSEG5 == instr_temp ||
4016 RO_V_VSSEG6 == instr_temp || RO_V_VSSEG7 == instr_temp ||
4017 RO_V_VSSEG8 == instr_temp) {
4018 UNIMPLEMENTED_RISCV();
4019 return true;
4020 } else if (RO_V_VSSSEG2 == instr_temp || RO_V_VSSSEG3 == instr_temp ||
4021 RO_V_VSSSEG4 == instr_temp || RO_V_VSSSEG5 == instr_temp ||
4022 RO_V_VSSSEG6 == instr_temp || RO_V_VSSSEG7 == instr_temp ||
4023 RO_V_VSSSEG8 == instr_temp) {
4024 UNIMPLEMENTED_RISCV();
4025 return true;
4026 } else if (RO_V_VSXSEG2 == instr_temp || RO_V_VSXSEG3 == instr_temp ||
4027 RO_V_VSXSEG4 == instr_temp || RO_V_VSXSEG5 == instr_temp ||
4028 RO_V_VSXSEG6 == instr_temp || RO_V_VSXSEG7 == instr_temp ||
4029 RO_V_VSXSEG8 == instr_temp) {
4030 UNIMPLEMENTED_RISCV();
4031 return true;
4032 } else {
4033 return false;
4034 }
4035 }
4036 # endif
4037
4038 void Simulator::DecodeRVIType() {
4039 switch (instr_.InstructionBits() & kITypeMask) {
4040 case RO_JALR: {
4041 set_rd(get_pc() + kInstrSize);
4042 // Note: No need to shift 2 for JALR's imm12, but set lowest bit to 0.
4043 sreg_t next_pc = (rs1() + imm12()) & ~sreg_t(1);
4044 set_pc(next_pc);
4045 break;
4046 }
4047 case RO_LB: {
4048 sreg_t addr = rs1() + imm12();
4049 int8_t val = ReadMem<int8_t>(addr, instr_.instr());
4050 set_rd(sext_xlen(val), false);
4051 TraceMemRd(addr, val, getRegister(rd_reg()));
4052 break;
4053 }
4054 case RO_LH: {
4055 sreg_t addr = rs1() + imm12();
4056 int16_t val = ReadMem<int16_t>(addr, instr_.instr());
4057 set_rd(sext_xlen(val), false);
4058 TraceMemRd(addr, val, getRegister(rd_reg()));
4059 break;
4060 }
4061 case RO_LW: {
4062 sreg_t addr = rs1() + imm12();
4063 int32_t val = ReadMem<int32_t>(addr, instr_.instr());
4064 set_rd(sext_xlen(val), false);
4065 TraceMemRd(addr, val, getRegister(rd_reg()));
4066 break;
4067 }
4068 case RO_LBU: {
4069 sreg_t addr = rs1() + imm12();
4070 uint8_t val = ReadMem<uint8_t>(addr, instr_.instr());
4071 set_rd(zext_xlen(val), false);
4072 TraceMemRd(addr, val, getRegister(rd_reg()));
4073 break;
4074 }
4075 case RO_LHU: {
4076 sreg_t addr = rs1() + imm12();
4077 uint16_t val = ReadMem<uint16_t>(addr, instr_.instr());
4078 set_rd(zext_xlen(val), false);
4079 TraceMemRd(addr, val, getRegister(rd_reg()));
4080 break;
4081 }
4082 # ifdef JS_CODEGEN_RISCV64
4083 case RO_LWU: {
4084 int64_t addr = rs1() + imm12();
4085 uint32_t val = ReadMem<uint32_t>(addr, instr_.instr());
4086 set_rd(zext_xlen(val), false);
4087 TraceMemRd(addr, val, getRegister(rd_reg()));
4088 break;
4089 }
4090 case RO_LD: {
4091 int64_t addr = rs1() + imm12();
4092 int64_t val = ReadMem<int64_t>(addr, instr_.instr());
4093 set_rd(sext_xlen(val), false);
4094 TraceMemRd(addr, val, getRegister(rd_reg()));
4095 break;
4096 }
4097 # endif /*JS_CODEGEN_RISCV64*/
4098 case RO_ADDI: {
4099 set_rd(sext_xlen(rs1() + imm12()));
4100 break;
4101 }
4102 case RO_SLTI: {
4103 set_rd(sreg_t(rs1()) < sreg_t(imm12()));
4104 break;
4105 }
4106 case RO_SLTIU: {
4107 set_rd(reg_t(rs1()) < reg_t(imm12()));
4108 break;
4109 }
4110 case RO_XORI: {
4111 set_rd(imm12() ^ rs1());
4112 break;
4113 }
4114 case RO_ORI: {
4115 set_rd(imm12() | rs1());
4116 break;
4117 }
4118 case RO_ANDI: {
4119 set_rd(imm12() & rs1());
4120 break;
4121 }
4122 case RO_SLLI: {
4123 require(shamt6() < xlen);
4124 set_rd(sext_xlen(rs1() << shamt6()));
4125 break;
4126 }
4127 case RO_SRLI: { // RO_SRAI
4128 if (!instr_.IsArithShift()) {
4129 require(shamt6() < xlen);
4130 set_rd(sext_xlen(zext_xlen(rs1()) >> shamt6()));
4131 } else {
4132 require(shamt6() < xlen);
4133 set_rd(sext_xlen(sext_xlen(rs1()) >> shamt6()));
4134 }
4135 break;
4136 }
4137 # ifdef JS_CODEGEN_RISCV64
4138 case RO_ADDIW: {
4139 set_rd(sext32(rs1() + imm12()));
4140 break;
4141 }
4142 case RO_SLLIW: {
4143 set_rd(sext32(rs1() << shamt5()));
4144 break;
4145 }
4146 case RO_SRLIW: { // RO_SRAIW
4147 if (!instr_.IsArithShift()) {
4148 set_rd(sext32(uint32_t(rs1()) >> shamt5()));
4149 } else {
4150 set_rd(sext32(int32_t(rs1()) >> shamt5()));
4151 }
4152 break;
4153 }
4154 # endif /*JS_CODEGEN_RISCV64*/
4155 case RO_FENCE: {
4156 // DO nothing in sumulator
4157 break;
4158 }
4159 case RO_ECALL: { // RO_EBREAK
4160 if (instr_.Imm12Value() == 0) { // ECALL
4161 SoftwareInterrupt();
4162 } else if (instr_.Imm12Value() == 1) { // EBREAK
4163 uint8_t code = get_ebreak_code(instr_.instr());
4164 if (code == kWasmTrapCode) {
4165 HandleWasmTrap();
4166 }
4167 SoftwareInterrupt();
4168 } else {
4169 UNSUPPORTED();
4170 }
4171 break;
4172 }
4173 // TODO(riscv): use Zifencei Standard Extension macro block
4174 case RO_FENCE_I: {
4175 // spike: flush icache.
4176 break;
4177 }
4178 // TODO(riscv): use Zicsr Standard Extension macro block
4179 case RO_CSRRW: {
4180 if (rd_reg() != zero_reg) {
4181 set_rd(zext_xlen(read_csr_value(csr_reg())));
4182 }
4183 write_csr_value(csr_reg(), rs1());
4184 break;
4185 }
4186 case RO_CSRRS: {
4187 set_rd(zext_xlen(read_csr_value(csr_reg())));
4188 if (rs1_reg() != zero_reg) {
4189 set_csr_bits(csr_reg(), rs1());
4190 }
4191 break;
4192 }
4193 case RO_CSRRC: {
4194 set_rd(zext_xlen(read_csr_value(csr_reg())));
4195 if (rs1_reg() != zero_reg) {
4196 clear_csr_bits(csr_reg(), rs1());
4197 }
4198 break;
4199 }
4200 case RO_CSRRWI: {
4201 if (rd_reg() != zero_reg) {
4202 set_rd(zext_xlen(read_csr_value(csr_reg())));
4203 }
4204 if (csr_reg() == csr_cycle) {
4205 if (imm5CSR() == kWasmTrapCode) {
4206 HandleWasmTrap();
4207 return;
4208 }
4209 }
4210 write_csr_value(csr_reg(), imm5CSR());
4211 break;
4212 }
4213 case RO_CSRRSI: {
4214 set_rd(zext_xlen(read_csr_value(csr_reg())));
4215 if (imm5CSR() != 0) {
4216 set_csr_bits(csr_reg(), imm5CSR());
4217 }
4218 break;
4219 }
4220 case RO_CSRRCI: {
4221 set_rd(zext_xlen(read_csr_value(csr_reg())));
4222 if (imm5CSR() != 0) {
4223 clear_csr_bits(csr_reg(), imm5CSR());
4224 }
4225 break;
4226 }
4227 // TODO(riscv): use F Extension macro block
4228 case RO_FLW: {
4229 sreg_t addr = rs1() + imm12();
4230 uint32_t val = ReadMem<uint32_t>(addr, instr_.instr());
4231 set_frd(Float32::FromBits(val), false);
4232 TraceMemRdFloat(addr, Float32::FromBits(val), getFpuRegister(frd_reg()));
4233 break;
4234 }
4235 // TODO(riscv): use D Extension macro block
4236 case RO_FLD: {
4237 sreg_t addr = rs1() + imm12();
4238 uint64_t val = ReadMem<uint64_t>(addr, instr_.instr());
4239 set_drd(Float64::FromBits(val), false);
4240 TraceMemRdDouble(addr, Float64::FromBits(val), getFpuRegister(frd_reg()));
4241 break;
4242 }
4243 default: {
4244 # ifdef CAN_USE_RVV_INSTRUCTIONS
4245 if (!DecodeRvvVL()) {
4246 UNSUPPORTED();
4247 }
4248 break;
4249 # else
4250 UNSUPPORTED();
4251 # endif
4252 }
4253 }
4254 }
4255
4256 void Simulator::DecodeRVSType() {
4257 switch (instr_.InstructionBits() & kSTypeMask) {
4258 case RO_SB:
4259 WriteMem<uint8_t>(rs1() + s_imm12(), (uint8_t)rs2(), instr_.instr());
4260 break;
4261 case RO_SH:
4262 WriteMem<uint16_t>(rs1() + s_imm12(), (uint16_t)rs2(), instr_.instr());
4263 break;
4264 case RO_SW:
4265 WriteMem<uint32_t>(rs1() + s_imm12(), (uint32_t)rs2(), instr_.instr());
4266 break;
4267 # ifdef JS_CODEGEN_RISCV64
4268 case RO_SD:
4269 WriteMem<uint64_t>(rs1() + s_imm12(), (uint64_t)rs2(), instr_.instr());
4270 break;
4271 # endif /*JS_CODEGEN_RISCV64*/
4272 // TODO(riscv): use F Extension macro block
4273 case RO_FSW: {
4274 WriteMem<Float32>(rs1() + s_imm12(), getFpuRegisterFloat32(rs2_reg()),
4275 instr_.instr());
4276 break;
4277 }
4278 // TODO(riscv): use D Extension macro block
4279 case RO_FSD: {
4280 WriteMem<Float64>(rs1() + s_imm12(), getFpuRegisterFloat64(rs2_reg()),
4281 instr_.instr());
4282 break;
4283 }
4284 default:
4285 # ifdef CAN_USE_RVV_INSTRUCTIONS
4286 if (!DecodeRvvVS()) {
4287 UNSUPPORTED();
4288 }
4289 break;
4290 # else
4291 UNSUPPORTED();
4292 # endif
4293 }
4294 }
4295
4296 void Simulator::DecodeRVBType() {
4297 switch (instr_.InstructionBits() & kBTypeMask) {
4298 case RO_BEQ:
4299 if (rs1() == rs2()) {
4300 int64_t next_pc = get_pc() + boffset();
4301 set_pc(next_pc);
4302 }
4303 break;
4304 case RO_BNE:
4305 if (rs1() != rs2()) {
4306 int64_t next_pc = get_pc() + boffset();
4307 set_pc(next_pc);
4308 }
4309 break;
4310 case RO_BLT:
4311 if (rs1() < rs2()) {
4312 int64_t next_pc = get_pc() + boffset();
4313 set_pc(next_pc);
4314 }
4315 break;
4316 case RO_BGE:
4317 if (rs1() >= rs2()) {
4318 int64_t next_pc = get_pc() + boffset();
4319 set_pc(next_pc);
4320 }
4321 break;
4322 case RO_BLTU:
4323 if ((reg_t)rs1() < (reg_t)rs2()) {
4324 int64_t next_pc = get_pc() + boffset();
4325 set_pc(next_pc);
4326 }
4327 break;
4328 case RO_BGEU:
4329 if ((reg_t)rs1() >= (reg_t)rs2()) {
4330 int64_t next_pc = get_pc() + boffset();
4331 set_pc(next_pc);
4332 }
4333 break;
4334 default:
4335 UNSUPPORTED();
4336 }
4337 }
4338 void Simulator::DecodeRVUType() {
4339 // U Type doesn't have additoinal mask
4340 switch (instr_.BaseOpcodeFieldRaw()) {
4341 case LUI:
4342 set_rd(u_imm20());
4343 break;
4344 case AUIPC:
4345 set_rd(sext_xlen(u_imm20() + get_pc()));
4346 break;
4347 default:
4348 UNSUPPORTED();
4349 }
4350 }
4351 void Simulator::DecodeRVJType() {
4352 // J Type doesn't have additional mask
4353 switch (instr_.BaseOpcodeValue()) {
4354 case JAL: {
4355 set_rd(get_pc() + kInstrSize);
4356 int64_t next_pc = get_pc() + imm20J();
4357 set_pc(next_pc);
4358 break;
4359 }
4360 default:
4361 UNSUPPORTED();
4362 }
4363 }
4364 void Simulator::DecodeCRType() {
4365 switch (instr_.RvcFunct4Value()) {
4366 case 0b1000:
4367 if (instr_.RvcRs1Value() != 0 && instr_.RvcRs2Value() == 0) { // c.jr
4368 set_pc(rvc_rs1());
4369 } else if (instr_.RvcRdValue() != 0 &&
4370 instr_.RvcRs2Value() != 0) { // c.mv
4371 set_rvc_rd(sext_xlen(rvc_rs2()));
4372 } else {
4373 UNSUPPORTED();
4374 }
4375 break;
4376 case 0b1001:
4377 if (instr_.RvcRs1Value() == 0 && instr_.RvcRs2Value() == 0) { // c.ebreak
4378 DieOrDebug();
4379 } else if (instr_.RvcRdValue() != 0 &&
4380 instr_.RvcRs2Value() == 0) { // c.jalr
4381 setRegister(ra, get_pc() + kShortInstrSize);
4382 set_pc(rvc_rs1());
4383 } else if (instr_.RvcRdValue() != 0 &&
4384 instr_.RvcRs2Value() != 0) { // c.add
4385 set_rvc_rd(sext_xlen(rvc_rs1() + rvc_rs2()));
4386 } else {
4387 UNSUPPORTED();
4388 }
4389 break;
4390 default:
4391 UNSUPPORTED();
4392 }
4393 }
4394
4395 void Simulator::DecodeCAType() {
4396 switch (instr_.InstructionBits() & kCATypeMask) {
4397 case RO_C_SUB:
4398 set_rvc_rs1s(sext_xlen(rvc_rs1s() - rvc_rs2s()));
4399 break;
4400 case RO_C_XOR:
4401 set_rvc_rs1s(rvc_rs1s() ^ rvc_rs2s());
4402 break;
4403 case RO_C_OR:
4404 set_rvc_rs1s(rvc_rs1s() | rvc_rs2s());
4405 break;
4406 case RO_C_AND:
4407 set_rvc_rs1s(rvc_rs1s() & rvc_rs2s());
4408 break;
4409 # if JS_CODEGEN_RISCV64
4410 case RO_C_SUBW:
4411 set_rvc_rs1s(sext32(rvc_rs1s() - rvc_rs2s()));
4412 break;
4413 case RO_C_ADDW:
4414 set_rvc_rs1s(sext32(rvc_rs1s() + rvc_rs2s()));
4415 break;
4416 # endif
4417 default:
4418 UNSUPPORTED();
4419 }
4420 }
4421
4422 void Simulator::DecodeCIType() {
4423 switch (instr_.RvcOpcode()) {
4424 case RO_C_NOP_ADDI:
4425 if (instr_.RvcRdValue() == 0) // c.nop
4426 break;
4427 else // c.addi
4428 set_rvc_rd(sext_xlen(rvc_rs1() + rvc_imm6()));
4429 break;
4430 # if JS_CODEGEN_RISCV64
4431 case RO_C_ADDIW:
4432 set_rvc_rd(sext32(rvc_rs1() + rvc_imm6()));
4433 break;
4434 # endif
4435 case RO_C_LI:
4436 set_rvc_rd(sext_xlen(rvc_imm6()));
4437 break;
4438 case RO_C_LUI_ADD:
4439 if (instr_.RvcRdValue() == 2) {
4440 // c.addi16sp
4441 int64_t value = getRegister(sp) + rvc_imm6_addi16sp();
4442 setRegister(sp, value);
4443 } else if (instr_.RvcRdValue() != 0 && instr_.RvcRdValue() != 2) {
4444 // c.lui
4445 set_rvc_rd(rvc_u_imm6());
4446 } else {
4447 UNSUPPORTED();
4448 }
4449 break;
4450 case RO_C_SLLI:
4451 set_rvc_rd(sext_xlen(rvc_rs1() << rvc_shamt6()));
4452 break;
4453 case RO_C_FLDSP: {
4454 sreg_t addr = getRegister(sp) + rvc_imm6_ldsp();
4455 uint64_t val = ReadMem<uint64_t>(addr, instr_.instr());
4456 set_rvc_drd(Float64::FromBits(val), false);
4457 TraceMemRdDouble(addr, Float64::FromBits(val),
4458 getFpuRegister(rvc_frd_reg()));
4459 break;
4460 }
4461 # if JS_CODEGEN_RISCV64
4462 case RO_C_LWSP: {
4463 sreg_t addr = getRegister(sp) + rvc_imm6_lwsp();
4464 int64_t val = ReadMem<int32_t>(addr, instr_.instr());
4465 set_rvc_rd(sext_xlen(val), false);
4466 TraceMemRd(addr, val, getRegister(rvc_rd_reg()));
4467 break;
4468 }
4469 case RO_C_LDSP: {
4470 sreg_t addr = getRegister(sp) + rvc_imm6_ldsp();
4471 int64_t val = ReadMem<int64_t>(addr, instr_.instr());
4472 set_rvc_rd(sext_xlen(val), false);
4473 TraceMemRd(addr, val, getRegister(rvc_rd_reg()));
4474 break;
4475 }
4476 # elif JS_CODEGEN_RISCV32
4477 case RO_C_FLWSP: {
4478 sreg_t addr = getRegister(sp) + rvc_imm6_ldsp();
4479 uint32_t val = ReadMem<uint32_t>(addr, instr_.instr());
4480 set_rvc_frd(Float32::FromBits(val), false);
4481 TraceMemRdFloat(addr, Float32::FromBits(val),
4482 getFpuRegister(rvc_frd_reg()));
4483 break;
4484 }
4485 case RO_C_LWSP: {
4486 sreg_t addr = getRegister(sp) + rvc_imm6_lwsp();
4487 int32_t val = ReadMem<int32_t>(addr, instr_.instr());
4488 set_rvc_rd(sext_xlen(val), false);
4489 TraceMemRd(addr, val, getRegister(rvc_rd_reg()));
4490 break;
4491 }
4492 # endif
4493 default:
4494 UNSUPPORTED();
4495 }
4496 }
4497
4498 void Simulator::DecodeCIWType() {
4499 switch (instr_.RvcOpcode()) {
4500 case RO_C_ADDI4SPN: {
4501 set_rvc_rs2s(getRegister(sp) + rvc_imm8_addi4spn());
4502 break;
4503 default:
4504 UNSUPPORTED();
4505 }
4506 }
4507 }
4508
4509 void Simulator::DecodeCSSType() {
4510 switch (instr_.RvcOpcode()) {
4511 case RO_C_FSDSP: {
4512 sreg_t addr = getRegister(sp) + rvc_imm6_sdsp();
4513 WriteMem<Float64>(addr, getFpuRegisterFloat64(rvc_rs2_reg()),
4514 instr_.instr());
4515 break;
4516 }
4517 # if JS_CODEGEN_RISCV32
4518 case RO_C_FSWSP: {
4519 sreg_t addr = getRegister(sp) + rvc_imm6_sdsp();
4520 WriteMem<Float32>(addr, getFpuRegisterFloat32(rvc_rs2_reg()),
4521 instr_.instr());
4522 break;
4523 }
4524 # endif
4525 case RO_C_SWSP: {
4526 sreg_t addr = getRegister(sp) + rvc_imm6_swsp();
4527 WriteMem<int32_t>(addr, (int32_t)rvc_rs2(), instr_.instr());
4528 break;
4529 }
4530 # if JS_CODEGEN_RISCV64
4531 case RO_C_SDSP: {
4532 sreg_t addr = getRegister(sp) + rvc_imm6_sdsp();
4533 WriteMem<int64_t>(addr, (int64_t)rvc_rs2(), instr_.instr());
4534 break;
4535 }
4536 # endif
4537 default:
4538 UNSUPPORTED();
4539 }
4540 }
4541
4542 void Simulator::DecodeCLType() {
4543 switch (instr_.RvcOpcode()) {
4544 case RO_C_LW: {
4545 sreg_t addr = rvc_rs1s() + rvc_imm5_w();
4546 int64_t val = ReadMem<int32_t>(addr, instr_.instr());
4547 set_rvc_rs2s(sext_xlen(val), false);
4548 TraceMemRd(addr, val, getRegister(rvc_rs2s_reg()));
4549 break;
4550 }
4551 case RO_C_FLD: {
4552 sreg_t addr = rvc_rs1s() + rvc_imm5_d();
4553 uint64_t val = ReadMem<uint64_t>(addr, instr_.instr());
4554 set_rvc_drs2s(Float64::FromBits(val), false);
4555 break;
4556 }
4557 # if JS_CODEGEN_RISCV64
4558 case RO_C_LD: {
4559 sreg_t addr = rvc_rs1s() + rvc_imm5_d();
4560 int64_t val = ReadMem<int64_t>(addr, instr_.instr());
4561 set_rvc_rs2s(sext_xlen(val), false);
4562 TraceMemRd(addr, val, getRegister(rvc_rs2s_reg()));
4563 break;
4564 }
4565 # elif JS_CODEGEN_RISCV32
4566 case RO_C_FLW: {
4567 sreg_t addr = rvc_rs1s() + rvc_imm5_d();
4568 uint32_t val = ReadMem<uint32_t>(addr, instr_.instr());
4569 set_rvc_frs2s(Float32::FromBits(val), false);
4570 break;
4571 }
4572 # endif
4573 default:
4574 UNSUPPORTED();
4575 }
4576 }
4577
4578 void Simulator::DecodeCSType() {
4579 switch (instr_.RvcOpcode()) {
4580 case RO_C_SW: {
4581 sreg_t addr = rvc_rs1s() + rvc_imm5_w();
4582 WriteMem<int32_t>(addr, (int32_t)rvc_rs2s(), instr_.instr());
4583 break;
4584 }
4585 # if JS_CODEGEN_RISCV64
4586 case RO_C_SD: {
4587 sreg_t addr = rvc_rs1s() + rvc_imm5_d();
4588 WriteMem<int64_t>(addr, (int64_t)rvc_rs2s(), instr_.instr());
4589 break;
4590 }
4591 # endif
4592 case RO_C_FSD: {
4593 sreg_t addr = rvc_rs1s() + rvc_imm5_d();
4594 WriteMem<double>(addr, static_cast<double>(rvc_drs2s()), instr_.instr());
4595 break;
4596 }
4597 default:
4598 UNSUPPORTED();
4599 }
4600 }
4601
4602 void Simulator::DecodeCJType() {
4603 switch (instr_.RvcOpcode()) {
4604 case RO_C_J: {
4605 set_pc(get_pc() + instr_.RvcImm11CJValue());
4606 break;
4607 }
4608 default:
4609 UNSUPPORTED();
4610 }
4611 }
4612
4613 void Simulator::DecodeCBType() {
4614 switch (instr_.RvcOpcode()) {
4615 case RO_C_BNEZ:
4616 if (rvc_rs1() != 0) {
4617 sreg_t next_pc = get_pc() + rvc_imm8_b();
4618 set_pc(next_pc);
4619 }
4620 break;
4621 case RO_C_BEQZ:
4622 if (rvc_rs1() == 0) {
4623 sreg_t next_pc = get_pc() + rvc_imm8_b();
4624 set_pc(next_pc);
4625 }
4626 break;
4627 case RO_C_MISC_ALU:
4628 if (instr_.RvcFunct2BValue() == 0b00) { // c.srli
4629 set_rvc_rs1s(sext_xlen(sext_xlen(rvc_rs1s()) >> rvc_shamt6()));
4630 } else if (instr_.RvcFunct2BValue() == 0b01) { // c.srai
4631 require(rvc_shamt6() < xlen);
4632 set_rvc_rs1s(sext_xlen(sext_xlen(rvc_rs1s()) >> rvc_shamt6()));
4633 } else if (instr_.RvcFunct2BValue() == 0b10) { // c.andi
4634 set_rvc_rs1s(rvc_imm6() & rvc_rs1s());
4635 } else {
4636 UNSUPPORTED();
4637 }
4638 break;
4639 default:
4640 UNSUPPORTED();
4641 }
4642 }
4643
4644 void Simulator::callInternal(uint8_t* entry) {
4645 // Prepare to execute the code at entry.
4646 setRegister(pc, reinterpret_cast<int64_t>(entry));
4647 // Put down marker for end of simulation. The simulator will stop simulation
4648 // when the PC reaches this value. By saving the "end simulation" value into
4649 // the LR the simulation stops when returning to this call point.
4650 setRegister(ra, end_sim_pc);
4651 // Remember the values of callee-saved registers.
4652 intptr_t s0_val = getRegister(Simulator::Register::fp);
4653 intptr_t s1_val = getRegister(Simulator::Register::s1);
4654 intptr_t s2_val = getRegister(Simulator::Register::s2);
4655 intptr_t s3_val = getRegister(Simulator::Register::s3);
4656 intptr_t s4_val = getRegister(Simulator::Register::s4);
4657 intptr_t s5_val = getRegister(Simulator::Register::s5);
4658 intptr_t s6_val = getRegister(Simulator::Register::s6);
4659 intptr_t s7_val = getRegister(Simulator::Register::s7);
4660 intptr_t s8_val = getRegister(Simulator::Register::s8);
4661 intptr_t s9_val = getRegister(Simulator::Register::s9);
4662 intptr_t s10_val = getRegister(Simulator::Register::s10);
4663 intptr_t s11_val = getRegister(Simulator::Register::s11);
4664 intptr_t gp_val = getRegister(Simulator::Register::gp);
4665 intptr_t sp_val = getRegister(Simulator::Register::sp);
4666
4667 // Set up the callee-saved registers with a known value. To be able to check
4668 // that they are preserved properly across JS execution. If this value is
4669 // small int, it should be SMI.
4670 intptr_t callee_saved_value = icount_;
4671 setRegister(Simulator::Register::fp, callee_saved_value);
4672 setRegister(Simulator::Register::s1, callee_saved_value);
4673 setRegister(Simulator::Register::s2, callee_saved_value);
4674 setRegister(Simulator::Register::s3, callee_saved_value);
4675 setRegister(Simulator::Register::s4, callee_saved_value);
4676 setRegister(Simulator::Register::s5, callee_saved_value);
4677 setRegister(Simulator::Register::s6, callee_saved_value);
4678 setRegister(Simulator::Register::s7, callee_saved_value);
4679 setRegister(Simulator::Register::s8, callee_saved_value);
4680 setRegister(Simulator::Register::s9, callee_saved_value);
4681 setRegister(Simulator::Register::s10, callee_saved_value);
4682 setRegister(Simulator::Register::s11, callee_saved_value);
4683 setRegister(Simulator::Register::gp, callee_saved_value);
4684
4685 // Start the simulation.
4686 if (Simulator::StopSimAt != -1) {
4687 execute<true>();
4688 } else {
4689 execute<false>();
4690 }
4691
4692 // Check that the callee-saved registers have been preserved.
4693 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::fp));
4694 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::s1));
4695 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::s2));
4696 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::s3));
4697 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::s4));
4698 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::s5));
4699 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::s6));
4700 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::s7));
4701 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::s8));
4702 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::s9));
4703 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::s10));
4704 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::s11));
4705 MOZ_ASSERT(callee_saved_value == getRegister(Simulator::Register::gp));
4706
4707 // Restore callee-saved registers with the original value.
4708 setRegister(Simulator::Register::fp, s0_val);
4709 setRegister(Simulator::Register::s1, s1_val);
4710 setRegister(Simulator::Register::s2, s2_val);
4711 setRegister(Simulator::Register::s3, s3_val);
4712 setRegister(Simulator::Register::s4, s4_val);
4713 setRegister(Simulator::Register::s5, s5_val);
4714 setRegister(Simulator::Register::s6, s6_val);
4715 setRegister(Simulator::Register::s7, s7_val);
4716 setRegister(Simulator::Register::s8, s8_val);
4717 setRegister(Simulator::Register::s9, s9_val);
4718 setRegister(Simulator::Register::s10, s10_val);
4719 setRegister(Simulator::Register::s11, s11_val);
4720 setRegister(Simulator::Register::gp, gp_val);
4721 setRegister(Simulator::Register::sp, sp_val);
4722 }
4723
4724 int64_t Simulator::call(uint8_t* entry, int argument_count, ...) {
4725 va_list parameters;
4726 va_start(parameters, argument_count);
4727
4728 int64_t original_stack = getRegister(sp);
4729 // Compute position of stack on entry to generated code.
4730 int64_t entry_stack = original_stack;
4731 if (argument_count > kCArgSlotCount) {
4732 entry_stack = entry_stack - argument_count * sizeof(int64_t);
4733 } else {
4734 entry_stack = entry_stack - kCArgsSlotsSize;
4735 }
4736
4737 entry_stack &= ~U64(ABIStackAlignment - 1);
4738
4739 intptr_t* stack_argument = reinterpret_cast<intptr_t*>(entry_stack);
4740
4741 // Setup the arguments.
4742 for (int i = 0; i < argument_count; i++) {
4743 js::jit::Register argReg;
4744 if (GetIntArgReg(i, &argReg)) {
4745 setRegister(argReg.code(), va_arg(parameters, int64_t));
4746 } else {
4747 stack_argument[i] = va_arg(parameters, int64_t);
4748 }
4749 }
4750
4751 va_end(parameters);
4752 setRegister(sp, entry_stack);
4753
4754 callInternal(entry);
4755
4756 // Pop stack passed arguments.
4757 MOZ_ASSERT(entry_stack == getRegister(sp));
4758 setRegister(sp, original_stack);
4759
4760 int64_t result = getRegister(a0);
4761 return result;
4762 }
4763
4764 uintptr_t Simulator::pushAddress(uintptr_t address) {
4765 int new_sp = getRegister(sp) - sizeof(uintptr_t);
4766 uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp);
4767 *stack_slot = address;
4768 setRegister(sp, new_sp);
4769 return new_sp;
4770 }
4771
4772 uintptr_t Simulator::popAddress() {
4773 int current_sp = getRegister(sp);
4774 uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(current_sp);
4775 uintptr_t address = *stack_slot;
4776 setRegister(sp, current_sp + sizeof(uintptr_t));
4777 return address;
4778 }
4779
4780 } // namespace jit
4781 } // namespace js
4782
4783 js::jit::Simulator* JSContext::simulator() const { return simulator_; }
4784
4785 #endif // JS_SIMULATOR_RISCV64