Debian Codegraph @

js/src/jit/mips64/Simulator-mips64.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 2011 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
30 #include "jit/mips64/Simulator-mips64.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 <limits>
40
41 #include "jit/AtomicOperations.h"
42 #include "jit/mips64/Assembler-mips64.h"
43 #include "js/Conversions.h"
44 #include "js/UniquePtr.h"
45 #include "js/Utility.h"
46 #include "threading/LockGuard.h"
47 #include "vm/JSContext.h"
48 #include "vm/Runtime.h"
49 #include "wasm/WasmInstance.h"
50 #include "wasm/WasmSignalHandlers.h"
51
52 #define I8(v) static_cast<int8_t>(v)
53 #define I16(v) static_cast<int16_t>(v)
54 #define U16(v) static_cast<uint16_t>(v)
55 #define I32(v) static_cast<int32_t>(v)
56 #define U32(v) static_cast<uint32_t>(v)
57 #define I64(v) static_cast<int64_t>(v)
58 #define U64(v) static_cast<uint64_t>(v)
59 #define I128(v) static_cast<__int128_t>(v)
60 #define U128(v) static_cast<__uint128_t>(v)
61
62 #define I32_CHECK(v) \
63 ({ \
64 MOZ_ASSERT(I64(I32(v)) == I64(v)); \
65 I32((v)); \
66 })
67
68 namespace js {
69 namespace jit {
70
71 static const Instr kCallRedirInstr =
72 op_special | MAX_BREAK_CODE << FunctionBits | ff_break;
73
74 // Utils functions.
75 static uint32_t GetFCSRConditionBit(uint32_t cc) {
76 if (cc == 0) {
77 return 23;
78 }
79 return 24 + cc;
80 }
81
82 // -----------------------------------------------------------------------------
83 // MIPS assembly various constants.
84
85 class SimInstruction {
86 public:
87 enum {
88 kInstrSize = 4,
89 // On MIPS PC cannot actually be directly accessed. We behave as if PC was
90 // always the value of the current instruction being executed.
91 kPCReadOffset = 0
92 };
93
94 // Get the raw instruction bits.
95 inline Instr instructionBits() const {
96 return *reinterpret_cast<const Instr*>(this);
97 }
98
99 // Set the raw instruction bits to value.
100 inline void setInstructionBits(Instr value) {
101 *reinterpret_cast<Instr*>(this) = value;
102 }
103
104 // Read one particular bit out of the instruction bits.
105 inline int bit(int nr) const { return (instructionBits() >> nr) & 1; }
106
107 // Read a bit field out of the instruction bits.
108 inline int bits(int hi, int lo) const {
109 return (instructionBits() >> lo) & ((2 << (hi - lo)) - 1);
110 }
111
112 // Instruction type.
113 enum Type { kRegisterType, kImmediateType, kJumpType, kUnsupported = -1 };
114
115 // Get the encoding type of the instruction.
116 Type instructionType() const;
117
118 // Accessors for the different named fields used in the MIPS encoding.
119 inline OpcodeField opcodeValue() const {
120 return static_cast<OpcodeField>(
121 bits(OpcodeShift + OpcodeBits - 1, OpcodeShift));
122 }
123
124 inline int rsValue() const {
125 MOZ_ASSERT(instructionType() == kRegisterType ||
126 instructionType() == kImmediateType);
127 return bits(RSShift + RSBits - 1, RSShift);
128 }
129
130 inline int rtValue() const {
131 MOZ_ASSERT(instructionType() == kRegisterType ||
132 instructionType() == kImmediateType);
133 return bits(RTShift + RTBits - 1, RTShift);
134 }
135
136 inline int rdValue() const {
137 MOZ_ASSERT(instructionType() == kRegisterType);
138 return bits(RDShift + RDBits - 1, RDShift);
139 }
140
141 inline int saValue() const {
142 MOZ_ASSERT(instructionType() == kRegisterType);
143 return bits(SAShift + SABits - 1, SAShift);
144 }
145
146 inline int functionValue() const {
147 MOZ_ASSERT(instructionType() == kRegisterType ||
148 instructionType() == kImmediateType);
149 return bits(FunctionShift + FunctionBits - 1, FunctionShift);
150 }
151
152 inline int fdValue() const { return bits(FDShift + FDBits - 1, FDShift); }
153
154 inline int fsValue() const { return bits(FSShift + FSBits - 1, FSShift); }
155
156 inline int ftValue() const { return bits(FTShift + FTBits - 1, FTShift); }
157
158 inline int frValue() const { return bits(FRShift + FRBits - 1, FRShift); }
159
160 // Float Compare condition code instruction bits.
161 inline int fcccValue() const {
162 return bits(FCccShift + FCccBits - 1, FCccShift);
163 }
164
165 // Float Branch condition code instruction bits.
166 inline int fbccValue() const {
167 return bits(FBccShift + FBccBits - 1, FBccShift);
168 }
169
170 // Float Branch true/false instruction bit.
171 inline int fbtrueValue() const {
172 return bits(FBtrueShift + FBtrueBits - 1, FBtrueShift);
173 }
174
175 // Return the fields at their original place in the instruction encoding.
176 inline OpcodeField opcodeFieldRaw() const {
177 return static_cast<OpcodeField>(instructionBits() & OpcodeMask);
178 }
179
180 inline int rsFieldRaw() const {
181 MOZ_ASSERT(instructionType() == kRegisterType ||
182 instructionType() == kImmediateType);
183 return instructionBits() & RSMask;
184 }
185
186 // Same as above function, but safe to call within instructionType().
187 inline int rsFieldRawNoAssert() const { return instructionBits() & RSMask; }
188
189 inline int rtFieldRaw() const {
190 MOZ_ASSERT(instructionType() == kRegisterType ||
191 instructionType() == kImmediateType);
192 return instructionBits() & RTMask;
193 }
194
195 inline int rdFieldRaw() const {
196 MOZ_ASSERT(instructionType() == kRegisterType);
197 return instructionBits() & RDMask;
198 }
199
200 inline int saFieldRaw() const {
201 MOZ_ASSERT(instructionType() == kRegisterType);
202 return instructionBits() & SAMask;
203 }
204
205 inline int functionFieldRaw() const {
206 return instructionBits() & FunctionMask;
207 }
208
209 // Get the secondary field according to the opcode.
210 inline int secondaryValue() const {
211 OpcodeField op = opcodeFieldRaw();
212 switch (op) {
213 case op_special:
214 case op_special2:
215 return functionValue();
216 case op_cop1:
217 return rsValue();
218 case op_regimm:
219 return rtValue();
220 default:
221 return ff_null;
222 }
223 }
224
225 inline int32_t imm16Value() const {
226 MOZ_ASSERT(instructionType() == kImmediateType);
227 return bits(Imm16Shift + Imm16Bits - 1, Imm16Shift);
228 }
229
230 inline int32_t imm26Value() const {
231 MOZ_ASSERT(instructionType() == kJumpType);
232 return bits(Imm26Shift + Imm26Bits - 1, Imm26Shift);
233 }
234
235 // Say if the instruction should not be used in a branch delay slot.
236 bool isForbiddenInBranchDelay() const;
237 // Say if the instruction 'links'. e.g. jal, bal.
238 bool isLinkingInstruction() const;
239 // Say if the instruction is a debugger break/trap.
240 bool isTrap() const;
241
242 private:
243 SimInstruction() = delete;
244 SimInstruction(const SimInstruction& other) = delete;
245 void operator=(const SimInstruction& other) = delete;
246 };
247
248 bool SimInstruction::isForbiddenInBranchDelay() const {
249 const int op = opcodeFieldRaw();
250 switch (op) {
251 case op_j:
252 case op_jal:
253 case op_beq:
254 case op_bne:
255 case op_blez:
256 case op_bgtz:
257 case op_beql:
258 case op_bnel:
259 case op_blezl:
260 case op_bgtzl:
261 return true;
262 case op_regimm:
263 switch (rtFieldRaw()) {
264 case rt_bltz:
265 case rt_bgez:
266 case rt_bltzal:
267 case rt_bgezal:
268 return true;
269 default:
270 return false;
271 };
272 break;
273 case op_special:
274 switch (functionFieldRaw()) {
275 case ff_jr:
276 case ff_jalr:
277 return true;
278 default:
279 return false;
280 };
281 break;
282 default:
283 return false;
284 };
285 }
286
287 bool SimInstruction::isLinkingInstruction() const {
288 const int op = opcodeFieldRaw();
289 switch (op) {
290 case op_jal:
291 return true;
292 case op_regimm:
293 switch (rtFieldRaw()) {
294 case rt_bgezal:
295 case rt_bltzal:
296 return true;
297 default:
298 return false;
299 };
300 case op_special:
301 switch (functionFieldRaw()) {
302 case ff_jalr:
303 return true;
304 default:
305 return false;
306 };
307 default:
308 return false;
309 };
310 }
311
312 bool SimInstruction::isTrap() const {
313 if (opcodeFieldRaw() != op_special) {
314 return false;
315 } else {
316 switch (functionFieldRaw()) {
317 case ff_break:
318 return instructionBits() != kCallRedirInstr;
319 case ff_tge:
320 case ff_tgeu:
321 case ff_tlt:
322 case ff_tltu:
323 case ff_teq:
324 case ff_tne:
325 return bits(15, 6) != kWasmTrapCode;
326 default:
327 return false;
328 };
329 }
330 }
331
332 SimInstruction::Type SimInstruction::instructionType() const {
333 switch (opcodeFieldRaw()) {
334 case op_special:
335 switch (functionFieldRaw()) {
336 case ff_jr:
337 case ff_jalr:
338 case ff_sync:
339 case ff_break:
340 case ff_sll:
341 case ff_dsll:
342 case ff_dsll32:
343 case ff_srl:
344 case ff_dsrl:
345 case ff_dsrl32:
346 case ff_sra:
347 case ff_dsra:
348 case ff_dsra32:
349 case ff_sllv:
350 case ff_dsllv:
351 case ff_srlv:
352 case ff_dsrlv:
353 case ff_srav:
354 case ff_dsrav:
355 case ff_mfhi:
356 case ff_mflo:
357 case ff_mult:
358 case ff_dmult:
359 case ff_multu:
360 case ff_dmultu:
361 case ff_div:
362 case ff_ddiv:
363 case ff_divu:
364 case ff_ddivu:
365 case ff_add:
366 case ff_dadd:
367 case ff_addu:
368 case ff_daddu:
369 case ff_sub:
370 case ff_dsub:
371 case ff_subu:
372 case ff_dsubu:
373 case ff_and:
374 case ff_or:
375 case ff_xor:
376 case ff_nor:
377 case ff_slt:
378 case ff_sltu:
379 case ff_tge:
380 case ff_tgeu:
381 case ff_tlt:
382 case ff_tltu:
383 case ff_teq:
384 case ff_tne:
385 case ff_movz:
386 case ff_movn:
387 case ff_movci:
388 return kRegisterType;
389 default:
390 return kUnsupported;
391 };
392 break;
393 case op_special2:
394 switch (functionFieldRaw()) {
395 case ff_mul:
396 case ff_clz:
397 case ff_dclz:
398 return kRegisterType;
399 default:
400 return kUnsupported;
401 };
402 break;
403 case op_special3:
404 switch (functionFieldRaw()) {
405 case ff_ins:
406 case ff_dins:
407 case ff_dinsm:
408 case ff_dinsu:
409 case ff_ext:
410 case ff_dext:
411 case ff_dextm:
412 case ff_dextu:
413 case ff_bshfl:
414 case ff_dbshfl:
415 return kRegisterType;
416 default:
417 return kUnsupported;
418 };
419 break;
420 case op_cop1: // Coprocessor instructions.
421 switch (rsFieldRawNoAssert()) {
422 case rs_bc1: // Branch on coprocessor condition.
423 return kImmediateType;
424 default:
425 return kRegisterType;
426 };
427 break;
428 case op_cop1x:
429 return kRegisterType;
430 // 16 bits Immediate type instructions. e.g.: addi dest, src, imm16.
431 case op_regimm:
432 case op_beq:
433 case op_bne:
434 case op_blez:
435 case op_bgtz:
436 case op_addi:
437 case op_daddi:
438 case op_addiu:
439 case op_daddiu:
440 case op_slti:
441 case op_sltiu:
442 case op_andi:
443 case op_ori:
444 case op_xori:
445 case op_lui:
446 case op_beql:
447 case op_bnel:
448 case op_blezl:
449 case op_bgtzl:
450 case op_lb:
451 case op_lbu:
452 case op_lh:
453 case op_lhu:
454 case op_lw:
455 case op_lwu:
456 case op_lwl:
457 case op_lwr:
458 case op_ll:
459 case op_lld:
460 case op_ld:
461 case op_ldl:
462 case op_ldr:
463 case op_sb:
464 case op_sh:
465 case op_sw:
466 case op_swl:
467 case op_swr:
468 case op_sc:
469 case op_scd:
470 case op_sd:
471 case op_sdl:
472 case op_sdr:
473 case op_lwc1:
474 case op_ldc1:
475 case op_swc1:
476 case op_sdc1:
477 return kImmediateType;
478 // 26 bits immediate type instructions. e.g.: j imm26.
479 case op_j:
480 case op_jal:
481 return kJumpType;
482 default:
483 return kUnsupported;
484 };
485 return kUnsupported;
486 }
487
488 // C/C++ argument slots size.
489 const int kCArgSlotCount = 0;
490 const int kCArgsSlotsSize = kCArgSlotCount * sizeof(uintptr_t);
491 const int kBranchReturnOffset = 2 * SimInstruction::kInstrSize;
492
493 class CachePage {
494 public:
495 static const int LINE_VALID = 0;
496 static const int LINE_INVALID = 1;
497
498 static const int kPageShift = 12;
499 static const int kPageSize = 1 << kPageShift;
500 static const int kPageMask = kPageSize - 1;
501 static const int kLineShift = 2; // The cache line is only 4 bytes right now.
502 static const int kLineLength = 1 << kLineShift;
503 static const int kLineMask = kLineLength - 1;
504
505 CachePage() { memset(&validity_map_, LINE_INVALID, sizeof(validity_map_)); }
506
507 char* validityByte(int offset) {
508 return &validity_map_[offset >> kLineShift];
509 }
510
511 char* cachedData(int offset) { return &data_[offset]; }
512
513 private:
514 char data_[kPageSize]; // The cached data.
515 static const int kValidityMapSize = kPageSize >> kLineShift;
516 char validity_map_[kValidityMapSize]; // One byte per line.
517 };
518
519 // Protects the icache() and redirection() properties of the
520 // Simulator.
521 class AutoLockSimulatorCache : public LockGuard<Mutex> {
522 using Base = LockGuard<Mutex>;
523
524 public:
525 explicit AutoLockSimulatorCache()
526 : Base(SimulatorProcess::singleton_->cacheLock_) {}
527 };
528
529 mozilla::Atomic<size_t, mozilla::ReleaseAcquire>
530 SimulatorProcess::ICacheCheckingDisableCount(
531 1); // Checking is disabled by default.
532 SimulatorProcess* SimulatorProcess::singleton_ = nullptr;
533
534 int64_t Simulator::StopSimAt = -1;
535
536 Simulator* Simulator::Create() {
537 auto sim = MakeUnique<Simulator>();
538 if (!sim) {
539 return nullptr;
540 }
541
542 if (!sim->init()) {
543 return nullptr;
544 }
545
546 int64_t stopAt;
547 char* stopAtStr = getenv("MIPS_SIM_STOP_AT");
548 if (stopAtStr && sscanf(stopAtStr, "%" PRIi64, &stopAt) == 1) {
549 fprintf(stderr, "\nStopping simulation at icount %" PRIi64 "\n", stopAt);
550 Simulator::StopSimAt = stopAt;
551 }
552
553 return sim.release();
554 }
555
556 void Simulator::Destroy(Simulator* sim) { js_delete(sim); }
557
558 // The MipsDebugger class is used by the simulator while debugging simulated
559 // code.
560 class MipsDebugger {
561 public:
562 explicit MipsDebugger(Simulator* sim) : sim_(sim) {}
563
564 void stop(SimInstruction* instr);
565 void debug();
566 // Print all registers with a nice formatting.
567 void printAllRegs();
568 void printAllRegsIncludingFPU();
569
570 private:
571 // We set the breakpoint code to 0xfffff to easily recognize it.
572 static const Instr kBreakpointInstr = op_special | ff_break | 0xfffff << 6;
573 static const Instr kNopInstr = op_special | ff_sll;
574
575 Simulator* sim_;
576
577 int64_t getRegisterValue(int regnum);
578 int64_t getFPURegisterValueLong(int regnum);
579 float getFPURegisterValueFloat(int regnum);
580 double getFPURegisterValueDouble(int regnum);
581 bool getValue(const char* desc, int64_t* value);
582
583 // Set or delete a breakpoint. Returns true if successful.
584 bool setBreakpoint(SimInstruction* breakpc);
585 bool deleteBreakpoint(SimInstruction* breakpc);
586
587 // Undo and redo all breakpoints. This is needed to bracket disassembly and
588 // execution to skip past breakpoints when run from the debugger.
589 void undoBreakpoints();
590 void redoBreakpoints();
591 };
592
593 static void UNSUPPORTED() {
594 printf("Unsupported instruction.\n");
595 MOZ_CRASH();
596 }
597
598 void MipsDebugger::stop(SimInstruction* instr) {
599 // Get the stop code.
600 uint32_t code = instr->bits(25, 6);
601 // Retrieve the encoded address, which comes just after this stop.
602 char* msg =
603 *reinterpret_cast<char**>(sim_->get_pc() + SimInstruction::kInstrSize);
604 // Update this stop description.
605 if (!sim_->watchedStops_[code].desc_) {
606 sim_->watchedStops_[code].desc_ = msg;
607 }
608 // Print the stop message and code if it is not the default code.
609 if (code != kMaxStopCode) {
610 printf("Simulator hit stop %u: %s\n", code, msg);
611 } else {
612 printf("Simulator hit %s\n", msg);
613 }
614 sim_->set_pc(sim_->get_pc() + 2 * SimInstruction::kInstrSize);
615 debug();
616 }
617
618 int64_t MipsDebugger::getRegisterValue(int regnum) {
619 if (regnum == kPCRegister) {
620 return sim_->get_pc();
621 }
622 return sim_->getRegister(regnum);
623 }
624
625 int64_t MipsDebugger::getFPURegisterValueLong(int regnum) {
626 return sim_->getFpuRegister(regnum);
627 }
628
629 float MipsDebugger::getFPURegisterValueFloat(int regnum) {
630 return sim_->getFpuRegisterFloat(regnum);
631 }
632
633 double MipsDebugger::getFPURegisterValueDouble(int regnum) {
634 return sim_->getFpuRegisterDouble(regnum);
635 }
636
637 bool MipsDebugger::getValue(const char* desc, int64_t* value) {
638 Register reg = Register::FromName(desc);
639 if (reg != InvalidReg) {
640 *value = getRegisterValue(reg.code());
641 return true;
642 }
643
644 if (strncmp(desc, "0x", 2) == 0) {
645 return sscanf(desc, "%" PRIu64, reinterpret_cast<uint64_t*>(value)) == 1;
646 }
647 return sscanf(desc, "%" PRIi64, value) == 1;
648 }
649
650 bool MipsDebugger::setBreakpoint(SimInstruction* breakpc) {
651 // Check if a breakpoint can be set. If not return without any side-effects.
652 if (sim_->break_pc_ != nullptr) {
653 return false;
654 }
655
656 // Set the breakpoint.
657 sim_->break_pc_ = breakpc;
658 sim_->break_instr_ = breakpc->instructionBits();
659 // Not setting the breakpoint instruction in the code itself. It will be set
660 // when the debugger shell continues.
661 return true;
662 }
663
664 bool MipsDebugger::deleteBreakpoint(SimInstruction* breakpc) {
665 if (sim_->break_pc_ != nullptr) {
666 sim_->break_pc_->setInstructionBits(sim_->break_instr_);
667 }
668
669 sim_->break_pc_ = nullptr;
670 sim_->break_instr_ = 0;
671 return true;
672 }
673
674 void MipsDebugger::undoBreakpoints() {
675 if (sim_->break_pc_) {
676 sim_->break_pc_->setInstructionBits(sim_->break_instr_);
677 }
678 }
679
680 void MipsDebugger::redoBreakpoints() {
681 if (sim_->break_pc_) {
682 sim_->break_pc_->setInstructionBits(kBreakpointInstr);
683 }
684 }
685
686 void MipsDebugger::printAllRegs() {
687 int64_t value;
688 for (uint32_t i = 0; i < Registers::Total; i++) {
689 value = getRegisterValue(i);
690 printf("%3s: 0x%016" PRIx64 " %20" PRIi64 " ", Registers::GetName(i),
691 value, value);
692
693 if (i % 2) {
694 printf("\n");
695 }
696 }
697 printf("\n");
698
699 value = getRegisterValue(Simulator::LO);
700 printf(" LO: 0x%016" PRIx64 " %20" PRIi64 " ", value, value);
701 value = getRegisterValue(Simulator::HI);
702 printf(" HI: 0x%016" PRIx64 " %20" PRIi64 "\n", value, value);
703 value = getRegisterValue(Simulator::pc);
704 printf(" pc: 0x%016" PRIx64 "\n", value);
705 }
706
707 void MipsDebugger::printAllRegsIncludingFPU() {
708 printAllRegs();
709
710 printf("\n\n");
711 // f0, f1, f2, ... f31.
712 for (uint32_t i = 0; i < FloatRegisters::TotalPhys; i++) {
713 printf("%3s: 0x%016" PRIi64 "\tflt: %-8.4g\tdbl: %-16.4g\n",
714 FloatRegisters::GetName(i), getFPURegisterValueLong(i),
715 getFPURegisterValueFloat(i), getFPURegisterValueDouble(i));
716 }
717 }
718
719 static char* ReadLine(const char* prompt) {
720 UniqueChars result;
721 char lineBuf[256];
722 int offset = 0;
723 bool keepGoing = true;
724 fprintf(stdout, "%s", prompt);
725 fflush(stdout);
726 while (keepGoing) {
727 if (fgets(lineBuf, sizeof(lineBuf), stdin) == nullptr) {
728 // fgets got an error. Just give up.
729 return nullptr;
730 }
731 int len = strlen(lineBuf);
732 if (len > 0 && lineBuf[len - 1] == '\n') {
733 // Since we read a new line we are done reading the line. This
734 // will exit the loop after copying this buffer into the result.
735 keepGoing = false;
736 }
737 if (!result) {
738 // Allocate the initial result and make room for the terminating '\0'
739 result.reset(js_pod_malloc<char>(len + 1));
740 if (!result) {
741 return nullptr;
742 }
743 } else {
744 // Allocate a new result with enough room for the new addition.
745 int new_len = offset + len + 1;
746 char* new_result = js_pod_malloc<char>(new_len);
747 if (!new_result) {
748 return nullptr;
749 }
750 // Copy the existing input into the new array and set the new
751 // array as the result.
752 memcpy(new_result, result.get(), offset * sizeof(char));
753 result.reset(new_result);
754 }
755 // Copy the newly read line into the result.
756 memcpy(result.get() + offset, lineBuf, len * sizeof(char));
757 offset += len;
758 }
759
760 MOZ_ASSERT(result);
761 result[offset] = '\0';
762 return result.release();
763 }
764
765 static void DisassembleInstruction(uint64_t pc) {
766 uint8_t* bytes = reinterpret_cast<uint8_t*>(pc);
767 char hexbytes[256];
768 sprintf(hexbytes, "0x%x 0x%x 0x%x 0x%x", bytes[0], bytes[1], bytes[2],
769 bytes[3]);
770 char llvmcmd[1024];
771 sprintf(llvmcmd,
772 "bash -c \"echo -n '%p'; echo '%s' | "
773 "llvm-mc -disassemble -arch=mips64el -mcpu=mips64r2 | "
774 "grep -v pure_instructions | grep -v .text\"",
775 static_cast<void*>(bytes), hexbytes);
776 if (system(llvmcmd)) {
777 printf("Cannot disassemble instruction.\n");
778 }
779 }
780
781 void MipsDebugger::debug() {
782 intptr_t lastPC = -1;
783 bool done = false;
784
785 #define COMMAND_SIZE 63
786 #define ARG_SIZE 255
787
788 #define STR(a) #a
789 #define XSTR(a) STR(a)
790
791 char cmd[COMMAND_SIZE + 1];
792 char arg1[ARG_SIZE + 1];
793 char arg2[ARG_SIZE + 1];
794 char* argv[3] = {cmd, arg1, arg2};
795
796 // Make sure to have a proper terminating character if reaching the limit.
797 cmd[COMMAND_SIZE] = 0;
798 arg1[ARG_SIZE] = 0;
799 arg2[ARG_SIZE] = 0;
800
801 // Undo all set breakpoints while running in the debugger shell. This will
802 // make them invisible to all commands.
803 undoBreakpoints();
804
805 while (!done && (sim_->get_pc() != Simulator::end_sim_pc)) {
806 if (lastPC != sim_->get_pc()) {
807 DisassembleInstruction(sim_->get_pc());
808 lastPC = sim_->get_pc();
809 }
810 char* line = ReadLine("sim> ");
811 if (line == nullptr) {
812 break;
813 } else {
814 char* last_input = sim_->lastDebuggerInput();
815 if (strcmp(line, "\n") == 0 && last_input != nullptr) {
816 line = last_input;
817 } else {
818 // Ownership is transferred to sim_;
819 sim_->setLastDebuggerInput(line);
820 }
821 // Use sscanf to parse the individual parts of the command line. At the
822 // moment no command expects more than two parameters.
823 int argc = sscanf(line,
824 "%" XSTR(COMMAND_SIZE) "s "
825 "%" XSTR(ARG_SIZE) "s "
826 "%" XSTR(ARG_SIZE) "s",
827 cmd, arg1, arg2);
828 if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) {
829 SimInstruction* instr =
830 reinterpret_cast<SimInstruction*>(sim_->get_pc());
831 if (!instr->isTrap()) {
832 sim_->instructionDecode(
833 reinterpret_cast<SimInstruction*>(sim_->get_pc()));
834 } else {
835 // Allow si to jump over generated breakpoints.
836 printf("/!\\ Jumping over generated breakpoint.\n");
837 sim_->set_pc(sim_->get_pc() + SimInstruction::kInstrSize);
838 }
839 } else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) {
840 // Execute the one instruction we broke at with breakpoints disabled.
841 sim_->instructionDecode(
842 reinterpret_cast<SimInstruction*>(sim_->get_pc()));
843 // Leave the debugger shell.
844 done = true;
845 } else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) {
846 if (argc == 2) {
847 int64_t value;
848 if (strcmp(arg1, "all") == 0) {
849 printAllRegs();
850 } else if (strcmp(arg1, "allf") == 0) {
851 printAllRegsIncludingFPU();
852 } else {
853 Register reg = Register::FromName(arg1);
854 FloatRegisters::Encoding fReg = FloatRegisters::FromName(arg1);
855 if (reg != InvalidReg) {
856 value = getRegisterValue(reg.code());
857 printf("%s: 0x%016" PRIi64 " %20" PRIi64 " \n", arg1, value,
858 value);
859 } else if (fReg != FloatRegisters::Invalid) {
860 printf("%3s: 0x%016" PRIi64 "\tflt: %-8.4g\tdbl: %-16.4g\n",
861 FloatRegisters::GetName(fReg),
862 getFPURegisterValueLong(fReg),
863 getFPURegisterValueFloat(fReg),
864 getFPURegisterValueDouble(fReg));
865 } else {
866 printf("%s unrecognized\n", arg1);
867 }
868 }
869 } else {
870 printf("print <register> or print <fpu register> single\n");
871 }
872 } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) {
873 int64_t* cur = nullptr;
874 int64_t* end = nullptr;
875 int next_arg = 1;
876
877 if (strcmp(cmd, "stack") == 0) {
878 cur = reinterpret_cast<int64_t*>(sim_->getRegister(Simulator::sp));
879 } else { // Command "mem".
880 int64_t value;
881 if (!getValue(arg1, &value)) {
882 printf("%s unrecognized\n", arg1);
883 continue;
884 }
885 cur = reinterpret_cast<int64_t*>(value);
886 next_arg++;
887 }
888
889 int64_t words;
890 if (argc == next_arg) {
891 words = 10;
892 } else {
893 if (!getValue(argv[next_arg], &words)) {
894 words = 10;
895 }
896 }
897 end = cur + words;
898
899 while (cur < end) {
900 printf(" %p: 0x%016" PRIx64 " %20" PRIi64, cur, *cur, *cur);
901 printf("\n");
902 cur++;
903 }
904
905 } else if ((strcmp(cmd, "disasm") == 0) || (strcmp(cmd, "dpc") == 0) ||
906 (strcmp(cmd, "di") == 0)) {
907 uint8_t* cur = nullptr;
908 uint8_t* end = nullptr;
909
910 if (argc == 1) {
911 cur = reinterpret_cast<uint8_t*>(sim_->get_pc());
912 end = cur + (10 * SimInstruction::kInstrSize);
913 } else if (argc == 2) {
914 Register reg = Register::FromName(arg1);
915 if (reg != InvalidReg || strncmp(arg1, "0x", 2) == 0) {
916 // The argument is an address or a register name.
917 int64_t value;
918 if (getValue(arg1, &value)) {
919 cur = reinterpret_cast<uint8_t*>(value);
920 // Disassemble 10 instructions at <arg1>.
921 end = cur + (10 * SimInstruction::kInstrSize);
922 }
923 } else {
924 // The argument is the number of instructions.
925 int64_t value;
926 if (getValue(arg1, &value)) {
927 cur = reinterpret_cast<uint8_t*>(sim_->get_pc());
928 // Disassemble <arg1> instructions.
929 end = cur + (value * SimInstruction::kInstrSize);
930 }
931 }
932 } else {
933 int64_t value1;
934 int64_t value2;
935 if (getValue(arg1, &value1) && getValue(arg2, &value2)) {
936 cur = reinterpret_cast<uint8_t*>(value1);
937 end = cur + (value2 * SimInstruction::kInstrSize);
938 }
939 }
940
941 while (cur < end) {
942 DisassembleInstruction(uint64_t(cur));
943 cur += SimInstruction::kInstrSize;
944 }
945 } else if (strcmp(cmd, "gdb") == 0) {
946 printf("relinquishing control to gdb\n");
947 #if defined(__x86_64__)
948 asm("int $3");
949 #elif defined(__aarch64__)
950 // see masm.breakpoint for arm64
951 asm("brk #0xf000");
952 #endif
953 printf("regaining control from gdb\n");
954 } else if (strcmp(cmd, "break") == 0) {
955 if (argc == 2) {
956 int64_t value;
957 if (getValue(arg1, &value)) {
958 if (!setBreakpoint(reinterpret_cast<SimInstruction*>(value))) {
959 printf("setting breakpoint failed\n");
960 }
961 } else {
962 printf("%s unrecognized\n", arg1);
963 }
964 } else {
965 printf("break <address>\n");
966 }
967 } else if (strcmp(cmd, "del") == 0) {
968 if (!deleteBreakpoint(nullptr)) {
969 printf("deleting breakpoint failed\n");
970 }
971 } else if (strcmp(cmd, "flags") == 0) {
972 printf("No flags on MIPS !\n");
973 } else if (strcmp(cmd, "stop") == 0) {
974 int64_t value;
975 intptr_t stop_pc = sim_->get_pc() - 2 * SimInstruction::kInstrSize;
976 SimInstruction* stop_instr = reinterpret_cast<SimInstruction*>(stop_pc);
977 SimInstruction* msg_address = reinterpret_cast<SimInstruction*>(
978 stop_pc + SimInstruction::kInstrSize);
979 if ((argc == 2) && (strcmp(arg1, "unstop") == 0)) {
980 // Remove the current stop.
981 if (sim_->isStopInstruction(stop_instr)) {
982 stop_instr->setInstructionBits(kNopInstr);
983 msg_address->setInstructionBits(kNopInstr);
984 } else {
985 printf("Not at debugger stop.\n");
986 }
987 } else if (argc == 3) {
988 // Print information about all/the specified breakpoint(s).
989 if (strcmp(arg1, "info") == 0) {
990 if (strcmp(arg2, "all") == 0) {
991 printf("Stop information:\n");
992 for (uint32_t i = kMaxWatchpointCode + 1; i <= kMaxStopCode;
993 i++) {
994 sim_->printStopInfo(i);
995 }
996 } else if (getValue(arg2, &value)) {
997 sim_->printStopInfo(value);
998 } else {
999 printf("Unrecognized argument.\n");
1000 }
1001 } else if (strcmp(arg1, "enable") == 0) {
1002 // Enable all/the specified breakpoint(s).
1003 if (strcmp(arg2, "all") == 0) {
1004 for (uint32_t i = kMaxWatchpointCode + 1; i <= kMaxStopCode;
1005 i++) {
1006 sim_->enableStop(i);
1007 }
1008 } else if (getValue(arg2, &value)) {
1009 sim_->enableStop(value);
1010 } else {
1011 printf("Unrecognized argument.\n");
1012 }
1013 } else if (strcmp(arg1, "disable") == 0) {
1014 // Disable all/the specified breakpoint(s).
1015 if (strcmp(arg2, "all") == 0) {
1016 for (uint32_t i = kMaxWatchpointCode + 1; i <= kMaxStopCode;
1017 i++) {
1018 sim_->disableStop(i);
1019 }
1020 } else if (getValue(arg2, &value)) {
1021 sim_->disableStop(value);
1022 } else {
1023 printf("Unrecognized argument.\n");
1024 }
1025 }
1026 } else {
1027 printf("Wrong usage. Use help command for more information.\n");
1028 }
1029 } else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) {
1030 printf("cont\n");
1031 printf(" continue execution (alias 'c')\n");
1032 printf("stepi\n");
1033 printf(" step one instruction (alias 'si')\n");
1034 printf("print <register>\n");
1035 printf(" print register content (alias 'p')\n");
1036 printf(" use register name 'all' to print all registers\n");
1037 printf("printobject <register>\n");
1038 printf(" print an object from a register (alias 'po')\n");
1039 printf("stack [<words>]\n");
1040 printf(" dump stack content, default dump 10 words)\n");
1041 printf("mem <address> [<words>]\n");
1042 printf(" dump memory content, default dump 10 words)\n");
1043 printf("flags\n");
1044 printf(" print flags\n");
1045 printf("disasm [<instructions>]\n");
1046 printf("disasm [<address/register>]\n");
1047 printf("disasm [[<address/register>] <instructions>]\n");
1048 printf(" disassemble code, default is 10 instructions\n");
1049 printf(" from pc (alias 'di')\n");
1050 printf("gdb\n");
1051 printf(" enter gdb\n");
1052 printf("break <address>\n");
1053 printf(" set a break point on the address\n");
1054 printf("del\n");
1055 printf(" delete the breakpoint\n");
1056 printf("stop feature:\n");
1057 printf(" Description:\n");
1058 printf(" Stops are debug instructions inserted by\n");
1059 printf(" the Assembler::stop() function.\n");
1060 printf(" When hitting a stop, the Simulator will\n");
1061 printf(" stop and and give control to the Debugger.\n");
1062 printf(" All stop codes are watched:\n");
1063 printf(" - They can be enabled / disabled: the Simulator\n");
1064 printf(" will / won't stop when hitting them.\n");
1065 printf(" - The Simulator keeps track of how many times they \n");
1066 printf(" are met. (See the info command.) Going over a\n");
1067 printf(" disabled stop still increases its counter. \n");
1068 printf(" Commands:\n");
1069 printf(" stop info all/<code> : print infos about number <code>\n");
1070 printf(" or all stop(s).\n");
1071 printf(" stop enable/disable all/<code> : enables / disables\n");
1072 printf(" all or number <code> stop(s)\n");
1073 printf(" stop unstop\n");
1074 printf(" ignore the stop instruction at the current location\n");
1075 printf(" from now on\n");
1076 } else {
1077 printf("Unknown command: %s\n", cmd);
1078 }
1079 }
1080 }
1081
1082 // Add all the breakpoints back to stop execution and enter the debugger
1083 // shell when hit.
1084 redoBreakpoints();
1085
1086 #undef COMMAND_SIZE
1087 #undef ARG_SIZE
1088
1089 #undef STR
1090 #undef XSTR
1091 }
1092
1093 static bool AllOnOnePage(uintptr_t start, int size) {
1094 intptr_t start_page = (start & ~CachePage::kPageMask);
1095 intptr_t end_page = ((start + size) & ~CachePage::kPageMask);
1096 return start_page == end_page;
1097 }
1098
1099 void Simulator::setLastDebuggerInput(char* input) {
1100 js_free(lastDebuggerInput_);
1101 lastDebuggerInput_ = input;
1102 }
1103
1104 static CachePage* GetCachePageLocked(SimulatorProcess::ICacheMap& i_cache,
1105 void* page) {
1106 SimulatorProcess::ICacheMap::AddPtr p = i_cache.lookupForAdd(page);
1107 if (p) {
1108 return p->value();
1109 }
1110 AutoEnterOOMUnsafeRegion oomUnsafe;
1111 CachePage* new_page = js_new<CachePage>();
1112 if (!new_page || !i_cache.add(p, page, new_page)) {
1113 oomUnsafe.crash("Simulator CachePage");
1114 }
1115 return new_page;
1116 }
1117
1118 // Flush from start up to and not including start + size.
1119 static void FlushOnePageLocked(SimulatorProcess::ICacheMap& i_cache,
1120 intptr_t start, int size) {
1121 MOZ_ASSERT(size <= CachePage::kPageSize);
1122 MOZ_ASSERT(AllOnOnePage(start, size - 1));
1123 MOZ_ASSERT((start & CachePage::kLineMask) == 0);
1124 MOZ_ASSERT((size & CachePage::kLineMask) == 0);
1125 void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask));
1126 int offset = (start & CachePage::kPageMask);
1127 CachePage* cache_page = GetCachePageLocked(i_cache, page);
1128 char* valid_bytemap = cache_page->validityByte(offset);
1129 memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift);
1130 }
1131
1132 static void FlushICacheLocked(SimulatorProcess::ICacheMap& i_cache,
1133 void* start_addr, size_t size) {
1134 intptr_t start = reinterpret_cast<intptr_t>(start_addr);
1135 int intra_line = (start & CachePage::kLineMask);
1136 start -= intra_line;
1137 size += intra_line;
1138 size = ((size - 1) | CachePage::kLineMask) + 1;
1139 int offset = (start & CachePage::kPageMask);
1140 while (!AllOnOnePage(start, size - 1)) {
1141 int bytes_to_flush = CachePage::kPageSize - offset;
1142 FlushOnePageLocked(i_cache, start, bytes_to_flush);
1143 start += bytes_to_flush;
1144 size -= bytes_to_flush;
1145 MOZ_ASSERT((start & CachePage::kPageMask) == 0);
1146 offset = 0;
1147 }
1148 if (size != 0) {
1149 FlushOnePageLocked(i_cache, start, size);
1150 }
1151 }
1152
1153 /* static */
1154 void SimulatorProcess::checkICacheLocked(SimInstruction* instr) {
1155 intptr_t address = reinterpret_cast<intptr_t>(instr);
1156 void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask));
1157 void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask));
1158 int offset = (address & CachePage::kPageMask);
1159 CachePage* cache_page = GetCachePageLocked(icache(), page);
1160 char* cache_valid_byte = cache_page->validityByte(offset);
1161 bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID);
1162 char* cached_line = cache_page->cachedData(offset & ~CachePage::kLineMask);
1163
1164 if (cache_hit) {
1165 // Check that the data in memory matches the contents of the I-cache.
1166 int cmpret =
1167 memcmp(reinterpret_cast<void*>(instr), cache_page->cachedData(offset),
1168 SimInstruction::kInstrSize);
1169 MOZ_ASSERT(cmpret == 0);
1170 } else {
1171 // Cache miss. Load memory into the cache.
1172 memcpy(cached_line, line, CachePage::kLineLength);
1173 *cache_valid_byte = CachePage::LINE_VALID;
1174 }
1175 }
1176
1177 HashNumber SimulatorProcess::ICacheHasher::hash(const Lookup& l) {
1178 return U32(reinterpret_cast<uintptr_t>(l)) >> 2;
1179 }
1180
1181 bool SimulatorProcess::ICacheHasher::match(const Key& k, const Lookup& l) {
1182 MOZ_ASSERT((reinterpret_cast<intptr_t>(k) & CachePage::kPageMask) == 0);
1183 MOZ_ASSERT((reinterpret_cast<intptr_t>(l) & CachePage::kPageMask) == 0);
1184 return k == l;
1185 }
1186
1187 /* static */
1188 void SimulatorProcess::FlushICache(void* start_addr, size_t size) {
1189 if (!ICacheCheckingDisableCount) {
1190 AutoLockSimulatorCache als;
1191 js::jit::FlushICacheLocked(icache(), start_addr, size);
1192 }
1193 }
1194
1195 Simulator::Simulator() {
1196 // Set up simulator support first. Some of this information is needed to
1197 // setup the architecture state.
1198
1199 // Note, allocation and anything that depends on allocated memory is
1200 // deferred until init(), in order to handle OOM properly.
1201
1202 stack_ = nullptr;
1203 stackLimit_ = 0;
1204 pc_modified_ = false;
1205 icount_ = 0;
1206 break_count_ = 0;
1207 break_pc_ = nullptr;
1208 break_instr_ = 0;
1209 single_stepping_ = false;
1210 single_step_callback_ = nullptr;
1211 single_step_callback_arg_ = nullptr;
1212
1213 // Set up architecture state.
1214 // All registers are initialized to zero to start with.
1215 for (int i = 0; i < Register::kNumSimuRegisters; i++) {
1216 registers_[i] = 0;
1217 }
1218 for (int i = 0; i < Simulator::FPURegister::kNumFPURegisters; i++) {
1219 FPUregisters_[i] = 0;
1220 }
1221 FCSR_ = 0;
1222 LLBit_ = false;
1223 LLAddr_ = 0;
1224 lastLLValue_ = 0;
1225
1226 // The ra and pc are initialized to a known bad value that will cause an
1227 // access violation if the simulator ever tries to execute it.
1228 registers_[pc] = bad_ra;
1229 registers_[ra] = bad_ra;
1230
1231 for (int i = 0; i < kNumExceptions; i++) {
1232 exceptions[i] = 0;
1233 }
1234
1235 lastDebuggerInput_ = nullptr;
1236 }
1237
1238 bool Simulator::init() {
1239 // Allocate 2MB for the stack. Note that we will only use 1MB, see below.
1240 static const size_t stackSize = 2 * 1024 * 1024;
1241 stack_ = js_pod_malloc<char>(stackSize);
1242 if (!stack_) {
1243 return false;
1244 }
1245
1246 // Leave a safety margin of 1MB to prevent overrunning the stack when
1247 // pushing values (total stack size is 2MB).
1248 stackLimit_ = reinterpret_cast<uintptr_t>(stack_) + 1024 * 1024;
1249
1250 // The sp is initialized to point to the bottom (high address) of the
1251 // allocated stack area. To be safe in potential stack underflows we leave
1252 // some buffer below.
1253 registers_[sp] = reinterpret_cast<int64_t>(stack_) + stackSize - 64;
1254
1255 return true;
1256 }
1257
1258 // When the generated code calls an external reference we need to catch that in
1259 // the simulator. The external reference will be a function compiled for the
1260 // host architecture. We need to call that function instead of trying to
1261 // execute it with the simulator. We do that by redirecting the external
1262 // reference to a swi (software-interrupt) instruction that is handled by
1263 // the simulator. We write the original destination of the jump just at a known
1264 // offset from the swi instruction so the simulator knows what to call.
1265 class Redirection {
1266 friend class SimulatorProcess;
1267
1268 // sim's lock must already be held.
1269 Redirection(void* nativeFunction, ABIFunctionType type)
1270 : nativeFunction_(nativeFunction),
1271 swiInstruction_(kCallRedirInstr),
1272 type_(type),
1273 next_(nullptr) {
1274 next_ = SimulatorProcess::redirection();
1275 if (!SimulatorProcess::ICacheCheckingDisableCount) {
1276 FlushICacheLocked(SimulatorProcess::icache(), addressOfSwiInstruction(),
1277 SimInstruction::kInstrSize);
1278 }
1279 SimulatorProcess::setRedirection(this);
1280 }
1281
1282 public:
1283 void* addressOfSwiInstruction() { return &swiInstruction_; }
1284 void* nativeFunction() const { return nativeFunction_; }
1285 ABIFunctionType type() const { return type_; }
1286
1287 static Redirection* Get(void* nativeFunction, ABIFunctionType type) {
1288 AutoLockSimulatorCache als;
1289
1290 Redirection* current = SimulatorProcess::redirection();
1291 for (; current != nullptr; current = current->next_) {
1292 if (current->nativeFunction_ == nativeFunction) {
1293 MOZ_ASSERT(current->type() == type);
1294 return current;
1295 }
1296 }
1297
1298 // Note: we can't use js_new here because the constructor is private.
1299 AutoEnterOOMUnsafeRegion oomUnsafe;
1300 Redirection* redir = js_pod_malloc<Redirection>(1);
1301 if (!redir) {
1302 oomUnsafe.crash("Simulator redirection");
1303 }
1304 new (redir) Redirection(nativeFunction, type);
1305 return redir;
1306 }
1307
1308 static Redirection* FromSwiInstruction(SimInstruction* swiInstruction) {
1309 uint8_t* addrOfSwi = reinterpret_cast<uint8_t*>(swiInstruction);
1310 uint8_t* addrOfRedirection =
1311 addrOfSwi - offsetof(Redirection, swiInstruction_);
1312 return reinterpret_cast<Redirection*>(addrOfRedirection);
1313 }
1314
1315 private:
1316 void* nativeFunction_;
1317 uint32_t swiInstruction_;
1318 ABIFunctionType type_;
1319 Redirection* next_;
1320 };
1321
1322 Simulator::~Simulator() { js_free(stack_); }
1323
1324 SimulatorProcess::SimulatorProcess()
1325 : cacheLock_(mutexid::SimulatorCacheLock), redirection_(nullptr) {
1326 if (getenv("MIPS_SIM_ICACHE_CHECKS")) {
1327 ICacheCheckingDisableCount = 0;
1328 }
1329 }
1330
1331 SimulatorProcess::~SimulatorProcess() {
1332 Redirection* r = redirection_;
1333 while (r) {
1334 Redirection* next = r->next_;
1335 js_delete(r);
1336 r = next;
1337 }
1338 }
1339
1340 /* static */
1341 void* Simulator::RedirectNativeFunction(void* nativeFunction,
1342 ABIFunctionType type) {
1343 Redirection* redirection = Redirection::Get(nativeFunction, type);
1344 return redirection->addressOfSwiInstruction();
1345 }
1346
1347 // Get the active Simulator for the current thread.
1348 Simulator* Simulator::Current() {
1349 JSContext* cx = TlsContext.get();
1350 MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
1351 return cx->simulator();
1352 }
1353
1354 // Sets the register in the architecture state. It will also deal with updating
1355 // Simulator internal state for special registers such as PC.
1356 void Simulator::setRegister(int reg, int64_t value) {
1357 MOZ_ASSERT((reg >= 0) && (reg < Register::kNumSimuRegisters));
1358 if (reg == pc) {
1359 pc_modified_ = true;
1360 }
1361
1362 // Zero register always holds 0.
1363 registers_[reg] = (reg == 0) ? 0 : value;
1364 }
1365
1366 void Simulator::setFpuRegister(int fpureg, int64_t value) {
1367 MOZ_ASSERT((fpureg >= 0) &&
1368 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1369 FPUregisters_[fpureg] = value;
1370 }
1371
1372 void Simulator::setFpuRegisterLo(int fpureg, int32_t value) {
1373 MOZ_ASSERT((fpureg >= 0) &&
1374 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1375 *mozilla::BitwiseCast<int32_t*>(&FPUregisters_[fpureg]) = value;
1376 }
1377
1378 void Simulator::setFpuRegisterHi(int fpureg, int32_t value) {
1379 MOZ_ASSERT((fpureg >= 0) &&
1380 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1381 *((mozilla::BitwiseCast<int32_t*>(&FPUregisters_[fpureg])) + 1) = value;
1382 }
1383
1384 void Simulator::setFpuRegisterFloat(int fpureg, float value) {
1385 MOZ_ASSERT((fpureg >= 0) &&
1386 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1387 *mozilla::BitwiseCast<float*>(&FPUregisters_[fpureg]) = value;
1388 }
1389
1390 void Simulator::setFpuRegisterDouble(int fpureg, double value) {
1391 MOZ_ASSERT((fpureg >= 0) &&
1392 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1393 *mozilla::BitwiseCast<double*>(&FPUregisters_[fpureg]) = value;
1394 }
1395
1396 // Get the register from the architecture state. This function does handle
1397 // the special case of accessing the PC register.
1398 int64_t Simulator::getRegister(int reg) const {
1399 MOZ_ASSERT((reg >= 0) && (reg < Register::kNumSimuRegisters));
1400 if (reg == 0) {
1401 return 0;
1402 }
1403 return registers_[reg] + ((reg == pc) ? SimInstruction::kPCReadOffset : 0);
1404 }
1405
1406 int64_t Simulator::getFpuRegister(int fpureg) const {
1407 MOZ_ASSERT((fpureg >= 0) &&
1408 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1409 return FPUregisters_[fpureg];
1410 }
1411
1412 int32_t Simulator::getFpuRegisterLo(int fpureg) const {
1413 MOZ_ASSERT((fpureg >= 0) &&
1414 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1415 return *mozilla::BitwiseCast<int32_t*>(&FPUregisters_[fpureg]);
1416 }
1417
1418 int32_t Simulator::getFpuRegisterHi(int fpureg) const {
1419 MOZ_ASSERT((fpureg >= 0) &&
1420 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1421 return *((mozilla::BitwiseCast<int32_t*>(&FPUregisters_[fpureg])) + 1);
1422 }
1423
1424 float Simulator::getFpuRegisterFloat(int fpureg) const {
1425 MOZ_ASSERT((fpureg >= 0) &&
1426 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1427 return *mozilla::BitwiseCast<float*>(&FPUregisters_[fpureg]);
1428 }
1429
1430 double Simulator::getFpuRegisterDouble(int fpureg) const {
1431 MOZ_ASSERT((fpureg >= 0) &&
1432 (fpureg < Simulator::FPURegister::kNumFPURegisters));
1433 return *mozilla::BitwiseCast<double*>(&FPUregisters_[fpureg]);
1434 }
1435
1436 void Simulator::setCallResultDouble(double result) {
1437 setFpuRegisterDouble(f0, result);
1438 }
1439
1440 void Simulator::setCallResultFloat(float result) {
1441 setFpuRegisterFloat(f0, result);
1442 }
1443
1444 void Simulator::setCallResult(int64_t res) { setRegister(v0, res); }
1445 #ifdef XP_DARWIN
1446 // add a dedicated setCallResult for intptr_t on Darwin
1447 void Simulator::setCallResult(intptr_t res) { setRegister(v0, I64(res)); }
1448 #endif
1449 void Simulator::setCallResult(__int128_t res) {
1450 setRegister(v0, I64(res));
1451 setRegister(v1, I64(res >> 64));
1452 }
1453
1454 // Helper functions for setting and testing the FCSR register's bits.
1455 void Simulator::setFCSRBit(uint32_t cc, bool value) {
1456 if (value) {
1457 FCSR_ |= (1 << cc);
1458 } else {
1459 FCSR_ &= ~(1 << cc);
1460 }
1461 }
1462
1463 bool Simulator::testFCSRBit(uint32_t cc) { return FCSR_ & (1 << cc); }
1464
1465 // Sets the rounding error codes in FCSR based on the result of the rounding.
1466 // Returns true if the operation was invalid.
1467 template <typename T>
1468 bool Simulator::setFCSRRoundError(double original, double rounded) {
1469 bool ret = false;
1470
1471 setFCSRBit(kFCSRInexactCauseBit, false);
1472 setFCSRBit(kFCSRUnderflowCauseBit, false);
1473 setFCSRBit(kFCSROverflowCauseBit, false);
1474 setFCSRBit(kFCSRInvalidOpCauseBit, false);
1475
1476 if (!std::isfinite(original) || !std::isfinite(rounded)) {
1477 setFCSRBit(kFCSRInvalidOpFlagBit, true);
1478 setFCSRBit(kFCSRInvalidOpCauseBit, true);
1479 ret = true;
1480 }
1481
1482 if (original != rounded) {
1483 setFCSRBit(kFCSRInexactFlagBit, true);
1484 setFCSRBit(kFCSRInexactCauseBit, true);
1485 }
1486
1487 if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) {
1488 setFCSRBit(kFCSRUnderflowFlagBit, true);
1489 setFCSRBit(kFCSRUnderflowCauseBit, true);
1490 ret = true;
1491 }
1492
1493 if ((long double)rounded > (long double)std::numeric_limits<T>::max() ||
1494 (long double)rounded < (long double)std::numeric_limits<T>::min()) {
1495 setFCSRBit(kFCSROverflowFlagBit, true);
1496 setFCSRBit(kFCSROverflowCauseBit, true);
1497 // The reference is not really clear but it seems this is required:
1498 setFCSRBit(kFCSRInvalidOpFlagBit, true);
1499 setFCSRBit(kFCSRInvalidOpCauseBit, true);
1500 ret = true;
1501 }
1502
1503 return ret;
1504 }
1505
1506 // Raw access to the PC register.
1507 void Simulator::set_pc(int64_t value) {
1508 pc_modified_ = true;
1509 registers_[pc] = value;
1510 }
1511
1512 bool Simulator::has_bad_pc() const {
1513 return ((registers_[pc] == bad_ra) || (registers_[pc] == end_sim_pc));
1514 }
1515
1516 // Raw access to the PC register without the special adjustment when reading.
1517 int64_t Simulator::get_pc() const { return registers_[pc]; }
1518
1519 JS::ProfilingFrameIterator::RegisterState Simulator::registerState() {
1520 wasm::RegisterState state;
1521 state.pc = (void*)get_pc();
1522 state.fp = (void*)getRegister(fp);
1523 state.sp = (void*)getRegister(sp);
1524 state.lr = (void*)getRegister(ra);
1525 return state;
1526 }
1527
1528 static bool AllowUnaligned() {
1529 static bool hasReadFlag = false;
1530 static bool unalignedAllowedFlag = false;
1531 if (!hasReadFlag) {
1532 unalignedAllowedFlag = !!getenv("MIPS_UNALIGNED");
1533 hasReadFlag = true;
1534 }
1535 return unalignedAllowedFlag;
1536 }
1537
1538 // MIPS memory instructions (except lw(d)l/r , sw(d)l/r) trap on unaligned
1539 // memory access enabling the OS to handle them via trap-and-emulate. Note that
1540 // simulator runs have the runtime system running directly on the host system
1541 // and only generated code is executed in the simulator. Since the host is
1542 // typically IA32 it will not trap on unaligned memory access. We assume that
1543 // that executing correct generated code will not produce unaligned memory
1544 // access, so we explicitly check for address alignment and trap. Note that
1545 // trapping does not occur when executing wasm code, which requires that
1546 // unaligned memory access provides correct result.
1547
1548 uint8_t Simulator::readBU(uint64_t addr, SimInstruction* instr) {
1549 if (handleWasmSegFault(addr, 1)) {
1550 return 0xff;
1551 }
1552
1553 uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
1554 return *ptr;
1555 }
1556
1557 int8_t Simulator::readB(uint64_t addr, SimInstruction* instr) {
1558 if (handleWasmSegFault(addr, 1)) {
1559 return -1;
1560 }
1561
1562 int8_t* ptr = reinterpret_cast<int8_t*>(addr);
1563 return *ptr;
1564 }
1565
1566 void Simulator::writeB(uint64_t addr, uint8_t value, SimInstruction* instr) {
1567 if (handleWasmSegFault(addr, 1)) {
1568 return;
1569 }
1570
1571 uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
1572 *ptr = value;
1573 }
1574
1575 void Simulator::writeB(uint64_t addr, int8_t value, SimInstruction* instr) {
1576 if (handleWasmSegFault(addr, 1)) {
1577 return;
1578 }
1579
1580 int8_t* ptr = reinterpret_cast<int8_t*>(addr);
1581 *ptr = value;
1582 }
1583
1584 uint16_t Simulator::readHU(uint64_t addr, SimInstruction* instr) {
1585 if (handleWasmSegFault(addr, 2)) {
1586 return 0xffff;
1587 }
1588
1589 if (AllowUnaligned() || (addr & 1) == 0 ||
1590 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1591 uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
1592 return *ptr;
1593 }
1594 printf("Unaligned unsigned halfword read at 0x%016" PRIx64
1595 ", pc=0x%016" PRIxPTR "\n",
1596 addr, reinterpret_cast<intptr_t>(instr));
1597 MOZ_CRASH();
1598 return 0;
1599 }
1600
1601 int16_t Simulator::readH(uint64_t addr, SimInstruction* instr) {
1602 if (handleWasmSegFault(addr, 2)) {
1603 return -1;
1604 }
1605
1606 if (AllowUnaligned() || (addr & 1) == 0 ||
1607 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1608 int16_t* ptr = reinterpret_cast<int16_t*>(addr);
1609 return *ptr;
1610 }
1611 printf("Unaligned signed halfword read at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR
1612 "\n",
1613 addr, reinterpret_cast<intptr_t>(instr));
1614 MOZ_CRASH();
1615 return 0;
1616 }
1617
1618 void Simulator::writeH(uint64_t addr, uint16_t value, SimInstruction* instr) {
1619 if (handleWasmSegFault(addr, 2)) {
1620 return;
1621 }
1622
1623 if (AllowUnaligned() || (addr & 1) == 0 ||
1624 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1625 uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
1626 LLBit_ = false;
1627 *ptr = value;
1628 return;
1629 }
1630 printf("Unaligned unsigned halfword write at 0x%016" PRIx64
1631 ", pc=0x%016" PRIxPTR "\n",
1632 addr, reinterpret_cast<intptr_t>(instr));
1633 MOZ_CRASH();
1634 }
1635
1636 void Simulator::writeH(uint64_t addr, int16_t value, SimInstruction* instr) {
1637 if (handleWasmSegFault(addr, 2)) {
1638 return;
1639 }
1640
1641 if (AllowUnaligned() || (addr & 1) == 0 ||
1642 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1643 int16_t* ptr = reinterpret_cast<int16_t*>(addr);
1644 LLBit_ = false;
1645 *ptr = value;
1646 return;
1647 }
1648 printf("Unaligned halfword write at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n",
1649 addr, reinterpret_cast<intptr_t>(instr));
1650 MOZ_CRASH();
1651 }
1652
1653 uint32_t Simulator::readWU(uint64_t addr, SimInstruction* instr) {
1654 if (handleWasmSegFault(addr, 4)) {
1655 return -1;
1656 }
1657
1658 if (AllowUnaligned() || (addr & 3) == 0 ||
1659 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1660 uint32_t* ptr = reinterpret_cast<uint32_t*>(addr);
1661 return *ptr;
1662 }
1663 printf("Unaligned read at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
1664 reinterpret_cast<intptr_t>(instr));
1665 MOZ_CRASH();
1666 return 0;
1667 }
1668
1669 int32_t Simulator::readW(uint64_t addr, SimInstruction* instr) {
1670 if (handleWasmSegFault(addr, 4)) {
1671 return -1;
1672 }
1673
1674 if (AllowUnaligned() || (addr & 3) == 0 ||
1675 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1676 int32_t* ptr = reinterpret_cast<int32_t*>(addr);
1677 return *ptr;
1678 }
1679 printf("Unaligned read at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
1680 reinterpret_cast<intptr_t>(instr));
1681 MOZ_CRASH();
1682 return 0;
1683 }
1684
1685 void Simulator::writeW(uint64_t addr, uint32_t value, SimInstruction* instr) {
1686 if (handleWasmSegFault(addr, 4)) {
1687 return;
1688 }
1689
1690 if (AllowUnaligned() || (addr & 3) == 0 ||
1691 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1692 uint32_t* ptr = reinterpret_cast<uint32_t*>(addr);
1693 LLBit_ = false;
1694 *ptr = value;
1695 return;
1696 }
1697 printf("Unaligned write at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
1698 reinterpret_cast<intptr_t>(instr));
1699 MOZ_CRASH();
1700 }
1701
1702 void Simulator::writeW(uint64_t addr, int32_t value, SimInstruction* instr) {
1703 if (handleWasmSegFault(addr, 4)) {
1704 return;
1705 }
1706
1707 if (AllowUnaligned() || (addr & 3) == 0 ||
1708 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1709 int32_t* ptr = reinterpret_cast<int32_t*>(addr);
1710 LLBit_ = false;
1711 *ptr = value;
1712 return;
1713 }
1714 printf("Unaligned write at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
1715 reinterpret_cast<intptr_t>(instr));
1716 MOZ_CRASH();
1717 }
1718
1719 int64_t Simulator::readDW(uint64_t addr, SimInstruction* instr) {
1720 if (handleWasmSegFault(addr, 8)) {
1721 return -1;
1722 }
1723
1724 if (AllowUnaligned() || (addr & kPointerAlignmentMask) == 0 ||
1725 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1726 intptr_t* ptr = reinterpret_cast<intptr_t*>(addr);
1727 return *ptr;
1728 }
1729 printf("Unaligned read at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
1730 reinterpret_cast<intptr_t>(instr));
1731 MOZ_CRASH();
1732 return 0;
1733 }
1734
1735 void Simulator::writeDW(uint64_t addr, int64_t value, SimInstruction* instr) {
1736 if (handleWasmSegFault(addr, 8)) {
1737 return;
1738 }
1739
1740 if (AllowUnaligned() || (addr & kPointerAlignmentMask) == 0 ||
1741 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1742 int64_t* ptr = reinterpret_cast<int64_t*>(addr);
1743 LLBit_ = false;
1744 *ptr = value;
1745 return;
1746 }
1747 printf("Unaligned write at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
1748 reinterpret_cast<intptr_t>(instr));
1749 MOZ_CRASH();
1750 }
1751
1752 double Simulator::readD(uint64_t addr, SimInstruction* instr) {
1753 if (handleWasmSegFault(addr, 8)) {
1754 return NAN;
1755 }
1756
1757 if (AllowUnaligned() || (addr & kDoubleAlignmentMask) == 0 ||
1758 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1759 double* ptr = reinterpret_cast<double*>(addr);
1760 return *ptr;
1761 }
1762 printf("Unaligned (double) read at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n",
1763 addr, reinterpret_cast<intptr_t>(instr));
1764 MOZ_CRASH();
1765 return 0;
1766 }
1767
1768 void Simulator::writeD(uint64_t addr, double value, SimInstruction* instr) {
1769 if (handleWasmSegFault(addr, 8)) {
1770 return;
1771 }
1772
1773 if (AllowUnaligned() || (addr & kDoubleAlignmentMask) == 0 ||
1774 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1775 double* ptr = reinterpret_cast<double*>(addr);
1776 LLBit_ = false;
1777 *ptr = value;
1778 return;
1779 }
1780 printf("Unaligned (double) write at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n",
1781 addr, reinterpret_cast<intptr_t>(instr));
1782 MOZ_CRASH();
1783 }
1784
1785 int Simulator::loadLinkedW(uint64_t addr, SimInstruction* instr) {
1786 if ((addr & 3) == 0) {
1787 if (handleWasmSegFault(addr, 4)) {
1788 return -1;
1789 }
1790
1791 volatile int32_t* ptr = reinterpret_cast<volatile int32_t*>(addr);
1792 int32_t value = *ptr;
1793 lastLLValue_ = value;
1794 LLAddr_ = addr;
1795 // Note that any memory write or "external" interrupt should reset this
1796 // value to false.
1797 LLBit_ = true;
1798 return value;
1799 }
1800 printf("Unaligned write at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
1801 reinterpret_cast<intptr_t>(instr));
1802 MOZ_CRASH();
1803 return 0;
1804 }
1805
1806 int Simulator::storeConditionalW(uint64_t addr, int value,
1807 SimInstruction* instr) {
1808 // Correct behavior in this case, as defined by architecture, is to just
1809 // return 0, but there is no point at allowing that. It is certainly an
1810 // indicator of a bug.
1811 if (addr != LLAddr_) {
1812 printf("SC to bad address: 0x%016" PRIx64 ", pc=0x%016" PRIxPTR
1813 ", expected: 0x%016" PRIxPTR "\n",
1814 addr, reinterpret_cast<intptr_t>(instr), LLAddr_);
1815 MOZ_CRASH();
1816 }
1817
1818 if ((addr & 3) == 0) {
1819 SharedMem<int32_t*> ptr =
1820 SharedMem<int32_t*>::shared(reinterpret_cast<int32_t*>(addr));
1821
1822 if (!LLBit_) {
1823 return 0;
1824 }
1825
1826 LLBit_ = false;
1827 LLAddr_ = 0;
1828 int32_t expected = int32_t(lastLLValue_);
1829 int32_t old =
1830 AtomicOperations::compareExchangeSeqCst(ptr, expected, int32_t(value));
1831 return (old == expected) ? 1 : 0;
1832 }
1833 printf("Unaligned SC at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
1834 reinterpret_cast<intptr_t>(instr));
1835 MOZ_CRASH();
1836 return 0;
1837 }
1838
1839 int64_t Simulator::loadLinkedD(uint64_t addr, SimInstruction* instr) {
1840 if ((addr & kPointerAlignmentMask) == 0) {
1841 if (handleWasmSegFault(addr, 8)) {
1842 return -1;
1843 }
1844
1845 volatile int64_t* ptr = reinterpret_cast<volatile int64_t*>(addr);
1846 int64_t value = *ptr;
1847 lastLLValue_ = value;
1848 LLAddr_ = addr;
1849 // Note that any memory write or "external" interrupt should reset this
1850 // value to false.
1851 LLBit_ = true;
1852 return value;
1853 }
1854 printf("Unaligned write at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
1855 reinterpret_cast<intptr_t>(instr));
1856 MOZ_CRASH();
1857 return 0;
1858 }
1859
1860 int Simulator::storeConditionalD(uint64_t addr, int64_t value,
1861 SimInstruction* instr) {
1862 // Correct behavior in this case, as defined by architecture, is to just
1863 // return 0, but there is no point at allowing that. It is certainly an
1864 // indicator of a bug.
1865 if (addr != LLAddr_) {
1866 printf("SC to bad address: 0x%016" PRIx64 ", pc=0x%016" PRIxPTR
1867 ", expected: 0x%016" PRIxPTR "\n",
1868 addr, reinterpret_cast<intptr_t>(instr), LLAddr_);
1869 MOZ_CRASH();
1870 }
1871
1872 if ((addr & kPointerAlignmentMask) == 0) {
1873 SharedMem<int64_t*> ptr =
1874 SharedMem<int64_t*>::shared(reinterpret_cast<int64_t*>(addr));
1875
1876 if (!LLBit_) {
1877 return 0;
1878 }
1879
1880 LLBit_ = false;
1881 LLAddr_ = 0;
1882 int64_t expected = lastLLValue_;
1883 int64_t old =
1884 AtomicOperations::compareExchangeSeqCst(ptr, expected, int64_t(value));
1885 return (old == expected) ? 1 : 0;
1886 }
1887 printf("Unaligned SC at 0x%016" PRIx64 ", pc=0x%016" PRIxPTR "\n", addr,
1888 reinterpret_cast<intptr_t>(instr));
1889 MOZ_CRASH();
1890 return 0;
1891 }
1892
1893 uintptr_t Simulator::stackLimit() const { return stackLimit_; }
1894
1895 uintptr_t* Simulator::addressOfStackLimit() { return &stackLimit_; }
1896
1897 bool Simulator::overRecursed(uintptr_t newsp) const {
1898 if (newsp == 0) {
1899 newsp = getRegister(sp);
1900 }
1901 return newsp <= stackLimit();
1902 }
1903
1904 bool Simulator::overRecursedWithExtra(uint32_t extra) const {
1905 uintptr_t newsp = getRegister(sp) - extra;
1906 return newsp <= stackLimit();
1907 }
1908
1909 // Unsupported instructions use format to print an error and stop execution.
1910 void Simulator::format(SimInstruction* instr, const char* format) {
1911 printf("Simulator found unsupported instruction:\n 0x%016lx: %s\n",
1912 reinterpret_cast<intptr_t>(instr), format);
1913 MOZ_CRASH();
1914 }
1915
1916 // Note: With the code below we assume that all runtime calls return a 64 bits
1917 // result. If they don't, the v1 result register contains a bogus value, which
1918 // is fine because it is caller-saved.
1919 ABI_FUNCTION_TYPE_SIM_PROTOTYPES
1920
1921 // Software interrupt instructions are used by the simulator to call into C++.
1922 void Simulator::softwareInterrupt(SimInstruction* instr) {
1923 int32_t func = instr->functionFieldRaw();
1924 uint32_t code = (func == ff_break) ? instr->bits(25, 6) : -1;
1925
1926 // We first check if we met a call_rt_redirected.
1927 if (instr->instructionBits() == kCallRedirInstr) {
1928 #if !defined(USES_N64_ABI)
1929 MOZ_CRASH("Only N64 ABI supported.");
1930 #else
1931 Redirection* redirection = Redirection::FromSwiInstruction(instr);
1932 uintptr_t nativeFn =
1933 reinterpret_cast<uintptr_t>(redirection->nativeFunction());
1934
1935 // Get the SP for reading stack arguments
1936 int64_t* sp_ = reinterpret_cast<int64_t*>(getRegister(sp));
1937
1938 // Store argument register values in local variables for ease of use below.
1939 int64_t a0_ = getRegister(a0);
1940 int64_t a1_ = getRegister(a1);
1941 int64_t a2_ = getRegister(a2);
1942 int64_t a3_ = getRegister(a3);
1943 int64_t a4_ = getRegister(a4);
1944 int64_t a5_ = getRegister(a5);
1945 int64_t a6_ = getRegister(a6);
1946 int64_t a7_ = getRegister(a7);
1947 float f12_s = getFpuRegisterFloat(f12);
1948 float f13_s = getFpuRegisterFloat(f13);
1949 float f14_s = getFpuRegisterFloat(f14);
1950 float f15_s = getFpuRegisterFloat(f15);
1951 float f16_s = getFpuRegisterFloat(f16);
1952 float f17_s = getFpuRegisterFloat(f17);
1953 float f18_s = getFpuRegisterFloat(f18);
1954 double f12_d = getFpuRegisterDouble(f12);
1955 double f13_d = getFpuRegisterDouble(f13);
1956 double f14_d = getFpuRegisterDouble(f14);
1957 double f15_d = getFpuRegisterDouble(f15);
1958
1959 // This is dodgy but it works because the C entry stubs are never moved.
1960 // See comment in codegen-arm.cc and bug 1242173.
1961 int64_t saved_ra = getRegister(ra);
1962
1963 bool stack_aligned = (getRegister(sp) & (ABIStackAlignment - 1)) == 0;
1964 if (!stack_aligned) {
1965 fprintf(stderr, "Runtime call with unaligned stack!\n");
1966 MOZ_CRASH();
1967 }
1968
1969 if (single_stepping_) {
1970 single_step_callback_(single_step_callback_arg_, this, nullptr);
1971 }
1972
1973 switch (redirection->type()) {
1974 ABI_FUNCTION_TYPE_MIPS64_SIM_DISPATCH
1975
1976 default:
1977 MOZ_CRASH("Unknown function type.");
1978 }
1979
1980 if (single_stepping_) {
1981 single_step_callback_(single_step_callback_arg_, this, nullptr);
1982 }
1983
1984 setRegister(ra, saved_ra);
1985 set_pc(getRegister(ra));
1986 #endif
1987 } else if (func == ff_break && code <= kMaxStopCode) {
1988 if (isWatchpoint(code)) {
1989 printWatchpoint(code);
1990 } else {
1991 increaseStopCounter(code);
1992 handleStop(code, instr);
1993 }
1994 } else {
1995 switch (func) {
1996 case ff_tge:
1997 case ff_tgeu:
1998 case ff_tlt:
1999 case ff_tltu:
2000 case ff_teq:
2001 case ff_tne:
2002 if (instr->bits(15, 6) == kWasmTrapCode) {
2003 uint8_t* newPC;
2004 if (wasm::HandleIllegalInstruction(registerState(), &newPC)) {
2005 set_pc(int64_t(newPC));
2006 return;
2007 }
2008 }
2009 };
2010 // All remaining break_ codes, and all traps are handled here.
2011 MipsDebugger dbg(this);
2012 dbg.debug();
2013 }
2014 }
2015
2016 // Stop helper functions.
2017 bool Simulator::isWatchpoint(uint32_t code) {
2018 return (code <= kMaxWatchpointCode);
2019 }
2020
2021 void Simulator::printWatchpoint(uint32_t code) {
2022 MipsDebugger dbg(this);
2023 ++break_count_;
2024 printf("\n---- break %d marker: %20" PRIi64 " (instr count: %20" PRIi64
2025 ") ----\n",
2026 code, break_count_, icount_);
2027 dbg.printAllRegs(); // Print registers and continue running.
2028 }
2029
2030 void Simulator::handleStop(uint32_t code, SimInstruction* instr) {
2031 // Stop if it is enabled, otherwise go on jumping over the stop
2032 // and the message address.
2033 if (isEnabledStop(code)) {
2034 MipsDebugger dbg(this);
2035 dbg.stop(instr);
2036 } else {
2037 set_pc(get_pc() + 2 * SimInstruction::kInstrSize);
2038 }
2039 }
2040
2041 bool Simulator::isStopInstruction(SimInstruction* instr) {
2042 int32_t func = instr->functionFieldRaw();
2043 uint32_t code = U32(instr->bits(25, 6));
2044 return (func == ff_break) && code > kMaxWatchpointCode &&
2045 code <= kMaxStopCode;
2046 }
2047
2048 bool Simulator::isEnabledStop(uint32_t code) {
2049 MOZ_ASSERT(code <= kMaxStopCode);
2050 MOZ_ASSERT(code > kMaxWatchpointCode);
2051 return !(watchedStops_[code].count_ & kStopDisabledBit);
2052 }
2053
2054 void Simulator::enableStop(uint32_t code) {
2055 if (!isEnabledStop(code)) {
2056 watchedStops_[code].count_ &= ~kStopDisabledBit;
2057 }
2058 }
2059
2060 void Simulator::disableStop(uint32_t code) {
2061 if (isEnabledStop(code)) {
2062 watchedStops_[code].count_ |= kStopDisabledBit;
2063 }
2064 }
2065
2066 void Simulator::increaseStopCounter(uint32_t code) {
2067 MOZ_ASSERT(code <= kMaxStopCode);
2068 if ((watchedStops_[code].count_ & ~(1 << 31)) == 0x7fffffff) {
2069 printf(
2070 "Stop counter for code %i has overflowed.\n"
2071 "Enabling this code and reseting the counter to 0.\n",
2072 code);
2073 watchedStops_[code].count_ = 0;
2074 enableStop(code);
2075 } else {
2076 watchedStops_[code].count_++;
2077 }
2078 }
2079
2080 // Print a stop status.
2081 void Simulator::printStopInfo(uint32_t code) {
2082 if (code <= kMaxWatchpointCode) {
2083 printf("That is a watchpoint, not a stop.\n");
2084 return;
2085 } else if (code > kMaxStopCode) {
2086 printf("Code too large, only %u stops can be used\n", kMaxStopCode + 1);
2087 return;
2088 }
2089 const char* state = isEnabledStop(code) ? "Enabled" : "Disabled";
2090 int32_t count = watchedStops_[code].count_ & ~kStopDisabledBit;
2091 // Don't print the state of unused breakpoints.
2092 if (count != 0) {
2093 if (watchedStops_[code].desc_) {
2094 printf("stop %i - 0x%x: \t%s, \tcounter = %i, \t%s\n", code, code, state,
2095 count, watchedStops_[code].desc_);
2096 } else {
2097 printf("stop %i - 0x%x: \t%s, \tcounter = %i\n", code, code, state,
2098 count);
2099 }
2100 }
2101 }
2102
2103 void Simulator::signalExceptions() {
2104 for (int i = 1; i < kNumExceptions; i++) {
2105 if (exceptions[i] != 0) {
2106 MOZ_CRASH("Error: Exception raised.");
2107 }
2108 }
2109 }
2110
2111 // Helper function for decodeTypeRegister.
2112 void Simulator::configureTypeRegister(SimInstruction* instr, int64_t& alu_out,
2113 __int128& i128hilo,
2114 unsigned __int128& u128hilo,
2115 int64_t& next_pc,
2116 int32_t& return_addr_reg,
2117 bool& do_interrupt) {
2118 // Every local variable declared here needs to be const.
2119 // This is to make sure that changed values are sent back to
2120 // decodeTypeRegister correctly.
2121
2122 // Instruction fields.
2123 const OpcodeField op = instr->opcodeFieldRaw();
2124 const int32_t rs_reg = instr->rsValue();
2125 const int64_t rs = getRegister(rs_reg);
2126 const int32_t rt_reg = instr->rtValue();
2127 const int64_t rt = getRegister(rt_reg);
2128 const int32_t rd_reg = instr->rdValue();
2129 const uint32_t sa = instr->saValue();
2130
2131 const int32_t fs_reg = instr->fsValue();
2132 __int128 temp;
2133
2134 // ---------- Configuration.
2135 switch (op) {
2136 case op_cop1: // Coprocessor instructions.
2137 switch (instr->rsFieldRaw()) {
2138 case rs_bc1: // Handled in DecodeTypeImmed, should never come here.
2139 MOZ_CRASH();
2140 break;
2141 case rs_cfc1:
2142 // At the moment only FCSR is supported.
2143 MOZ_ASSERT(fs_reg == kFCSRRegister);
2144 alu_out = FCSR_;
2145 break;
2146 case rs_mfc1:
2147 alu_out = getFpuRegisterLo(fs_reg);
2148 break;
2149 case rs_dmfc1:
2150 alu_out = getFpuRegister(fs_reg);
2151 break;
2152 case rs_mfhc1:
2153 alu_out = getFpuRegisterHi(fs_reg);
2154 break;
2155 case rs_ctc1:
2156 case rs_mtc1:
2157 case rs_dmtc1:
2158 case rs_mthc1:
2159 // Do the store in the execution step.
2160 break;
2161 case rs_s:
2162 case rs_d:
2163 case rs_w:
2164 case rs_l:
2165 case rs_ps:
2166 // Do everything in the execution step.
2167 break;
2168 default:
2169 MOZ_CRASH();
2170 };
2171 break;
2172 case op_cop1x:
2173 break;
2174 case op_special:
2175 switch (instr->functionFieldRaw()) {
2176 case ff_jr:
2177 case ff_jalr:
2178 next_pc = getRegister(instr->rsValue());
2179 return_addr_reg = instr->rdValue();
2180 break;
2181 case ff_sll:
2182 alu_out = I64(I32(rt) << sa);
2183 break;
2184 case ff_dsll:
2185 alu_out = rt << sa;
2186 break;
2187 case ff_dsll32:
2188 alu_out = rt << (sa + 32);
2189 break;
2190 case ff_srl:
2191 if (rs_reg == 0) {
2192 // Regular logical right shift of a word by a fixed number of
2193 // bits instruction. RS field is always equal to 0.
2194 alu_out = I64(I32(U32(I32_CHECK(rt)) >> sa));
2195 } else {
2196 // Logical right-rotate of a word by a fixed number of bits. This
2197 // is special case of SRL instruction, added in MIPS32 Release 2.
2198 // RS field is equal to 00001.
2199 alu_out = I64(I32((U32(I32_CHECK(rt)) >> sa) |
2200 (U32(I32_CHECK(rt)) << (32 - sa))));
2201 }
2202 break;
2203 case ff_dsrl:
2204 if (rs_reg == 0) {
2205 // Regular logical right shift of a double word by a fixed number of
2206 // bits instruction. RS field is always equal to 0.
2207 alu_out = U64(rt) >> sa;
2208 } else {
2209 // Logical right-rotate of a word by a fixed number of bits. This
2210 // is special case of DSRL instruction, added in MIPS64 Release 2.
2211 // RS field is equal to 00001.
2212 alu_out = (U64(rt) >> sa) | (U64(rt) << (64 - sa));
2213 }
2214 break;
2215 case ff_dsrl32:
2216 if (rs_reg == 0) {
2217 // Regular logical right shift of a double word by a fixed number of
2218 // bits instruction. RS field is always equal to 0.
2219 alu_out = U64(rt) >> (sa + 32);
2220 } else {
2221 // Logical right-rotate of a double word by a fixed number of bits.
2222 // This is special case of DSRL instruction, added in MIPS64
2223 // Release 2. RS field is equal to 00001.
2224 alu_out = (U64(rt) >> (sa + 32)) | (U64(rt) << (64 - (sa + 32)));
2225 }
2226 break;
2227 case ff_sra:
2228 alu_out = I64(I32_CHECK(rt)) >> sa;
2229 break;
2230 case ff_dsra:
2231 alu_out = rt >> sa;
2232 break;
2233 case ff_dsra32:
2234 alu_out = rt >> (sa + 32);
2235 break;
2236 case ff_sllv:
2237 alu_out = I64(I32(rt) << rs);
2238 break;
2239 case ff_dsllv:
2240 alu_out = rt << rs;
2241 break;
2242 case ff_srlv:
2243 if (sa == 0) {
2244 // Regular logical right-shift of a word by a variable number of
2245 // bits instruction. SA field is always equal to 0.
2246 alu_out = I64(I32(U32(I32_CHECK(rt)) >> rs));
2247 } else {
2248 // Logical right-rotate of a word by a variable number of bits.
2249 // This is special case od SRLV instruction, added in MIPS32
2250 // Release 2. SA field is equal to 00001.
2251 alu_out = I64(I32((U32(I32_CHECK(rt)) >> rs) |
2252 (U32(I32_CHECK(rt)) << (32 - rs))));
2253 }
2254 break;
2255 case ff_dsrlv:
2256 if (sa == 0) {
2257 // Regular logical right-shift of a double word by a variable number
2258 // of bits instruction. SA field is always equal to 0.
2259 alu_out = U64(rt) >> rs;
2260 } else {
2261 // Logical right-rotate of a double word by a variable number of
2262 // bits. This is special case od DSRLV instruction, added in MIPS64
2263 // Release 2. SA field is equal to 00001.
2264 alu_out = (U64(rt) >> rs) | (U64(rt) << (64 - rs));
2265 }
2266 break;
2267 case ff_srav:
2268 alu_out = I64(I32_CHECK(rt) >> rs);
2269 break;
2270 case ff_dsrav:
2271 alu_out = rt >> rs;
2272 break;
2273 case ff_mfhi:
2274 alu_out = getRegister(HI);
2275 break;
2276 case ff_mflo:
2277 alu_out = getRegister(LO);
2278 break;
2279 case ff_mult:
2280 i128hilo = I64(U32(I32_CHECK(rs))) * I64(U32(I32_CHECK(rt)));
2281 break;
2282 case ff_dmult:
2283 i128hilo = I128(rs) * I128(rt);
2284 break;
2285 case ff_multu:
2286 u128hilo = U64(U32(I32_CHECK(rs))) * U64(U32(I32_CHECK(rt)));
2287 break;
2288 case ff_dmultu:
2289 u128hilo = U128(rs) * U128(rt);
2290 break;
2291 case ff_add:
2292 alu_out = I32_CHECK(rs) + I32_CHECK(rt);
2293 if ((alu_out << 32) != (alu_out << 31)) {
2294 exceptions[kIntegerOverflow] = 1;
2295 }
2296 alu_out = I32(alu_out);
2297 break;
2298 case ff_dadd:
2299 temp = I128(rs) + I128(rt);
2300 if ((temp << 64) != (temp << 63)) {
2301 exceptions[kIntegerOverflow] = 1;
2302 }
2303 alu_out = I64(temp);
2304 break;
2305 case ff_addu:
2306 alu_out = I32(I32_CHECK(rs) + I32_CHECK(rt));
2307 break;
2308 case ff_daddu:
2309 alu_out = rs + rt;
2310 break;
2311 case ff_sub:
2312 alu_out = I32_CHECK(rs) - I32_CHECK(rt);
2313 if ((alu_out << 32) != (alu_out << 31)) {
2314 exceptions[kIntegerUnderflow] = 1;
2315 }
2316 alu_out = I32(alu_out);
2317 break;
2318 case ff_dsub:
2319 temp = I128(rs) - I128(rt);
2320 if ((temp << 64) != (temp << 63)) {
2321 exceptions[kIntegerUnderflow] = 1;
2322 }
2323 alu_out = I64(temp);
2324 break;
2325 case ff_subu:
2326 alu_out = I32(I32_CHECK(rs) - I32_CHECK(rt));
2327 break;
2328 case ff_dsubu:
2329 alu_out = rs - rt;
2330 break;
2331 case ff_and:
2332 alu_out = rs & rt;
2333 break;
2334 case ff_or:
2335 alu_out = rs | rt;
2336 break;
2337 case ff_xor:
2338 alu_out = rs ^ rt;
2339 break;
2340 case ff_nor:
2341 alu_out = ~(rs | rt);
2342 break;
2343 case ff_slt:
2344 alu_out = I64(rs) < I64(rt) ? 1 : 0;
2345 break;
2346 case ff_sltu:
2347 alu_out = U64(rs) < U64(rt) ? 1 : 0;
2348 break;
2349 case ff_sync:
2350 break;
2351 // Break and trap instructions.
2352 case ff_break:
2353 do_interrupt = true;
2354 break;
2355 case ff_tge:
2356 do_interrupt = rs >= rt;
2357 break;
2358 case ff_tgeu:
2359 do_interrupt = U64(rs) >= U64(rt);
2360 break;
2361 case ff_tlt:
2362 do_interrupt = rs < rt;
2363 break;
2364 case ff_tltu:
2365 do_interrupt = U64(rs) < U64(rt);
2366 break;
2367 case ff_teq:
2368 do_interrupt = rs == rt;
2369 break;
2370 case ff_tne:
2371 do_interrupt = rs != rt;
2372 break;
2373 case ff_movn:
2374 case ff_movz:
2375 case ff_movci:
2376 // No action taken on decode.
2377 break;
2378 case ff_div:
2379 if (I32_CHECK(rs) == INT_MIN && I32_CHECK(rt) == -1) {
2380 i128hilo = U32(INT_MIN);
2381 } else {
2382 uint32_t div = I32_CHECK(rs) / I32_CHECK(rt);
2383 uint32_t mod = I32_CHECK(rs) % I32_CHECK(rt);
2384 i128hilo = (I64(mod) << 32) | div;
2385 }
2386 break;
2387 case ff_ddiv:
2388 if (I64(rs) == INT64_MIN && I64(rt) == -1) {
2389 i128hilo = U64(INT64_MIN);
2390 } else {
2391 uint64_t div = rs / rt;
2392 uint64_t mod = rs % rt;
2393 i128hilo = (I128(mod) << 64) | div;
2394 }
2395 break;
2396 case ff_divu: {
2397 uint32_t div = U32(I32_CHECK(rs)) / U32(I32_CHECK(rt));
2398 uint32_t mod = U32(I32_CHECK(rs)) % U32(I32_CHECK(rt));
2399 i128hilo = (U64(mod) << 32) | div;
2400 } break;
2401 case ff_ddivu:
2402 if (0 == rt) {
2403 i128hilo = (I128(Unpredictable) << 64) | I64(Unpredictable);
2404 } else {
2405 uint64_t div = U64(rs) / U64(rt);
2406 uint64_t mod = U64(rs) % U64(rt);
2407 i128hilo = (I128(mod) << 64) | div;
2408 }
2409 break;
2410 default:
2411 MOZ_CRASH();
2412 };
2413 break;
2414 case op_special2:
2415 switch (instr->functionFieldRaw()) {
2416 case ff_mul:
2417 alu_out = I32(I32_CHECK(rs) *
2418 I32_CHECK(rt)); // Only the lower 32 bits are kept.
2419 break;
2420 case ff_clz:
2421 alu_out = U32(I32_CHECK(rs)) ? __builtin_clz(U32(I32_CHECK(rs))) : 32;
2422 break;
2423 case ff_dclz:
2424 alu_out = U64(rs) ? __builtin_clzl(U64(rs)) : 64;
2425 break;
2426 default:
2427 MOZ_CRASH();
2428 };
2429 break;
2430 case op_special3:
2431 switch (instr->functionFieldRaw()) {
2432 case ff_ins: { // Mips64r2 instruction.
2433 // Interpret rd field as 5-bit msb of insert.
2434 uint16_t msb = rd_reg;
2435 // Interpret sa field as 5-bit lsb of insert.
2436 uint16_t lsb = sa;
2437 uint16_t size = msb - lsb + 1;
2438 uint32_t mask = (1 << size) - 1;
2439 if (lsb > msb) {
2440 alu_out = Unpredictable;
2441 } else {
2442 alu_out = I32((U32(I32_CHECK(rt)) & ~(mask << lsb)) |
2443 ((U32(I32_CHECK(rs)) & mask) << lsb));
2444 }
2445 break;
2446 }
2447 case ff_dins: { // Mips64r2 instruction.
2448 // Interpret rd field as 5-bit msb of insert.
2449 uint16_t msb = rd_reg;
2450 // Interpret sa field as 5-bit lsb of insert.
2451 uint16_t lsb = sa;
2452 uint16_t size = msb - lsb + 1;
2453 uint64_t mask = (1ul << size) - 1;
2454 if (lsb > msb) {
2455 alu_out = Unpredictable;
2456 } else {
2457 alu_out = (U64(rt) & ~(mask << lsb)) | ((U64(rs) & mask) << lsb);
2458 }
2459 break;
2460 }
2461 case ff_dinsm: { // Mips64r2 instruction.
2462 // Interpret rd field as 5-bit msb of insert.
2463 uint16_t msb = rd_reg;
2464 // Interpret sa field as 5-bit lsb of insert.
2465 uint16_t lsb = sa;
2466 uint16_t size = msb - lsb + 33;
2467 uint64_t mask = (1ul << size) - 1;
2468 alu_out = (U64(rt) & ~(mask << lsb)) | ((U64(rs) & mask) << lsb);
2469 break;
2470 }
2471 case ff_dinsu: { // Mips64r2 instruction.
2472 // Interpret rd field as 5-bit msb of insert.
2473 uint16_t msb = rd_reg;
2474 // Interpret sa field as 5-bit lsb of insert.
2475 uint16_t lsb = sa + 32;
2476 uint16_t size = msb - lsb + 33;
2477 uint64_t mask = (1ul << size) - 1;
2478 if (sa > msb) {
2479 alu_out = Unpredictable;
2480 } else {
2481 alu_out = (U64(rt) & ~(mask << lsb)) | ((U64(rs) & mask) << lsb);
2482 }
2483 break;
2484 }
2485 case ff_ext: { // Mips64r2 instruction.
2486 // Interpret rd field as 5-bit msb of extract.
2487 uint16_t msb = rd_reg;
2488 // Interpret sa field as 5-bit lsb of extract.
2489 uint16_t lsb = sa;
2490 uint16_t size = msb + 1;
2491 uint32_t mask = (1 << size) - 1;
2492 if ((lsb + msb) > 31) {
2493 alu_out = Unpredictable;
2494 } else {
2495 alu_out = (U32(I32_CHECK(rs)) & (mask << lsb)) >> lsb;
2496 }
2497 break;
2498 }
2499 case ff_dext: { // Mips64r2 instruction.
2500 // Interpret rd field as 5-bit msb of extract.
2501 uint16_t msb = rd_reg;
2502 // Interpret sa field as 5-bit lsb of extract.
2503 uint16_t lsb = sa;
2504 uint16_t size = msb + 1;
2505 uint64_t mask = (1ul << size) - 1;
2506 alu_out = (U64(rs) & (mask << lsb)) >> lsb;
2507 break;
2508 }
2509 case ff_dextm: { // Mips64r2 instruction.
2510 // Interpret rd field as 5-bit msb of extract.
2511 uint16_t msb = rd_reg;
2512 // Interpret sa field as 5-bit lsb of extract.
2513 uint16_t lsb = sa;
2514 uint16_t size = msb + 33;
2515 uint64_t mask = (1ul << size) - 1;
2516 if ((lsb + msb + 32 + 1) > 64) {
2517 alu_out = Unpredictable;
2518 } else {
2519 alu_out = (U64(rs) & (mask << lsb)) >> lsb;
2520 }
2521 break;
2522 }
2523 case ff_dextu: { // Mips64r2 instruction.
2524 // Interpret rd field as 5-bit msb of extract.
2525 uint16_t msb = rd_reg;
2526 // Interpret sa field as 5-bit lsb of extract.
2527 uint16_t lsb = sa + 32;
2528 uint16_t size = msb + 1;
2529 uint64_t mask = (1ul << size) - 1;
2530 if ((lsb + msb + 1) > 64) {
2531 alu_out = Unpredictable;
2532 } else {
2533 alu_out = (U64(rs) & (mask << lsb)) >> lsb;
2534 }
2535 break;
2536 }
2537 case ff_bshfl: { // Mips32r2 instruction.
2538 if (16 == sa) { // seb
2539 alu_out = I64(I8(I32_CHECK(rt)));
2540 } else if (24 == sa) { // seh
2541 alu_out = I64(I16(I32_CHECK(rt)));
2542 } else if (2 == sa) { // wsbh
2543 uint32_t input = U32(I32_CHECK(rt));
2544 uint64_t output = 0;
2545
2546 uint32_t mask = 0xFF000000;
2547 for (int i = 0; i < 4; i++) {
2548 uint32_t tmp = mask & input;
2549 if (i % 2 == 0) {
2550 tmp = tmp >> 8;
2551 } else {
2552 tmp = tmp << 8;
2553 }
2554 output = output | tmp;
2555 mask = mask >> 8;
2556 }
2557 alu_out = I64(I32(output));
2558 } else {
2559 MOZ_CRASH();
2560 }
2561 break;
2562 }
2563 case ff_dbshfl: { // Mips64r2 instruction.
2564 uint64_t input = U64(rt);
2565 uint64_t output = 0;
2566
2567 if (2 == sa) { // dsbh
2568 uint64_t mask = 0xFF00000000000000;
2569 for (int i = 0; i < 8; i++) {
2570 uint64_t tmp = mask & input;
2571 if (i % 2 == 0)
2572 tmp = tmp >> 8;
2573 else
2574 tmp = tmp << 8;
2575
2576 output = output | tmp;
2577 mask = mask >> 8;
2578 }
2579 } else if (5 == sa) { // dshd
2580 uint64_t mask = 0xFFFF000000000000;
2581 for (int i = 0; i < 4; i++) {
2582 uint64_t tmp = mask & input;
2583 if (i == 0)
2584 tmp = tmp >> 48;
2585 else if (i == 1)
2586 tmp = tmp >> 16;
2587 else if (i == 2)
2588 tmp = tmp << 16;
2589 else
2590 tmp = tmp << 48;
2591 output = output | tmp;
2592 mask = mask >> 16;
2593 }
2594 } else {
2595 MOZ_CRASH();
2596 }
2597
2598 alu_out = I64(output);
2599 break;
2600 }
2601 default:
2602 MOZ_CRASH();
2603 };
2604 break;
2605 default:
2606 MOZ_CRASH();
2607 };
2608 }
2609
2610 // Handle execution based on instruction types.
2611 void Simulator::decodeTypeRegister(SimInstruction* instr) {
2612 // Instruction fields.
2613 const OpcodeField op = instr->opcodeFieldRaw();
2614 const int32_t rs_reg = instr->rsValue();
2615 const int64_t rs = getRegister(rs_reg);
2616 const int32_t rt_reg = instr->rtValue();
2617 const int64_t rt = getRegister(rt_reg);
2618 const int32_t rd_reg = instr->rdValue();
2619
2620 const int32_t fr_reg = instr->frValue();
2621 const int32_t fs_reg = instr->fsValue();
2622 const int32_t ft_reg = instr->ftValue();
2623 const int32_t fd_reg = instr->fdValue();
2624 __int128 i128hilo = 0;
2625 unsigned __int128 u128hilo = 0;
2626
2627 // ALU output.
2628 // It should not be used as is. Instructions using it should always
2629 // initialize it first.
2630 int64_t alu_out = 0x12345678;
2631
2632 // For break and trap instructions.
2633 bool do_interrupt = false;
2634
2635 // For jr and jalr.
2636 // Get current pc.
2637 int64_t current_pc = get_pc();
2638 // Next pc
2639 int64_t next_pc = 0;
2640 int32_t return_addr_reg = 31;
2641
2642 // Set up the variables if needed before executing the instruction.
2643 configureTypeRegister(instr, alu_out, i128hilo, u128hilo, next_pc,
2644 return_addr_reg, do_interrupt);
2645
2646 // ---------- Raise exceptions triggered.
2647 signalExceptions();
2648
2649 // ---------- Execution.
2650 switch (op) {
2651 case op_cop1:
2652 switch (instr->rsFieldRaw()) {
2653 case rs_bc1: // Branch on coprocessor condition.
2654 MOZ_CRASH();
2655 break;
2656 case rs_cfc1:
2657 setRegister(rt_reg, alu_out);
2658 [[fallthrough]];
2659 case rs_mfc1:
2660 setRegister(rt_reg, alu_out);
2661 break;
2662 case rs_dmfc1:
2663 setRegister(rt_reg, alu_out);
2664 break;
2665 case rs_mfhc1:
2666 setRegister(rt_reg, alu_out);
2667 break;
2668 case rs_ctc1:
2669 // At the moment only FCSR is supported.
2670 MOZ_ASSERT(fs_reg == kFCSRRegister);
2671 FCSR_ = registers_[rt_reg];
2672 break;
2673 case rs_mtc1:
2674 setFpuRegisterLo(fs_reg, registers_[rt_reg]);
2675 break;
2676 case rs_dmtc1:
2677 setFpuRegister(fs_reg, registers_[rt_reg]);
2678 break;
2679 case rs_mthc1:
2680 setFpuRegisterHi(fs_reg, registers_[rt_reg]);
2681 break;
2682 case rs_s:
2683 float f, ft_value, fs_value;
2684 uint32_t cc, fcsr_cc;
2685 int64_t i64;
2686 fs_value = getFpuRegisterFloat(fs_reg);
2687 ft_value = getFpuRegisterFloat(ft_reg);
2688 cc = instr->fcccValue();
2689 fcsr_cc = GetFCSRConditionBit(cc);
2690 switch (instr->functionFieldRaw()) {
2691 case ff_add_fmt:
2692 setFpuRegisterFloat(fd_reg, fs_value + ft_value);
2693 break;
2694 case ff_sub_fmt:
2695 setFpuRegisterFloat(fd_reg, fs_value - ft_value);
2696 break;
2697 case ff_mul_fmt:
2698 setFpuRegisterFloat(fd_reg, fs_value * ft_value);
2699 break;
2700 case ff_div_fmt:
2701 setFpuRegisterFloat(fd_reg, fs_value / ft_value);
2702 break;
2703 case ff_abs_fmt:
2704 setFpuRegisterFloat(fd_reg, fabsf(fs_value));
2705 break;
2706 case ff_mov_fmt:
2707 setFpuRegisterFloat(fd_reg, fs_value);
2708 break;
2709 case ff_neg_fmt:
2710 setFpuRegisterFloat(fd_reg, -fs_value);
2711 break;
2712 case ff_sqrt_fmt:
2713 setFpuRegisterFloat(fd_reg, sqrtf(fs_value));
2714 break;
2715 case ff_c_un_fmt:
2716 setFCSRBit(fcsr_cc, std::isnan(fs_value) || std::isnan(ft_value));
2717 break;
2718 case ff_c_eq_fmt:
2719 setFCSRBit(fcsr_cc, (fs_value == ft_value));
2720 break;
2721 case ff_c_ueq_fmt:
2722 setFCSRBit(fcsr_cc,
2723 (fs_value == ft_value) ||
2724 (std::isnan(fs_value) || std::isnan(ft_value)));
2725 break;
2726 case ff_c_olt_fmt:
2727 setFCSRBit(fcsr_cc, (fs_value < ft_value));
2728 break;
2729 case ff_c_ult_fmt:
2730 setFCSRBit(fcsr_cc,
2731 (fs_value < ft_value) ||
2732 (std::isnan(fs_value) || std::isnan(ft_value)));
2733 break;
2734 case ff_c_ole_fmt:
2735 setFCSRBit(fcsr_cc, (fs_value <= ft_value));
2736 break;
2737 case ff_c_ule_fmt:
2738 setFCSRBit(fcsr_cc,
2739 (fs_value <= ft_value) ||
2740 (std::isnan(fs_value) || std::isnan(ft_value)));
2741 break;
2742 case ff_cvt_d_fmt:
2743 f = getFpuRegisterFloat(fs_reg);
2744 setFpuRegisterDouble(fd_reg, static_cast<double>(f));
2745 break;
2746 case ff_cvt_w_fmt: // Convert float to word.
2747 // Rounding modes are not yet supported.
2748 MOZ_ASSERT((FCSR_ & 3) == 0);
2749 // In rounding mode 0 it should behave like ROUND.
2750 [[fallthrough]];
2751 case ff_round_w_fmt: { // Round double to word (round half to
2752 // even).
2753 float rounded = std::floor(fs_value + 0.5);
2754 int32_t result = I32(rounded);
2755 if ((result & 1) != 0 && result - fs_value == 0.5) {
2756 // If the number is halfway between two integers,
2757 // round to the even one.
2758 result--;
2759 }
2760 setFpuRegisterLo(fd_reg, result);
2761 if (setFCSRRoundError<int32_t>(fs_value, rounded)) {
2762 setFpuRegisterLo(fd_reg, kFPUInvalidResult);
2763 }
2764 break;
2765 }
2766 case ff_trunc_w_fmt: { // Truncate float to word (round towards 0).
2767 float rounded = truncf(fs_value);
2768 int32_t result = I32(rounded);
2769 setFpuRegisterLo(fd_reg, result);
2770 if (setFCSRRoundError<int32_t>(fs_value, rounded)) {
2771 setFpuRegisterLo(fd_reg, kFPUInvalidResult);
2772 }
2773 break;
2774 }
2775 case ff_floor_w_fmt: { // Round float to word towards negative
2776 // infinity.
2777 float rounded = std::floor(fs_value);
2778 int32_t result = I32(rounded);
2779 setFpuRegisterLo(fd_reg, result);
2780 if (setFCSRRoundError<int32_t>(fs_value, rounded)) {
2781 setFpuRegisterLo(fd_reg, kFPUInvalidResult);
2782 }
2783 break;
2784 }
2785 case ff_ceil_w_fmt: { // Round double to word towards positive
2786 // infinity.
2787 float rounded = std::ceil(fs_value);
2788 int32_t result = I32(rounded);
2789 setFpuRegisterLo(fd_reg, result);
2790 if (setFCSRRoundError<int32_t>(fs_value, rounded)) {
2791 setFpuRegisterLo(fd_reg, kFPUInvalidResult);
2792 }
2793 break;
2794 }
2795 case ff_cvt_l_fmt: // Mips64r2: Truncate float to 64-bit long-word.
2796 // Rounding modes are not yet supported.
2797 MOZ_ASSERT((FCSR_ & 3) == 0);
2798 // In rounding mode 0 it should behave like ROUND.
2799 [[fallthrough]];
2800 case ff_round_l_fmt: { // Mips64r2 instruction.
2801 float rounded = fs_value > 0 ? std::floor(fs_value + 0.5)
2802 : std::ceil(fs_value - 0.5);
2803 i64 = I64(rounded);
2804 setFpuRegister(fd_reg, i64);
2805 if (setFCSRRoundError<int64_t>(fs_value, rounded)) {
2806 setFpuRegister(fd_reg, kFPUInvalidResult64);
2807 }
2808 break;
2809 }
2810 case ff_trunc_l_fmt: { // Mips64r2 instruction.
2811 float rounded = truncf(fs_value);
2812 i64 = I64(rounded);
2813 setFpuRegister(fd_reg, i64);
2814 if (setFCSRRoundError<int64_t>(fs_value, rounded)) {
2815 setFpuRegister(fd_reg, kFPUInvalidResult64);
2816 }
2817 break;
2818 }
2819 case ff_floor_l_fmt: { // Mips64r2 instruction.
2820 float rounded = std::floor(fs_value);
2821 i64 = I64(rounded);
2822 setFpuRegister(fd_reg, i64);
2823 if (setFCSRRoundError<int64_t>(fs_value, rounded)) {
2824 setFpuRegister(fd_reg, kFPUInvalidResult64);
2825 }
2826 break;
2827 }
2828 case ff_ceil_l_fmt: { // Mips64r2 instruction.
2829 float rounded = std::ceil(fs_value);
2830 i64 = I64(rounded);
2831 setFpuRegister(fd_reg, i64);
2832 if (setFCSRRoundError<int64_t>(fs_value, rounded)) {
2833 setFpuRegister(fd_reg, kFPUInvalidResult64);
2834 }
2835 break;
2836 }
2837 case ff_cvt_ps_s:
2838 case ff_c_f_fmt:
2839 MOZ_CRASH();
2840 break;
2841 case ff_movf_fmt:
2842 if (testFCSRBit(fcsr_cc)) {
2843 setFpuRegisterFloat(fd_reg, getFpuRegisterFloat(fs_reg));
2844 }
2845 break;
2846 case ff_movz_fmt:
2847 if (rt == 0) {
2848 setFpuRegisterFloat(fd_reg, getFpuRegisterFloat(fs_reg));
2849 }
2850 break;
2851 case ff_movn_fmt:
2852 if (rt != 0) {
2853 setFpuRegisterFloat(fd_reg, getFpuRegisterFloat(fs_reg));
2854 }
2855 break;
2856 default:
2857 MOZ_CRASH();
2858 }
2859 break;
2860 case rs_d:
2861 double dt_value, ds_value;
2862 ds_value = getFpuRegisterDouble(fs_reg);
2863 dt_value = getFpuRegisterDouble(ft_reg);
2864 cc = instr->fcccValue();
2865 fcsr_cc = GetFCSRConditionBit(cc);
2866 switch (instr->functionFieldRaw()) {
2867 case ff_add_fmt:
2868 setFpuRegisterDouble(fd_reg, ds_value + dt_value);
2869 break;
2870 case ff_sub_fmt:
2871 setFpuRegisterDouble(fd_reg, ds_value - dt_value);
2872 break;
2873 case ff_mul_fmt:
2874 setFpuRegisterDouble(fd_reg, ds_value * dt_value);
2875 break;
2876 case ff_div_fmt:
2877 setFpuRegisterDouble(fd_reg, ds_value / dt_value);
2878 break;
2879 case ff_abs_fmt:
2880 setFpuRegisterDouble(fd_reg, fabs(ds_value));
2881 break;
2882 case ff_mov_fmt:
2883 setFpuRegisterDouble(fd_reg, ds_value);
2884 break;
2885 case ff_neg_fmt:
2886 setFpuRegisterDouble(fd_reg, -ds_value);
2887 break;
2888 case ff_sqrt_fmt:
2889 setFpuRegisterDouble(fd_reg, sqrt(ds_value));
2890 break;
2891 case ff_c_un_fmt:
2892 setFCSRBit(fcsr_cc, std::isnan(ds_value) || std::isnan(dt_value));
2893 break;
2894 case ff_c_eq_fmt:
2895 setFCSRBit(fcsr_cc, (ds_value == dt_value));
2896 break;
2897 case ff_c_ueq_fmt:
2898 setFCSRBit(fcsr_cc,
2899 (ds_value == dt_value) ||
2900 (std::isnan(ds_value) || std::isnan(dt_value)));
2901 break;
2902 case ff_c_olt_fmt:
2903 setFCSRBit(fcsr_cc, (ds_value < dt_value));
2904 break;
2905 case ff_c_ult_fmt:
2906 setFCSRBit(fcsr_cc,
2907 (ds_value < dt_value) ||
2908 (std::isnan(ds_value) || std::isnan(dt_value)));
2909 break;
2910 case ff_c_ole_fmt:
2911 setFCSRBit(fcsr_cc, (ds_value <= dt_value));
2912 break;
2913 case ff_c_ule_fmt:
2914 setFCSRBit(fcsr_cc,
2915 (ds_value <= dt_value) ||
2916 (std::isnan(ds_value) || std::isnan(dt_value)));
2917 break;
2918 case ff_cvt_w_fmt: // Convert double to word.
2919 // Rounding modes are not yet supported.
2920 MOZ_ASSERT((FCSR_ & 3) == 0);
2921 // In rounding mode 0 it should behave like ROUND.
2922 [[fallthrough]];
2923 case ff_round_w_fmt: { // Round double to word (round half to
2924 // even).
2925 double rounded = std::floor(ds_value + 0.5);
2926 int32_t result = I32(rounded);
2927 if ((result & 1) != 0 && result - ds_value == 0.5) {
2928 // If the number is halfway between two integers,
2929 // round to the even one.
2930 result--;
2931 }
2932 setFpuRegisterLo(fd_reg, result);
2933 if (setFCSRRoundError<int32_t>(ds_value, rounded)) {
2934 setFpuRegisterLo(fd_reg, kFPUInvalidResult);
2935 }
2936 break;
2937 }
2938 case ff_trunc_w_fmt: { // Truncate double to word (round towards
2939 // 0).
2940 double rounded = trunc(ds_value);
2941 int32_t result = I32(rounded);
2942 setFpuRegisterLo(fd_reg, result);
2943 if (setFCSRRoundError<int32_t>(ds_value, rounded)) {
2944 setFpuRegisterLo(fd_reg, kFPUInvalidResult);
2945 }
2946 break;
2947 }
2948 case ff_floor_w_fmt: { // Round double to word towards negative
2949 // infinity.
2950 double rounded = std::floor(ds_value);
2951 int32_t result = I32(rounded);
2952 setFpuRegisterLo(fd_reg, result);
2953 if (setFCSRRoundError<int32_t>(ds_value, rounded)) {
2954 setFpuRegisterLo(fd_reg, kFPUInvalidResult);
2955 }
2956 break;
2957 }
2958 case ff_ceil_w_fmt: { // Round double to word towards positive
2959 // infinity.
2960 double rounded = std::ceil(ds_value);
2961 int32_t result = I32(rounded);
2962 setFpuRegisterLo(fd_reg, result);
2963 if (setFCSRRoundError<int32_t>(ds_value, rounded)) {
2964 setFpuRegisterLo(fd_reg, kFPUInvalidResult);
2965 }
2966 break;
2967 }
2968 case ff_cvt_s_fmt: // Convert double to float (single).
2969 setFpuRegisterFloat(fd_reg, static_cast<float>(ds_value));
2970 break;
2971 case ff_cvt_l_fmt: // Mips64r2: Truncate double to 64-bit
2972 // long-word.
2973 // Rounding modes are not yet supported.
2974 MOZ_ASSERT((FCSR_ & 3) == 0);
2975 // In rounding mode 0 it should behave like ROUND.
2976 [[fallthrough]];
2977 case ff_round_l_fmt: { // Mips64r2 instruction.
2978 double rounded = ds_value > 0 ? std::floor(ds_value + 0.5)
2979 : std::ceil(ds_value - 0.5);
2980 i64 = I64(rounded);
2981 setFpuRegister(fd_reg, i64);
2982 if (setFCSRRoundError<int64_t>(ds_value, rounded)) {
2983 setFpuRegister(fd_reg, kFPUInvalidResult64);
2984 }
2985 break;
2986 }
2987 case ff_trunc_l_fmt: { // Mips64r2 instruction.
2988 double rounded = trunc(ds_value);
2989 i64 = I64(rounded);
2990 setFpuRegister(fd_reg, i64);
2991 if (setFCSRRoundError<int64_t>(ds_value, rounded)) {
2992 setFpuRegister(fd_reg, kFPUInvalidResult64);
2993 }
2994 break;
2995 }
2996 case ff_floor_l_fmt: { // Mips64r2 instruction.
2997 double rounded = std::floor(ds_value);
2998 i64 = I64(rounded);
2999 setFpuRegister(fd_reg, i64);
3000 if (setFCSRRoundError<int64_t>(ds_value, rounded)) {
3001 setFpuRegister(fd_reg, kFPUInvalidResult64);
3002 }
3003 break;
3004 }
3005 case ff_ceil_l_fmt: { // Mips64r2 instruction.
3006 double rounded = std::ceil(ds_value);
3007 i64 = I64(rounded);
3008 setFpuRegister(fd_reg, i64);
3009 if (setFCSRRoundError<int64_t>(ds_value, rounded)) {
3010 setFpuRegister(fd_reg, kFPUInvalidResult64);
3011 }
3012 break;
3013 }
3014 case ff_c_f_fmt:
3015 MOZ_CRASH();
3016 break;
3017 case ff_movz_fmt:
3018 if (rt == 0) {
3019 setFpuRegisterDouble(fd_reg, getFpuRegisterDouble(fs_reg));
3020 }
3021 break;
3022 case ff_movn_fmt:
3023 if (rt != 0) {
3024 setFpuRegisterDouble(fd_reg, getFpuRegisterDouble(fs_reg));
3025 }
3026 break;
3027 case ff_movf_fmt:
3028 // location of cc field in MOVF is equal to float branch
3029 // instructions
3030 cc = instr->fbccValue();
3031 fcsr_cc = GetFCSRConditionBit(cc);
3032 if (testFCSRBit(fcsr_cc)) {
3033 setFpuRegisterDouble(fd_reg, getFpuRegisterDouble(fs_reg));
3034 }
3035 break;
3036 default:
3037 MOZ_CRASH();
3038 }
3039 break;
3040 case rs_w:
3041 switch (instr->functionFieldRaw()) {
3042 case ff_cvt_s_fmt: // Convert word to float (single).
3043 i64 = getFpuRegisterLo(fs_reg);
3044 setFpuRegisterFloat(fd_reg, static_cast<float>(i64));
3045 break;
3046 case ff_cvt_d_fmt: // Convert word to double.
3047 i64 = getFpuRegisterLo(fs_reg);
3048 setFpuRegisterDouble(fd_reg, static_cast<double>(i64));
3049 break;
3050 default:
3051 MOZ_CRASH();
3052 };
3053 break;
3054 case rs_l:
3055 switch (instr->functionFieldRaw()) {
3056 case ff_cvt_d_fmt: // Mips64r2 instruction.
3057 i64 = getFpuRegister(fs_reg);
3058 setFpuRegisterDouble(fd_reg, static_cast<double>(i64));
3059 break;
3060 case ff_cvt_s_fmt:
3061 i64 = getFpuRegister(fs_reg);
3062 setFpuRegisterFloat(fd_reg, static_cast<float>(i64));
3063 break;
3064 default:
3065 MOZ_CRASH();
3066 }
3067 break;
3068 case rs_ps:
3069 break;
3070 default:
3071 MOZ_CRASH();
3072 };
3073 break;
3074 case op_cop1x:
3075 switch (instr->functionFieldRaw()) {
3076 case ff_madd_s:
3077 float fr, ft, fs;
3078 fr = getFpuRegisterFloat(fr_reg);
3079 fs = getFpuRegisterFloat(fs_reg);
3080 ft = getFpuRegisterFloat(ft_reg);
3081 setFpuRegisterFloat(fd_reg, fs * ft + fr);
3082 break;
3083 case ff_madd_d:
3084 double dr, dt, ds;
3085 dr = getFpuRegisterDouble(fr_reg);
3086 ds = getFpuRegisterDouble(fs_reg);
3087 dt = getFpuRegisterDouble(ft_reg);
3088 setFpuRegisterDouble(fd_reg, ds * dt + dr);
3089 break;
3090 default:
3091 MOZ_CRASH();
3092 };
3093 break;
3094 case op_special:
3095 switch (instr->functionFieldRaw()) {
3096 case ff_jr: {
3097 SimInstruction* branch_delay_instr =
3098 reinterpret_cast<SimInstruction*>(current_pc +
3099 SimInstruction::kInstrSize);
3100 branchDelayInstructionDecode(branch_delay_instr);
3101 set_pc(next_pc);
3102 pc_modified_ = true;
3103 break;
3104 }
3105 case ff_jalr: {
3106 SimInstruction* branch_delay_instr =
3107 reinterpret_cast<SimInstruction*>(current_pc +
3108 SimInstruction::kInstrSize);
3109 setRegister(return_addr_reg,
3110 current_pc + 2 * SimInstruction::kInstrSize);
3111 branchDelayInstructionDecode(branch_delay_instr);
3112 set_pc(next_pc);
3113 pc_modified_ = true;
3114 break;
3115 }
3116 // Instructions using HI and LO registers.
3117 case ff_mult:
3118 setRegister(LO, I32(i128hilo & 0xffffffff));
3119 setRegister(HI, I32(i128hilo >> 32));
3120 break;
3121 case ff_dmult:
3122 setRegister(LO, I64(i128hilo & 0xfffffffffffffffful));
3123 setRegister(HI, I64(i128hilo >> 64));
3124 break;
3125 case ff_multu:
3126 setRegister(LO, I32(u128hilo & 0xffffffff));
3127 setRegister(HI, I32(u128hilo >> 32));
3128 break;
3129 case ff_dmultu:
3130 setRegister(LO, I64(u128hilo & 0xfffffffffffffffful));
3131 setRegister(HI, I64(u128hilo >> 64));
3132 break;
3133 case ff_div:
3134 case ff_divu:
3135 // Divide by zero and overflow was not checked in the configuration
3136 // step - div and divu do not raise exceptions. On division by 0
3137 // the result will be UNPREDICTABLE. On overflow (INT_MIN/-1),
3138 // return INT_MIN which is what the hardware does.
3139 setRegister(LO, I32(i128hilo & 0xffffffff));
3140 setRegister(HI, I32(i128hilo >> 32));
3141 break;
3142 case ff_ddiv:
3143 case ff_ddivu:
3144 // Divide by zero and overflow was not checked in the configuration
3145 // step - div and divu do not raise exceptions. On division by 0
3146 // the result will be UNPREDICTABLE. On overflow (INT_MIN/-1),
3147 // return INT_MIN which is what the hardware does.
3148 setRegister(LO, I64(i128hilo & 0xfffffffffffffffful));
3149 setRegister(HI, I64(i128hilo >> 64));
3150 break;
3151 case ff_sync:
3152 break;
3153 // Break and trap instructions.
3154 case ff_break:
3155 case ff_tge:
3156 case ff_tgeu:
3157 case ff_tlt:
3158 case ff_tltu:
3159 case ff_teq:
3160 case ff_tne:
3161 if (do_interrupt) {
3162 softwareInterrupt(instr);
3163 }
3164 break;
3165 // Conditional moves.
3166 case ff_movn:
3167 if (rt) {
3168 setRegister(rd_reg, rs);
3169 }
3170 break;
3171 case ff_movci: {
3172 uint32_t cc = instr->fbccValue();
3173 uint32_t fcsr_cc = GetFCSRConditionBit(cc);
3174 if (instr->bit(16)) { // Read Tf bit.
3175 if (testFCSRBit(fcsr_cc)) {
3176 setRegister(rd_reg, rs);
3177 }
3178 } else {
3179 if (!testFCSRBit(fcsr_cc)) {
3180 setRegister(rd_reg, rs);
3181 }
3182 }
3183 break;
3184 }
3185 case ff_movz:
3186 if (!rt) {
3187 setRegister(rd_reg, rs);
3188 }
3189 break;
3190 default: // For other special opcodes we do the default operation.
3191 setRegister(rd_reg, alu_out);
3192 };
3193 break;
3194 case op_special2:
3195 switch (instr->functionFieldRaw()) {
3196 case ff_mul:
3197 setRegister(rd_reg, alu_out);
3198 // HI and LO are UNPREDICTABLE after the operation.
3199 setRegister(LO, Unpredictable);
3200 setRegister(HI, Unpredictable);
3201 break;
3202 default: // For other special2 opcodes we do the default operation.
3203 setRegister(rd_reg, alu_out);
3204 }
3205 break;
3206 case op_special3:
3207 switch (instr->functionFieldRaw()) {
3208 case ff_ins:
3209 case ff_dins:
3210 case ff_dinsm:
3211 case ff_dinsu:
3212 // Ins instr leaves result in Rt, rather than Rd.
3213 setRegister(rt_reg, alu_out);
3214 break;
3215 case ff_ext:
3216 case ff_dext:
3217 case ff_dextm:
3218 case ff_dextu:
3219 // Ext instr leaves result in Rt, rather than Rd.
3220 setRegister(rt_reg, alu_out);
3221 break;
3222 case ff_bshfl:
3223 setRegister(rd_reg, alu_out);
3224 break;
3225 case ff_dbshfl:
3226 setRegister(rd_reg, alu_out);
3227 break;
3228 default:
3229 MOZ_CRASH();
3230 };
3231 break;
3232 // Unimplemented opcodes raised an error in the configuration step before,
3233 // so we can use the default here to set the destination register in
3234 // common cases.
3235 default:
3236 setRegister(rd_reg, alu_out);
3237 };
3238 }
3239
3240 // Type 2: instructions using a 16 bits immediate. (e.g. addi, beq).
3241 void Simulator::decodeTypeImmediate(SimInstruction* instr) {
3242 // Instruction fields.
3243 OpcodeField op = instr->opcodeFieldRaw();
3244 int64_t rs = getRegister(instr->rsValue());
3245 int32_t rt_reg = instr->rtValue(); // Destination register.
3246 int64_t rt = getRegister(rt_reg);
3247 int16_t imm16 = instr->imm16Value();
3248
3249 int32_t ft_reg = instr->ftValue(); // Destination register.
3250
3251 // Zero extended immediate.
3252 uint32_t oe_imm16 = 0xffff & imm16;
3253 // Sign extended immediate.
3254 int32_t se_imm16 = imm16;
3255
3256 // Get current pc.
3257 int64_t current_pc = get_pc();
3258 // Next pc.
3259 int64_t next_pc = bad_ra;
3260
3261 // Used for conditional branch instructions.
3262 bool do_branch = false;
3263 bool execute_branch_delay_instruction = false;
3264
3265 // Used for arithmetic instructions.
3266 int64_t alu_out = 0;
3267 // Floating point.
3268 double fp_out = 0.0;
3269 uint32_t cc, cc_value, fcsr_cc;
3270
3271 // Used for memory instructions.
3272 uint64_t addr = 0x0;
3273 // Value to be written in memory.
3274 uint64_t mem_value = 0x0;
3275 __int128 temp;
3276
3277 // ---------- Configuration (and execution for op_regimm).
3278 switch (op) {
3279 // ------------- op_cop1. Coprocessor instructions.
3280 case op_cop1:
3281 switch (instr->rsFieldRaw()) {
3282 case rs_bc1: // Branch on coprocessor condition.
3283 cc = instr->fbccValue();
3284 fcsr_cc = GetFCSRConditionBit(cc);
3285 cc_value = testFCSRBit(fcsr_cc);
3286 do_branch = (instr->fbtrueValue()) ? cc_value : !cc_value;
3287 execute_branch_delay_instruction = true;
3288 // Set next_pc.
3289 if (do_branch) {
3290 next_pc = current_pc + (imm16 << 2) + SimInstruction::kInstrSize;
3291 } else {
3292 next_pc = current_pc + kBranchReturnOffset;
3293 }
3294 break;
3295 default:
3296 MOZ_CRASH();
3297 };
3298 break;
3299 // ------------- op_regimm class.
3300 case op_regimm:
3301 switch (instr->rtFieldRaw()) {
3302 case rt_bltz:
3303 do_branch = (rs < 0);
3304 break;
3305 case rt_bltzal:
3306 do_branch = rs < 0;
3307 break;
3308 case rt_bgez:
3309 do_branch = rs >= 0;
3310 break;
3311 case rt_bgezal:
3312 do_branch = rs >= 0;
3313 break;
3314 default:
3315 MOZ_CRASH();
3316 };
3317 switch (instr->rtFieldRaw()) {
3318 case rt_bltz:
3319 case rt_bltzal:
3320 case rt_bgez:
3321 case rt_bgezal:
3322 // Branch instructions common part.
3323 execute_branch_delay_instruction = true;
3324 // Set next_pc.
3325 if (do_branch) {
3326 next_pc = current_pc + (imm16 << 2) + SimInstruction::kInstrSize;
3327 if (instr->isLinkingInstruction()) {
3328 setRegister(31, current_pc + kBranchReturnOffset);
3329 }
3330 } else {
3331 next_pc = current_pc + kBranchReturnOffset;
3332 }
3333 break;
3334 default:
3335 break;
3336 };
3337 break; // case op_regimm.
3338 // ------------- Branch instructions.
3339 // When comparing to zero, the encoding of rt field is always 0, so we
3340 // don't need to replace rt with zero.
3341 case op_beq:
3342 do_branch = (rs == rt);
3343 break;
3344 case op_bne:
3345 do_branch = rs != rt;
3346 break;
3347 case op_blez:
3348 do_branch = rs <= 0;
3349 break;
3350 case op_bgtz:
3351 do_branch = rs > 0;
3352 break;
3353 // ------------- Arithmetic instructions.
3354 case op_addi:
3355 alu_out = I32_CHECK(rs) + se_imm16;
3356 if ((alu_out << 32) != (alu_out << 31)) {
3357 exceptions[kIntegerOverflow] = 1;
3358 }
3359 alu_out = I32_CHECK(alu_out);
3360 break;
3361 case op_daddi:
3362 temp = alu_out = rs + se_imm16;
3363 if ((temp << 64) != (temp << 63)) {
3364 exceptions[kIntegerOverflow] = 1;
3365 }
3366 alu_out = I64(temp);
3367 break;
3368 case op_addiu:
3369 alu_out = I32(I32_CHECK(rs) + se_imm16);
3370 break;
3371 case op_daddiu:
3372 alu_out = rs + se_imm16;
3373 break;
3374 case op_slti:
3375 alu_out = (rs < se_imm16) ? 1 : 0;
3376 break;
3377 case op_sltiu:
3378 alu_out = (U64(rs) < U64(se_imm16)) ? 1 : 0;
3379 break;
3380 case op_andi:
3381 alu_out = rs & oe_imm16;
3382 break;
3383 case op_ori:
3384 alu_out = rs | oe_imm16;
3385 break;
3386 case op_xori:
3387 alu_out = rs ^ oe_imm16;
3388 break;
3389 case op_lui:
3390 alu_out = (se_imm16 << 16);
3391 break;
3392 // ------------- Memory instructions.
3393 case op_lbu:
3394 addr = rs + se_imm16;
3395 alu_out = readBU(addr, instr);
3396 break;
3397 case op_lb:
3398 addr = rs + se_imm16;
3399 alu_out = readB(addr, instr);
3400 break;
3401 case op_lhu:
3402 addr = rs + se_imm16;
3403 alu_out = readHU(addr, instr);
3404 break;
3405 case op_lh:
3406 addr = rs + se_imm16;
3407 alu_out = readH(addr, instr);
3408 break;
3409 case op_lwu:
3410 addr = rs + se_imm16;
3411 alu_out = readWU(addr, instr);
3412 break;
3413 case op_lw:
3414 addr = rs + se_imm16;
3415 alu_out = readW(addr, instr);
3416 break;
3417 case op_lwl: {
3418 // al_offset is offset of the effective address within an aligned word.
3419 uint8_t al_offset = (rs + se_imm16) & 3;
3420 uint8_t byte_shift = 3 - al_offset;
3421 uint32_t mask = (1 << byte_shift * 8) - 1;
3422 addr = rs + se_imm16 - al_offset;
3423 alu_out = readW(addr, instr);
3424 alu_out <<= byte_shift * 8;
3425 alu_out |= rt & mask;
3426 break;
3427 }
3428 case op_lwr: {
3429 // al_offset is offset of the effective address within an aligned word.
3430 uint8_t al_offset = (rs + se_imm16) & 3;
3431 uint8_t byte_shift = 3 - al_offset;
3432 uint32_t mask = al_offset ? (~0 << (byte_shift + 1) * 8) : 0;
3433 addr = rs + se_imm16 - al_offset;
3434 alu_out = readW(addr, instr);
3435 alu_out = U32(alu_out) >> al_offset * 8;
3436 alu_out |= rt & mask;
3437 alu_out = I32(alu_out);
3438 break;
3439 }
3440 case op_ll:
3441 addr = rs + se_imm16;
3442 alu_out = loadLinkedW(addr, instr);
3443 break;
3444 case op_lld:
3445 addr = rs + se_imm16;
3446 alu_out = loadLinkedD(addr, instr);
3447 break;
3448 case op_ld:
3449 addr = rs + se_imm16;
3450 alu_out = readDW(addr, instr);
3451 break;
3452 case op_ldl: {
3453 // al_offset is offset of the effective address within an aligned word.
3454 uint8_t al_offset = (rs + se_imm16) & 7;
3455 uint8_t byte_shift = 7 - al_offset;
3456 uint64_t mask = (1ul << byte_shift * 8) - 1;
3457 addr = rs + se_imm16 - al_offset;
3458 alu_out = readDW(addr, instr);
3459 alu_out <<= byte_shift * 8;
3460 alu_out |= rt & mask;
3461 break;
3462 }
3463 case op_ldr: {
3464 // al_offset is offset of the effective address within an aligned word.
3465 uint8_t al_offset = (rs + se_imm16) & 7;
3466 uint8_t byte_shift = 7 - al_offset;
3467 uint64_t mask = al_offset ? (~0ul << (byte_shift + 1) * 8) : 0;
3468 addr = rs + se_imm16 - al_offset;
3469 alu_out = readDW(addr, instr);
3470 alu_out = U64(alu_out) >> al_offset * 8;
3471 alu_out |= rt & mask;
3472 break;
3473 }
3474 case op_sb:
3475 addr = rs + se_imm16;
3476 break;
3477 case op_sh:
3478 addr = rs + se_imm16;
3479 break;
3480 case op_sw:
3481 addr = rs + se_imm16;
3482 break;
3483 case op_swl: {
3484 uint8_t al_offset = (rs + se_imm16) & 3;
3485 uint8_t byte_shift = 3 - al_offset;
3486 uint32_t mask = byte_shift ? (~0 << (al_offset + 1) * 8) : 0;
3487 addr = rs + se_imm16 - al_offset;
3488 mem_value = readW(addr, instr) & mask;
3489 mem_value |= U32(rt) >> byte_shift * 8;
3490 break;
3491 }
3492 case op_swr: {
3493 uint8_t al_offset = (rs + se_imm16) & 3;
3494 uint32_t mask = (1 << al_offset * 8) - 1;
3495 addr = rs + se_imm16 - al_offset;
3496 mem_value = readW(addr, instr);
3497 mem_value = (rt << al_offset * 8) | (mem_value & mask);
3498 break;
3499 }
3500 case op_sc:
3501 addr = rs + se_imm16;
3502 break;
3503 case op_scd:
3504 addr = rs + se_imm16;
3505 break;
3506 case op_sd:
3507 addr = rs + se_imm16;
3508 break;
3509 case op_sdl: {
3510 uint8_t al_offset = (rs + se_imm16) & 7;
3511 uint8_t byte_shift = 7 - al_offset;
3512 uint64_t mask = byte_shift ? (~0ul << (al_offset + 1) * 8) : 0;
3513 addr = rs + se_imm16 - al_offset;
3514 mem_value = readW(addr, instr) & mask;
3515 mem_value |= U64(rt) >> byte_shift * 8;
3516 break;
3517 }
3518 case op_sdr: {
3519 uint8_t al_offset = (rs + se_imm16) & 7;
3520 uint64_t mask = (1ul << al_offset * 8) - 1;
3521 addr = rs + se_imm16 - al_offset;
3522 mem_value = readW(addr, instr);
3523 mem_value = (rt << al_offset * 8) | (mem_value & mask);
3524 break;
3525 }
3526 case op_lwc1:
3527 addr = rs + se_imm16;
3528 alu_out = readW(addr, instr);
3529 break;
3530 case op_ldc1:
3531 addr = rs + se_imm16;
3532 fp_out = readD(addr, instr);
3533 break;
3534 case op_swc1:
3535 case op_sdc1:
3536 addr = rs + se_imm16;
3537 break;
3538 default:
3539 MOZ_CRASH();
3540 };
3541
3542 // ---------- Raise exceptions triggered.
3543 signalExceptions();
3544
3545 // ---------- Execution.
3546 switch (op) {
3547 // ------------- Branch instructions.
3548 case op_beq:
3549 case op_bne:
3550 case op_blez:
3551 case op_bgtz:
3552 // Branch instructions common part.
3553 execute_branch_delay_instruction = true;
3554 // Set next_pc.
3555 if (do_branch) {
3556 next_pc = current_pc + (imm16 << 2) + SimInstruction::kInstrSize;
3557 if (instr->isLinkingInstruction()) {
3558 setRegister(31, current_pc + 2 * SimInstruction::kInstrSize);
3559 }
3560 } else {
3561 next_pc = current_pc + 2 * SimInstruction::kInstrSize;
3562 }
3563 break;
3564 // ------------- Arithmetic instructions.
3565 case op_addi:
3566 case op_daddi:
3567 case op_addiu:
3568 case op_daddiu:
3569 case op_slti:
3570 case op_sltiu:
3571 case op_andi:
3572 case op_ori:
3573 case op_xori:
3574 case op_lui:
3575 setRegister(rt_reg, alu_out);
3576 break;
3577 // ------------- Memory instructions.
3578 case op_lbu:
3579 case op_lb:
3580 case op_lhu:
3581 case op_lh:
3582 case op_lwu:
3583 case op_lw:
3584 case op_lwl:
3585 case op_lwr:
3586 case op_ll:
3587 case op_lld:
3588 case op_ld:
3589 case op_ldl:
3590 case op_ldr:
3591 setRegister(rt_reg, alu_out);
3592 break;
3593 case op_sb:
3594 writeB(addr, I8(rt), instr);
3595 break;
3596 case op_sh:
3597 writeH(addr, U16(rt), instr);
3598 break;
3599 case op_sw:
3600 writeW(addr, I32(rt), instr);
3601 break;
3602 case op_swl:
3603 writeW(addr, I32(mem_value), instr);
3604 break;
3605 case op_swr:
3606 writeW(addr, I32(mem_value), instr);
3607 break;
3608 case op_sc:
3609 setRegister(rt_reg, storeConditionalW(addr, I32(rt), instr));
3610 break;
3611 case op_scd:
3612 setRegister(rt_reg, storeConditionalD(addr, rt, instr));
3613 break;
3614 case op_sd:
3615 writeDW(addr, rt, instr);
3616 break;
3617 case op_sdl:
3618 writeDW(addr, mem_value, instr);
3619 break;
3620 case op_sdr:
3621 writeDW(addr, mem_value, instr);
3622 break;
3623 case op_lwc1:
3624 setFpuRegisterLo(ft_reg, alu_out);
3625 break;
3626 case op_ldc1:
3627 setFpuRegisterDouble(ft_reg, fp_out);
3628 break;
3629 case op_swc1:
3630 writeW(addr, getFpuRegisterLo(ft_reg), instr);
3631 break;
3632 case op_sdc1:
3633 writeD(addr, getFpuRegisterDouble(ft_reg), instr);
3634 break;
3635 default:
3636 break;
3637 };
3638
3639 if (execute_branch_delay_instruction) {
3640 // Execute branch delay slot
3641 // We don't check for end_sim_pc. First it should not be met as the current
3642 // pc is valid. Secondly a jump should always execute its branch delay slot.
3643 SimInstruction* branch_delay_instr = reinterpret_cast<SimInstruction*>(
3644 current_pc + SimInstruction::kInstrSize);
3645 branchDelayInstructionDecode(branch_delay_instr);
3646 }
3647
3648 // If needed update pc after the branch delay execution.
3649 if (next_pc != bad_ra) {
3650 set_pc(next_pc);
3651 }
3652 }
3653
3654 // Type 3: instructions using a 26 bits immediate. (e.g. j, jal).
3655 void Simulator::decodeTypeJump(SimInstruction* instr) {
3656 // Get current pc.
3657 int64_t current_pc = get_pc();
3658 // Get unchanged bits of pc.
3659 int64_t pc_high_bits = current_pc & 0xfffffffff0000000ul;
3660 // Next pc.
3661 int64_t next_pc = pc_high_bits | (instr->imm26Value() << 2);
3662
3663 // Execute branch delay slot.
3664 // We don't check for end_sim_pc. First it should not be met as the current pc
3665 // is valid. Secondly a jump should always execute its branch delay slot.
3666 SimInstruction* branch_delay_instr = reinterpret_cast<SimInstruction*>(
3667 current_pc + SimInstruction::kInstrSize);
3668 branchDelayInstructionDecode(branch_delay_instr);
3669
3670 // Update pc and ra if necessary.
3671 // Do this after the branch delay execution.
3672 if (instr->isLinkingInstruction()) {
3673 setRegister(31, current_pc + 2 * SimInstruction::kInstrSize);
3674 }
3675 set_pc(next_pc);
3676 pc_modified_ = true;
3677 }
3678
3679 // Executes the current instruction.
3680 void Simulator::instructionDecode(SimInstruction* instr) {
3681 if (!SimulatorProcess::ICacheCheckingDisableCount) {
3682 AutoLockSimulatorCache als;
3683 SimulatorProcess::checkICacheLocked(instr);
3684 }
3685 pc_modified_ = false;
3686
3687 switch (instr->instructionType()) {
3688 case SimInstruction::kRegisterType:
3689 decodeTypeRegister(instr);
3690 break;
3691 case SimInstruction::kImmediateType:
3692 decodeTypeImmediate(instr);
3693 break;
3694 case SimInstruction::kJumpType:
3695 decodeTypeJump(instr);
3696 break;
3697 default:
3698 UNSUPPORTED();
3699 }
3700 if (!pc_modified_) {
3701 setRegister(pc,
3702 reinterpret_cast<int64_t>(instr) + SimInstruction::kInstrSize);
3703 }
3704 }
3705
3706 void Simulator::branchDelayInstructionDecode(SimInstruction* instr) {
3707 if (instr->instructionBits() == NopInst) {
3708 // Short-cut generic nop instructions. They are always valid and they
3709 // never change the simulator state.
3710 return;
3711 }
3712
3713 if (instr->isForbiddenInBranchDelay()) {
3714 MOZ_CRASH("Eror:Unexpected opcode in a branch delay slot.");
3715 }
3716 instructionDecode(instr);
3717 }
3718
3719 void Simulator::enable_single_stepping(SingleStepCallback cb, void* arg) {
3720 single_stepping_ = true;
3721 single_step_callback_ = cb;
3722 single_step_callback_arg_ = arg;
3723 single_step_callback_(single_step_callback_arg_, this, (void*)get_pc());
3724 }
3725
3726 void Simulator::disable_single_stepping() {
3727 if (!single_stepping_) {
3728 return;
3729 }
3730 single_step_callback_(single_step_callback_arg_, this, (void*)get_pc());
3731 single_stepping_ = false;
3732 single_step_callback_ = nullptr;
3733 single_step_callback_arg_ = nullptr;
3734 }
3735
3736 template <bool enableStopSimAt>
3737 void Simulator::execute() {
3738 if (single_stepping_) {
3739 single_step_callback_(single_step_callback_arg_, this, nullptr);
3740 }
3741
3742 // Get the PC to simulate. Cannot use the accessor here as we need the
3743 // raw PC value and not the one used as input to arithmetic instructions.
3744 int64_t program_counter = get_pc();
3745
3746 while (program_counter != end_sim_pc) {
3747 if (enableStopSimAt && (icount_ == Simulator::StopSimAt)) {
3748 MipsDebugger dbg(this);
3749 dbg.debug();
3750 } else {
3751 if (single_stepping_) {
3752 single_step_callback_(single_step_callback_arg_, this,
3753 (void*)program_counter);
3754 }
3755 SimInstruction* instr =
3756 reinterpret_cast<SimInstruction*>(program_counter);
3757 instructionDecode(instr);
3758 icount_++;
3759 }
3760 program_counter = get_pc();
3761 }
3762
3763 if (single_stepping_) {
3764 single_step_callback_(single_step_callback_arg_, this, nullptr);
3765 }
3766 }
3767
3768 void Simulator::callInternal(uint8_t* entry) {
3769 // Prepare to execute the code at entry.
3770 setRegister(pc, reinterpret_cast<int64_t>(entry));
3771 // Put down marker for end of simulation. The simulator will stop simulation
3772 // when the PC reaches this value. By saving the "end simulation" value into
3773 // the LR the simulation stops when returning to this call point.
3774 setRegister(ra, end_sim_pc);
3775
3776 // Remember the values of callee-saved registers.
3777 // The code below assumes that r9 is not used as sb (static base) in
3778 // simulator code and therefore is regarded as a callee-saved register.
3779 int64_t s0_val = getRegister(s0);
3780 int64_t s1_val = getRegister(s1);
3781 int64_t s2_val = getRegister(s2);
3782 int64_t s3_val = getRegister(s3);
3783 int64_t s4_val = getRegister(s4);
3784 int64_t s5_val = getRegister(s5);
3785 int64_t s6_val = getRegister(s6);
3786 int64_t s7_val = getRegister(s7);
3787 int64_t gp_val = getRegister(gp);
3788 int64_t sp_val = getRegister(sp);
3789 int64_t fp_val = getRegister(fp);
3790
3791 // Set up the callee-saved registers with a known value. To be able to check
3792 // that they are preserved properly across JS execution.
3793 int64_t callee_saved_value = icount_;
3794 setRegister(s0, callee_saved_value);
3795 setRegister(s1, callee_saved_value);
3796 setRegister(s2, callee_saved_value);
3797 setRegister(s3, callee_saved_value);
3798 setRegister(s4, callee_saved_value);
3799 setRegister(s5, callee_saved_value);
3800 setRegister(s6, callee_saved_value);
3801 setRegister(s7, callee_saved_value);
3802 setRegister(gp, callee_saved_value);
3803 setRegister(fp, callee_saved_value);
3804
3805 // Start the simulation.
3806 if (Simulator::StopSimAt != -1) {
3807 execute<true>();
3808 } else {
3809 execute<false>();
3810 }
3811
3812 // Check that the callee-saved registers have been preserved.
3813 MOZ_ASSERT(callee_saved_value == getRegister(s0));
3814 MOZ_ASSERT(callee_saved_value == getRegister(s1));
3815 MOZ_ASSERT(callee_saved_value == getRegister(s2));
3816 MOZ_ASSERT(callee_saved_value == getRegister(s3));
3817 MOZ_ASSERT(callee_saved_value == getRegister(s4));
3818 MOZ_ASSERT(callee_saved_value == getRegister(s5));
3819 MOZ_ASSERT(callee_saved_value == getRegister(s6));
3820 MOZ_ASSERT(callee_saved_value == getRegister(s7));
3821 MOZ_ASSERT(callee_saved_value == getRegister(gp));
3822 MOZ_ASSERT(callee_saved_value == getRegister(fp));
3823
3824 // Restore callee-saved registers with the original value.
3825 setRegister(s0, s0_val);
3826 setRegister(s1, s1_val);
3827 setRegister(s2, s2_val);
3828 setRegister(s3, s3_val);
3829 setRegister(s4, s4_val);
3830 setRegister(s5, s5_val);
3831 setRegister(s6, s6_val);
3832 setRegister(s7, s7_val);
3833 setRegister(gp, gp_val);
3834 setRegister(sp, sp_val);
3835 setRegister(fp, fp_val);
3836 }
3837
3838 int64_t Simulator::call(uint8_t* entry, int argument_count, ...) {
3839 va_list parameters;
3840 va_start(parameters, argument_count);
3841
3842 int64_t original_stack = getRegister(sp);
3843 // Compute position of stack on entry to generated code.
3844 int64_t entry_stack = original_stack;
3845 if (argument_count > kCArgSlotCount) {
3846 entry_stack = entry_stack - argument_count * sizeof(int64_t);
3847 } else {
3848 entry_stack = entry_stack - kCArgsSlotsSize;
3849 }
3850
3851 entry_stack &= ~U64(ABIStackAlignment - 1);
3852
3853 intptr_t* stack_argument = reinterpret_cast<intptr_t*>(entry_stack);
3854
3855 // Setup the arguments.
3856 for (int i = 0; i < argument_count; i++) {
3857 js::jit::Register argReg;
3858 if (GetIntArgReg(i, &argReg)) {
3859 setRegister(argReg.code(), va_arg(parameters, int64_t));
3860 } else {
3861 stack_argument[i] = va_arg(parameters, int64_t);
3862 }
3863 }
3864
3865 va_end(parameters);
3866 setRegister(sp, entry_stack);
3867
3868 callInternal(entry);
3869
3870 // Pop stack passed arguments.
3871 MOZ_ASSERT(entry_stack == getRegister(sp));
3872 setRegister(sp, original_stack);
3873
3874 int64_t result = getRegister(v0);
3875 return result;
3876 }
3877
3878 uintptr_t Simulator::pushAddress(uintptr_t address) {
3879 int new_sp = getRegister(sp) - sizeof(uintptr_t);
3880 uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp);
3881 *stack_slot = address;
3882 setRegister(sp, new_sp);
3883 return new_sp;
3884 }
3885
3886 uintptr_t Simulator::popAddress() {
3887 int current_sp = getRegister(sp);
3888 uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(current_sp);
3889 uintptr_t address = *stack_slot;
3890 setRegister(sp, current_sp + sizeof(uintptr_t));
3891 return address;
3892 }
3893
3894 } // namespace jit
3895 } // namespace js
3896
3897 js::jit::Simulator* JSContext::simulator() const { return simulator_; }