simulator-arm.cc 203 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5 6 7 8
#include "src/arm/simulator-arm.h"

#if defined(USE_SIMULATOR)

9
#include <stdarg.h>
10
#include <stdlib.h>
11
#include <cmath>
12

13
#include "src/arm/constants-arm.h"
14
#include "src/assembler-inl.h"
15
#include "src/base/bits.h"
16
#include "src/base/lazy-instance.h"
17
#include "src/disasm.h"
18
#include "src/macro-assembler.h"
19
#include "src/objects-inl.h"
20
#include "src/ostreams.h"
21
#include "src/runtime/runtime-utils.h"
22 23

// Only build the simulator if not compiling for real ARM hardware.
24 25
namespace v8 {
namespace internal {
26

27
DEFINE_LAZY_LEAKY_OBJECT_GETTER(Simulator::GlobalMonitor,
28
                                Simulator::GlobalMonitor::Get)
29

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

36
// The ArmDebugger class is used by the simulator while debugging simulated ARM
37
// code.
38
class ArmDebugger {
39
 public:
yangguo@chromium.org's avatar
yangguo@chromium.org committed
40
  explicit ArmDebugger(Simulator* sim) : sim_(sim) { }
41

42
  void Stop(Instruction* instr);
43 44 45
  void Debug();

 private:
46 47 48
  static const Instr kBreakpointInstr =
      (al | (7*B25) | (1*B24) | kBreakpoint);
  static const Instr kNopInstr = (al | (13*B21));
49 50 51

  Simulator* sim_;

52
  int32_t GetRegisterValue(int regnum);
53
  double GetRegisterPairDoubleValue(int regnum);
54
  double GetVFPDoubleRegisterValue(int regnum);
55
  bool GetValue(const char* desc, int32_t* value);
56 57
  bool GetVFPSingleValue(const char* desc, float* value);
  bool GetVFPDoubleValue(const char* desc, double* value);
58 59

  // Set or delete a breakpoint. Returns true if successful.
60 61
  bool SetBreakpoint(Instruction* breakpc);
  bool DeleteBreakpoint(Instruction* breakpc);
62 63 64 65 66 67 68

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

69
void ArmDebugger::Stop(Instruction* instr) {
70
  // Get the stop code.
71
  uint32_t code = instr->SvcValue() & kStopCodeMask;
72 73
  // Print the stop message and code if it is not the default code.
  if (code != kMaxStopCode) {
74
    PrintF("Simulator hit stop %u\n", code);
75
  } else {
76
    PrintF("Simulator hit\n");
77
  }
78 79 80
  Debug();
}

81
int32_t ArmDebugger::GetRegisterValue(int regnum) {
82 83 84 85
  if (regnum == kPCRegister) {
    return sim_->get_pc();
  } else {
    return sim_->get_register(regnum);
86 87 88
  }
}

89 90 91 92 93
double ArmDebugger::GetRegisterPairDoubleValue(int regnum) {
  return sim_->get_double_from_register_pair(regnum);
}


94
double ArmDebugger::GetVFPDoubleRegisterValue(int regnum) {
95
  return sim_->get_double_from_d_register(regnum).get_scalar();
96 97 98
}


99
bool ArmDebugger::GetValue(const char* desc, int32_t* value) {
100 101 102
  int regnum = Registers::Number(desc);
  if (regnum != kNoRegister) {
    *value = GetRegisterValue(regnum);
103 104
    return true;
  } else {
105 106 107 108 109
    if (strncmp(desc, "0x", 2) == 0) {
      return SScanF(desc + 2, "%x", reinterpret_cast<uint32_t*>(value)) == 1;
    } else {
      return SScanF(desc, "%u", reinterpret_cast<uint32_t*>(value)) == 1;
    }
110 111 112 113 114
  }
  return false;
}


115
bool ArmDebugger::GetVFPSingleValue(const char* desc, float* value) {
116 117 118
  bool is_double;
  int regnum = VFPRegisters::Number(desc, &is_double);
  if (regnum != kNoRegister && !is_double) {
119
    *value = sim_->get_float_from_s_register(regnum).get_scalar();
120 121 122 123 124 125
    return true;
  }
  return false;
}


126
bool ArmDebugger::GetVFPDoubleValue(const char* desc, double* value) {
127 128 129
  bool is_double;
  int regnum = VFPRegisters::Number(desc, &is_double);
  if (regnum != kNoRegister && is_double) {
130
    *value = sim_->get_double_from_d_register(regnum).get_scalar();
131 132 133 134 135 136
    return true;
  }
  return false;
}


137
bool ArmDebugger::SetBreakpoint(Instruction* breakpc) {
138
  // Check if a breakpoint can be set. If not return without any side-effects.
139
  if (sim_->break_pc_ != nullptr) {
140 141 142 143 144 145 146 147 148 149 150 151
    return false;
  }

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


152
bool ArmDebugger::DeleteBreakpoint(Instruction* breakpc) {
153
  if (sim_->break_pc_ != nullptr) {
154 155 156
    sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
  }

157
  sim_->break_pc_ = nullptr;
158 159 160 161 162
  sim_->break_instr_ = 0;
  return true;
}


163
void ArmDebugger::UndoBreakpoints() {
164
  if (sim_->break_pc_ != nullptr) {
165 166 167 168 169
    sim_->break_pc_->SetInstructionBits(sim_->break_instr_);
  }
}


170
void ArmDebugger::RedoBreakpoints() {
171
  if (sim_->break_pc_ != nullptr) {
172 173 174 175 176
    sim_->break_pc_->SetInstructionBits(kBreakpointInstr);
  }
}


177
void ArmDebugger::Debug() {
178 179 180 181 182 183 184 185 186 187 188 189
  intptr_t last_pc = -1;
  bool done = false;

#define COMMAND_SIZE 63
#define ARG_SIZE 255

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

  char cmd[COMMAND_SIZE + 1];
  char arg1[ARG_SIZE + 1];
  char arg2[ARG_SIZE + 1];
190
  char* argv[3] = { cmd, arg1, arg2 };
191 192 193 194 195 196 197 198 199 200

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

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

201
  while (!done && !sim_->has_bad_pc()) {
202
    if (last_pc != sim_->get_pc()) {
203 204
      disasm::NameConverter converter;
      disasm::Disassembler dasm(converter);
205 206 207
      // use a reasonably large buffer
      v8::internal::EmbeddedVector<char, 256> buffer;
      dasm.InstructionDecode(buffer,
208
                             reinterpret_cast<byte*>(sim_->get_pc()));
209
      PrintF("  0x%08x  %s\n", sim_->get_pc(), buffer.start());
210 211 212
      last_pc = sim_->get_pc();
    }
    char* line = ReadLine("sim> ");
213
    if (line == nullptr) {
214 215
      break;
    } else {
216
      char* last_input = sim_->last_debugger_input();
217
      if (strcmp(line, "\n") == 0 && last_input != nullptr) {
218 219 220 221 222
        line = last_input;
      } else {
        // Ownership is transferred to sim_;
        sim_->set_last_debugger_input(line);
      }
223 224
      // Use sscanf to parse the individual parts of the command line. At the
      // moment no command expects more than two parameters.
225
      int argc = SScanF(line,
226 227 228 229 230
                        "%" XSTR(COMMAND_SIZE) "s "
                        "%" XSTR(ARG_SIZE) "s "
                        "%" XSTR(ARG_SIZE) "s",
                        cmd, arg1, arg2);
      if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) {
231
        sim_->InstructionDecode(reinterpret_cast<Instruction*>(sim_->get_pc()));
232 233
      } else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) {
        // Execute the one instruction we broke at with breakpoints disabled.
234
        sim_->InstructionDecode(reinterpret_cast<Instruction*>(sim_->get_pc()));
235 236 237
        // Leave the debugger shell.
        done = true;
      } else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) {
238
        if (argc == 2 || (argc == 3 && strcmp(arg2, "fp") == 0)) {
239
          int32_t value;
240 241
          float svalue;
          double dvalue;
242
          if (strcmp(arg1, "all") == 0) {
243 244
            for (int i = 0; i < kNumRegisters; i++) {
              value = GetRegisterValue(i);
245 246
              PrintF("%3s: 0x%08x %10d", RegisterName(Register::from_code(i)),
                     value, value);
247 248 249 250 251 252 253 254
              if ((argc == 3 && strcmp(arg2, "fp") == 0) &&
                  i < 8 &&
                  (i % 2) == 0) {
                dvalue = GetRegisterPairDoubleValue(i);
                PrintF(" (%f)\n", dvalue);
              } else {
                PrintF("\n");
              }
255
            }
256
            for (int i = 0; i < DwVfpRegister::NumRegisters(); i++) {
257
              dvalue = GetVFPDoubleRegisterValue(i);
258
              uint64_t as_words = bit_cast<uint64_t>(dvalue);
259 260 261
              PrintF("%3s: %f 0x%08x %08x\n", VFPRegisters::Name(i, true),
                     dvalue, static_cast<uint32_t>(as_words >> 32),
                     static_cast<uint32_t>(as_words & 0xFFFFFFFF));
262
            }
263
          } else {
264 265
            if (GetValue(arg1, &value)) {
              PrintF("%s: 0x%08x %d \n", arg1, value, value);
266
            } else if (GetVFPSingleValue(arg1, &svalue)) {
267
              uint32_t as_word = bit_cast<uint32_t>(svalue);
268
              PrintF("%s: %f 0x%08x\n", arg1, svalue, as_word);
269
            } else if (GetVFPDoubleValue(arg1, &dvalue)) {
270
              uint64_t as_words = bit_cast<uint64_t>(dvalue);
271
              PrintF("%s: %f 0x%08x %08x\n", arg1, dvalue,
272
                     static_cast<uint32_t>(as_words >> 32),
273
                     static_cast<uint32_t>(as_words & 0xFFFFFFFF));
274 275 276
            } else {
              PrintF("%s unrecognized\n", arg1);
            }
277 278
          }
        } else {
279
          PrintF("print <register>\n");
280 281 282
        }
      } else if ((strcmp(cmd, "po") == 0)
                 || (strcmp(cmd, "printobject") == 0)) {
283
        if (argc == 2) {
284
          int32_t value;
285
          StdoutStream os;
286
          if (GetValue(arg1, &value)) {
287
            Object obj(value);
288
            os << arg1 << ": \n";
289
#ifdef DEBUG
290
            obj->Print(os);
291
            os << "\n";
292
#else
293
            os << Brief(obj) << "\n";
294
#endif
295
          } else {
296
            os << arg1 << " unrecognized\n";
297 298
          }
        } else {
299
          PrintF("printobject <value>\n");
300
        }
301
      } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) {
302 303
        int32_t* cur = nullptr;
        int32_t* end = nullptr;
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
        int next_arg = 1;

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

        int32_t words;
        if (argc == next_arg) {
          words = 10;
321
        } else {
322 323 324 325 326 327 328
          if (!GetValue(argv[next_arg], &words)) {
            words = 10;
          }
        }
        end = cur + words;

        while (cur < end) {
329
          PrintF("  0x%08" V8PRIxPTR ":  0x%08x %10d",
330
                 reinterpret_cast<intptr_t>(cur), *cur, *cur);
331
          Object obj(*cur);
332
          Heap* current_heap = sim_->isolate_->heap();
333
          if (obj.IsSmi() || current_heap->Contains(HeapObject::cast(obj))) {
334
            PrintF(" (");
335 336
            if (obj.IsSmi()) {
              PrintF("smi %d", Smi::ToInt(obj));
337 338 339 340 341 342
            } else {
              obj->ShortPrint();
            }
            PrintF(")");
          }
          PrintF("\n");
343 344
          cur++;
        }
345
      } else if (strcmp(cmd, "disasm") == 0 || strcmp(cmd, "di") == 0) {
346 347
        disasm::NameConverter converter;
        disasm::Disassembler dasm(converter);
348 349
        // use a reasonably large buffer
        v8::internal::EmbeddedVector<char, 256> buffer;
350

351 352 353
        byte* prev = nullptr;
        byte* cur = nullptr;
        byte* end = nullptr;
354

355
        if (argc == 1) {
356
          cur = reinterpret_cast<byte*>(sim_->get_pc());
357
          end = cur + (10 * kInstrSize);
358
        } else if (argc == 2) {
359 360 361 362 363 364 365
          int regnum = Registers::Number(arg1);
          if (regnum != kNoRegister || strncmp(arg1, "0x", 2) == 0) {
            // The argument is an address or a register name.
            int32_t value;
            if (GetValue(arg1, &value)) {
              cur = reinterpret_cast<byte*>(value);
              // Disassemble 10 instructions at <arg1>.
366
              end = cur + (10 * kInstrSize);
367 368 369 370 371 372 373
            }
          } else {
            // The argument is the number of instructions.
            int32_t value;
            if (GetValue(arg1, &value)) {
              cur = reinterpret_cast<byte*>(sim_->get_pc());
              // Disassemble <arg1> instructions.
374
              end = cur + (value * kInstrSize);
375
            }
376 377 378 379 380 381
          }
        } else {
          int32_t value1;
          int32_t value2;
          if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) {
            cur = reinterpret_cast<byte*>(value1);
382
            end = cur + (value2 * kInstrSize);
383 384 385 386
          }
        }

        while (cur < end) {
387 388
          prev = cur;
          cur += dasm.InstructionDecode(buffer, cur);
389 390
          PrintF("  0x%08" V8PRIxPTR "  %s\n", reinterpret_cast<intptr_t>(prev),
                 buffer.start());
391 392 393
        }
      } else if (strcmp(cmd, "gdb") == 0) {
        PrintF("relinquishing control to gdb\n");
394
        v8::base::OS::DebugBreak();
395 396
        PrintF("regaining control from gdb\n");
      } else if (strcmp(cmd, "break") == 0) {
397
        if (argc == 2) {
398 399
          int32_t value;
          if (GetValue(arg1, &value)) {
400
            if (!SetBreakpoint(reinterpret_cast<Instruction*>(value))) {
401 402 403 404 405 406
              PrintF("setting breakpoint failed\n");
            }
          } else {
            PrintF("%s unrecognized\n", arg1);
          }
        } else {
407
          PrintF("break <address>\n");
408 409
        }
      } else if (strcmp(cmd, "del") == 0) {
410
        if (!DeleteBreakpoint(nullptr)) {
411 412 413 414 415 416 417
          PrintF("deleting breakpoint failed\n");
        }
      } else if (strcmp(cmd, "flags") == 0) {
        PrintF("N flag: %d; ", sim_->n_flag_);
        PrintF("Z flag: %d; ", sim_->z_flag_);
        PrintF("C flag: %d; ", sim_->c_flag_);
        PrintF("V flag: %d\n", sim_->v_flag_);
418 419 420 421
        PrintF("INVALID OP flag: %d; ", sim_->inv_op_vfp_flag_);
        PrintF("DIV BY ZERO flag: %d; ", sim_->div_zero_vfp_flag_);
        PrintF("OVERFLOW flag: %d; ", sim_->overflow_vfp_flag_);
        PrintF("UNDERFLOW flag: %d; ", sim_->underflow_vfp_flag_);
422
        PrintF("INEXACT flag: %d;\n", sim_->inexact_vfp_flag_);
423 424
      } else if (strcmp(cmd, "stop") == 0) {
        int32_t value;
425
        intptr_t stop_pc = sim_->get_pc() - kInstrSize;
426
        Instruction* stop_instr = reinterpret_cast<Instruction*>(stop_pc);
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
        if ((argc == 2) && (strcmp(arg1, "unstop") == 0)) {
          // Remove the current stop.
          if (sim_->isStopInstruction(stop_instr)) {
            stop_instr->SetInstructionBits(kNopInstr);
          } else {
            PrintF("Not at debugger stop.\n");
          }
        } else if (argc == 3) {
          // Print information about all/the specified breakpoint(s).
          if (strcmp(arg1, "info") == 0) {
            if (strcmp(arg2, "all") == 0) {
              PrintF("Stop information:\n");
              for (uint32_t i = 0; i < sim_->kNumOfWatchedStops; i++) {
                sim_->PrintStopInfo(i);
              }
            } else if (GetValue(arg2, &value)) {
              sim_->PrintStopInfo(value);
            } else {
              PrintF("Unrecognized argument.\n");
            }
          } else if (strcmp(arg1, "enable") == 0) {
            // Enable all/the specified breakpoint(s).
            if (strcmp(arg2, "all") == 0) {
              for (uint32_t i = 0; i < sim_->kNumOfWatchedStops; i++) {
                sim_->EnableStop(i);
              }
            } else if (GetValue(arg2, &value)) {
              sim_->EnableStop(value);
            } else {
              PrintF("Unrecognized argument.\n");
            }
          } else if (strcmp(arg1, "disable") == 0) {
            // Disable all/the specified breakpoint(s).
            if (strcmp(arg2, "all") == 0) {
              for (uint32_t i = 0; i < sim_->kNumOfWatchedStops; i++) {
                sim_->DisableStop(i);
              }
            } else if (GetValue(arg2, &value)) {
              sim_->DisableStop(value);
            } else {
              PrintF("Unrecognized argument.\n");
            }
          }
470
        } else {
471
          PrintF("Wrong usage. Use help command for more information.\n");
472
        }
473 474 475 476
      } else if ((strcmp(cmd, "t") == 0) || strcmp(cmd, "trace") == 0) {
        ::v8::internal::FLAG_trace_sim = !::v8::internal::FLAG_trace_sim;
        PrintF("Trace of executed instructions is %s\n",
               ::v8::internal::FLAG_trace_sim ? "on" : "off");
477 478 479 480 481 482 483 484
      } else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) {
        PrintF("cont\n");
        PrintF("  continue execution (alias 'c')\n");
        PrintF("stepi\n");
        PrintF("  step one instruction (alias 'si')\n");
        PrintF("print <register>\n");
        PrintF("  print register content (alias 'p')\n");
        PrintF("  use register name 'all' to print all registers\n");
485
        PrintF("  add argument 'fp' to print register pair double values\n");
486 487 488 489
        PrintF("printobject <register>\n");
        PrintF("  print an object from a register (alias 'po')\n");
        PrintF("flags\n");
        PrintF("  print flags\n");
490 491 492 493
        PrintF("stack [<words>]\n");
        PrintF("  dump stack content, default dump 10 words)\n");
        PrintF("mem <address> [<words>]\n");
        PrintF("  dump memory content, default dump 10 words)\n");
494
        PrintF("disasm [<instructions>]\n");
495 496 497 498
        PrintF("disasm [<address/register>]\n");
        PrintF("disasm [[<address/register>] <instructions>]\n");
        PrintF("  disassemble code, default is 10 instructions\n");
        PrintF("  from pc (alias 'di')\n");
499 500 501 502 503 504
        PrintF("gdb\n");
        PrintF("  enter gdb\n");
        PrintF("break <address>\n");
        PrintF("  set a break point on the address\n");
        PrintF("del\n");
        PrintF("  delete the breakpoint\n");
505
        PrintF("trace (alias 't')\n");
506
        PrintF("  toogle the tracing of all executed statements\n");
507 508 509 510 511
        PrintF("stop feature:\n");
        PrintF("  Description:\n");
        PrintF("    Stops are debug instructions inserted by\n");
        PrintF("    the Assembler::stop() function.\n");
        PrintF("    When hitting a stop, the Simulator will\n");
512
        PrintF("    stop and give control to the ArmDebugger.\n");
513 514 515
        PrintF("    The first %d stop codes are watched:\n",
               Simulator::kNumOfWatchedStops);
        PrintF("    - They can be enabled / disabled: the Simulator\n");
516
        PrintF("      will / won't stop when hitting them.\n");
517 518 519 520 521 522 523 524 525 526 527
        PrintF("    - The Simulator keeps track of how many times they \n");
        PrintF("      are met. (See the info command.) Going over a\n");
        PrintF("      disabled stop still increases its counter. \n");
        PrintF("  Commands:\n");
        PrintF("    stop info all/<code> : print infos about number <code>\n");
        PrintF("      or all stop(s).\n");
        PrintF("    stop enable/disable all/<code> : enables / disables\n");
        PrintF("      all or number <code> stop(s)\n");
        PrintF("    stop unstop\n");
        PrintF("      ignore the stop instruction at the current location\n");
        PrintF("      from now on\n");
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
      } else {
        PrintF("Unknown command: %s\n", cmd);
      }
    }
  }

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

#undef COMMAND_SIZE
#undef ARG_SIZE

#undef STR
#undef XSTR
}

545
bool Simulator::ICacheMatch(void* one, void* two) {
546 547
  DCHECK_EQ(reinterpret_cast<intptr_t>(one) & CachePage::kPageMask, 0);
  DCHECK_EQ(reinterpret_cast<intptr_t>(two) & CachePage::kPageMask, 0);
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
  return one == two;
}


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


static bool AllOnOnePage(uintptr_t start, int size) {
  intptr_t start_page = (start & ~CachePage::kPageMask);
  intptr_t end_page = ((start + size) & ~CachePage::kPageMask);
  return start_page == end_page;
}

563 564 565 566 567
void Simulator::set_last_debugger_input(char* input) {
  DeleteArray(last_debugger_input_);
  last_debugger_input_ = input;
}

568 569 570 571
void Simulator::SetRedirectInstruction(Instruction* instruction) {
  instruction->SetInstructionBits(al | (0xF * B24) | kCallRtRedirected);
}

572 573
void Simulator::FlushICache(base::CustomMatcherHashMap* i_cache,
                            void* start_addr, size_t size) {
574 575 576 577 578 579 580 581
  intptr_t start = reinterpret_cast<intptr_t>(start_addr);
  int intra_line = (start & CachePage::kLineMask);
  start -= intra_line;
  size += intra_line;
  size = ((size - 1) | CachePage::kLineMask) + 1;
  int offset = (start & CachePage::kPageMask);
  while (!AllOnOnePage(start, size - 1)) {
    int bytes_to_flush = CachePage::kPageSize - offset;
582
    FlushOnePage(i_cache, start, bytes_to_flush);
583 584
    start += bytes_to_flush;
    size -= bytes_to_flush;
585
    DCHECK_EQ(0, start & CachePage::kPageMask);
586 587 588
    offset = 0;
  }
  if (size != 0) {
589
    FlushOnePage(i_cache, start, size);
590 591 592
  }
}

593 594
CachePage* Simulator::GetCachePage(base::CustomMatcherHashMap* i_cache,
                                   void* page) {
lpy's avatar
lpy committed
595
  base::HashMap::Entry* entry = i_cache->LookupOrInsert(page, ICacheHash(page));
596
  if (entry->value == nullptr) {
597 598 599 600 601 602 603 604
    CachePage* new_page = new CachePage();
    entry->value = new_page;
  }
  return reinterpret_cast<CachePage*>(entry->value);
}


// Flush from start up to and not including start + size.
605 606
void Simulator::FlushOnePage(base::CustomMatcherHashMap* i_cache,
                             intptr_t start, int size) {
607
  DCHECK_LE(size, CachePage::kPageSize);
608
  DCHECK(AllOnOnePage(start, size - 1));
609 610
  DCHECK_EQ(start & CachePage::kLineMask, 0);
  DCHECK_EQ(size & CachePage::kLineMask, 0);
611 612
  void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask));
  int offset = (start & CachePage::kPageMask);
613
  CachePage* cache_page = GetCachePage(i_cache, page);
614 615 616 617
  char* valid_bytemap = cache_page->ValidityByte(offset);
  memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift);
}

618 619
void Simulator::CheckICache(base::CustomMatcherHashMap* i_cache,
                            Instruction* instr) {
620 621 622 623
  intptr_t address = reinterpret_cast<intptr_t>(instr);
  void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask));
  void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask));
  int offset = (address & CachePage::kPageMask);
624
  CachePage* cache_page = GetCachePage(i_cache, page);
625 626 627 628 629
  char* cache_valid_byte = cache_page->ValidityByte(offset);
  bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID);
  char* cached_line = cache_page->CachedData(offset & ~CachePage::kLineMask);
  if (cache_hit) {
    // Check that the data in memory matches the contents of the I-cache.
630 631
    CHECK_EQ(0, memcmp(reinterpret_cast<void*>(instr),
                       cache_page->CachedData(offset), kInstrSize));
632 633
  } else {
    // Cache miss.  Load memory into the cache.
634
    memcpy(cached_line, line, CachePage::kLineLength);
635 636 637 638 639
    *cache_valid_byte = CachePage::LINE_VALID;
  }
}


640
Simulator::Simulator(Isolate* isolate) : isolate_(isolate) {
641
  // Set up simulator support first. Some of this information is needed to
642 643 644 645 646
  // setup the architecture state.
  size_t stack_size = 1 * 1024*1024;  // allocate 1MB for stack
  stack_ = reinterpret_cast<char*>(malloc(stack_size));
  pc_modified_ = false;
  icount_ = 0;
647
  break_pc_ = nullptr;
648 649
  break_instr_ = 0;

650
  // Set up architecture state.
651 652 653 654 655 656 657 658 659
  // All registers are initialized to zero to start with.
  for (int i = 0; i < num_registers; i++) {
    registers_[i] = 0;
  }
  n_flag_ = false;
  z_flag_ = false;
  c_flag_ = false;
  v_flag_ = false;

660
  // Initializing VFP registers.
661
  // All registers are initialized to zero to start with
662
  // even though s_registers_ & d_registers_ share the same
663
  // physical registers in the target.
664
  for (int i = 0; i < num_d_registers * 2; i++) {
665
    vfp_registers_[i] = 0;
666 667 668 669 670
  }
  n_flag_FPSCR_ = false;
  z_flag_FPSCR_ = false;
  c_flag_FPSCR_ = false;
  v_flag_FPSCR_ = false;
671 672
  FPSCR_rounding_mode_ = RN;
  FPSCR_default_NaN_mode_ = false;
673 674 675 676 677 678 679

  inv_op_vfp_flag_ = false;
  div_zero_vfp_flag_ = false;
  overflow_vfp_flag_ = false;
  underflow_vfp_flag_ = false;
  inexact_vfp_flag_ = false;

680 681 682 683 684 685 686 687
  // The sp is initialized to point to the bottom (high address) of the
  // allocated stack area. To be safe in potential stack underflows we leave
  // some buffer below.
  registers_[sp] = reinterpret_cast<int32_t>(stack_) + stack_size - 64;
  // The lr and pc are initialized to a known bad value that will cause an
  // access violation if the simulator ever tries to execute it.
  registers_[pc] = bad_lr;
  registers_[lr] = bad_lr;
688

689
  last_debugger_input_ = nullptr;
690 691
}

692
Simulator::~Simulator() {
693
  GlobalMonitor::Get()->RemoveProcessor(&global_monitor_processor_);
694 695
  free(stack_);
}
696

697

698
// Get the active Simulator for the current thread.
699 700
Simulator* Simulator::current(Isolate* isolate) {
  v8::internal::Isolate::PerIsolateThreadData* isolate_data =
701
      isolate->FindOrAllocatePerThreadDataForThisThread();
702
  DCHECK_NOT_NULL(isolate_data);
703 704

  Simulator* sim = isolate_data->simulator();
705
  if (sim == nullptr) {
706
    // TODO(146): delete the simulator object when a thread/isolate goes away.
707
    sim = new Simulator(isolate);
708
    isolate_data->set_simulator(sim);
709
  }
710
  return sim;
711 712 713 714 715 716
}


// Sets the register in the architecture state. It will also deal with updating
// Simulator internal state for special registers such as PC.
void Simulator::set_register(int reg, int32_t value) {
717
  DCHECK((reg >= 0) && (reg < num_registers));
718 719 720 721 722 723 724 725 726 727
  if (reg == pc) {
    pc_modified_ = true;
  }
  registers_[reg] = value;
}


// Get the register from the architecture state. This function does handle
// the special case of accessing the PC register.
int32_t Simulator::get_register(int reg) const {
728
  DCHECK((reg >= 0) && (reg < num_registers));
729 730 731 732
  // Stupid code added to avoid bug in GCC.
  // See: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43949
  if (reg >= num_registers) return 0;
  // End stupid code.
733
  return registers_[reg] + ((reg == pc) ? Instruction::kPcLoadDelta : 0);
734 735 736
}


737
double Simulator::get_double_from_register_pair(int reg) {
738
  DCHECK((reg >= 0) && (reg < num_registers) && ((reg % 2) == 0));
739 740 741 742

  double dm_val = 0.0;
  // Read the bits from the unsigned integer register_[] array
  // into the double precision floating point value and return it.
743
  char buffer[2 * sizeof(vfp_registers_[0])];
744 745
  memcpy(buffer, &registers_[reg], 2 * sizeof(registers_[0]));
  memcpy(&dm_val, buffer, 2 * sizeof(registers_[0]));
746 747 748 749
  return(dm_val);
}


750
void Simulator::set_register_pair_from_double(int reg, double* value) {
751
  DCHECK((reg >= 0) && (reg < num_registers) && ((reg % 2) == 0));
752 753 754 755
  memcpy(registers_ + reg, value, sizeof(*value));
}


756
void Simulator::set_dw_register(int dreg, const int* dbl) {
757
  DCHECK((dreg >= 0) && (dreg < num_d_registers));
758 759 760 761 762
  registers_[dreg] = dbl[0];
  registers_[dreg + 1] = dbl[1];
}


763
void Simulator::get_d_register(int dreg, uint64_t* value) {
764
  DCHECK((dreg >= 0) && (dreg < DwVfpRegister::NumRegisters()));
765 766 767 768 769
  memcpy(value, vfp_registers_ + dreg * 2, sizeof(*value));
}


void Simulator::set_d_register(int dreg, const uint64_t* value) {
770
  DCHECK((dreg >= 0) && (dreg < DwVfpRegister::NumRegisters()));
771 772 773 774 775
  memcpy(vfp_registers_ + dreg * 2, value, sizeof(*value));
}


void Simulator::get_d_register(int dreg, uint32_t* value) {
776
  DCHECK((dreg >= 0) && (dreg < DwVfpRegister::NumRegisters()));
777 778 779 780 781
  memcpy(value, vfp_registers_ + dreg * 2, sizeof(*value) * 2);
}


void Simulator::set_d_register(int dreg, const uint32_t* value) {
782
  DCHECK((dreg >= 0) && (dreg < DwVfpRegister::NumRegisters()));
783 784 785
  memcpy(vfp_registers_ + dreg * 2, value, sizeof(*value) * 2);
}

786 787 788 789 790 791
template <typename T, int SIZE>
void Simulator::get_neon_register(int reg, T (&value)[SIZE / sizeof(T)]) {
  DCHECK(SIZE == kSimd128Size || SIZE == kDoubleSize);
  DCHECK_LE(0, reg);
  DCHECK_GT(SIZE == kSimd128Size ? num_q_registers : num_d_registers, reg);
  memcpy(value, vfp_registers_ + reg * (SIZE / 4), SIZE);
792 793
}

794 795 796 797 798 799
template <typename T, int SIZE>
void Simulator::set_neon_register(int reg, const T (&value)[SIZE / sizeof(T)]) {
  DCHECK(SIZE == kSimd128Size || SIZE == kDoubleSize);
  DCHECK_LE(0, reg);
  DCHECK_GT(SIZE == kSimd128Size ? num_q_registers : num_d_registers, reg);
  memcpy(vfp_registers_ + reg * (SIZE / 4), value, SIZE);
800 801
}

802 803 804 805 806 807 808
// Raw access to the PC register.
void Simulator::set_pc(int32_t value) {
  pc_modified_ = true;
  registers_[pc] = value;
}


809 810 811 812 813
bool Simulator::has_bad_pc() const {
  return ((registers_[pc] == bad_lr) || (registers_[pc] == end_sim_pc));
}


814 815 816 817 818
// Raw access to the PC register without the special adjustment when reading.
int32_t Simulator::get_pc() const {
  return registers_[pc];
}

819

820 821
// Getting from and setting into VFP registers.
void Simulator::set_s_register(int sreg, unsigned int value) {
822
  DCHECK((sreg >= 0) && (sreg < num_s_registers));
823
  vfp_registers_[sreg] = value;
824 825
}

826

827
unsigned int Simulator::get_s_register(int sreg) const {
828
  DCHECK((sreg >= 0) && (sreg < num_s_registers));
829
  return vfp_registers_[sreg];
830 831
}

832

833 834
template<class InputType, int register_size>
void Simulator::SetVFPRegister(int reg_index, const InputType& value) {
835 836 837
  unsigned bytes = register_size * sizeof(vfp_registers_[0]);
  DCHECK_EQ(sizeof(InputType), bytes);
  DCHECK_GE(reg_index, 0);
838 839
  if (register_size == 1) DCHECK(reg_index < num_s_registers);
  if (register_size == 2) DCHECK(reg_index < DwVfpRegister::NumRegisters());
840

841
  memcpy(&vfp_registers_[reg_index * register_size], &value, bytes);
842 843 844 845 846
}


template<class ReturnType, int register_size>
ReturnType Simulator::GetFromVFPRegister(int reg_index) {
847 848 849
  unsigned bytes = register_size * sizeof(vfp_registers_[0]);
  DCHECK_EQ(sizeof(ReturnType), bytes);
  DCHECK_GE(reg_index, 0);
850 851
  if (register_size == 1) DCHECK(reg_index < num_s_registers);
  if (register_size == 2) DCHECK(reg_index < DwVfpRegister::NumRegisters());
852

853 854
  ReturnType value;
  memcpy(&value, &vfp_registers_[register_size * reg_index], bytes);
855
  return value;
856 857
}

858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
void Simulator::SetSpecialRegister(SRegisterFieldMask reg_and_mask,
                                   uint32_t value) {
  // Only CPSR_f is implemented. Of that, only N, Z, C and V are implemented.
  if ((reg_and_mask == CPSR_f) && ((value & ~kSpecialCondition) == 0)) {
    n_flag_ = ((value & (1 << 31)) != 0);
    z_flag_ = ((value & (1 << 30)) != 0);
    c_flag_ = ((value & (1 << 29)) != 0);
    v_flag_ = ((value & (1 << 28)) != 0);
  } else {
    UNIMPLEMENTED();
  }
}

uint32_t Simulator::GetFromSpecialRegister(SRegister reg) {
  uint32_t result = 0;
  // Only CPSR_f is implemented.
  if (reg == CPSR) {
    if (n_flag_) result |= (1 << 31);
    if (z_flag_) result |= (1 << 30);
    if (c_flag_) result |= (1 << 29);
    if (v_flag_) result |= (1 << 28);
  } else {
    UNIMPLEMENTED();
  }
  return result;
}
884

885 886 887 888
// Runtime FP routines take:
// - two double arguments
// - one double argument and zero or one integer arguments.
// All are consructed here from r0-r3 or d0, d1 and r0.
889
void Simulator::GetFpArgs(double* x, double* y, int32_t* z) {
890
  if (use_eabi_hardfloat()) {
891 892
    *x = get_double_from_d_register(0).get_scalar();
    *y = get_double_from_d_register(1).get_scalar();
893
    *z = get_register(0);
894 895
  } else {
    // Registers 0 and 1 -> x.
896
    *x = get_double_from_register_pair(0);
897
    // Register 2 and 3 -> y.
898
    *y = get_double_from_register_pair(2);
899
    // Register 2 -> z
900
    *z = get_register(2);
901 902 903 904 905
  }
}


// The return value is either in r0/r1 or d0.
906
void Simulator::SetFpResult(const double& result) {
907
  if (use_eabi_hardfloat()) {
908
    char buffer[2 * sizeof(vfp_registers_[0])];
909
    memcpy(buffer, &result, sizeof(buffer));
910
    // Copy result to d0.
911
    memcpy(vfp_registers_, buffer, sizeof(buffer));
912 913
  } else {
    char buffer[2 * sizeof(registers_[0])];
914
    memcpy(buffer, &result, sizeof(buffer));
915
    // Copy result to r0 and r1.
916
    memcpy(registers_, buffer, sizeof(buffer));
917
  }
918 919 920 921 922
}


void Simulator::TrashCallerSaveRegisters() {
  // We don't trash the registers with the return value.
923 924 925
  registers_[2] = 0x50BAD4U;
  registers_[3] = 0x50BAD4U;
  registers_[12] = 0x50BAD4U;
926 927
}

928
int Simulator::ReadW(int32_t addr) {
929 930
  // All supported ARM targets allow unaligned accesses, so we don't need to
  // check the alignment here.
931
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
932
  local_monitor_.NotifyLoad(addr);
933 934
  intptr_t* ptr = reinterpret_cast<intptr_t*>(addr);
  return *ptr;
935 936
}

937
int Simulator::ReadExW(int32_t addr) {
938
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
939
  local_monitor_.NotifyLoadExcl(addr, TransactionSize::Word);
940
  GlobalMonitor::Get()->NotifyLoadExcl_Locked(addr, &global_monitor_processor_);
941 942 943
  intptr_t* ptr = reinterpret_cast<intptr_t*>(addr);
  return *ptr;
}
944

945
void Simulator::WriteW(int32_t addr, int value) {
946 947
  // All supported ARM targets allow unaligned accesses, so we don't need to
  // check the alignment here.
948
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
949
  local_monitor_.NotifyStore(addr);
950
  GlobalMonitor::Get()->NotifyStore_Locked(addr, &global_monitor_processor_);
951 952
  intptr_t* ptr = reinterpret_cast<intptr_t*>(addr);
  *ptr = value;
953 954
}

955
int Simulator::WriteExW(int32_t addr, int value) {
956
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
957
  if (local_monitor_.NotifyStoreExcl(addr, TransactionSize::Word) &&
958
      GlobalMonitor::Get()->NotifyStoreExcl_Locked(
959 960 961 962 963 964 965 966
          addr, &global_monitor_processor_)) {
    intptr_t* ptr = reinterpret_cast<intptr_t*>(addr);
    *ptr = value;
    return 0;
  } else {
    return 1;
  }
}
967

968
uint16_t Simulator::ReadHU(int32_t addr) {
969 970
  // All supported ARM targets allow unaligned accesses, so we don't need to
  // check the alignment here.
971
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
972
  local_monitor_.NotifyLoad(addr);
973 974
  uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
  return *ptr;
975 976
}

977
int16_t Simulator::ReadH(int32_t addr) {
978 979
  // All supported ARM targets allow unaligned accesses, so we don't need to
  // check the alignment here.
980
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
981
  local_monitor_.NotifyLoad(addr);
982 983
  int16_t* ptr = reinterpret_cast<int16_t*>(addr);
  return *ptr;
984 985
}

986
uint16_t Simulator::ReadExHU(int32_t addr) {
987
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
988
  local_monitor_.NotifyLoadExcl(addr, TransactionSize::HalfWord);
989
  GlobalMonitor::Get()->NotifyLoadExcl_Locked(addr, &global_monitor_processor_);
990 991 992
  uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
  return *ptr;
}
993

994
void Simulator::WriteH(int32_t addr, uint16_t value) {
995 996
  // All supported ARM targets allow unaligned accesses, so we don't need to
  // check the alignment here.
997
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
998
  local_monitor_.NotifyStore(addr);
999
  GlobalMonitor::Get()->NotifyStore_Locked(addr, &global_monitor_processor_);
1000 1001
  uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
  *ptr = value;
1002 1003
}

1004
void Simulator::WriteH(int32_t addr, int16_t value) {
1005 1006
  // All supported ARM targets allow unaligned accesses, so we don't need to
  // check the alignment here.
1007
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
1008
  local_monitor_.NotifyStore(addr);
1009
  GlobalMonitor::Get()->NotifyStore_Locked(addr, &global_monitor_processor_);
1010 1011
  int16_t* ptr = reinterpret_cast<int16_t*>(addr);
  *ptr = value;
1012 1013
}

1014
int Simulator::WriteExH(int32_t addr, uint16_t value) {
1015
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
1016
  if (local_monitor_.NotifyStoreExcl(addr, TransactionSize::HalfWord) &&
1017
      GlobalMonitor::Get()->NotifyStoreExcl_Locked(
1018 1019 1020 1021 1022 1023 1024 1025
          addr, &global_monitor_processor_)) {
    uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
    *ptr = value;
    return 0;
  } else {
    return 1;
  }
}
1026 1027

uint8_t Simulator::ReadBU(int32_t addr) {
1028
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
1029
  local_monitor_.NotifyLoad(addr);
1030 1031 1032 1033 1034
  uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
  return *ptr;
}

int8_t Simulator::ReadB(int32_t addr) {
1035
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
1036
  local_monitor_.NotifyLoad(addr);
1037 1038 1039 1040
  int8_t* ptr = reinterpret_cast<int8_t*>(addr);
  return *ptr;
}

1041
uint8_t Simulator::ReadExBU(int32_t addr) {
1042
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
1043
  local_monitor_.NotifyLoadExcl(addr, TransactionSize::Byte);
1044
  GlobalMonitor::Get()->NotifyLoadExcl_Locked(addr, &global_monitor_processor_);
1045 1046 1047
  uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
  return *ptr;
}
1048 1049

void Simulator::WriteB(int32_t addr, uint8_t value) {
1050
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
1051
  local_monitor_.NotifyStore(addr);
1052
  GlobalMonitor::Get()->NotifyStore_Locked(addr, &global_monitor_processor_);
1053 1054 1055 1056 1057
  uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
  *ptr = value;
}

void Simulator::WriteB(int32_t addr, int8_t value) {
1058
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
1059
  local_monitor_.NotifyStore(addr);
1060
  GlobalMonitor::Get()->NotifyStore_Locked(addr, &global_monitor_processor_);
1061 1062 1063 1064
  int8_t* ptr = reinterpret_cast<int8_t*>(addr);
  *ptr = value;
}

1065
int Simulator::WriteExB(int32_t addr, uint8_t value) {
1066
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
1067
  if (local_monitor_.NotifyStoreExcl(addr, TransactionSize::Byte) &&
1068
      GlobalMonitor::Get()->NotifyStoreExcl_Locked(
1069 1070 1071 1072 1073 1074 1075 1076
          addr, &global_monitor_processor_)) {
    uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
    *ptr = value;
    return 0;
  } else {
    return 1;
  }
}
1077

1078
int32_t* Simulator::ReadDW(int32_t addr) {
1079 1080
  // All supported ARM targets allow unaligned accesses, so we don't need to
  // check the alignment here.
1081
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
1082
  local_monitor_.NotifyLoad(addr);
1083 1084
  int32_t* ptr = reinterpret_cast<int32_t*>(addr);
  return ptr;
1085 1086
}

1087
int32_t* Simulator::ReadExDW(int32_t addr) {
1088
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
1089
  local_monitor_.NotifyLoadExcl(addr, TransactionSize::DoubleWord);
1090
  GlobalMonitor::Get()->NotifyLoadExcl_Locked(addr, &global_monitor_processor_);
1091 1092 1093
  int32_t* ptr = reinterpret_cast<int32_t*>(addr);
  return ptr;
}
1094 1095

void Simulator::WriteDW(int32_t addr, int32_t value1, int32_t value2) {
1096 1097
  // All supported ARM targets allow unaligned accesses, so we don't need to
  // check the alignment here.
1098
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
1099
  local_monitor_.NotifyStore(addr);
1100
  GlobalMonitor::Get()->NotifyStore_Locked(addr, &global_monitor_processor_);
1101 1102 1103
  int32_t* ptr = reinterpret_cast<int32_t*>(addr);
  *ptr++ = value1;
  *ptr = value2;
1104 1105
}

1106
int Simulator::WriteExDW(int32_t addr, int32_t value1, int32_t value2) {
1107
  base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex);
1108
  if (local_monitor_.NotifyStoreExcl(addr, TransactionSize::DoubleWord) &&
1109
      GlobalMonitor::Get()->NotifyStoreExcl_Locked(
1110 1111 1112 1113 1114 1115 1116 1117 1118
          addr, &global_monitor_processor_)) {
    intptr_t* ptr = reinterpret_cast<intptr_t*>(addr);
    *ptr++ = value1;
    *ptr = value2;
    return 0;
  } else {
    return 1;
  }
}
1119

1120
// Returns the limit of the stack area to enable checking for stack overflows.
1121 1122 1123 1124 1125 1126 1127 1128 1129
uintptr_t Simulator::StackLimit(uintptr_t c_limit) const {
  // The simulator uses a separate JS stack. If we have exhausted the C stack,
  // we also drop down the JS limit to reflect the exhaustion on the JS stack.
  if (GetCurrentStackPosition() < c_limit) {
    return reinterpret_cast<uintptr_t>(get_sp());
  }

  // Otherwise the limit is the JS stack. Leave a safety margin of 1024 bytes
  // to prevent overrunning the stack when pushing values.
1130
  return reinterpret_cast<uintptr_t>(stack_) + 1024;
1131 1132 1133 1134
}


// Unsupported instructions use Format to print an error and stop execution.
1135
void Simulator::Format(Instruction* instr, const char* format) {
1136
  PrintF("Simulator found unsupported instruction:\n 0x%08" V8PRIxPTR ": %s\n",
1137
         reinterpret_cast<intptr_t>(instr), format);
1138 1139 1140 1141 1142 1143
  UNIMPLEMENTED();
}


// Checks if the current instruction should be executed based on its
// condition bits.
1144
bool Simulator::ConditionallyExecute(Instruction* instr) {
1145
  switch (instr->ConditionField()) {
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
    case eq: return z_flag_;
    case ne: return !z_flag_;
    case cs: return c_flag_;
    case cc: return !c_flag_;
    case mi: return n_flag_;
    case pl: return !n_flag_;
    case vs: return v_flag_;
    case vc: return !v_flag_;
    case hi: return c_flag_ && !z_flag_;
    case ls: return !c_flag_ || z_flag_;
    case ge: return n_flag_ == v_flag_;
    case lt: return n_flag_ != v_flag_;
    case gt: return !z_flag_ && (n_flag_ == v_flag_);
    case le: return z_flag_ || (n_flag_ != v_flag_);
    case al: return true;
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    default: UNREACHABLE();
  }
  return false;
}


// Calculate and set the Negative and Zero flags.
void Simulator::SetNZFlags(int32_t val) {
  n_flag_ = (val < 0);
  z_flag_ = (val == 0);
}


// Set the Carry flag.
void Simulator::SetCFlag(bool val) {
  c_flag_ = val;
}


// Set the oVerflow flag.
void Simulator::SetVFlag(bool val) {
  v_flag_ = val;
}


// Calculate C flag value for additions.
1187
bool Simulator::CarryFrom(int32_t left, int32_t right, int32_t carry) {
1188 1189
  uint32_t uleft = static_cast<uint32_t>(left);
  uint32_t uright = static_cast<uint32_t>(right);
1190
  uint32_t urest = 0xFFFFFFFFU - uleft;
1191

1192 1193
  return (uright > urest) ||
         (carry && (((uright + 1) > urest) || (uright > (urest - 1))));
1194 1195 1196 1197
}


// Calculate C flag value for subtractions.
1198
bool Simulator::BorrowFrom(int32_t left, int32_t right, int32_t carry) {
1199 1200 1201
  uint32_t uleft = static_cast<uint32_t>(left);
  uint32_t uright = static_cast<uint32_t>(right);

1202 1203
  return (uright > uleft) ||
         (!carry && (((uright + 1) > uleft) || (uright > (uleft - 1))));
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
}


// Calculate V flag value for additions and subtractions.
bool Simulator::OverflowFrom(int32_t alu_out,
                             int32_t left, int32_t right, bool addition) {
  bool overflow;
  if (addition) {
               // operands have the same sign
    overflow = ((left >= 0 && right >= 0) || (left < 0 && right < 0))
               // and operands and result have different sign
               && ((left < 0 && alu_out >= 0) || (left >= 0 && alu_out < 0));
  } else {
               // operands have different signs
    overflow = ((left < 0 && right >= 0) || (left >= 0 && right < 0))
               // and first operand and result have different signs
               && ((left < 0 && alu_out >= 0) || (left >= 0 && alu_out < 0));
  }
  return overflow;
}

1225

1226
// Support for VFP comparisons.
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
void Simulator::Compute_FPSCR_Flags(float val1, float val2) {
  if (std::isnan(val1) || std::isnan(val2)) {
    n_flag_FPSCR_ = false;
    z_flag_FPSCR_ = false;
    c_flag_FPSCR_ = true;
    v_flag_FPSCR_ = true;
    // All non-NaN cases.
  } else if (val1 == val2) {
    n_flag_FPSCR_ = false;
    z_flag_FPSCR_ = true;
    c_flag_FPSCR_ = true;
    v_flag_FPSCR_ = false;
  } else if (val1 < val2) {
    n_flag_FPSCR_ = true;
    z_flag_FPSCR_ = false;
    c_flag_FPSCR_ = false;
    v_flag_FPSCR_ = false;
  } else {
    // Case when (val1 > val2).
    n_flag_FPSCR_ = false;
    z_flag_FPSCR_ = false;
    c_flag_FPSCR_ = true;
    v_flag_FPSCR_ = false;
  }
}


1254
void Simulator::Compute_FPSCR_Flags(double val1, double val2) {
1255
  if (std::isnan(val1) || std::isnan(val2)) {
1256 1257 1258 1259
    n_flag_FPSCR_ = false;
    z_flag_FPSCR_ = false;
    c_flag_FPSCR_ = true;
    v_flag_FPSCR_ = true;
1260
  // All non-NaN cases.
1261
  } else if (val1 == val2) {
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
    n_flag_FPSCR_ = false;
    z_flag_FPSCR_ = true;
    c_flag_FPSCR_ = true;
    v_flag_FPSCR_ = false;
  } else if (val1 < val2) {
    n_flag_FPSCR_ = true;
    z_flag_FPSCR_ = false;
    c_flag_FPSCR_ = false;
    v_flag_FPSCR_ = false;
  } else {
    // Case when (val1 > val2).
    n_flag_FPSCR_ = false;
    z_flag_FPSCR_ = false;
    c_flag_FPSCR_ = true;
    v_flag_FPSCR_ = false;
  }
}


void Simulator::Copy_FPSCR_to_APSR() {
  n_flag_ = n_flag_FPSCR_;
  z_flag_ = z_flag_FPSCR_;
  c_flag_ = c_flag_FPSCR_;
  v_flag_ = v_flag_FPSCR_;
}


1289 1290
// Addressing Mode 1 - Data-processing operands:
// Get the value based on the shifter_operand with register.
1291 1292 1293 1294
int32_t Simulator::GetShiftRm(Instruction* instr, bool* carry_out) {
  ShiftOp shift = instr->ShiftField();
  int shift_amount = instr->ShiftAmountValue();
  int32_t result = get_register(instr->RmValue());
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
  if (instr->Bit(4) == 0) {
    // by immediate
    if ((shift == ROR) && (shift_amount == 0)) {
      UNIMPLEMENTED();
      return result;
    } else if (((shift == LSR) || (shift == ASR)) && (shift_amount == 0)) {
      shift_amount = 32;
    }
    switch (shift) {
      case ASR: {
        if (shift_amount == 0) {
          if (result < 0) {
1307
            result = 0xFFFFFFFF;
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
            *carry_out = true;
          } else {
            result = 0;
            *carry_out = false;
          }
        } else {
          result >>= (shift_amount - 1);
          *carry_out = (result & 1) == 1;
          result >>= 1;
        }
        break;
      }

      case LSL: {
        if (shift_amount == 0) {
          *carry_out = c_flag_;
        } else {
          result <<= (shift_amount - 1);
          *carry_out = (result < 0);
          result <<= 1;
        }
        break;
      }

      case LSR: {
        if (shift_amount == 0) {
          result = 0;
          *carry_out = c_flag_;
        } else {
          uint32_t uresult = static_cast<uint32_t>(result);
          uresult >>= (shift_amount - 1);
          *carry_out = (uresult & 1) == 1;
          uresult >>= 1;
          result = static_cast<int32_t>(uresult);
        }
        break;
      }

      case ROR: {
1347 1348 1349 1350 1351 1352 1353 1354
        if (shift_amount == 0) {
          *carry_out = c_flag_;
        } else {
          uint32_t left = static_cast<uint32_t>(result) >> shift_amount;
          uint32_t right = static_cast<uint32_t>(result) << (32 - shift_amount);
          result = right | left;
          *carry_out = (static_cast<uint32_t>(result) >> 31) != 0;
        }
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
        break;
      }

      default: {
        UNREACHABLE();
        break;
      }
    }
  } else {
    // by register
1365
    int rs = instr->RsValue();
1366
    shift_amount = get_register(rs) & 0xFF;
1367 1368 1369 1370 1371 1372 1373 1374 1375
    switch (shift) {
      case ASR: {
        if (shift_amount == 0) {
          *carry_out = c_flag_;
        } else if (shift_amount < 32) {
          result >>= (shift_amount - 1);
          *carry_out = (result & 1) == 1;
          result >>= 1;
        } else {
1376
          DCHECK_GE(shift_amount, 32);
1377 1378
          if (result < 0) {
            *carry_out = true;
1379
            result = 0xFFFFFFFF;
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
          } else {
            *carry_out = false;
            result = 0;
          }
        }
        break;
      }

      case LSL: {
        if (shift_amount == 0) {
          *carry_out = c_flag_;
        } else if (shift_amount < 32) {
          result <<= (shift_amount - 1);
          *carry_out = (result < 0);
          result <<= 1;
        } else if (shift_amount == 32) {
          *carry_out = (result & 1) == 1;
          result = 0;
        } else {
1399
          DCHECK_GT(shift_amount, 32);
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
          *carry_out = false;
          result = 0;
        }
        break;
      }

      case LSR: {
        if (shift_amount == 0) {
          *carry_out = c_flag_;
        } else if (shift_amount < 32) {
          uint32_t uresult = static_cast<uint32_t>(result);
          uresult >>= (shift_amount - 1);
          *carry_out = (uresult & 1) == 1;
          uresult >>= 1;
          result = static_cast<int32_t>(uresult);
        } else if (shift_amount == 32) {
          *carry_out = (result < 0);
          result = 0;
        } else {
          *carry_out = false;
          result = 0;
        }
        break;
      }

      case ROR: {
1426 1427 1428 1429 1430 1431 1432 1433
        if (shift_amount == 0) {
          *carry_out = c_flag_;
        } else {
          uint32_t left = static_cast<uint32_t>(result) >> shift_amount;
          uint32_t right = static_cast<uint32_t>(result) << (32 - shift_amount);
          result = right | left;
          *carry_out = (static_cast<uint32_t>(result) >> 31) != 0;
        }
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
        break;
      }

      default: {
        UNREACHABLE();
        break;
      }
    }
  }
  return result;
}


// Addressing Mode 1 - Data-processing operands:
// Get the value based on the shifter_operand with immediate.
1449 1450 1451
int32_t Simulator::GetImm(Instruction* instr, bool* carry_out) {
  int rotate = instr->RotateValue() * 2;
  int immed8 = instr->Immed8Value();
1452
  int imm = base::bits::RotateRight32(immed8, rotate);
1453 1454 1455 1456 1457 1458 1459 1460
  *carry_out = (rotate == 0) ? c_flag_ : (imm < 0);
  return imm;
}


static int count_bits(int bit_vector) {
  int count = 0;
  while (bit_vector != 0) {
1461
    if ((bit_vector & 1) != 0) {
1462 1463 1464 1465 1466 1467 1468 1469
      count++;
    }
    bit_vector >>= 1;
  }
  return count;
}


1470 1471 1472 1473 1474
int32_t Simulator::ProcessPU(Instruction* instr,
                             int num_regs,
                             int reg_size,
                             intptr_t* start_address,
                             intptr_t* end_address) {
1475
  int rn = instr->RnValue();
1476 1477
  int32_t rn_val = get_register(rn);
  switch (instr->PUField()) {
1478
    case da_x: {
1479 1480 1481
      UNIMPLEMENTED();
      break;
    }
1482
    case ia_x: {
1483 1484 1485
      *start_address = rn_val;
      *end_address = rn_val + (num_regs * reg_size) - reg_size;
      rn_val = rn_val + (num_regs * reg_size);
1486 1487
      break;
    }
1488
    case db_x: {
1489 1490 1491
      *start_address = rn_val - (num_regs * reg_size);
      *end_address = rn_val - reg_size;
      rn_val = *start_address;
1492 1493
      break;
    }
1494
    case ib_x: {
1495 1496 1497
      *start_address = rn_val + reg_size;
      *end_address = rn_val + (num_regs * reg_size);
      rn_val = *end_address;
1498 1499 1500 1501 1502 1503 1504
      break;
    }
    default: {
      UNREACHABLE();
      break;
    }
  }
1505
  return rn_val;
1506 1507
}

1508

1509 1510 1511 1512 1513 1514 1515
// Addressing Mode 4 - Load and Store Multiple
void Simulator::HandleRList(Instruction* instr, bool load) {
  int rlist = instr->RlistValue();
  int num_regs = count_bits(rlist);

  intptr_t start_address = 0;
  intptr_t end_address = 0;
1516 1517
  int32_t rn_val =
      ProcessPU(instr, num_regs, kPointerSize, &start_address, &end_address);
1518

1519
  intptr_t* address = reinterpret_cast<intptr_t*>(start_address);
1520
  // Catch null pointers a little earlier.
1521
  DCHECK(start_address > 8191 || start_address < 0);
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
  int reg = 0;
  while (rlist != 0) {
    if ((rlist & 1) != 0) {
      if (load) {
        set_register(reg, *address);
      } else {
        *address = get_register(reg);
      }
      address += 1;
    }
    reg++;
    rlist >>= 1;
  }
1535
  DCHECK(end_address == ((intptr_t)address) - 4);
1536 1537 1538
  if (instr->HasW()) {
    set_register(instr->RnValue(), rn_val);
  }
1539 1540 1541
}


1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
// Addressing Mode 6 - Load and Store Multiple Coprocessor registers.
void Simulator::HandleVList(Instruction* instr) {
  VFPRegPrecision precision =
      (instr->SzValue() == 0) ? kSinglePrecision : kDoublePrecision;
  int operand_size = (precision == kSinglePrecision) ? 4 : 8;

  bool load = (instr->VLValue() == 0x1);

  int vd;
  int num_regs;
  vd = instr->VFPDRegValue(precision);
  if (precision == kSinglePrecision) {
    num_regs = instr->Immed8Value();
  } else {
    num_regs = instr->Immed8Value() / 2;
  }

  intptr_t start_address = 0;
  intptr_t end_address = 0;
1561 1562
  int32_t rn_val =
      ProcessPU(instr, num_regs, operand_size, &start_address, &end_address);
1563 1564 1565 1566 1567

  intptr_t* address = reinterpret_cast<intptr_t*>(start_address);
  for (int reg = vd; reg < vd + num_regs; reg++) {
    if (precision == kSinglePrecision) {
      if (load) {
1568 1569
        set_s_register_from_sinteger(reg,
                                     ReadW(reinterpret_cast<int32_t>(address)));
1570 1571
      } else {
        WriteW(reinterpret_cast<int32_t>(address),
1572
               get_sinteger_from_s_register(reg));
1573 1574 1575 1576
      }
      address += 1;
    } else {
      if (load) {
1577 1578
        int32_t data[] = {ReadW(reinterpret_cast<int32_t>(address)),
                          ReadW(reinterpret_cast<int32_t>(address + 1))};
1579
        set_d_register(reg, reinterpret_cast<uint32_t*>(data));
1580
      } else {
1581 1582
        uint32_t data[2];
        get_d_register(reg, data);
1583 1584
        WriteW(reinterpret_cast<int32_t>(address), data[0]);
        WriteW(reinterpret_cast<int32_t>(address + 1), data[1]);
1585 1586 1587 1588
      }
      address += 2;
    }
  }
1589
  DCHECK(reinterpret_cast<intptr_t>(address) - operand_size == end_address);
1590 1591 1592
  if (instr->HasW()) {
    set_register(instr->RnValue(), rn_val);
  }
1593 1594 1595
}


1596 1597 1598 1599 1600 1601
// Calls into the V8 runtime are based on this very simple interface.
// Note: To be able to return two values from some calls the code in runtime.cc
// uses the ObjectPair which is essentially two 32-bit values stuffed into a
// 64-bit value. With the code below we assume that all runtime calls return
// 64 bits of result. If they don't, the r1 result register contains a bogus
// value, which is fine because it is caller-saved.
1602 1603 1604 1605 1606
typedef int64_t (*SimulatorRuntimeCall)(int32_t arg0, int32_t arg1,
                                        int32_t arg2, int32_t arg3,
                                        int32_t arg4, int32_t arg5,
                                        int32_t arg6, int32_t arg7,
                                        int32_t arg8);
1607 1608 1609 1610 1611 1612

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

1614 1615
// This signature supports direct call in to API function native callback
// (refer to InvocationCallback in v8.h).
1616
typedef void (*SimulatorRuntimeDirectApiCall)(int32_t arg0);
1617
typedef void (*SimulatorRuntimeProfilingApiCall)(int32_t arg0, void* arg1);
1618 1619

// This signature supports direct call to accessor getter callback.
1620 1621
typedef void (*SimulatorRuntimeDirectGetterCall)(int32_t arg0, int32_t arg1);
typedef void (*SimulatorRuntimeProfilingGetterCall)(
1622
    int32_t arg0, int32_t arg1, void* arg2);
1623 1624 1625

// Software interrupt instructions are used by the simulator to call into the
// C-based V8 runtime.
1626 1627
void Simulator::SoftwareInterrupt(Instruction* instr) {
  int svc = instr->SvcValue();
1628
  switch (svc) {
1629
    case kCallRtRedirected: {
1630 1631 1632 1633 1634
      // Check if stack is aligned. Error if not aligned is reported below to
      // include information on the function called.
      bool stack_aligned =
          (get_register(sp)
           & (::v8::internal::FLAG_sim_stack_alignment - 1)) == 0;
1635
      Redirection* redirection = Redirection::FromInstruction(instr);
1636 1637 1638 1639
      int32_t arg0 = get_register(r0);
      int32_t arg1 = get_register(r1);
      int32_t arg2 = get_register(r2);
      int32_t arg3 = get_register(r3);
1640
      int32_t* stack_pointer = reinterpret_cast<int32_t*>(get_register(sp));
1641 1642
      int32_t arg4 = stack_pointer[0];
      int32_t arg5 = stack_pointer[1];
1643 1644 1645 1646 1647
      int32_t arg6 = stack_pointer[2];
      int32_t arg7 = stack_pointer[3];
      int32_t arg8 = stack_pointer[4];
      STATIC_ASSERT(kMaxCParameters == 9);

1648 1649 1650 1651 1652
      bool fp_call =
         (redirection->type() == ExternalReference::BUILTIN_FP_FP_CALL) ||
         (redirection->type() == ExternalReference::BUILTIN_COMPARE_CALL) ||
         (redirection->type() == ExternalReference::BUILTIN_FP_CALL) ||
         (redirection->type() == ExternalReference::BUILTIN_FP_INT_CALL);
1653 1654 1655
      // This is dodgy but it works because the C entry stubs are never moved.
      // See comment in codegen-arm.cc and bug 1242173.
      int32_t saved_lr = get_register(lr);
1656 1657
      intptr_t external =
          reinterpret_cast<intptr_t>(redirection->external_function());
1658
      if (fp_call) {
1659 1660 1661 1662 1663
        double dval0, dval1;  // one or two double parameters
        int32_t ival;         // zero or one integer parameters
        int64_t iresult = 0;  // integer return value
        double dresult = 0;   // double return value
        GetFpArgs(&dval0, &dval1, &ival);
1664
        if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
1665 1666
          SimulatorRuntimeCall generic_target =
            reinterpret_cast<SimulatorRuntimeCall>(external);
1667 1668 1669 1670
          switch (redirection->type()) {
          case ExternalReference::BUILTIN_FP_FP_CALL:
          case ExternalReference::BUILTIN_COMPARE_CALL:
            PrintF("Call to host function at %p with args %f, %f",
1671 1672
                   reinterpret_cast<void*>(FUNCTION_ADDR(generic_target)),
                   dval0, dval1);
1673 1674 1675
            break;
          case ExternalReference::BUILTIN_FP_CALL:
            PrintF("Call to host function at %p with arg %f",
1676 1677
                   reinterpret_cast<void*>(FUNCTION_ADDR(generic_target)),
                   dval0);
1678 1679 1680
            break;
          case ExternalReference::BUILTIN_FP_INT_CALL:
            PrintF("Call to host function at %p with args %f, %d",
1681 1682
                   reinterpret_cast<void*>(FUNCTION_ADDR(generic_target)),
                   dval0, ival);
1683 1684 1685 1686 1687
            break;
          default:
            UNREACHABLE();
            break;
          }
1688 1689 1690 1691
          if (!stack_aligned) {
            PrintF(" with unaligned stack %08x\n", get_register(sp));
          }
          PrintF("\n");
1692
        }
1693
        CHECK(stack_aligned);
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
        switch (redirection->type()) {
        case ExternalReference::BUILTIN_COMPARE_CALL: {
          SimulatorRuntimeCompareCall target =
            reinterpret_cast<SimulatorRuntimeCompareCall>(external);
          iresult = target(dval0, dval1);
          set_register(r0, static_cast<int32_t>(iresult));
          set_register(r1, static_cast<int32_t>(iresult >> 32));
          break;
        }
        case ExternalReference::BUILTIN_FP_FP_CALL: {
          SimulatorRuntimeFPFPCall target =
            reinterpret_cast<SimulatorRuntimeFPFPCall>(external);
          dresult = target(dval0, dval1);
          SetFpResult(dresult);
          break;
        }
        case ExternalReference::BUILTIN_FP_CALL: {
1711
          SimulatorRuntimeFPCall target =
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
            reinterpret_cast<SimulatorRuntimeFPCall>(external);
          dresult = target(dval0);
          SetFpResult(dresult);
          break;
        }
        case ExternalReference::BUILTIN_FP_INT_CALL: {
          SimulatorRuntimeFPIntCall target =
            reinterpret_cast<SimulatorRuntimeFPIntCall>(external);
          dresult = target(dval0, ival);
          SetFpResult(dresult);
          break;
        }
        default:
          UNREACHABLE();
          break;
        }
        if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
          switch (redirection->type()) {
          case ExternalReference::BUILTIN_COMPARE_CALL:
            PrintF("Returned %08x\n", static_cast<int32_t>(iresult));
            break;
          case ExternalReference::BUILTIN_FP_FP_CALL:
          case ExternalReference::BUILTIN_FP_CALL:
          case ExternalReference::BUILTIN_FP_INT_CALL:
            PrintF("Returned %f\n", dresult);
            break;
          default:
            UNREACHABLE();
            break;
1741
          }
1742
        }
1743
      } else if (redirection->type() == ExternalReference::DIRECT_API_CALL) {
1744
        if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
1745
          PrintF("Call to host function at %p args %08x",
1746
              reinterpret_cast<void*>(external), arg0);
1747 1748 1749 1750 1751 1752
          if (!stack_aligned) {
            PrintF(" with unaligned stack %08x\n", get_register(sp));
          }
          PrintF("\n");
        }
        CHECK(stack_aligned);
1753 1754 1755
        SimulatorRuntimeDirectApiCall target =
            reinterpret_cast<SimulatorRuntimeDirectApiCall>(external);
        target(arg0);
1756
      } else if (
1757
          redirection->type() == ExternalReference::PROFILING_API_CALL) {
1758 1759 1760 1761 1762 1763 1764 1765 1766
        if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
          PrintF("Call to host function at %p args %08x %08x",
              reinterpret_cast<void*>(external), arg0, arg1);
          if (!stack_aligned) {
            PrintF(" with unaligned stack %08x\n", get_register(sp));
          }
          PrintF("\n");
        }
        CHECK(stack_aligned);
1767 1768
        SimulatorRuntimeProfilingApiCall target =
            reinterpret_cast<SimulatorRuntimeProfilingApiCall>(external);
1769
        target(arg0, Redirection::ReverseRedirection(arg1));
1770
      } else if (
1771
          redirection->type() == ExternalReference::DIRECT_GETTER_CALL) {
1772 1773
        if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
          PrintF("Call to host function at %p args %08x %08x",
1774
              reinterpret_cast<void*>(external), arg0, arg1);
1775 1776 1777 1778 1779 1780
          if (!stack_aligned) {
            PrintF(" with unaligned stack %08x\n", get_register(sp));
          }
          PrintF("\n");
        }
        CHECK(stack_aligned);
1781 1782 1783
        SimulatorRuntimeDirectGetterCall target =
            reinterpret_cast<SimulatorRuntimeDirectGetterCall>(external);
        target(arg0, arg1);
1784
      } else if (
1785
          redirection->type() == ExternalReference::PROFILING_GETTER_CALL) {
1786 1787 1788 1789 1790 1791 1792 1793 1794
        if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
          PrintF("Call to host function at %p args %08x %08x %08x",
              reinterpret_cast<void*>(external), arg0, arg1, arg2);
          if (!stack_aligned) {
            PrintF(" with unaligned stack %08x\n", get_register(sp));
          }
          PrintF("\n");
        }
        CHECK(stack_aligned);
1795 1796 1797
        SimulatorRuntimeProfilingGetterCall target =
            reinterpret_cast<SimulatorRuntimeProfilingGetterCall>(
                external);
1798
        target(arg0, arg1, Redirection::ReverseRedirection(arg2));
1799
      } else {
1800
        // builtin call.
mbrandy's avatar
mbrandy committed
1801 1802
        DCHECK(redirection->type() == ExternalReference::BUILTIN_CALL ||
               redirection->type() == ExternalReference::BUILTIN_CALL_PAIR);
1803 1804
        SimulatorRuntimeCall target =
            reinterpret_cast<SimulatorRuntimeCall>(external);
1805
        if (::v8::internal::FLAG_trace_sim || !stack_aligned) {
1806
          PrintF(
1807
              "Call to host function at %p "
1808
              "args %08x, %08x, %08x, %08x, %08x, %08x, %08x, %08x, %08x",
1809 1810
              reinterpret_cast<void*>(FUNCTION_ADDR(target)), arg0, arg1, arg2,
              arg3, arg4, arg5, arg6, arg7, arg8);
1811 1812 1813 1814
          if (!stack_aligned) {
            PrintF(" with unaligned stack %08x\n", get_register(sp));
          }
          PrintF("\n");
1815
        }
1816
        CHECK(stack_aligned);
1817 1818
        int64_t result =
            target(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
1819 1820
        int32_t lo_res = static_cast<int32_t>(result);
        int32_t hi_res = static_cast<int32_t>(result >> 32);
1821 1822 1823
        if (::v8::internal::FLAG_trace_sim) {
          PrintF("Returned %08x\n", lo_res);
        }
1824 1825 1826 1827 1828
        set_register(r0, lo_res);
        set_register(r1, hi_res);
      }
      set_register(lr, saved_lr);
      set_pc(get_register(lr));
1829 1830
      break;
    }
1831
    case kBreakpoint: {
1832
      ArmDebugger dbg(this);
1833 1834 1835
      dbg.Debug();
      break;
    }
1836
    // stop uses all codes greater than 1 << 23.
1837
    default: {
1838 1839 1840 1841 1842 1843 1844 1845
      if (svc >= (1 << 23)) {
        uint32_t code = svc & kStopCodeMask;
        if (isWatchedStop(code)) {
          IncreaseStopCounter(code);
        }
        // Stop if it is enabled, otherwise go on jumping over the stop
        // and the message address.
        if (isEnabledStop(code)) {
1846
          ArmDebugger dbg(this);
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
          dbg.Stop(instr);
        }
      } else {
        // This is not a valid svc code.
        UNREACHABLE();
        break;
      }
    }
  }
}


1859 1860 1861
float Simulator::canonicalizeNaN(float value) {
  // Default NaN value, see "NaN handling" in "IEEE 754 standard implementation
  // choices" of the ARM Reference Manual.
1862
  constexpr uint32_t kDefaultNaN = 0x7FC00000u;
1863 1864 1865 1866 1867 1868
  if (FPSCR_default_NaN_mode_ && std::isnan(value)) {
    value = bit_cast<float>(kDefaultNaN);
  }
  return value;
}

1869 1870 1871 1872 1873 1874
Float32 Simulator::canonicalizeNaN(Float32 value) {
  // Default NaN value, see "NaN handling" in "IEEE 754 standard implementation
  // choices" of the ARM Reference Manual.
  constexpr Float32 kDefaultNaN = Float32::FromBits(0x7FC00000u);
  return FPSCR_default_NaN_mode_ && value.is_nan() ? kDefaultNaN : value;
}
1875

1876
double Simulator::canonicalizeNaN(double value) {
1877 1878
  // Default NaN value, see "NaN handling" in "IEEE 754 standard implementation
  // choices" of the ARM Reference Manual.
1879
  constexpr uint64_t kDefaultNaN = uint64_t{0x7FF8000000000000};
1880 1881 1882 1883
  if (FPSCR_default_NaN_mode_ && std::isnan(value)) {
    value = bit_cast<double>(kDefaultNaN);
  }
  return value;
1884 1885
}

1886 1887 1888 1889
Float64 Simulator::canonicalizeNaN(Float64 value) {
  // Default NaN value, see "NaN handling" in "IEEE 754 standard implementation
  // choices" of the ARM Reference Manual.
  constexpr Float64 kDefaultNaN =
1890
      Float64::FromBits(uint64_t{0x7FF8000000000000});
1891 1892
  return FPSCR_default_NaN_mode_ && value.is_nan() ? kDefaultNaN : value;
}
1893

1894
// Stop helper functions.
1895 1896
bool Simulator::isStopInstruction(Instruction* instr) {
  return (instr->Bits(27, 24) == 0xF) && (instr->SvcValue() >= kStopCode);
1897 1898 1899 1900
}


bool Simulator::isWatchedStop(uint32_t code) {
1901
  DCHECK_LE(code, kMaxStopCode);
1902 1903 1904 1905 1906
  return code < kNumOfWatchedStops;
}


bool Simulator::isEnabledStop(uint32_t code) {
1907
  DCHECK_LE(code, kMaxStopCode);
1908 1909
  // Unwatched stops are always enabled.
  return !isWatchedStop(code) ||
1910
    !(watched_stops_[code].count & kStopDisabledBit);
1911 1912 1913 1914
}


void Simulator::EnableStop(uint32_t code) {
1915
  DCHECK(isWatchedStop(code));
1916
  if (!isEnabledStop(code)) {
1917
    watched_stops_[code].count &= ~kStopDisabledBit;
1918 1919 1920 1921 1922
  }
}


void Simulator::DisableStop(uint32_t code) {
1923
  DCHECK(isWatchedStop(code));
1924
  if (isEnabledStop(code)) {
1925
    watched_stops_[code].count |= kStopDisabledBit;
1926 1927 1928 1929 1930
  }
}


void Simulator::IncreaseStopCounter(uint32_t code) {
1931
  DCHECK_LE(code, kMaxStopCode);
1932
  DCHECK(isWatchedStop(code));
1933
  if ((watched_stops_[code].count & ~(1 << 31)) == 0x7FFFFFFF) {
1934 1935
    PrintF("Stop counter for code %i has overflowed.\n"
           "Enabling this code and reseting the counter to 0.\n", code);
1936
    watched_stops_[code].count = 0;
1937 1938
    EnableStop(code);
  } else {
1939
    watched_stops_[code].count++;
1940 1941 1942 1943 1944 1945
  }
}


// Print a stop status.
void Simulator::PrintStopInfo(uint32_t code) {
1946
  DCHECK_LE(code, kMaxStopCode);
1947 1948 1949 1950
  if (!isWatchedStop(code)) {
    PrintF("Stop not watched.");
  } else {
    const char* state = isEnabledStop(code) ? "Enabled" : "Disabled";
1951
    int32_t count = watched_stops_[code].count & ~kStopDisabledBit;
1952 1953
    // Don't print the state of unused breakpoints.
    if (count != 0) {
1954
      if (watched_stops_[code].desc) {
1955
        PrintF("stop %i - 0x%x: \t%s, \tcounter = %i, \t%s\n",
1956
               code, code, state, count, watched_stops_[code].desc);
1957 1958 1959 1960
      } else {
        PrintF("stop %i - 0x%x: \t%s, \tcounter = %i\n",
               code, code, state, count);
      }
1961 1962 1963 1964 1965 1966 1967 1968 1969
    }
  }
}


// Handle execution based on instruction types.

// Instruction types 0 and 1 are both rolled into one function because they
// only differ in the handling of the shifter_operand.
1970 1971
void Simulator::DecodeType01(Instruction* instr) {
  int type = instr->TypeValue();
1972 1973 1974 1975
  if ((type == 0) && instr->IsSpecialType0()) {
    // multiply instruction or extra loads and stores
    if (instr->Bits(7, 4) == 9) {
      if (instr->Bit(24) == 0) {
1976 1977
        // Raw field decoding here. Multiply instructions have their Rd in
        // funny places.
1978 1979 1980
        int rn = instr->RnValue();
        int rm = instr->RmValue();
        int rs = instr->RsValue();
1981 1982 1983 1984
        int32_t rs_val = get_register(rs);
        int32_t rm_val = get_register(rm);
        if (instr->Bit(23) == 0) {
          if (instr->Bit(21) == 0) {
1985 1986 1987
            // The MUL instruction description (A 4.1.33) refers to Rd as being
            // the destination for the operation, but it confusingly uses the
            // Rn field to encode it.
1988
            // Format(instr, "mul'cond's 'rn, 'rm, 'rs");
1989
            int rd = rn;  // Remap the rn field to the Rd register.
1990 1991 1992 1993 1994 1995
            int32_t alu_out = rm_val * rs_val;
            set_register(rd, alu_out);
            if (instr->HasS()) {
              SetNZFlags(alu_out);
            }
          } else {
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
            int rd = instr->RdValue();
            int32_t acc_value = get_register(rd);
            if (instr->Bit(22) == 0) {
              // The MLA instruction description (A 4.1.28) refers to the order
              // of registers as "Rd, Rm, Rs, Rn". But confusingly it uses the
              // Rn field to encode the Rd register and the Rd field to encode
              // the Rn register.
              // Format(instr, "mla'cond's 'rn, 'rm, 'rs, 'rd");
              int32_t mul_out = rm_val * rs_val;
              int32_t result = acc_value + mul_out;
              set_register(rn, result);
            } else {
              // Format(instr, "mls'cond's 'rn, 'rm, 'rs, 'rd");
              int32_t mul_out = rm_val * rs_val;
              int32_t result = acc_value - mul_out;
              set_register(rn, result);
            }
2013 2014
          }
        } else {
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
          // The signed/long multiply instructions use the terms RdHi and RdLo
          // when referring to the target registers. They are mapped to the Rn
          // and Rd fields as follows:
          // RdLo == Rd
          // RdHi == Rn (This is confusingly stored in variable rd here
          //             because the mul instruction from above uses the
          //             Rn field to encode the Rd register. Good luck figuring
          //             this out without reading the ARM instruction manual
          //             at a very detailed level.)
          // Format(instr, "'um'al'cond's 'rd, 'rn, 'rs, 'rm");
          int rd_hi = rn;  // Remap the rn field to the RdHi register.
2026
          int rd_lo = instr->RdValue();
2027 2028
          int32_t hi_res = 0;
          int32_t lo_res = 0;
2029 2030 2031 2032 2033
          if (instr->Bit(22) == 1) {
            int64_t left_op  = static_cast<int32_t>(rm_val);
            int64_t right_op = static_cast<int32_t>(rs_val);
            uint64_t result = left_op * right_op;
            hi_res = static_cast<int32_t>(result >> 32);
2034
            lo_res = static_cast<int32_t>(result & 0xFFFFFFFF);
2035 2036
          } else {
            // unsigned multiply
2037 2038
            uint64_t left_op  = static_cast<uint32_t>(rm_val);
            uint64_t right_op = static_cast<uint32_t>(rs_val);
2039 2040
            uint64_t result = left_op * right_op;
            hi_res = static_cast<int32_t>(result >> 32);
2041
            lo_res = static_cast<int32_t>(result & 0xFFFFFFFF);
2042
          }
2043
          set_register(rd_lo, lo_res);
2044
          set_register(rd_hi, hi_res);
2045 2046 2047 2048 2049
          if (instr->HasS()) {
            UNIMPLEMENTED();
          }
        }
      } else {
2050 2051 2052 2053 2054 2055 2056 2057 2058
        if (instr->Bits(24, 23) == 3) {
          if (instr->Bit(20) == 1) {
            // ldrex
            int rt = instr->RtValue();
            int rn = instr->RnValue();
            int32_t addr = get_register(rn);
            switch (instr->Bits(22, 21)) {
              case 0: {
                // Format(instr, "ldrex'cond 'rt, ['rn]");
2059
                int value = ReadExW(addr);
2060 2061 2062
                set_register(rt, value);
                break;
              }
2063 2064 2065 2066 2067 2068
              case 1: {
                // Format(instr, "ldrexd'cond 'rt, ['rn]");
                int* rn_data = ReadExDW(addr);
                set_dw_register(rt, rn_data);
                break;
              }
2069 2070 2071 2072 2073 2074 2075 2076
              case 2: {
                // Format(instr, "ldrexb'cond 'rt, ['rn]");
                uint8_t value = ReadExBU(addr);
                set_register(rt, value);
                break;
              }
              case 3: {
                // Format(instr, "ldrexh'cond 'rt, ['rn]");
2077
                uint16_t value = ReadExHU(addr);
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
                set_register(rt, value);
                break;
              }
              default:
                UNREACHABLE();
                break;
            }
          } else {
            // The instruction is documented as strex rd, rt, [rn], but the
            // "rt" register is using the rm bits.
            int rd = instr->RdValue();
            int rt = instr->RmValue();
            int rn = instr->RnValue();
2091 2092
            DCHECK_NE(rd, rn);
            DCHECK_NE(rd, rt);
2093 2094 2095 2096 2097
            int32_t addr = get_register(rn);
            switch (instr->Bits(22, 21)) {
              case 0: {
                // Format(instr, "strex'cond 'rd, 'rm, ['rn]");
                int value = get_register(rt);
2098
                int status = WriteExW(addr, value);
2099 2100 2101
                set_register(rd, status);
                break;
              }
2102 2103 2104 2105 2106 2107 2108 2109 2110
              case 1: {
                // Format(instr, "strexd'cond 'rd, 'rm, ['rn]");
                DCHECK_EQ(rt % 2, 0);
                int32_t value1 = get_register(rt);
                int32_t value2 = get_register(rt + 1);
                int status = WriteExDW(addr, value1, value2);
                set_register(rd, status);
                break;
              }
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
              case 2: {
                // Format(instr, "strexb'cond 'rd, 'rm, ['rn]");
                uint8_t value = get_register(rt);
                int status = WriteExB(addr, value);
                set_register(rd, status);
                break;
              }
              case 3: {
                // Format(instr, "strexh'cond 'rd, 'rm, ['rn]");
                uint16_t value = get_register(rt);
2121
                int status = WriteExH(addr, value);
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
                set_register(rd, status);
                break;
              }
              default:
                UNREACHABLE();
                break;
            }
          }
        } else {
          UNIMPLEMENTED();  // Not used by V8.
        }
2133 2134 2135
      }
    } else {
      // extra load/store instructions
2136 2137
      int rd = instr->RdValue();
      int rn = instr->RnValue();
2138 2139 2140
      int32_t rn_val = get_register(rn);
      int32_t addr = 0;
      if (instr->Bit(22) == 0) {
2141
        int rm = instr->RmValue();
2142 2143
        int32_t rm_val = get_register(rm);
        switch (instr->PUField()) {
2144
          case da_x: {
2145
            // Format(instr, "'memop'cond'sign'h 'rd, ['rn], -'rm");
2146
            DCHECK(!instr->HasW());
2147 2148 2149 2150 2151
            addr = rn_val;
            rn_val -= rm_val;
            set_register(rn, rn_val);
            break;
          }
2152
          case ia_x: {
2153
            // Format(instr, "'memop'cond'sign'h 'rd, ['rn], +'rm");
2154
            DCHECK(!instr->HasW());
2155 2156 2157 2158 2159
            addr = rn_val;
            rn_val += rm_val;
            set_register(rn, rn_val);
            break;
          }
2160
          case db_x: {
2161 2162 2163 2164 2165 2166 2167 2168
            // Format(instr, "'memop'cond'sign'h 'rd, ['rn, -'rm]'w");
            rn_val -= rm_val;
            addr = rn_val;
            if (instr->HasW()) {
              set_register(rn, rn_val);
            }
            break;
          }
2169
          case ib_x: {
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
            // Format(instr, "'memop'cond'sign'h 'rd, ['rn, +'rm]'w");
            rn_val += rm_val;
            addr = rn_val;
            if (instr->HasW()) {
              set_register(rn, rn_val);
            }
            break;
          }
          default: {
            // The PU field is a 2-bit field.
            UNREACHABLE();
            break;
          }
        }
      } else {
2185
        int32_t imm_val = (instr->ImmedHValue() << 4) | instr->ImmedLValue();
2186
        switch (instr->PUField()) {
2187
          case da_x: {
2188
            // Format(instr, "'memop'cond'sign'h 'rd, ['rn], #-'off8");
2189
            DCHECK(!instr->HasW());
2190 2191 2192 2193 2194
            addr = rn_val;
            rn_val -= imm_val;
            set_register(rn, rn_val);
            break;
          }
2195
          case ia_x: {
2196
            // Format(instr, "'memop'cond'sign'h 'rd, ['rn], #+'off8");
2197
            DCHECK(!instr->HasW());
2198 2199 2200 2201 2202
            addr = rn_val;
            rn_val += imm_val;
            set_register(rn, rn_val);
            break;
          }
2203
          case db_x: {
2204 2205 2206 2207 2208 2209 2210 2211
            // Format(instr, "'memop'cond'sign'h 'rd, ['rn, #-'off8]'w");
            rn_val -= imm_val;
            addr = rn_val;
            if (instr->HasW()) {
              set_register(rn, rn_val);
            }
            break;
          }
2212
          case ib_x: {
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
            // Format(instr, "'memop'cond'sign'h 'rd, ['rn, #+'off8]'w");
            rn_val += imm_val;
            addr = rn_val;
            if (instr->HasW()) {
              set_register(rn, rn_val);
            }
            break;
          }
          default: {
            // The PU field is a 2-bit field.
            UNREACHABLE();
            break;
          }
        }
      }
2228
      if (((instr->Bits(7, 4) & 0xD) == 0xD) && (instr->Bit(20) == 0)) {
2229
        DCHECK_EQ(rd % 2, 0);
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
        if (instr->HasH()) {
          // The strd instruction.
          int32_t value1 = get_register(rd);
          int32_t value2 = get_register(rd+1);
          WriteDW(addr, value1, value2);
        } else {
          // The ldrd instruction.
          int* rn_data = ReadDW(addr);
          set_dw_register(rd, rn_data);
        }
      } else if (instr->HasH()) {
2241 2242
        if (instr->HasSign()) {
          if (instr->HasL()) {
2243
            int16_t val = ReadH(addr);
2244 2245 2246
            set_register(rd, val);
          } else {
            int16_t val = get_register(rd);
2247
            WriteH(addr, val);
2248 2249 2250
          }
        } else {
          if (instr->HasL()) {
2251
            uint16_t val = ReadHU(addr);
2252 2253 2254
            set_register(rd, val);
          } else {
            uint16_t val = get_register(rd);
2255
            WriteH(addr, val);
2256 2257 2258 2259
          }
        }
      } else {
        // signed byte loads
2260 2261
        DCHECK(instr->HasSign());
        DCHECK(instr->HasL());
2262
        int8_t val = ReadB(addr);
2263 2264 2265 2266
        set_register(rd, val);
      }
      return;
    }
2267
  } else if ((type == 0) && instr->IsMiscType0()) {
2268
    if ((instr->Bits(27, 23) == 2) && (instr->Bits(21, 20) == 2) &&
2269
        (instr->Bits(15, 4) == 0xF00)) {
2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
      // MSR
      int rm = instr->RmValue();
      DCHECK_NE(pc, rm);  // UNPREDICTABLE
      SRegisterFieldMask sreg_and_mask =
          instr->BitField(22, 22) | instr->BitField(19, 16);
      SetSpecialRegister(sreg_and_mask, get_register(rm));
    } else if ((instr->Bits(27, 23) == 2) && (instr->Bits(21, 20) == 0) &&
               (instr->Bits(11, 0) == 0)) {
      // MRS
      int rd = instr->RdValue();
      DCHECK_NE(pc, rd);  // UNPREDICTABLE
      SRegister sreg = static_cast<SRegister>(instr->BitField(22, 22));
      set_register(rd, GetFromSpecialRegister(sreg));
    } else if (instr->Bits(22, 21) == 1) {
2284 2285
      int rm = instr->RmValue();
      switch (instr->BitField(7, 4)) {
2286 2287 2288 2289 2290 2291
        case BX:
          set_pc(get_register(rm));
          break;
        case BLX: {
          uint32_t old_pc = get_pc();
          set_pc(get_register(rm));
2292
          set_register(lr, old_pc + kInstrSize);
2293 2294
          break;
        }
2295
        case BKPT: {
2296
          ArmDebugger dbg(this);
2297 2298
          PrintF("Simulator hit BKPT.\n");
          dbg.Debug();
2299
          break;
2300
        }
2301 2302 2303 2304
        default:
          UNIMPLEMENTED();
      }
    } else if (instr->Bits(22, 21) == 3) {
2305 2306 2307
      int rm = instr->RmValue();
      int rd = instr->RdValue();
      switch (instr->BitField(7, 4)) {
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
        case CLZ: {
          uint32_t bits = get_register(rm);
          int leading_zeros = 0;
          if (bits == 0) {
            leading_zeros = 32;
          } else {
            while ((bits & 0x80000000u) == 0) {
              bits <<= 1;
              leading_zeros++;
            }
          }
          set_register(rd, leading_zeros);
          break;
        }
        default:
          UNIMPLEMENTED();
      }
    } else {
      PrintF("%08x\n", instr->InstructionBits());
      UNIMPLEMENTED();
    }
2329 2330 2331 2332 2333 2334 2335 2336 2337
  } else if ((type == 1) && instr->IsNopLikeType1()) {
    if (instr->BitField(7, 0) == 0) {
      // NOP.
    } else if (instr->BitField(7, 0) == 20) {
      // CSDB.
    } else {
      PrintF("%08x\n", instr->InstructionBits());
      UNIMPLEMENTED();
    }
2338
  } else {
2339 2340
    int rd = instr->RdValue();
    int rn = instr->RnValue();
2341 2342 2343 2344 2345 2346
    int32_t rn_val = get_register(rn);
    int32_t shifter_operand = 0;
    bool shifter_carry_out = 0;
    if (type == 0) {
      shifter_operand = GetShiftRm(instr, &shifter_carry_out);
    } else {
2347
      DCHECK_EQ(instr->TypeValue(), 1);
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
      shifter_operand = GetImm(instr, &shifter_carry_out);
    }
    int32_t alu_out;

    switch (instr->OpcodeField()) {
      case AND: {
        // Format(instr, "and'cond's 'rd, 'rn, 'shift_rm");
        // Format(instr, "and'cond's 'rd, 'rn, 'imm");
        alu_out = rn_val & shifter_operand;
        set_register(rd, alu_out);
        if (instr->HasS()) {
          SetNZFlags(alu_out);
          SetCFlag(shifter_carry_out);
        }
        break;
      }

      case EOR: {
        // Format(instr, "eor'cond's 'rd, 'rn, 'shift_rm");
        // Format(instr, "eor'cond's 'rd, 'rn, 'imm");
        alu_out = rn_val ^ shifter_operand;
        set_register(rd, alu_out);
        if (instr->HasS()) {
          SetNZFlags(alu_out);
          SetCFlag(shifter_carry_out);
        }
        break;
      }

      case SUB: {
        // Format(instr, "sub'cond's 'rd, 'rn, 'shift_rm");
        // Format(instr, "sub'cond's 'rd, 'rn, 'imm");
        alu_out = rn_val - shifter_operand;
        set_register(rd, alu_out);
        if (instr->HasS()) {
          SetNZFlags(alu_out);
          SetCFlag(!BorrowFrom(rn_val, shifter_operand));
          SetVFlag(OverflowFrom(alu_out, rn_val, shifter_operand, false));
        }
        break;
      }

      case RSB: {
        // Format(instr, "rsb'cond's 'rd, 'rn, 'shift_rm");
        // Format(instr, "rsb'cond's 'rd, 'rn, 'imm");
        alu_out = shifter_operand - rn_val;
        set_register(rd, alu_out);
        if (instr->HasS()) {
          SetNZFlags(alu_out);
          SetCFlag(!BorrowFrom(shifter_operand, rn_val));
          SetVFlag(OverflowFrom(alu_out, shifter_operand, rn_val, false));
        }
        break;
      }

      case ADD: {
        // Format(instr, "add'cond's 'rd, 'rn, 'shift_rm");
        // Format(instr, "add'cond's 'rd, 'rn, 'imm");
        alu_out = rn_val + shifter_operand;
        set_register(rd, alu_out);
        if (instr->HasS()) {
          SetNZFlags(alu_out);
          SetCFlag(CarryFrom(rn_val, shifter_operand));
          SetVFlag(OverflowFrom(alu_out, rn_val, shifter_operand, true));
        }
        break;
      }

      case ADC: {
2417 2418 2419 2420 2421 2422 2423 2424 2425
        // Format(instr, "adc'cond's 'rd, 'rn, 'shift_rm");
        // Format(instr, "adc'cond's 'rd, 'rn, 'imm");
        alu_out = rn_val + shifter_operand + GetCarry();
        set_register(rd, alu_out);
        if (instr->HasS()) {
          SetNZFlags(alu_out);
          SetCFlag(CarryFrom(rn_val, shifter_operand, GetCarry()));
          SetVFlag(OverflowFrom(alu_out, rn_val, shifter_operand, true));
        }
2426 2427 2428 2429
        break;
      }

      case SBC: {
2430 2431 2432 2433 2434 2435 2436 2437 2438
        //        Format(instr, "sbc'cond's 'rd, 'rn, 'shift_rm");
        //        Format(instr, "sbc'cond's 'rd, 'rn, 'imm");
        alu_out = (rn_val - shifter_operand) - (GetCarry() ? 0 : 1);
        set_register(rd, alu_out);
        if (instr->HasS()) {
          SetNZFlags(alu_out);
          SetCFlag(!BorrowFrom(rn_val, shifter_operand, GetCarry()));
          SetVFlag(OverflowFrom(alu_out, rn_val, shifter_operand, false));
        }
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
        break;
      }

      case RSC: {
        Format(instr, "rsc'cond's 'rd, 'rn, 'shift_rm");
        Format(instr, "rsc'cond's 'rd, 'rn, 'imm");
        break;
      }

      case TST: {
        if (instr->HasS()) {
          // Format(instr, "tst'cond 'rn, 'shift_rm");
          // Format(instr, "tst'cond 'rn, 'imm");
          alu_out = rn_val & shifter_operand;
          SetNZFlags(alu_out);
          SetCFlag(shifter_carry_out);
        } else {
2456
          // Format(instr, "movw'cond 'rd, 'imm").
2457
          alu_out = instr->ImmedMovwMovtValue();
2458
          set_register(rd, alu_out);
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
        }
        break;
      }

      case TEQ: {
        if (instr->HasS()) {
          // Format(instr, "teq'cond 'rn, 'shift_rm");
          // Format(instr, "teq'cond 'rn, 'imm");
          alu_out = rn_val ^ shifter_operand;
          SetNZFlags(alu_out);
          SetCFlag(shifter_carry_out);
        } else {
2471 2472 2473
          // Other instructions matching this pattern are handled in the
          // miscellaneous instructions part above.
          UNREACHABLE();
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
        }
        break;
      }

      case CMP: {
        if (instr->HasS()) {
          // Format(instr, "cmp'cond 'rn, 'shift_rm");
          // Format(instr, "cmp'cond 'rn, 'imm");
          alu_out = rn_val - shifter_operand;
          SetNZFlags(alu_out);
          SetCFlag(!BorrowFrom(rn_val, shifter_operand));
          SetVFlag(OverflowFrom(alu_out, rn_val, shifter_operand, false));
        } else {
2487
          // Format(instr, "movt'cond 'rd, 'imm").
2488 2489
          alu_out =
              (get_register(rd) & 0xFFFF) | (instr->ImmedMovwMovtValue() << 16);
2490
          set_register(rd, alu_out);
2491 2492 2493 2494 2495 2496
        }
        break;
      }

      case CMN: {
        if (instr->HasS()) {
lrn@chromium.org's avatar
lrn@chromium.org committed
2497 2498 2499 2500
          // Format(instr, "cmn'cond 'rn, 'shift_rm");
          // Format(instr, "cmn'cond 'rn, 'imm");
          alu_out = rn_val + shifter_operand;
          SetNZFlags(alu_out);
2501
          SetCFlag(CarryFrom(rn_val, shifter_operand));
lrn@chromium.org's avatar
lrn@chromium.org committed
2502
          SetVFlag(OverflowFrom(alu_out, rn_val, shifter_operand, true));
2503
        } else {
2504 2505 2506
          // Other instructions matching this pattern are handled in the
          // miscellaneous instructions part above.
          UNREACHABLE();
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
        }
        break;
      }

      case ORR: {
        // Format(instr, "orr'cond's 'rd, 'rn, 'shift_rm");
        // Format(instr, "orr'cond's 'rd, 'rn, 'imm");
        alu_out = rn_val | shifter_operand;
        set_register(rd, alu_out);
        if (instr->HasS()) {
          SetNZFlags(alu_out);
          SetCFlag(shifter_carry_out);
        }
        break;
      }

      case MOV: {
        // Format(instr, "mov'cond's 'rd, 'shift_rm");
        // Format(instr, "mov'cond's 'rd, 'imm");
        alu_out = shifter_operand;
        set_register(rd, alu_out);
        if (instr->HasS()) {
          SetNZFlags(alu_out);
          SetCFlag(shifter_carry_out);
        }
        break;
      }

      case BIC: {
        // Format(instr, "bic'cond's 'rd, 'rn, 'shift_rm");
        // Format(instr, "bic'cond's 'rd, 'rn, 'imm");
        alu_out = rn_val & ~shifter_operand;
        set_register(rd, alu_out);
        if (instr->HasS()) {
          SetNZFlags(alu_out);
          SetCFlag(shifter_carry_out);
        }
        break;
      }

      case MVN: {
        // Format(instr, "mvn'cond's 'rd, 'shift_rm");
        // Format(instr, "mvn'cond's 'rd, 'imm");
        alu_out = ~shifter_operand;
        set_register(rd, alu_out);
        if (instr->HasS()) {
          SetNZFlags(alu_out);
          SetCFlag(shifter_carry_out);
        }
        break;
      }

      default: {
        UNREACHABLE();
        break;
      }
    }
  }
}


2568 2569 2570
void Simulator::DecodeType2(Instruction* instr) {
  int rd = instr->RdValue();
  int rn = instr->RnValue();
2571
  int32_t rn_val = get_register(rn);
2572
  int32_t im_val = instr->Offset12Value();
2573 2574
  int32_t addr = 0;
  switch (instr->PUField()) {
2575
    case da_x: {
2576
      // Format(instr, "'memop'cond'b 'rd, ['rn], #-'off12");
2577
      DCHECK(!instr->HasW());
2578 2579 2580 2581 2582
      addr = rn_val;
      rn_val -= im_val;
      set_register(rn, rn_val);
      break;
    }
2583
    case ia_x: {
2584
      // Format(instr, "'memop'cond'b 'rd, ['rn], #+'off12");
2585
      DCHECK(!instr->HasW());
2586 2587 2588 2589 2590
      addr = rn_val;
      rn_val += im_val;
      set_register(rn, rn_val);
      break;
    }
2591
    case db_x: {
2592 2593 2594 2595 2596 2597 2598 2599
      // Format(instr, "'memop'cond'b 'rd, ['rn, #-'off12]'w");
      rn_val -= im_val;
      addr = rn_val;
      if (instr->HasW()) {
        set_register(rn, rn_val);
      }
      break;
    }
2600
    case ib_x: {
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
      // Format(instr, "'memop'cond'b 'rd, ['rn, #+'off12]'w");
      rn_val += im_val;
      addr = rn_val;
      if (instr->HasW()) {
        set_register(rn, rn_val);
      }
      break;
    }
    default: {
      UNREACHABLE();
      break;
    }
  }
  if (instr->HasB()) {
    if (instr->HasL()) {
2616
      byte val = ReadBU(addr);
2617 2618 2619
      set_register(rd, val);
    } else {
      byte val = get_register(rd);
2620
      WriteB(addr, val);
2621 2622 2623
    }
  } else {
    if (instr->HasL()) {
2624
      set_register(rd, ReadW(addr));
2625
    } else {
2626
      WriteW(addr, get_register(rd));
2627 2628 2629 2630 2631
    }
  }
}


2632 2633 2634
void Simulator::DecodeType3(Instruction* instr) {
  int rd = instr->RdValue();
  int rn = instr->RnValue();
2635 2636 2637 2638 2639
  int32_t rn_val = get_register(rn);
  bool shifter_carry_out = 0;
  int32_t shifter_operand = GetShiftRm(instr, &shifter_carry_out);
  int32_t addr = 0;
  switch (instr->PUField()) {
2640
    case da_x: {
2641
      DCHECK(!instr->HasW());
2642
      Format(instr, "'memop'cond'b 'rd, ['rn], -'shift_rm");
2643
      UNIMPLEMENTED();
2644 2645
      break;
    }
2646
    case ia_x: {
2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704
      if (instr->Bit(4) == 0) {
        // Memop.
      } else {
        if (instr->Bit(5) == 0) {
          switch (instr->Bits(22, 21)) {
            case 0:
              if (instr->Bit(20) == 0) {
                if (instr->Bit(6) == 0) {
                  // Pkhbt.
                  uint32_t rn_val = get_register(rn);
                  uint32_t rm_val = get_register(instr->RmValue());
                  int32_t shift = instr->Bits(11, 7);
                  rm_val <<= shift;
                  set_register(rd, (rn_val & 0xFFFF) | (rm_val & 0xFFFF0000U));
                } else {
                  // Pkhtb.
                  uint32_t rn_val = get_register(rn);
                  int32_t rm_val = get_register(instr->RmValue());
                  int32_t shift = instr->Bits(11, 7);
                  if (shift == 0) {
                    shift = 32;
                  }
                  rm_val >>= shift;
                  set_register(rd, (rn_val & 0xFFFF0000U) | (rm_val & 0xFFFF));
                }
              } else {
                UNIMPLEMENTED();
              }
              break;
            case 1:
              UNIMPLEMENTED();
              break;
            case 2:
              UNIMPLEMENTED();
              break;
            case 3: {
              // Usat.
              int32_t sat_pos = instr->Bits(20, 16);
              int32_t sat_val = (1 << sat_pos) - 1;
              int32_t shift = instr->Bits(11, 7);
              int32_t shift_type = instr->Bit(6);
              int32_t rm_val = get_register(instr->RmValue());
              if (shift_type == 0) {  // LSL
                rm_val <<= shift;
              } else {  // ASR
                rm_val >>= shift;
              }
              // If saturation occurs, the Q flag should be set in the CPSR.
              // There is no Q flag yet, and no instruction (MRS) to read the
              // CPSR directly.
              if (rm_val > sat_val) {
                rm_val = sat_val;
              } else if (rm_val < 0) {
                rm_val = 0;
              }
              set_register(rd, rm_val);
              break;
            }
2705
          }
2706 2707 2708 2709 2710 2711
        } else {
          switch (instr->Bits(22, 21)) {
            case 0:
              UNIMPLEMENTED();
              break;
            case 1:
2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
              if (instr->Bits(9, 6) == 1) {
                if (instr->Bit(20) == 0) {
                  if (instr->Bits(19, 16) == 0xF) {
                    // Sxtb.
                    int32_t rm_val = get_register(instr->RmValue());
                    int32_t rotate = instr->Bits(11, 10);
                    switch (rotate) {
                      case 0:
                        break;
                      case 1:
                        rm_val = (rm_val >> 8) | (rm_val << 24);
                        break;
                      case 2:
                        rm_val = (rm_val >> 16) | (rm_val << 16);
                        break;
                      case 3:
                        rm_val = (rm_val >> 24) | (rm_val << 8);
                        break;
                    }
                    set_register(rd, static_cast<int8_t>(rm_val));
                  } else {
                    // Sxtab.
                    int32_t rn_val = get_register(rn);
                    int32_t rm_val = get_register(instr->RmValue());
                    int32_t rotate = instr->Bits(11, 10);
                    switch (rotate) {
                      case 0:
                        break;
                      case 1:
                        rm_val = (rm_val >> 8) | (rm_val << 24);
                        break;
                      case 2:
                        rm_val = (rm_val >> 16) | (rm_val << 16);
                        break;
                      case 3:
                        rm_val = (rm_val >> 24) | (rm_val << 8);
                        break;
                    }
                    set_register(rd, rn_val + static_cast<int8_t>(rm_val));
                  }
                } else {
                  if (instr->Bits(19, 16) == 0xF) {
                    // Sxth.
                    int32_t rm_val = get_register(instr->RmValue());
                    int32_t rotate = instr->Bits(11, 10);
                    switch (rotate) {
                      case 0:
                        break;
                      case 1:
                        rm_val = (rm_val >> 8) | (rm_val << 24);
                        break;
                      case 2:
                        rm_val = (rm_val >> 16) | (rm_val << 16);
                        break;
                      case 3:
                        rm_val = (rm_val >> 24) | (rm_val << 8);
                        break;
                    }
                    set_register(rd, static_cast<int16_t>(rm_val));
                  } else {
                    // Sxtah.
                    int32_t rn_val = get_register(rn);
                    int32_t rm_val = get_register(instr->RmValue());
                    int32_t rotate = instr->Bits(11, 10);
                    switch (rotate) {
                      case 0:
                        break;
                      case 1:
                        rm_val = (rm_val >> 8) | (rm_val << 24);
                        break;
                      case 2:
                        rm_val = (rm_val >> 16) | (rm_val << 16);
                        break;
                      case 3:
                        rm_val = (rm_val >> 24) | (rm_val << 8);
                        break;
                    }
                    set_register(rd, rn_val + static_cast<int16_t>(rm_val));
                  }
                }
2792 2793 2794 2795 2796
              } else if (instr->Bits(27, 16) == 0x6BF &&
                         instr->Bits(11, 4) == 0xF3) {
                // Rev.
                uint32_t rm_val = get_register(instr->RmValue());
                set_register(rd, ByteReverse(rm_val));
2797 2798 2799
              } else {
                UNREACHABLE();
              }
2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
              break;
            case 2:
              if ((instr->Bit(20) == 0) && (instr->Bits(9, 6) == 1)) {
                if (instr->Bits(19, 16) == 0xF) {
                  // Uxtb16.
                  uint32_t rm_val = get_register(instr->RmValue());
                  int32_t rotate = instr->Bits(11, 10);
                  switch (rotate) {
                    case 0:
                      break;
                    case 1:
                      rm_val = (rm_val >> 8) | (rm_val << 24);
                      break;
                    case 2:
                      rm_val = (rm_val >> 16) | (rm_val << 16);
                      break;
                    case 3:
                      rm_val = (rm_val >> 24) | (rm_val << 8);
                      break;
                  }
2820
                  set_register(rd, (rm_val & 0xFF) | (rm_val & 0xFF0000));
2821 2822 2823 2824 2825 2826 2827 2828
                } else {
                  UNIMPLEMENTED();
                }
              } else {
                UNIMPLEMENTED();
              }
              break;
            case 3:
2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867
              if ((instr->Bits(9, 6) == 1)) {
                if (instr->Bit(20) == 0) {
                  if (instr->Bits(19, 16) == 0xF) {
                    // Uxtb.
                    uint32_t rm_val = get_register(instr->RmValue());
                    int32_t rotate = instr->Bits(11, 10);
                    switch (rotate) {
                      case 0:
                        break;
                      case 1:
                        rm_val = (rm_val >> 8) | (rm_val << 24);
                        break;
                      case 2:
                        rm_val = (rm_val >> 16) | (rm_val << 16);
                        break;
                      case 3:
                        rm_val = (rm_val >> 24) | (rm_val << 8);
                        break;
                    }
                    set_register(rd, (rm_val & 0xFF));
                  } else {
                    // Uxtab.
                    uint32_t rn_val = get_register(rn);
                    uint32_t rm_val = get_register(instr->RmValue());
                    int32_t rotate = instr->Bits(11, 10);
                    switch (rotate) {
                      case 0:
                        break;
                      case 1:
                        rm_val = (rm_val >> 8) | (rm_val << 24);
                        break;
                      case 2:
                        rm_val = (rm_val >> 16) | (rm_val << 16);
                        break;
                      case 3:
                        rm_val = (rm_val >> 24) | (rm_val << 8);
                        break;
                    }
                    set_register(rd, rn_val + (rm_val & 0xFF));
2868 2869
                  }
                } else {
2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
                  if (instr->Bits(19, 16) == 0xF) {
                    // Uxth.
                    uint32_t rm_val = get_register(instr->RmValue());
                    int32_t rotate = instr->Bits(11, 10);
                    switch (rotate) {
                      case 0:
                        break;
                      case 1:
                        rm_val = (rm_val >> 8) | (rm_val << 24);
                        break;
                      case 2:
                        rm_val = (rm_val >> 16) | (rm_val << 16);
                        break;
                      case 3:
                        rm_val = (rm_val >> 24) | (rm_val << 8);
                        break;
                    }
                    set_register(rd, (rm_val & 0xFFFF));
                  } else {
                    // Uxtah.
                    uint32_t rn_val = get_register(rn);
                    uint32_t rm_val = get_register(instr->RmValue());
                    int32_t rotate = instr->Bits(11, 10);
                    switch (rotate) {
                      case 0:
                        break;
                      case 1:
                        rm_val = (rm_val >> 8) | (rm_val << 24);
                        break;
                      case 2:
                        rm_val = (rm_val >> 16) | (rm_val << 16);
                        break;
                      case 3:
                        rm_val = (rm_val >> 24) | (rm_val << 8);
                        break;
                    }
                    set_register(rd, rn_val + (rm_val & 0xFFFF));
2907 2908 2909
                  }
                }
              } else {
2910
                // PU == 0b01, BW == 0b11, Bits(9, 6) != 0b0001
2911 2912
                if ((instr->Bits(20, 16) == 0x1F) &&
                    (instr->Bits(11, 4) == 0xF3)) {
2913 2914 2915 2916 2917 2918
                  // Rbit.
                  uint32_t rm_val = get_register(instr->RmValue());
                  set_register(rd, base::bits::ReverseBits(rm_val));
                } else {
                  UNIMPLEMENTED();
                }
2919 2920
              }
              break;
2921 2922 2923 2924
          }
        }
        return;
      }
2925 2926
      break;
    }
2927
    case db_x: {
2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948
      if (instr->Bits(22, 20) == 0x5) {
        if (instr->Bits(7, 4) == 0x1) {
          int rm = instr->RmValue();
          int32_t rm_val = get_register(rm);
          int rs = instr->RsValue();
          int32_t rs_val = get_register(rs);
          if (instr->Bits(15, 12) == 0xF) {
            // SMMUL (in V8 notation matching ARM ISA format)
            // Format(instr, "smmul'cond 'rn, 'rm, 'rs");
            rn_val = base::bits::SignedMulHigh32(rm_val, rs_val);
          } else {
            // SMMLA (in V8 notation matching ARM ISA format)
            // Format(instr, "smmla'cond 'rn, 'rm, 'rs, 'rd");
            int rd = instr->RdValue();
            int32_t rd_val = get_register(rd);
            rn_val = base::bits::SignedMulHighAndAdd32(rm_val, rs_val, rd_val);
          }
          set_register(rn, rn_val);
          return;
        }
      }
2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963
      if (instr->Bits(5, 4) == 0x1) {
        if ((instr->Bit(22) == 0x0) && (instr->Bit(20) == 0x1)) {
          // (s/u)div (in V8 notation matching ARM ISA format) rn = rm/rs
          // Format(instr, "'(s/u)div'cond'b 'rn, 'rm, 'rs);
          int rm = instr->RmValue();
          int32_t rm_val = get_register(rm);
          int rs = instr->RsValue();
          int32_t rs_val = get_register(rs);
          int32_t ret_val = 0;
          // udiv
          if (instr->Bit(21) == 0x1) {
            ret_val = bit_cast<int32_t>(base::bits::UnsignedDiv32(
                bit_cast<uint32_t>(rm_val), bit_cast<uint32_t>(rs_val)));
          } else {
            ret_val = base::bits::SignedDiv32(rm_val, rs_val);
2964
          }
2965 2966
          set_register(rn, ret_val);
          return;
2967 2968
        }
      }
2969 2970 2971 2972 2973 2974 2975
      // Format(instr, "'memop'cond'b 'rd, ['rn, -'shift_rm]'w");
      addr = rn_val - shifter_operand;
      if (instr->HasW()) {
        set_register(rn, addr);
      }
      break;
    }
2976
    case ib_x: {
2977 2978
      if (instr->HasW() && (instr->Bits(6, 4) == 0x5)) {
        uint32_t widthminus1 = static_cast<uint32_t>(instr->Bits(20, 16));
2979
        uint32_t lsbit = static_cast<uint32_t>(instr->Bits(11, 7));
2980 2981
        uint32_t msbit = widthminus1 + lsbit;
        if (msbit <= 31) {
2982 2983 2984
          if (instr->Bit(22)) {
            // ubfx - unsigned bitfield extract.
            uint32_t rm_val =
2985
                static_cast<uint32_t>(get_register(instr->RmValue()));
2986 2987
            uint32_t extr_val = rm_val << (31 - msbit);
            extr_val = extr_val >> (31 - widthminus1);
2988
            set_register(instr->RdValue(), extr_val);
2989 2990
          } else {
            // sbfx - signed bitfield extract.
2991
            int32_t rm_val = get_register(instr->RmValue());
2992 2993
            int32_t extr_val = rm_val << (31 - msbit);
            extr_val = extr_val >> (31 - widthminus1);
2994
            set_register(instr->RdValue(), extr_val);
2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
          }
        } else {
          UNREACHABLE();
        }
        return;
      } else if (!instr->HasW() && (instr->Bits(6, 4) == 0x1)) {
        uint32_t lsbit = static_cast<uint32_t>(instr->Bits(11, 7));
        uint32_t msbit = static_cast<uint32_t>(instr->Bits(20, 16));
        if (msbit >= lsbit) {
          // bfc or bfi - bitfield clear/insert.
          uint32_t rd_val =
3006
              static_cast<uint32_t>(get_register(instr->RdValue()));
3007
          uint32_t bitcount = msbit - lsbit + 1;
3008
          uint32_t mask = 0xFFFFFFFFu >> (32 - bitcount);
3009
          rd_val &= ~(mask << lsbit);
3010
          if (instr->RmValue() != 15) {
3011 3012
            // bfi - bitfield insert.
            uint32_t rm_val =
3013
                static_cast<uint32_t>(get_register(instr->RmValue()));
3014 3015 3016
            rm_val &= mask;
            rd_val |= rm_val << lsbit;
          }
3017
          set_register(instr->RdValue(), rd_val);
3018 3019 3020 3021 3022 3023 3024 3025 3026 3027
        } else {
          UNREACHABLE();
        }
        return;
      } else {
        // Format(instr, "'memop'cond'b 'rd, ['rn, +'shift_rm]'w");
        addr = rn_val + shifter_operand;
        if (instr->HasW()) {
          set_register(rn, addr);
        }
3028 3029 3030 3031 3032 3033 3034 3035 3036
      }
      break;
    }
    default: {
      UNREACHABLE();
      break;
    }
  }
  if (instr->HasB()) {
lrn@chromium.org's avatar
lrn@chromium.org committed
3037 3038 3039 3040
    if (instr->HasL()) {
      uint8_t byte = ReadB(addr);
      set_register(rd, byte);
    } else {
3041 3042
      uint8_t byte = get_register(rd);
      WriteB(addr, byte);
lrn@chromium.org's avatar
lrn@chromium.org committed
3043
    }
3044 3045
  } else {
    if (instr->HasL()) {
3046
      set_register(rd, ReadW(addr));
3047
    } else {
3048
      WriteW(addr, get_register(rd));
3049 3050 3051 3052 3053
    }
  }
}


3054
void Simulator::DecodeType4(Instruction* instr) {
3055
  DCHECK_EQ(instr->Bit(22), 0);  // only allowed to be set in privileged mode
3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
  if (instr->HasL()) {
    // Format(instr, "ldm'cond'pu 'rn'w, 'rlist");
    HandleRList(instr, true);
  } else {
    // Format(instr, "stm'cond'pu 'rn'w, 'rlist");
    HandleRList(instr, false);
  }
}


3066
void Simulator::DecodeType5(Instruction* instr) {
3067
  // Format(instr, "b'l'cond 'target");
3068
  int off = (instr->SImmed24Value() << 2);
lrn@chromium.org's avatar
lrn@chromium.org committed
3069
  intptr_t pc_address = get_pc();
3070
  if (instr->HasLink()) {
3071
    set_register(lr, pc_address + kInstrSize);
3072
  }
lrn@chromium.org's avatar
lrn@chromium.org committed
3073 3074
  int pc_reg = get_register(pc);
  set_pc(pc_reg + off);
3075 3076 3077
}


3078
void Simulator::DecodeType6(Instruction* instr) {
3079
  DecodeType6CoprocessorIns(instr);
3080 3081 3082
}


3083
void Simulator::DecodeType7(Instruction* instr) {
3084 3085 3086
  if (instr->Bit(24) == 1) {
    SoftwareInterrupt(instr);
  } else {
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
    switch (instr->CoprocessorValue()) {
      case 10:  // Fall through.
      case 11:
        DecodeTypeVFP(instr);
        break;
      case 15:
        DecodeTypeCP15(instr);
        break;
      default:
        UNIMPLEMENTED();
    }
3098 3099 3100 3101
  }
}


3102
// void Simulator::DecodeTypeVFP(Instruction* instr)
3103
// The Following ARMv7 VFPv instructions are currently supported.
3104 3105 3106 3107
// vmov :Sn = Rt
// vmov :Rt = Sn
// vcvt: Dd = Sm
// vcvt: Sd = Dm
3108
// vcvt.f64.s32 Dd, Dd, #<fbits>
3109
// Dd = vabs(Dm)
3110
// Sd = vabs(Sm)
3111
// Dd = vneg(Dm)
3112
// Sd = vneg(Sm)
3113
// Dd = vadd(Dn, Dm)
3114
// Sd = vadd(Sn, Sm)
3115
// Dd = vsub(Dn, Dm)
3116
// Sd = vsub(Sn, Sm)
3117
// Dd = vmul(Dn, Dm)
3118
// Sd = vmul(Sn, Sm)
3119
// Dd = vdiv(Dn, Dm)
3120
// Sd = vdiv(Sn, Sm)
3121
// vcmp(Dd, Dm)
3122
// vcmp(Sd, Sm)
3123
// Dd = vsqrt(Dm)
3124 3125
// Sd = vsqrt(Sm)
// vmrs
3126
// vdup.size Qd, Rt.
3127
void Simulator::DecodeTypeVFP(Instruction* instr) {
3128
  DCHECK((instr->TypeValue() == 7) && (instr->Bit(24) == 0x0) );
3129
  DCHECK_EQ(instr->Bits(11, 9), 0x5);
3130 3131 3132 3133
  // Obtain single precision register codes.
  int m = instr->VFPMRegValue(kSinglePrecision);
  int d = instr->VFPDRegValue(kSinglePrecision);
  int n = instr->VFPNRegValue(kSinglePrecision);
3134
  // Obtain double precision register codes.
3135 3136 3137
  int vm = instr->VFPMRegValue(kDoublePrecision);
  int vd = instr->VFPDRegValue(kDoublePrecision);
  int vn = instr->VFPNRegValue(kDoublePrecision);
3138 3139

  if (instr->Bit(4) == 0) {
3140
    if (instr->Opc1Value() == 0x7) {
3141
      // Other data processing instructions
3142
      if ((instr->Opc2Value() == 0x0) && (instr->Opc3Value() == 0x1)) {
3143
        // vmov register to register.
3144
        if (instr->SzValue() == 0x1) {
3145
          uint32_t data[2];
3146 3147
          get_d_register(vm, data);
          set_d_register(vd, data);
3148
        } else {
3149
          set_s_register(d, get_s_register(m));
3150
        }
3151 3152
      } else if ((instr->Opc2Value() == 0x0) && (instr->Opc3Value() == 0x3)) {
        // vabs
3153
        if (instr->SzValue() == 0x1) {
3154 3155 3156 3157 3158
          Float64 dm = get_double_from_d_register(vm);
          constexpr uint64_t kSignBit64 = uint64_t{1} << 63;
          Float64 dd = Float64::FromBits(dm.get_bits() & ~kSignBit64);
          dd = canonicalizeNaN(dd);
          set_d_register_from_double(vd, dd);
3159
        } else {
3160 3161 3162 3163 3164
          Float32 sm = get_float_from_s_register(m);
          constexpr uint32_t kSignBit32 = uint32_t{1} << 31;
          Float32 sd = Float32::FromBits(sm.get_bits() & ~kSignBit32);
          sd = canonicalizeNaN(sd);
          set_s_register_from_float(d, sd);
3165
        }
3166 3167
      } else if ((instr->Opc2Value() == 0x1) && (instr->Opc3Value() == 0x1)) {
        // vneg
3168
        if (instr->SzValue() == 0x1) {
3169 3170 3171 3172 3173
          Float64 dm = get_double_from_d_register(vm);
          constexpr uint64_t kSignBit64 = uint64_t{1} << 63;
          Float64 dd = Float64::FromBits(dm.get_bits() ^ kSignBit64);
          dd = canonicalizeNaN(dd);
          set_d_register_from_double(vd, dd);
3174
        } else {
3175 3176 3177 3178 3179
          Float32 sm = get_float_from_s_register(m);
          constexpr uint32_t kSignBit32 = uint32_t{1} << 31;
          Float32 sd = Float32::FromBits(sm.get_bits() ^ kSignBit32);
          sd = canonicalizeNaN(sd);
          set_s_register_from_float(d, sd);
3180
        }
3181
      } else if ((instr->Opc2Value() == 0x7) && (instr->Opc3Value() == 0x3)) {
3182
        DecodeVCVTBetweenDoubleAndSingle(instr);
3183
      } else if ((instr->Opc2Value() == 0x8) && (instr->Opc3Value() & 0x1)) {
3184
        DecodeVCVTBetweenFloatingPointAndInteger(instr);
3185 3186 3187
      } else if ((instr->Opc2Value() == 0xA) && (instr->Opc3Value() == 0x3) &&
                 (instr->Bit(8) == 1)) {
        // vcvt.f64.s32 Dd, Dd, #<fbits>
3188
        int fraction_bits = 32 - ((instr->Bits(3, 0) << 1) | instr->Bit(5));
3189 3190 3191
        int fixed_value = get_sinteger_from_s_register(vd * 2);
        double divide = 1 << fraction_bits;
        set_d_register_from_double(vd, fixed_value / divide);
3192 3193
      } else if (((instr->Opc2Value() >> 1) == 0x6) &&
                 (instr->Opc3Value() & 0x1)) {
3194
        DecodeVCVTBetweenFloatingPointAndInteger(instr);
3195 3196
      } else if (((instr->Opc2Value() == 0x4) || (instr->Opc2Value() == 0x5)) &&
                 (instr->Opc3Value() & 0x1)) {
3197
        DecodeVCMP(instr);
3198
      } else if (((instr->Opc2Value() == 0x1)) && (instr->Opc3Value() == 0x3)) {
3199
        // vsqrt
3200
        if (instr->SzValue() == 0x1) {
3201
          double dm_value = get_double_from_d_register(vm).get_scalar();
3202
          double dd_value = std::sqrt(dm_value);
3203 3204 3205
          dd_value = canonicalizeNaN(dd_value);
          set_d_register_from_double(vd, dd_value);
        } else {
3206
          float sm_value = get_float_from_s_register(m).get_scalar();
3207
          float sd_value = std::sqrt(sm_value);
3208 3209 3210
          sd_value = canonicalizeNaN(sd_value);
          set_s_register_from_float(d, sd_value);
        }
3211
      } else if (instr->Opc3Value() == 0x0) {
3212
        // vmov immediate.
3213
        if (instr->SzValue() == 0x1) {
3214 3215
          set_d_register_from_double(vd, instr->DoubleImmedVmov());
        } else {
3216 3217 3218
          // Cast double to float.
          float value = instr->DoubleImmedVmov().get_scalar();
          set_s_register_from_float(d, value);
3219
        }
3220 3221
      } else if (((instr->Opc2Value() == 0x6)) && (instr->Opc3Value() == 0x3)) {
        // vrintz - truncate
3222
        if (instr->SzValue() == 0x1) {
3223
          double dm_value = get_double_from_d_register(vm).get_scalar();
3224 3225 3226 3227
          double dd_value = trunc(dm_value);
          dd_value = canonicalizeNaN(dd_value);
          set_d_register_from_double(vd, dd_value);
        } else {
3228
          float sm_value = get_float_from_s_register(m).get_scalar();
3229 3230 3231 3232
          float sd_value = truncf(sm_value);
          sd_value = canonicalizeNaN(sd_value);
          set_s_register_from_float(d, sd_value);
        }
3233 3234 3235
      } else {
        UNREACHABLE();  // Not used by V8.
      }
3236 3237
    } else if (instr->Opc1Value() == 0x3) {
      if (instr->Opc3Value() & 0x1) {
3238
        // vsub
3239
        if (instr->SzValue() == 0x1) {
3240 3241
          double dn_value = get_double_from_d_register(vn).get_scalar();
          double dm_value = get_double_from_d_register(vm).get_scalar();
3242 3243 3244 3245
          double dd_value = dn_value - dm_value;
          dd_value = canonicalizeNaN(dd_value);
          set_d_register_from_double(vd, dd_value);
        } else {
3246 3247
          float sn_value = get_float_from_s_register(n).get_scalar();
          float sm_value = get_float_from_s_register(m).get_scalar();
3248 3249 3250 3251
          float sd_value = sn_value - sm_value;
          sd_value = canonicalizeNaN(sd_value);
          set_s_register_from_float(d, sd_value);
        }
3252 3253
      } else {
        // vadd
3254
        if (instr->SzValue() == 0x1) {
3255 3256
          double dn_value = get_double_from_d_register(vn).get_scalar();
          double dm_value = get_double_from_d_register(vm).get_scalar();
3257 3258 3259 3260
          double dd_value = dn_value + dm_value;
          dd_value = canonicalizeNaN(dd_value);
          set_d_register_from_double(vd, dd_value);
        } else {
3261 3262
          float sn_value = get_float_from_s_register(n).get_scalar();
          float sm_value = get_float_from_s_register(m).get_scalar();
3263 3264 3265 3266 3267 3268 3269 3270
          float sd_value = sn_value + sm_value;
          sd_value = canonicalizeNaN(sd_value);
          set_s_register_from_float(d, sd_value);
        }
      }
    } else if ((instr->Opc1Value() == 0x2) && !(instr->Opc3Value() & 0x1)) {
      // vmul
      if (instr->SzValue() == 0x1) {
3271 3272
        double dn_value = get_double_from_d_register(vn).get_scalar();
        double dm_value = get_double_from_d_register(vm).get_scalar();
3273
        double dd_value = dn_value * dm_value;
3274
        dd_value = canonicalizeNaN(dd_value);
3275
        set_d_register_from_double(vd, dd_value);
3276
      } else {
3277 3278
        float sn_value = get_float_from_s_register(n).get_scalar();
        float sm_value = get_float_from_s_register(m).get_scalar();
3279 3280 3281
        float sd_value = sn_value * sm_value;
        sd_value = canonicalizeNaN(sd_value);
        set_s_register_from_float(d, sd_value);
3282
      }
3283 3284 3285
    } else if ((instr->Opc1Value() == 0x0)) {
      // vmla, vmls
      const bool is_vmls = (instr->Opc3Value() & 0x1);
3286
      if (instr->SzValue() == 0x1) {
3287 3288 3289
        const double dd_val = get_double_from_d_register(vd).get_scalar();
        const double dn_val = get_double_from_d_register(vn).get_scalar();
        const double dm_val = get_double_from_d_register(vm).get_scalar();
3290 3291 3292

        // Note: we do the mul and add/sub in separate steps to avoid getting a
        // result with too high precision.
3293 3294
        const double res = dn_val * dm_val;
        set_d_register_from_double(vd, res);
3295
        if (is_vmls) {
3296
          set_d_register_from_double(vd, canonicalizeNaN(dd_val - res));
3297
        } else {
3298
          set_d_register_from_double(vd, canonicalizeNaN(dd_val + res));
3299
        }
3300
      } else {
3301 3302 3303
        const float sd_val = get_float_from_s_register(d).get_scalar();
        const float sn_val = get_float_from_s_register(n).get_scalar();
        const float sm_val = get_float_from_s_register(m).get_scalar();
3304 3305 3306

        // Note: we do the mul and add/sub in separate steps to avoid getting a
        // result with too high precision.
3307 3308
        const float res = sn_val * sm_val;
        set_s_register_from_float(d, res);
3309
        if (is_vmls) {
3310
          set_s_register_from_float(d, canonicalizeNaN(sd_val - res));
3311
        } else {
3312
          set_s_register_from_float(d, canonicalizeNaN(sd_val + res));
3313
        }
3314
      }
3315
    } else if ((instr->Opc1Value() == 0x4) && !(instr->Opc3Value() & 0x1)) {
3316
      // vdiv
3317
      if (instr->SzValue() == 0x1) {
3318 3319
        double dn_value = get_double_from_d_register(vn).get_scalar();
        double dm_value = get_double_from_d_register(vm).get_scalar();
3320 3321 3322 3323 3324
        double dd_value = dn_value / dm_value;
        div_zero_vfp_flag_ = (dm_value == 0);
        dd_value = canonicalizeNaN(dd_value);
        set_d_register_from_double(vd, dd_value);
      } else {
3325 3326
        float sn_value = get_float_from_s_register(n).get_scalar();
        float sm_value = get_float_from_s_register(m).get_scalar();
3327 3328 3329 3330
        float sd_value = sn_value / sm_value;
        div_zero_vfp_flag_ = (sm_value == 0);
        sd_value = canonicalizeNaN(sd_value);
        set_s_register_from_float(d, sd_value);
3331 3332 3333 3334 3335
      }
    } else {
      UNIMPLEMENTED();  // Not used by V8.
    }
  } else {
3336 3337
    if ((instr->VCValue() == 0x0) &&
        (instr->VAValue() == 0x0)) {
3338
      DecodeVMOVBetweenCoreAndSinglePrecisionRegisters(instr);
3339 3340 3341 3342 3343 3344
    } else if ((instr->VLValue() == 0x0) && (instr->VCValue() == 0x1)) {
      if (instr->Bit(23) == 0) {
        // vmov (ARM core register to scalar)
        int vd = instr->VFPNRegValue(kDoublePrecision);
        int rt = instr->RtValue();
        int opc1_opc2 = (instr->Bits(22, 21) << 2) | instr->Bits(6, 5);
3345
        if ((opc1_opc2 & 0xB) == 0) {
3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395
          // NeonS32/NeonU32
          uint32_t data[2];
          get_d_register(vd, data);
          data[instr->Bit(21)] = get_register(rt);
          set_d_register(vd, data);
        } else {
          uint64_t data;
          get_d_register(vd, &data);
          uint64_t rt_value = get_register(rt);
          if ((opc1_opc2 & 0x8) != 0) {
            // NeonS8 / NeonU8
            int i = opc1_opc2 & 0x7;
            int shift = i * kBitsPerByte;
            const uint64_t mask = 0xFF;
            data &= ~(mask << shift);
            data |= (rt_value & mask) << shift;
            set_d_register(vd, &data);
          } else if ((opc1_opc2 & 0x1) != 0) {
            // NeonS16 / NeonU16
            int i = (opc1_opc2 >> 1) & 0x3;
            int shift = i * kBitsPerByte * kShortSize;
            const uint64_t mask = 0xFFFF;
            data &= ~(mask << shift);
            data |= (rt_value & mask) << shift;
            set_d_register(vd, &data);
          } else {
            UNREACHABLE();  // Not used by V8.
          }
        }
      } else {
        // vdup.size Qd, Rt.
        NeonSize size = Neon32;
        if (instr->Bit(5) != 0)
          size = Neon16;
        else if (instr->Bit(22) != 0)
          size = Neon8;
        int vd = instr->VFPNRegValue(kSimd128Precision);
        int rt = instr->RtValue();
        uint32_t rt_value = get_register(rt);
        uint32_t q_data[4];
        switch (size) {
          case Neon8: {
            rt_value &= 0xFF;
            uint8_t* dst = reinterpret_cast<uint8_t*>(q_data);
            for (int i = 0; i < 16; i++) {
              dst[i] = rt_value;
            }
            break;
          }
          case Neon16: {
3396
            // Perform pairwise op.
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413
            rt_value &= 0xFFFFu;
            uint32_t rt_rt = (rt_value << 16) | (rt_value & 0xFFFFu);
            for (int i = 0; i < 4; i++) {
              q_data[i] = rt_rt;
            }
            break;
          }
          case Neon32: {
            for (int i = 0; i < 4; i++) {
              q_data[i] = rt_value;
            }
            break;
          }
          default:
            UNREACHABLE();
            break;
        }
3414
        set_neon_register(vd, q_data);
3415 3416
      }
    } else if ((instr->VLValue() == 0x1) && (instr->VCValue() == 0x1)) {
3417
      // vmov (scalar to ARM core register)
3418 3419 3420
      int vn = instr->VFPNRegValue(kDoublePrecision);
      int rt = instr->RtValue();
      int opc1_opc2 = (instr->Bits(22, 21) << 2) | instr->Bits(6, 5);
3421 3422
      uint64_t data;
      get_d_register(vn, &data);
3423
      if ((opc1_opc2 & 0xB) == 0) {
3424
        // NeonS32 / NeonU32
3425 3426 3427
        int32_t int_data[2];
        memcpy(int_data, &data, sizeof(int_data));
        set_register(rt, int_data[instr->Bit(21)]);
3428 3429 3430 3431 3432 3433 3434 3435 3436
      } else {
        uint64_t data;
        get_d_register(vn, &data);
        bool u = instr->Bit(23) != 0;
        if ((opc1_opc2 & 0x8) != 0) {
          // NeonS8 / NeonU8
          int i = opc1_opc2 & 0x7;
          int shift = i * kBitsPerByte;
          uint32_t scalar = (data >> shift) & 0xFFu;
3437
          if (!u && (scalar & 0x80) != 0) scalar |= 0xFFFFFF00;
3438 3439 3440 3441 3442 3443
          set_register(rt, scalar);
        } else if ((opc1_opc2 & 0x1) != 0) {
          // NeonS16 / NeonU16
          int i = (opc1_opc2 >> 1) & 0x3;
          int shift = i * kBitsPerByte * kShortSize;
          uint32_t scalar = (data >> shift) & 0xFFFFu;
3444
          if (!u && (scalar & 0x8000) != 0) scalar |= 0xFFFF0000;
3445 3446 3447 3448 3449
          set_register(rt, scalar);
        } else {
          UNREACHABLE();  // Not used by V8.
        }
      }
3450 3451 3452
    } else if ((instr->VLValue() == 0x1) &&
               (instr->VCValue() == 0x0) &&
               (instr->VAValue() == 0x7) &&
3453 3454
               (instr->Bits(19, 16) == 0x1)) {
      // vmrs
3455
      uint32_t rt = instr->RtValue();
3456
      if (rt == 0xF) {
3457
        Copy_FPSCR_to_APSR();
3458 3459 3460 3461 3462 3463
      } else {
        // Emulate FPSCR from the Simulator flags.
        uint32_t fpscr = (n_flag_FPSCR_ << 31) |
                         (z_flag_FPSCR_ << 30) |
                         (c_flag_FPSCR_ << 29) |
                         (v_flag_FPSCR_ << 28) |
3464
                         (FPSCR_default_NaN_mode_ << 25) |
3465 3466 3467 3468 3469
                         (inexact_vfp_flag_ << 4) |
                         (underflow_vfp_flag_ << 3) |
                         (overflow_vfp_flag_ << 2) |
                         (div_zero_vfp_flag_ << 1) |
                         (inv_op_vfp_flag_ << 0) |
3470
                         (FPSCR_rounding_mode_);
3471 3472
        set_register(rt, fpscr);
      }
3473 3474 3475
    } else if ((instr->VLValue() == 0x0) &&
               (instr->VCValue() == 0x0) &&
               (instr->VAValue() == 0x7) &&
3476 3477
               (instr->Bits(19, 16) == 0x1)) {
      // vmsr
3478
      uint32_t rt = instr->RtValue();
3479 3480 3481 3482 3483 3484 3485 3486
      if (rt == pc) {
        UNREACHABLE();
      } else {
        uint32_t rt_value = get_register(rt);
        n_flag_FPSCR_ = (rt_value >> 31) & 1;
        z_flag_FPSCR_ = (rt_value >> 30) & 1;
        c_flag_FPSCR_ = (rt_value >> 29) & 1;
        v_flag_FPSCR_ = (rt_value >> 28) & 1;
3487
        FPSCR_default_NaN_mode_ = (rt_value >> 25) & 1;
3488 3489 3490 3491 3492 3493
        inexact_vfp_flag_ = (rt_value >> 4) & 1;
        underflow_vfp_flag_ = (rt_value >> 3) & 1;
        overflow_vfp_flag_ = (rt_value >> 2) & 1;
        div_zero_vfp_flag_ = (rt_value >> 1) & 1;
        inv_op_vfp_flag_ = (rt_value >> 0) & 1;
        FPSCR_rounding_mode_ =
3494
            static_cast<VFPRoundingMode>((rt_value) & kVFPRoundingModeMask);
3495
      }
3496
    } else {
3497
      UNIMPLEMENTED();  // Not used by V8.
3498
    }
3499 3500 3501
  }
}

3502 3503
void Simulator::DecodeTypeCP15(Instruction* instr) {
  DCHECK((instr->TypeValue() == 7) && (instr->Bit(24) == 0x0));
3504
  DCHECK_EQ(instr->CoprocessorValue(), 15);
3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526

  if (instr->Bit(4) == 1) {
    // mcr
    int crn = instr->Bits(19, 16);
    int crm = instr->Bits(3, 0);
    int opc1 = instr->Bits(23, 21);
    int opc2 = instr->Bits(7, 5);
    if ((opc1 == 0) && (crn == 7)) {
      // ARMv6 memory barrier operations.
      // Details available in ARM DDI 0406C.b, B3-1750.
      if (((crm == 10) && (opc2 == 5)) ||  // CP15DMB
          ((crm == 10) && (opc2 == 4)) ||  // CP15DSB
          ((crm == 5) && (opc2 == 4))) {   // CP15ISB
        // These are ignored by the simulator for now.
      } else {
        UNIMPLEMENTED();
      }
    }
  } else {
    UNIMPLEMENTED();
  }
}
3527

3528 3529
void Simulator::DecodeVMOVBetweenCoreAndSinglePrecisionRegisters(
    Instruction* instr) {
3530
  DCHECK((instr->Bit(4) == 1) && (instr->VCValue() == 0x0) &&
3531
         (instr->VAValue() == 0x0));
3532

3533 3534 3535
  int t = instr->RtValue();
  int n = instr->VFPNRegValue(kSinglePrecision);
  bool to_arm_register = (instr->VLValue() == 0x1);
3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546

  if (to_arm_register) {
    int32_t int_value = get_sinteger_from_s_register(n);
    set_register(t, int_value);
  } else {
    int32_t rs_val = get_register(t);
    set_s_register_from_sinteger(n, rs_val);
  }
}


3547
void Simulator::DecodeVCMP(Instruction* instr) {
3548 3549
  DCHECK((instr->Bit(4) == 0) && (instr->Opc1Value() == 0x7));
  DCHECK(((instr->Opc2Value() == 0x4) || (instr->Opc2Value() == 0x5)) &&
3550
         (instr->Opc3Value() & 0x1));
3551
  // Comparison.
3552 3553

  VFPRegPrecision precision = kSinglePrecision;
3554
  if (instr->SzValue() == 0x1) {
3555 3556
    precision = kDoublePrecision;
  }
3557

3558
  int d = instr->VFPDRegValue(precision);
3559
  int m = 0;
3560 3561
  if (instr->Opc2Value() == 0x4) {
    m = instr->VFPMRegValue(precision);
3562
  }
3563

3564
  if (precision == kDoublePrecision) {
3565
    double dd_value = get_double_from_d_register(d).get_scalar();
3566
    double dm_value = 0.0;
3567
    if (instr->Opc2Value() == 0x4) {
3568
      dm_value = get_double_from_d_register(m).get_scalar();
3569
    }
3570

3571 3572
    // Raise exceptions for quiet NaNs if necessary.
    if (instr->Bit(7) == 1) {
3573
      if (std::isnan(dd_value)) {
3574 3575 3576 3577
        inv_op_vfp_flag_ = true;
      }
    }

3578 3579
    Compute_FPSCR_Flags(dd_value, dm_value);
  } else {
3580
    float sd_value = get_float_from_s_register(d).get_scalar();
3581 3582
    float sm_value = 0.0;
    if (instr->Opc2Value() == 0x4) {
3583
      sm_value = get_float_from_s_register(m).get_scalar();
3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
    }

    // Raise exceptions for quiet NaNs if necessary.
    if (instr->Bit(7) == 1) {
      if (std::isnan(sd_value)) {
        inv_op_vfp_flag_ = true;
      }
    }

    Compute_FPSCR_Flags(sd_value, sm_value);
3594 3595 3596 3597
  }
}


3598
void Simulator::DecodeVCVTBetweenDoubleAndSingle(Instruction* instr) {
3599 3600
  DCHECK((instr->Bit(4) == 0) && (instr->Opc1Value() == 0x7));
  DCHECK((instr->Opc2Value() == 0x7) && (instr->Opc3Value() == 0x3));
3601

3602 3603
  VFPRegPrecision dst_precision = kDoublePrecision;
  VFPRegPrecision src_precision = kSinglePrecision;
3604
  if (instr->SzValue() == 1) {
3605 3606 3607 3608
    dst_precision = kSinglePrecision;
    src_precision = kDoublePrecision;
  }

3609 3610
  int dst = instr->VFPDRegValue(dst_precision);
  int src = instr->VFPMRegValue(src_precision);
3611

3612
  if (dst_precision == kSinglePrecision) {
3613
    double val = get_double_from_d_register(src).get_scalar();
3614 3615
    set_s_register_from_float(dst, static_cast<float>(val));
  } else {
3616
    float val = get_float_from_s_register(src).get_scalar();
3617 3618 3619 3620
    set_d_register_from_double(dst, static_cast<double>(val));
  }
}

3621 3622 3623
bool get_inv_op_vfp_flag(VFPRoundingMode mode,
                         double val,
                         bool unsigned_) {
3624
  DCHECK((mode == RN) || (mode == RM) || (mode == RZ));
3625
  double max_uint = static_cast<double>(0xFFFFFFFFu);
3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666
  double max_int = static_cast<double>(kMaxInt);
  double min_int = static_cast<double>(kMinInt);

  // Check for NaN.
  if (val != val) {
    return true;
  }

  // Check for overflow. This code works because 32bit integers can be
  // exactly represented by ieee-754 64bit floating-point values.
  switch (mode) {
    case RN:
      return  unsigned_ ? (val >= (max_uint + 0.5)) ||
                          (val < -0.5)
                        : (val >= (max_int + 0.5)) ||
                          (val < (min_int - 0.5));

    case RM:
      return  unsigned_ ? (val >= (max_uint + 1.0)) ||
                          (val < 0)
                        : (val >= (max_int + 1.0)) ||
                          (val < min_int);

    case RZ:
      return  unsigned_ ? (val >= (max_uint + 1.0)) ||
                          (val <= -1)
                        : (val >= (max_int + 1.0)) ||
                          (val <= (min_int - 1.0));
    default:
      UNREACHABLE();
  }
}


// We call this function only if we had a vfp invalid exception.
// It returns the correct saturated value.
int VFPConversionSaturate(double val, bool unsigned_res) {
  if (val != val) {
    return 0;
  } else {
    if (unsigned_res) {
3667
      return (val < 0) ? 0 : 0xFFFFFFFFu;
3668 3669 3670 3671 3672 3673
    } else {
      return (val < 0) ? kMinInt : kMaxInt;
    }
  }
}

3674 3675
int32_t Simulator::ConvertDoubleToInt(double val, bool unsigned_integer,
                                      VFPRoundingMode mode) {
3676 3677
  // TODO(jkummerow): These casts are undefined behavior if the integral
  // part of {val} does not fit into the destination type.
3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717
  int32_t result =
      unsigned_integer ? static_cast<uint32_t>(val) : static_cast<int32_t>(val);

  inv_op_vfp_flag_ = get_inv_op_vfp_flag(mode, val, unsigned_integer);

  double abs_diff = unsigned_integer
                        ? std::fabs(val - static_cast<uint32_t>(result))
                        : std::fabs(val - result);

  inexact_vfp_flag_ = (abs_diff != 0);

  if (inv_op_vfp_flag_) {
    result = VFPConversionSaturate(val, unsigned_integer);
  } else {
    switch (mode) {
      case RN: {
        int val_sign = (val > 0) ? 1 : -1;
        if (abs_diff > 0.5) {
          result += val_sign;
        } else if (abs_diff == 0.5) {
          // Round to even if exactly halfway.
          result = ((result % 2) == 0) ? result : result + val_sign;
        }
        break;
      }

      case RM:
        result = result > val ? result - 1 : result;
        break;

      case RZ:
        // Nothing to do.
        break;

      default:
        UNREACHABLE();
    }
  }
  return result;
}
3718

3719
void Simulator::DecodeVCVTBetweenFloatingPointAndInteger(Instruction* instr) {
3720
  DCHECK((instr->Bit(4) == 0) && (instr->Opc1Value() == 0x7) &&
3721
         (instr->Bits(27, 23) == 0x1D));
3722
  DCHECK(((instr->Opc2Value() == 0x8) && (instr->Opc3Value() & 0x1)) ||
3723
         (((instr->Opc2Value() >> 1) == 0x6) && (instr->Opc3Value() & 0x1)));
3724 3725 3726

  // Conversion between floating-point and integer.
  bool to_integer = (instr->Bit(18) == 1);
3727

3728 3729
  VFPRegPrecision src_precision = (instr->SzValue() == 1) ? kDoublePrecision
                                                          : kSinglePrecision;
3730

3731
  if (to_integer) {
3732 3733 3734 3735 3736 3737
    // We are playing with code close to the C++ standard's limits below,
    // hence the very simple code and heavy checks.
    //
    // Note:
    // C++ defines default type casting from floating point to integer as
    // (close to) rounding toward zero ("fractional part discarded").
3738

3739 3740
    int dst = instr->VFPDRegValue(kSinglePrecision);
    int src = instr->VFPMRegValue(src_precision);
3741

3742 3743 3744 3745
    // Bit 7 in vcvt instructions indicates if we should use the FPSCR rounding
    // mode or the default Round to Zero mode.
    VFPRoundingMode mode = (instr->Bit(7) != 1) ? FPSCR_rounding_mode_
                                                : RZ;
3746
    DCHECK((mode == RM) || (mode == RZ) || (mode == RN));
3747

3748 3749
    bool unsigned_integer = (instr->Bit(16) == 0);
    bool double_precision = (src_precision == kDoublePrecision);
3750

3751 3752
    double val = double_precision ? get_double_from_d_register(src).get_scalar()
                                  : get_float_from_s_register(src).get_scalar();
3753

3754
    int32_t temp = ConvertDoubleToInt(val, unsigned_integer, mode);
3755

3756 3757 3758
    // Update the destination register.
    set_s_register_from_sinteger(dst, temp);

3759
  } else {
3760 3761
    bool unsigned_integer = (instr->Bit(7) == 0);

3762 3763
    int dst = instr->VFPDRegValue(src_precision);
    int src = instr->VFPMRegValue(kSinglePrecision);
3764 3765 3766

    int val = get_sinteger_from_s_register(src);

3767
    if (src_precision == kDoublePrecision) {
3768
      if (unsigned_integer) {
3769 3770
        set_d_register_from_double(
            dst, static_cast<double>(static_cast<uint32_t>(val)));
3771 3772 3773
      } else {
        set_d_register_from_double(dst, static_cast<double>(val));
      }
3774
    } else {
3775
      if (unsigned_integer) {
3776 3777
        set_s_register_from_float(
            dst, static_cast<float>(static_cast<uint32_t>(val)));
3778 3779 3780
      } else {
        set_s_register_from_float(dst, static_cast<float>(val));
      }
3781 3782 3783 3784 3785
    }
  }
}


3786
// void Simulator::DecodeType6CoprocessorIns(Instruction* instr)
3787
// Decode Type 6 coprocessor instructions.
3788 3789
// Dm = vmov(Rt, Rt2)
// <Rt, Rt2> = vmov(Dm)
3790 3791
// Ddst = MEM(Rbase + 4*offset).
// MEM(Rbase + 4*offset) = Dsrc.
3792
void Simulator::DecodeType6CoprocessorIns(Instruction* instr) {
3793
  DCHECK_EQ(instr->TypeValue(), 6);
3794

3795 3796
  if (instr->CoprocessorValue() == 0xA) {
    switch (instr->OpcodeValue()) {
3797
      case 0x8:
3798 3799 3800
      case 0xA:
      case 0xC:
      case 0xE: {  // Load and store single precision float to memory.
3801 3802 3803
        int rn = instr->RnValue();
        int vd = instr->VFPDRegValue(kSinglePrecision);
        int offset = instr->Immed8Value();
3804 3805 3806 3807 3808
        if (!instr->HasU()) {
          offset = -offset;
        }

        int32_t address = get_register(rn) + 4 * offset;
3809 3810
        // Load and store address for singles must be at least four-byte
        // aligned.
3811
        DCHECK_EQ(address % 4, 0);
3812
        if (instr->HasL()) {
3813
          // Load single from memory: vldr.
3814
          set_s_register_from_sinteger(vd, ReadW(address));
3815
        } else {
3816
          // Store single to memory: vstr.
3817
          WriteW(address, get_sinteger_from_s_register(vd));
3818 3819 3820
        }
        break;
      }
3821 3822 3823 3824 3825 3826 3827 3828 3829
      case 0x4:
      case 0x5:
      case 0x6:
      case 0x7:
      case 0x9:
      case 0xB:
        // Load/store multiple single from memory: vldm/vstm.
        HandleVList(instr);
        break;
3830 3831 3832
      default:
        UNIMPLEMENTED();  // Not used by V8.
    }
3833 3834
  } else if (instr->CoprocessorValue() == 0xB) {
    switch (instr->OpcodeValue()) {
3835 3836
      case 0x2:
        // Load and store double to two GP registers
3837
        if (instr->Bits(7, 6) != 0 || instr->Bit(4) != 1) {
3838 3839
          UNIMPLEMENTED();  // Not used by V8.
        } else {
3840 3841
          int rt = instr->RtValue();
          int rn = instr->RnValue();
3842
          int vm = instr->VFPMRegValue(kDoublePrecision);
3843
          if (instr->HasL()) {
3844 3845
            uint32_t data[2];
            get_d_register(vm, data);
3846 3847
            set_register(rt, data[0]);
            set_register(rn, data[1]);
3848
          } else {
3849
            int32_t data[] = { get_register(rt), get_register(rn) };
3850
            set_d_register(vm, reinterpret_cast<uint32_t*>(data));
3851 3852 3853 3854
          }
        }
        break;
      case 0x8:
3855 3856 3857
      case 0xA:
      case 0xC:
      case 0xE: {  // Load and store double to memory.
3858
        int rn = instr->RnValue();
3859
        int vd = instr->VFPDRegValue(kDoublePrecision);
3860
        int offset = instr->Immed8Value();
3861 3862 3863 3864
        if (!instr->HasU()) {
          offset = -offset;
        }
        int32_t address = get_register(rn) + 4 * offset;
3865 3866
        // Load and store address for doubles must be at least four-byte
        // aligned.
3867
        DCHECK_EQ(address % 4, 0);
3868 3869
        if (instr->HasL()) {
          // Load double from memory: vldr.
3870
          int32_t data[] = {ReadW(address), ReadW(address + 4)};
3871
          set_d_register(vd, reinterpret_cast<uint32_t*>(data));
3872 3873
        } else {
          // Store double to memory: vstr.
3874 3875
          uint32_t data[2];
          get_d_register(vd, data);
3876 3877
          WriteW(address, data[0]);
          WriteW(address + 4, data[1]);
3878 3879
        }
        break;
3880
      }
3881 3882
      case 0x4:
      case 0x5:
3883 3884
      case 0x6:
      case 0x7:
3885
      case 0x9:
3886
      case 0xB:
3887 3888 3889
        // Load/store multiple double from memory: vldm/vstm.
        HandleVList(instr);
        break;
3890 3891
      default:
        UNIMPLEMENTED();  // Not used by V8.
3892
    }
3893 3894
  } else {
    UNIMPLEMENTED();  // Not used by V8.
3895 3896 3897
  }
}

3898
// Templated operations for NEON instructions.
3899 3900
template <typename T, typename U>
U Widen(T value) {
3901
  static_assert(sizeof(int64_t) > sizeof(T), "T must be int32_t or smaller");
3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916
  static_assert(sizeof(U) > sizeof(T), "T must smaller than U");
  return static_cast<U>(value);
}

template <typename T, typename U>
U Narrow(T value) {
  static_assert(sizeof(int8_t) < sizeof(T), "T must be int16_t or larger");
  static_assert(sizeof(U) < sizeof(T), "T must larger than U");
  static_assert(std::is_unsigned<T>() == std::is_unsigned<U>(),
                "Signed-ness of T and U must match");
  // Make sure value can be expressed in the smaller type; otherwise, the
  // casted result is implementation defined.
  DCHECK_LE(std::numeric_limits<T>::min(), value);
  DCHECK_GE(std::numeric_limits<T>::max(), value);
  return static_cast<U>(value);
3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927
}

template <typename T>
T Clamp(int64_t value) {
  static_assert(sizeof(int64_t) > sizeof(T), "T must be int32_t or smaller");
  int64_t min = static_cast<int64_t>(std::numeric_limits<T>::min());
  int64_t max = static_cast<int64_t>(std::numeric_limits<T>::max());
  int64_t clamped = std::max(min, std::min(max, value));
  return static_cast<T>(clamped);
}

3928 3929 3930 3931 3932
template <typename T, typename U>
void Widen(Simulator* simulator, int Vd, int Vm) {
  static const int kLanes = 8 / sizeof(T);
  T src[kLanes];
  U dst[kLanes];
3933
  simulator->get_neon_register<T, kDoubleSize>(Vm, src);
3934 3935 3936
  for (int i = 0; i < kLanes; i++) {
    dst[i] = Widen<T, U>(src[i]);
  }
3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959
  simulator->set_neon_register(Vd, dst);
}

template <typename T, int SIZE>
void Abs(Simulator* simulator, int Vd, int Vm) {
  static const int kElems = SIZE / sizeof(T);
  T src[kElems];
  simulator->get_neon_register<T, SIZE>(Vm, src);
  for (int i = 0; i < kElems; i++) {
    src[i] = std::abs(src[i]);
  }
  simulator->set_neon_register<T, SIZE>(Vd, src);
}

template <typename T, int SIZE>
void Neg(Simulator* simulator, int Vd, int Vm) {
  static const int kElems = SIZE / sizeof(T);
  T src[kElems];
  simulator->get_neon_register<T, SIZE>(Vm, src);
  for (int i = 0; i < kElems; i++) {
    src[i] = -src[i];
  }
  simulator->set_neon_register<T, SIZE>(Vd, src);
3960 3961 3962 3963 3964 3965 3966
}

template <typename T, typename U>
void SaturatingNarrow(Simulator* simulator, int Vd, int Vm) {
  static const int kLanes = 16 / sizeof(T);
  T src[kLanes];
  U dst[kLanes];
3967
  simulator->get_neon_register(Vm, src);
3968 3969 3970
  for (int i = 0; i < kLanes; i++) {
    dst[i] = Narrow<T, U>(Clamp<U>(src[i]));
  }
3971
  simulator->set_neon_register<U, kDoubleSize>(Vd, dst);
3972 3973
}

3974 3975 3976 3977
template <typename T>
void AddSaturate(Simulator* simulator, int Vd, int Vm, int Vn) {
  static const int kLanes = 16 / sizeof(T);
  T src1[kLanes], src2[kLanes];
3978 3979
  simulator->get_neon_register(Vn, src1);
  simulator->get_neon_register(Vm, src2);
3980
  for (int i = 0; i < kLanes; i++) {
3981
    src1[i] = Clamp<T>(Widen<T, int64_t>(src1[i]) + Widen<T, int64_t>(src2[i]));
3982
  }
3983
  simulator->set_neon_register(Vd, src1);
3984 3985 3986 3987 3988 3989
}

template <typename T>
void SubSaturate(Simulator* simulator, int Vd, int Vm, int Vn) {
  static const int kLanes = 16 / sizeof(T);
  T src1[kLanes], src2[kLanes];
3990 3991
  simulator->get_neon_register(Vn, src1);
  simulator->get_neon_register(Vm, src2);
3992
  for (int i = 0; i < kLanes; i++) {
3993
    src1[i] = Clamp<T>(Widen<T, int64_t>(src1[i]) - Widen<T, int64_t>(src2[i]));
3994
  }
3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126
  simulator->set_neon_register(Vd, src1);
}

template <typename T, int SIZE>
void Zip(Simulator* simulator, int Vd, int Vm) {
  static const int kElems = SIZE / sizeof(T);
  static const int kPairs = kElems / 2;
  T src1[kElems], src2[kElems], dst1[kElems], dst2[kElems];
  simulator->get_neon_register<T, SIZE>(Vd, src1);
  simulator->get_neon_register<T, SIZE>(Vm, src2);
  for (int i = 0; i < kPairs; i++) {
    dst1[i * 2] = src1[i];
    dst1[i * 2 + 1] = src2[i];
    dst2[i * 2] = src1[i + kPairs];
    dst2[i * 2 + 1] = src2[i + kPairs];
  }
  simulator->set_neon_register<T, SIZE>(Vd, dst1);
  simulator->set_neon_register<T, SIZE>(Vm, dst2);
}

template <typename T, int SIZE>
void Unzip(Simulator* simulator, int Vd, int Vm) {
  static const int kElems = SIZE / sizeof(T);
  static const int kPairs = kElems / 2;
  T src1[kElems], src2[kElems], dst1[kElems], dst2[kElems];
  simulator->get_neon_register<T, SIZE>(Vd, src1);
  simulator->get_neon_register<T, SIZE>(Vm, src2);
  for (int i = 0; i < kPairs; i++) {
    dst1[i] = src1[i * 2];
    dst1[i + kPairs] = src2[i * 2];
    dst2[i] = src1[i * 2 + 1];
    dst2[i + kPairs] = src2[i * 2 + 1];
  }
  simulator->set_neon_register<T, SIZE>(Vd, dst1);
  simulator->set_neon_register<T, SIZE>(Vm, dst2);
}

template <typename T, int SIZE>
void Transpose(Simulator* simulator, int Vd, int Vm) {
  static const int kElems = SIZE / sizeof(T);
  static const int kPairs = kElems / 2;
  T src1[kElems], src2[kElems];
  simulator->get_neon_register<T, SIZE>(Vd, src1);
  simulator->get_neon_register<T, SIZE>(Vm, src2);
  for (int i = 0; i < kPairs; i++) {
    std::swap(src1[2 * i + 1], src2[2 * i]);
  }
  simulator->set_neon_register<T, SIZE>(Vd, src1);
  simulator->set_neon_register<T, SIZE>(Vm, src2);
}

template <typename T, int SIZE>
void Test(Simulator* simulator, int Vd, int Vm, int Vn) {
  static const int kElems = SIZE / sizeof(T);
  T src1[kElems], src2[kElems];
  simulator->get_neon_register<T, SIZE>(Vn, src1);
  simulator->get_neon_register<T, SIZE>(Vm, src2);
  for (int i = 0; i < kElems; i++) {
    src1[i] = (src1[i] & src2[i]) != 0 ? -1 : 0;
  }
  simulator->set_neon_register<T, SIZE>(Vd, src1);
}

template <typename T, int SIZE>
void Add(Simulator* simulator, int Vd, int Vm, int Vn) {
  static const int kElems = SIZE / sizeof(T);
  T src1[kElems], src2[kElems];
  simulator->get_neon_register<T, SIZE>(Vn, src1);
  simulator->get_neon_register<T, SIZE>(Vm, src2);
  for (int i = 0; i < kElems; i++) {
    src1[i] += src2[i];
  }
  simulator->set_neon_register<T, SIZE>(Vd, src1);
}

template <typename T, int SIZE>
void Sub(Simulator* simulator, int Vd, int Vm, int Vn) {
  static const int kElems = SIZE / sizeof(T);
  T src1[kElems], src2[kElems];
  simulator->get_neon_register<T, SIZE>(Vn, src1);
  simulator->get_neon_register<T, SIZE>(Vm, src2);
  for (int i = 0; i < kElems; i++) {
    src1[i] -= src2[i];
  }
  simulator->set_neon_register<T, SIZE>(Vd, src1);
}

template <typename T, int SIZE>
void Mul(Simulator* simulator, int Vd, int Vm, int Vn) {
  static const int kElems = SIZE / sizeof(T);
  T src1[kElems], src2[kElems];
  simulator->get_neon_register<T, SIZE>(Vn, src1);
  simulator->get_neon_register<T, SIZE>(Vm, src2);
  for (int i = 0; i < kElems; i++) {
    src1[i] *= src2[i];
  }
  simulator->set_neon_register<T, SIZE>(Vd, src1);
}

template <typename T, int SIZE>
void ShiftLeft(Simulator* simulator, int Vd, int Vm, int shift) {
  static const int kElems = SIZE / sizeof(T);
  T src[kElems];
  simulator->get_neon_register<T, SIZE>(Vm, src);
  for (int i = 0; i < kElems; i++) {
    src[i] <<= shift;
  }
  simulator->set_neon_register<T, SIZE>(Vd, src);
}

template <typename T, int SIZE>
void ShiftRight(Simulator* simulator, int Vd, int Vm, int shift) {
  static const int kElems = SIZE / sizeof(T);
  T src[kElems];
  simulator->get_neon_register<T, SIZE>(Vm, src);
  for (int i = 0; i < kElems; i++) {
    src[i] >>= shift;
  }
  simulator->set_neon_register<T, SIZE>(Vd, src);
}

template <typename T, int SIZE>
void ArithmeticShiftRight(Simulator* simulator, int Vd, int Vm, int shift) {
  static const int kElems = SIZE / sizeof(T);
  T src[kElems];
  simulator->get_neon_register<T, SIZE>(Vm, src);
  for (int i = 0; i < kElems; i++) {
    src[i] = ArithmeticShiftRight(src[i], shift);
  }
  simulator->set_neon_register<T, SIZE>(Vd, src);
}

4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154
template <typename T, int SIZE>
void ShiftLeftAndInsert(Simulator* simulator, int Vd, int Vm, int shift) {
  static const int kElems = SIZE / sizeof(T);
  T src[kElems];
  T dst[kElems];
  simulator->get_neon_register<T, SIZE>(Vm, src);
  simulator->get_neon_register<T, SIZE>(Vd, dst);
  uint64_t mask = (1llu << shift) - 1llu;
  for (int i = 0; i < kElems; i++) {
    dst[i] = (src[i] << shift) | (dst[i] & mask);
  }
  simulator->set_neon_register<T, SIZE>(Vd, dst);
}

template <typename T, int SIZE>
void ShiftRightAndInsert(Simulator* simulator, int Vd, int Vm, int shift) {
  static const int kElems = SIZE / sizeof(T);
  T src[kElems];
  T dst[kElems];
  simulator->get_neon_register<T, SIZE>(Vm, src);
  simulator->get_neon_register<T, SIZE>(Vd, dst);
  uint64_t mask = ~((1llu << (kBitsPerByte * SIZE - shift)) - 1llu);
  for (int i = 0; i < kElems; i++) {
    dst[i] = (src[i] >> shift) | (dst[i] & mask);
  }
  simulator->set_neon_register<T, SIZE>(Vd, dst);
}

4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210
template <typename T, int SIZE>
void CompareEqual(Simulator* simulator, int Vd, int Vm, int Vn) {
  static const int kElems = SIZE / sizeof(T);
  T src1[kElems], src2[kElems];
  simulator->get_neon_register<T, SIZE>(Vn, src1);
  simulator->get_neon_register<T, SIZE>(Vm, src2);
  for (int i = 0; i < kElems; i++) {
    src1[i] = src1[i] == src2[i] ? -1 : 0;
  }
  simulator->set_neon_register<T, SIZE>(Vd, src1);
}

template <typename T, int SIZE>
void CompareGreater(Simulator* simulator, int Vd, int Vm, int Vn, bool ge) {
  static const int kElems = SIZE / sizeof(T);
  T src1[kElems], src2[kElems];
  simulator->get_neon_register<T, SIZE>(Vn, src1);
  simulator->get_neon_register<T, SIZE>(Vm, src2);
  for (int i = 0; i < kElems; i++) {
    if (ge)
      src1[i] = src1[i] >= src2[i] ? -1 : 0;
    else
      src1[i] = src1[i] > src2[i] ? -1 : 0;
  }
  simulator->set_neon_register<T, SIZE>(Vd, src1);
}

template <typename T>
T MinMax(T a, T b, bool is_min) {
  return is_min ? std::min(a, b) : std::max(a, b);
}

template <typename T, int SIZE>
void MinMax(Simulator* simulator, int Vd, int Vm, int Vn, bool min) {
  static const int kElems = SIZE / sizeof(T);
  T src1[kElems], src2[kElems];
  simulator->get_neon_register<T, SIZE>(Vn, src1);
  simulator->get_neon_register<T, SIZE>(Vm, src2);
  for (int i = 0; i < kElems; i++) {
    src1[i] = MinMax(src1[i], src2[i], min);
  }
  simulator->set_neon_register<T, SIZE>(Vd, src1);
}

template <typename T>
void PairwiseMinMax(Simulator* simulator, int Vd, int Vm, int Vn, bool min) {
  static const int kElems = kDoubleSize / sizeof(T);
  static const int kPairs = kElems / 2;
  T dst[kElems], src1[kElems], src2[kElems];
  simulator->get_neon_register<T, kDoubleSize>(Vn, src1);
  simulator->get_neon_register<T, kDoubleSize>(Vm, src2);
  for (int i = 0; i < kPairs; i++) {
    dst[i] = MinMax(src1[i * 2], src1[i * 2 + 1], min);
    dst[i + kPairs] = MinMax(src2[i * 2], src2[i * 2 + 1], min);
  }
  simulator->set_neon_register<T, kDoubleSize>(Vd, dst);
4211 4212
}

4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226
template <typename T>
void PairwiseAdd(Simulator* simulator, int Vd, int Vm, int Vn) {
  static const int kElems = kDoubleSize / sizeof(T);
  static const int kPairs = kElems / 2;
  T dst[kElems], src1[kElems], src2[kElems];
  simulator->get_neon_register<T, kDoubleSize>(Vn, src1);
  simulator->get_neon_register<T, kDoubleSize>(Vm, src2);
  for (int i = 0; i < kPairs; i++) {
    dst[i] = src1[i * 2] + src1[i * 2 + 1];
    dst[i + kPairs] = src2[i * 2] + src2[i * 2 + 1];
  }
  simulator->set_neon_register<T, kDoubleSize>(Vd, dst);
}

4227 4228
void Simulator::DecodeSpecialCondition(Instruction* instr) {
  switch (instr->SpecialValue()) {
4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260
    case 4: {
      int Vd, Vm, Vn;
      if (instr->Bit(6) == 0) {
        Vd = instr->VFPDRegValue(kDoublePrecision);
        Vm = instr->VFPMRegValue(kDoublePrecision);
        Vn = instr->VFPNRegValue(kDoublePrecision);
      } else {
        Vd = instr->VFPDRegValue(kSimd128Precision);
        Vm = instr->VFPMRegValue(kSimd128Precision);
        Vn = instr->VFPNRegValue(kSimd128Precision);
      }
      switch (instr->Bits(11, 8)) {
        case 0x0: {
          if (instr->Bit(4) == 1) {
            // vqadd.s<size> Qd, Qm, Qn.
            NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
            switch (size) {
              case Neon8:
                AddSaturate<int8_t>(this, Vd, Vm, Vn);
                break;
              case Neon16:
                AddSaturate<int16_t>(this, Vd, Vm, Vn);
                break;
              case Neon32:
                AddSaturate<int32_t>(this, Vd, Vm, Vn);
                break;
              default:
                UNREACHABLE();
                break;
            }
          } else {
            UNIMPLEMENTED();
4261
          }
4262
          break;
4263
        }
4264 4265 4266 4267 4268 4269
        case 0x1: {
          if (instr->Bits(21, 20) == 2 && instr->Bit(6) == 1 &&
              instr->Bit(4) == 1) {
            // vmov Qd, Qm.
            // vorr, Qd, Qm, Qn.
            uint32_t src1[4];
4270
            get_neon_register(Vm, src1);
4271 4272
            if (Vm != Vn) {
              uint32_t src2[4];
4273
              get_neon_register(Vn, src2);
4274 4275 4276 4277
              for (int i = 0; i < 4; i++) {
                src1[i] = src1[i] | src2[i];
              }
            }
4278
            set_neon_register(Vd, src1);
4279 4280 4281 4282
          } else if (instr->Bits(21, 20) == 0 && instr->Bit(6) == 1 &&
                     instr->Bit(4) == 1) {
            // vand Qd, Qm, Qn.
            uint32_t src1[4], src2[4];
4283 4284
            get_neon_register(Vn, src1);
            get_neon_register(Vm, src2);
4285 4286 4287
            for (int i = 0; i < 4; i++) {
              src1[i] = src1[i] & src2[i];
            }
4288
            set_neon_register(Vd, src1);
4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320
          } else {
            UNIMPLEMENTED();
          }
          break;
        }
        case 0x2: {
          if (instr->Bit(4) == 1) {
            // vqsub.s<size> Qd, Qm, Qn.
            NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
            switch (size) {
              case Neon8:
                SubSaturate<int8_t>(this, Vd, Vm, Vn);
                break;
              case Neon16:
                SubSaturate<int16_t>(this, Vd, Vm, Vn);
                break;
              case Neon32:
                SubSaturate<int32_t>(this, Vd, Vm, Vn);
                break;
              default:
                UNREACHABLE();
                break;
            }
          } else {
            UNIMPLEMENTED();
          }
          break;
        }
        case 0x3: {
          // vcge/vcgt.s<size> Qd, Qm, Qn.
          bool ge = instr->Bit(4) == 1;
          NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
4321
          switch (size) {
4322 4323
            case Neon8:
              CompareGreater<int8_t, kSimd128Size>(this, Vd, Vm, Vn, ge);
4324
              break;
4325 4326
            case Neon16:
              CompareGreater<int16_t, kSimd128Size>(this, Vd, Vm, Vn, ge);
4327
              break;
4328 4329
            case Neon32:
              CompareGreater<int32_t, kSimd128Size>(this, Vd, Vm, Vn, ge);
4330 4331 4332 4333 4334
              break;
            default:
              UNREACHABLE();
              break;
          }
4335 4336 4337 4338 4339 4340
          break;
        }
        case 0x6: {
          // vmin/vmax.s<size> Qd, Qm, Qn.
          NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
          bool min = instr->Bit(4) != 0;
4341
          switch (size) {
4342 4343
            case Neon8:
              MinMax<int8_t, kSimd128Size>(this, Vd, Vm, Vn, min);
4344
              break;
4345 4346
            case Neon16:
              MinMax<int16_t, kSimd128Size>(this, Vd, Vm, Vn, min);
4347
              break;
4348 4349
            case Neon32:
              MinMax<int32_t, kSimd128Size>(this, Vd, Vm, Vn, min);
4350 4351 4352 4353 4354
              break;
            default:
              UNREACHABLE();
              break;
          }
4355
          break;
4356
        }
4357 4358 4359 4360 4361 4362
        case 0x8: {
          // vadd/vtst
          NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
          if (instr->Bit(4) == 0) {
            // vadd.i<size> Qd, Qm, Qn.
            switch (size) {
4363 4364
              case Neon8:
                Add<uint8_t, kSimd128Size>(this, Vd, Vm, Vn);
4365
                break;
4366 4367
              case Neon16:
                Add<uint16_t, kSimd128Size>(this, Vd, Vm, Vn);
4368
                break;
4369 4370
              case Neon32:
                Add<uint32_t, kSimd128Size>(this, Vd, Vm, Vn);
4371 4372 4373 4374 4375
                break;
              default:
                UNREACHABLE();
                break;
            }
4376
          } else {
4377 4378
            // vtst.i<size> Qd, Qm, Qn.
            switch (size) {
4379 4380
              case Neon8:
                Test<uint8_t, kSimd128Size>(this, Vd, Vm, Vn);
4381
                break;
4382 4383
              case Neon16:
                Test<uint16_t, kSimd128Size>(this, Vd, Vm, Vn);
4384
                break;
4385 4386
              case Neon32:
                Test<uint32_t, kSimd128Size>(this, Vd, Vm, Vn);
4387 4388 4389 4390
                break;
              default:
                UNREACHABLE();
                break;
4391 4392
            }
          }
4393 4394 4395 4396 4397 4398 4399
          break;
        }
        case 0x9: {
          if (instr->Bit(6) == 1 && instr->Bit(4) == 1) {
            // vmul.i<size> Qd, Qm, Qn.
            NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
            switch (size) {
4400 4401
              case Neon8:
                Mul<uint8_t, kSimd128Size>(this, Vd, Vm, Vn);
4402
                break;
4403 4404
              case Neon16:
                Mul<uint16_t, kSimd128Size>(this, Vd, Vm, Vn);
4405
                break;
4406 4407
              case Neon32:
                Mul<uint32_t, kSimd128Size>(this, Vd, Vm, Vn);
4408 4409 4410 4411
                break;
              default:
                UNREACHABLE();
                break;
4412
            }
4413 4414
          } else {
            UNIMPLEMENTED();
4415
          }
4416 4417
          break;
        }
4418
        case 0xA: {
4419 4420 4421 4422
          // vpmin/vpmax.s<size> Dd, Dm, Dn.
          NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
          bool min = instr->Bit(4) != 0;
          switch (size) {
4423 4424
            case Neon8:
              PairwiseMinMax<int8_t>(this, Vd, Vm, Vn, min);
4425
              break;
4426 4427
            case Neon16:
              PairwiseMinMax<int16_t>(this, Vd, Vm, Vn, min);
4428
              break;
4429 4430
            case Neon32:
              PairwiseMinMax<int32_t>(this, Vd, Vm, Vn, min);
4431 4432 4433 4434 4435 4436 4437
              break;
            default:
              UNREACHABLE();
              break;
          }
          break;
        }
4438
        case 0xB: {
4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456
          // vpadd.i<size> Dd, Dm, Dn.
          NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
          switch (size) {
            case Neon8:
              PairwiseAdd<int8_t>(this, Vd, Vm, Vn);
              break;
            case Neon16:
              PairwiseAdd<int16_t>(this, Vd, Vm, Vn);
              break;
            case Neon32:
              PairwiseAdd<int32_t>(this, Vd, Vm, Vn);
              break;
            default:
              UNREACHABLE();
              break;
          }
          break;
        }
4457
        case 0xD: {
4458 4459
          if (instr->Bit(4) == 0) {
            float src1[4], src2[4];
4460 4461
            get_neon_register(Vn, src1);
            get_neon_register(Vm, src2);
4462
            for (int i = 0; i < 4; i++) {
4463 4464 4465 4466 4467 4468 4469
              if (instr->Bit(21) == 0) {
                // vadd.f32 Qd, Qm, Qn.
                src1[i] = src1[i] + src2[i];
              } else {
                // vsub.f32 Qd, Qm, Qn.
                src1[i] = src1[i] - src2[i];
              }
4470
            }
4471
            set_neon_register(Vd, src1);
4472
          } else {
4473
            UNIMPLEMENTED();
4474
          }
4475 4476
          break;
        }
4477
        case 0xE: {
4478 4479 4480
          if (instr->Bits(21, 20) == 0 && instr->Bit(4) == 0) {
            // vceq.f32.
            float src1[4], src2[4];
4481 4482
            get_neon_register(Vn, src1);
            get_neon_register(Vm, src2);
4483
            uint32_t dst[4];
4484
            for (int i = 0; i < 4; i++) {
4485
              dst[i] = (src1[i] == src2[i]) ? 0xFFFFFFFF : 0;
4486
            }
4487
            set_neon_register(Vd, dst);
4488
          } else {
4489
            UNIMPLEMENTED();
4490
          }
4491
          break;
4492
        }
4493
        case 0xF: {
4494 4495
          if (instr->Bit(20) == 0 && instr->Bit(6) == 1) {
            float src1[4], src2[4];
4496 4497
            get_neon_register(Vn, src1);
            get_neon_register(Vm, src2);
4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510
            if (instr->Bit(4) == 1) {
              if (instr->Bit(21) == 0) {
                // vrecps.f32 Qd, Qm, Qn.
                for (int i = 0; i < 4; i++) {
                  src1[i] = 2.0f - src1[i] * src2[i];
                }
              } else {
                // vrsqrts.f32 Qd, Qm, Qn.
                for (int i = 0; i < 4; i++) {
                  src1[i] = (3.0f - src1[i] * src2[i]) * 0.5f;
                }
              }
            } else {
4511 4512 4513 4514
              // vmin/vmax.f32 Qd, Qm, Qn.
              bool min = instr->Bit(21) == 1;
              for (int i = 0; i < 4; i++) {
                src1[i] = MinMax(src1[i], src2[i], min);
4515
              }
4516
            }
4517
            set_neon_register(Vd, src1);
4518 4519
          } else {
            UNIMPLEMENTED();
4520
          }
4521
          break;
4522
        }
4523 4524 4525
        default:
          UNIMPLEMENTED();
          break;
4526 4527
      }
      break;
4528
    }
4529 4530 4531 4532
    case 5:
      if ((instr->Bits(18, 16) == 0) && (instr->Bits(11, 6) == 0x28) &&
          (instr->Bit(4) == 1)) {
        // vmovl signed
4533
        if ((instr->VdValue() & 1) != 0) UNIMPLEMENTED();
4534 4535
        int Vd = instr->VFPDRegValue(kSimd128Precision);
        int Vm = instr->VFPMRegValue(kDoublePrecision);
4536
        int imm3 = instr->Bits(21, 19);
4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549
        switch (imm3) {
          case 1:
            Widen<int8_t, int16_t>(this, Vd, Vm);
            break;
          case 2:
            Widen<int16_t, int32_t>(this, Vd, Vm);
            break;
          case 4:
            Widen<int32_t, int64_t>(this, Vd, Vm);
            break;
          default:
            UNIMPLEMENTED();
            break;
4550
        }
4551 4552 4553 4554 4555 4556
      } else if (instr->Bits(21, 20) == 3 && instr->Bit(4) == 0) {
        // vext.
        int imm4 = instr->Bits(11, 8);
        int Vd = instr->VFPDRegValue(kSimd128Precision);
        int Vm = instr->VFPMRegValue(kSimd128Precision);
        int Vn = instr->VFPNRegValue(kSimd128Precision);
4557
        uint8_t src1[16], src2[16], dst[16];
4558 4559
        get_neon_register(Vn, src1);
        get_neon_register(Vm, src2);
4560
        int boundary = kSimd128Size - imm4;
4561 4562
        int i = 0;
        for (; i < boundary; i++) {
4563
          dst[i] = src1[i + imm4];
4564 4565
        }
        for (; i < 16; i++) {
4566
          dst[i] = src2[i - boundary];
4567
        }
4568
        set_neon_register(Vd, dst);
4569 4570 4571 4572 4573 4574 4575 4576
      } else if (instr->Bits(11, 7) == 0xA && instr->Bit(4) == 1) {
        // vshl.i<size> Qd, Qm, shift
        int size = base::bits::RoundDownToPowerOfTwo32(instr->Bits(21, 16));
        int shift = instr->Bits(21, 16) - size;
        int Vd = instr->VFPDRegValue(kSimd128Precision);
        int Vm = instr->VFPMRegValue(kSimd128Precision);
        NeonSize ns = static_cast<NeonSize>(size / 16);
        switch (ns) {
4577 4578
          case Neon8:
            ShiftLeft<uint8_t, kSimd128Size>(this, Vd, Vm, shift);
4579
            break;
4580 4581
          case Neon16:
            ShiftLeft<uint16_t, kSimd128Size>(this, Vd, Vm, shift);
4582
            break;
4583 4584
          case Neon32:
            ShiftLeft<uint32_t, kSimd128Size>(this, Vd, Vm, shift);
4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597
            break;
          default:
            UNREACHABLE();
            break;
        }
      } else if (instr->Bits(11, 7) == 0 && instr->Bit(4) == 1) {
        // vshr.s<size> Qd, Qm, shift
        int size = base::bits::RoundDownToPowerOfTwo32(instr->Bits(21, 16));
        int shift = 2 * size - instr->Bits(21, 16);
        int Vd = instr->VFPDRegValue(kSimd128Precision);
        int Vm = instr->VFPMRegValue(kSimd128Precision);
        NeonSize ns = static_cast<NeonSize>(size / 16);
        switch (ns) {
4598 4599
          case Neon8:
            ArithmeticShiftRight<int8_t, kSimd128Size>(this, Vd, Vm, shift);
4600
            break;
4601 4602
          case Neon16:
            ArithmeticShiftRight<int16_t, kSimd128Size>(this, Vd, Vm, shift);
4603
            break;
4604 4605
          case Neon32:
            ArithmeticShiftRight<int32_t, kSimd128Size>(this, Vd, Vm, shift);
4606 4607 4608 4609 4610
            break;
          default:
            UNREACHABLE();
            break;
        }
4611 4612 4613 4614
      } else {
        UNIMPLEMENTED();
      }
      break;
4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643
    case 6: {
      int Vd, Vm, Vn;
      if (instr->Bit(6) == 0) {
        Vd = instr->VFPDRegValue(kDoublePrecision);
        Vm = instr->VFPMRegValue(kDoublePrecision);
        Vn = instr->VFPNRegValue(kDoublePrecision);
      } else {
        Vd = instr->VFPDRegValue(kSimd128Precision);
        Vm = instr->VFPMRegValue(kSimd128Precision);
        Vn = instr->VFPNRegValue(kSimd128Precision);
      }
      switch (instr->Bits(11, 8)) {
        case 0x0: {
          if (instr->Bit(4) == 1) {
            // vqadd.u<size> Qd, Qm, Qn.
            NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
            switch (size) {
              case Neon8:
                AddSaturate<uint8_t>(this, Vd, Vm, Vn);
                break;
              case Neon16:
                AddSaturate<uint16_t>(this, Vd, Vm, Vn);
                break;
              case Neon32:
                AddSaturate<uint32_t>(this, Vd, Vm, Vn);
                break;
              default:
                UNREACHABLE();
                break;
4644
            }
4645 4646
          } else {
            UNIMPLEMENTED();
4647
          }
4648 4649 4650 4651 4652 4653
          break;
        }
        case 0x1: {
          if (instr->Bits(21, 20) == 1 && instr->Bit(4) == 1) {
            // vbsl.size Qd, Qm, Qn.
            uint32_t dst[4], src1[4], src2[4];
4654 4655 4656
            get_neon_register(Vd, dst);
            get_neon_register(Vn, src1);
            get_neon_register(Vm, src2);
4657
            for (int i = 0; i < 4; i++) {
4658
              dst[i] = (dst[i] & src1[i]) | (~dst[i] & src2[i]);
4659
            }
4660
            set_neon_register(Vd, dst);
4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672
          } else if (instr->Bits(21, 20) == 0 && instr->Bit(4) == 1) {
            if (instr->Bit(6) == 0) {
              // veor Dd, Dn, Dm
              uint64_t src1, src2;
              get_d_register(Vn, &src1);
              get_d_register(Vm, &src2);
              src1 ^= src2;
              set_d_register(Vd, &src1);

            } else {
              // veor Qd, Qn, Qm
              uint32_t src1[4], src2[4];
4673 4674
              get_neon_register(Vn, src1);
              get_neon_register(Vm, src2);
4675
              for (int i = 0; i < 4; i++) src1[i] ^= src2[i];
4676
              set_neon_register(Vd, src1);
4677 4678 4679
            }
          } else {
            UNIMPLEMENTED();
4680
          }
4681
          break;
4682
        }
4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699
        case 0x2: {
          if (instr->Bit(4) == 1) {
            // vqsub.u<size> Qd, Qm, Qn.
            NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
            switch (size) {
              case Neon8:
                SubSaturate<uint8_t>(this, Vd, Vm, Vn);
                break;
              case Neon16:
                SubSaturate<uint16_t>(this, Vd, Vm, Vn);
                break;
              case Neon32:
                SubSaturate<uint32_t>(this, Vd, Vm, Vn);
                break;
              default:
                UNREACHABLE();
                break;
4700
            }
4701 4702
          } else {
            UNIMPLEMENTED();
4703
          }
4704 4705 4706 4707 4708 4709 4710
          break;
        }
        case 0x3: {
          // vcge/vcgt.u<size> Qd, Qm, Qn.
          bool ge = instr->Bit(4) == 1;
          NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
          switch (size) {
4711 4712
            case Neon8:
              CompareGreater<uint8_t, kSimd128Size>(this, Vd, Vm, Vn, ge);
4713
              break;
4714 4715
            case Neon16:
              CompareGreater<uint16_t, kSimd128Size>(this, Vd, Vm, Vn, ge);
4716
              break;
4717 4718
            case Neon32:
              CompareGreater<uint32_t, kSimd128Size>(this, Vd, Vm, Vn, ge);
4719 4720 4721 4722
              break;
            default:
              UNREACHABLE();
              break;
4723
          }
4724
          break;
4725
        }
4726 4727 4728 4729 4730
        case 0x6: {
          // vmin/vmax.u<size> Qd, Qm, Qn.
          NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
          bool min = instr->Bit(4) != 0;
          switch (size) {
4731 4732
            case Neon8:
              MinMax<uint8_t, kSimd128Size>(this, Vd, Vm, Vn, min);
4733
              break;
4734 4735
            case Neon16:
              MinMax<uint16_t, kSimd128Size>(this, Vd, Vm, Vn, min);
4736
              break;
4737 4738
            case Neon32:
              MinMax<uint32_t, kSimd128Size>(this, Vd, Vm, Vn, min);
4739 4740 4741 4742
              break;
            default:
              UNREACHABLE();
              break;
4743
          }
4744
          break;
4745
        }
4746 4747 4748 4749 4750
        case 0x8: {
          if (instr->Bit(4) == 0) {
            // vsub.size Qd, Qm, Qn.
            NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
            switch (size) {
4751 4752
              case Neon8:
                Sub<uint8_t, kSimd128Size>(this, Vd, Vm, Vn);
4753
                break;
4754 4755
              case Neon16:
                Sub<uint16_t, kSimd128Size>(this, Vd, Vm, Vn);
4756
                break;
4757 4758
              case Neon32:
                Sub<uint32_t, kSimd128Size>(this, Vd, Vm, Vn);
4759 4760 4761 4762 4763 4764 4765 4766 4767
                break;
              default:
                UNREACHABLE();
                break;
            }
          } else {
            // vceq.size Qd, Qm, Qn.
            NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
            switch (size) {
4768 4769
              case Neon8:
                CompareEqual<uint8_t, kSimd128Size>(this, Vd, Vm, Vn);
4770
                break;
4771 4772
              case Neon16:
                CompareEqual<uint16_t, kSimd128Size>(this, Vd, Vm, Vn);
4773
                break;
4774 4775
              case Neon32:
                CompareEqual<uint32_t, kSimd128Size>(this, Vd, Vm, Vn);
4776 4777 4778 4779
                break;
              default:
                UNREACHABLE();
                break;
4780 4781
            }
          }
4782 4783
          break;
        }
4784
        case 0xA: {
4785 4786 4787 4788
          // vpmin/vpmax.u<size> Dd, Dm, Dn.
          NeonSize size = static_cast<NeonSize>(instr->Bits(21, 20));
          bool min = instr->Bit(4) != 0;
          switch (size) {
4789 4790
            case Neon8:
              PairwiseMinMax<uint8_t>(this, Vd, Vm, Vn, min);
4791
              break;
4792 4793
            case Neon16:
              PairwiseMinMax<uint16_t>(this, Vd, Vm, Vn, min);
4794
              break;
4795 4796
            case Neon32:
              PairwiseMinMax<uint32_t>(this, Vd, Vm, Vn, min);
4797 4798 4799 4800 4801 4802 4803
              break;
            default:
              UNREACHABLE();
              break;
          }
          break;
        }
4804
        case 0xD: {
4805 4806
          if (instr->Bits(21, 20) == 0 && instr->Bit(6) == 1 &&
              instr->Bit(4) == 1) {
4807 4808
            // vmul.f32 Qd, Qn, Qm
            float src1[4], src2[4];
4809 4810
            get_neon_register(Vn, src1);
            get_neon_register(Vm, src2);
4811 4812
            for (int i = 0; i < 4; i++) {
              src1[i] = src1[i] * src2[i];
4813
            }
4814
            set_neon_register(Vd, src1);
4815 4816 4817 4818
          } else if (instr->Bits(21, 20) == 0 && instr->Bit(6) == 0 &&
                     instr->Bit(4) == 0) {
            // vpadd.f32 Dd, Dn, Dm
            PairwiseAdd<float>(this, Vd, Vm, Vn);
4819 4820
          } else {
            UNIMPLEMENTED();
4821
          }
4822 4823
          break;
        }
4824
        case 0xE: {
4825 4826 4827 4828
          if (instr->Bit(20) == 0 && instr->Bit(4) == 0) {
            // vcge/vcgt.f32 Qd, Qm, Qn
            bool ge = instr->Bit(21) == 0;
            float src1[4], src2[4];
4829 4830
            get_neon_register(Vn, src1);
            get_neon_register(Vm, src2);
4831
            uint32_t dst[4];
4832
            for (int i = 0; i < 4; i++) {
4833 4834 4835 4836 4837
              if (ge) {
                dst[i] = src1[i] >= src2[i] ? 0xFFFFFFFFu : 0;
              } else {
                dst[i] = src1[i] > src2[i] ? 0xFFFFFFFFu : 0;
              }
4838
            }
4839
            set_neon_register(Vd, dst);
4840 4841
          } else {
            UNIMPLEMENTED();
4842
          }
4843
          break;
4844
        }
4845 4846 4847
        default:
          UNREACHABLE();
          break;
4848 4849
      }
      break;
4850
    }
4851 4852 4853 4854
    case 7:
      if ((instr->Bits(18, 16) == 0) && (instr->Bits(11, 6) == 0x28) &&
          (instr->Bit(4) == 1)) {
        // vmovl unsigned
4855
        if ((instr->VdValue() & 1) != 0) UNIMPLEMENTED();
4856 4857
        int Vd = instr->VFPDRegValue(kSimd128Precision);
        int Vm = instr->VFPMRegValue(kDoublePrecision);
4858
        int imm3 = instr->Bits(21, 19);
4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871
        switch (imm3) {
          case 1:
            Widen<uint8_t, uint16_t>(this, Vd, Vm);
            break;
          case 2:
            Widen<uint16_t, uint32_t>(this, Vd, Vm);
            break;
          case 4:
            Widen<uint32_t, uint64_t>(this, Vd, Vm);
            break;
          default:
            UNIMPLEMENTED();
            break;
4872
        }
4873 4874 4875 4876 4877 4878 4879
      } else if (instr->Opc1Value() == 7 && instr->Bit(4) == 0) {
        if (instr->Bits(19, 16) == 0xB && instr->Bits(11, 9) == 0x3 &&
            instr->Bit(6) == 1) {
          // vcvt.<Td>.<Tm> Qd, Qm.
          int Vd = instr->VFPDRegValue(kSimd128Precision);
          int Vm = instr->VFPMRegValue(kSimd128Precision);
          uint32_t q_data[4];
4880
          get_neon_register(Vm, q_data);
4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905
          int op = instr->Bits(8, 7);
          for (int i = 0; i < 4; i++) {
            switch (op) {
              case 0:
                // f32 <- s32, round towards nearest.
                q_data[i] = bit_cast<uint32_t>(std::round(
                    static_cast<float>(bit_cast<int32_t>(q_data[i]))));
                break;
              case 1:
                // f32 <- u32, round towards nearest.
                q_data[i] = bit_cast<uint32_t>(
                    std::round(static_cast<float>(q_data[i])));
                break;
              case 2:
                // s32 <- f32, round to zero.
                q_data[i] = static_cast<uint32_t>(
                    ConvertDoubleToInt(bit_cast<float>(q_data[i]), false, RZ));
                break;
              case 3:
                // u32 <- f32, round to zero.
                q_data[i] = static_cast<uint32_t>(
                    ConvertDoubleToInt(bit_cast<float>(q_data[i]), true, RZ));
                break;
            }
          }
4906
          set_neon_register(Vd, q_data);
4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921
        } else if (instr->Bits(17, 16) == 0x2 && instr->Bits(11, 7) == 0) {
          if (instr->Bit(6) == 0) {
            // vswp Dd, Dm.
            uint64_t dval, mval;
            int vd = instr->VFPDRegValue(kDoublePrecision);
            int vm = instr->VFPMRegValue(kDoublePrecision);
            get_d_register(vd, &dval);
            get_d_register(vm, &mval);
            set_d_register(vm, &dval);
            set_d_register(vd, &mval);
          } else {
            // vswp Qd, Qm.
            uint32_t dval[4], mval[4];
            int vd = instr->VFPDRegValue(kSimd128Precision);
            int vm = instr->VFPMRegValue(kSimd128Precision);
4922 4923 4924 4925
            get_neon_register(vd, dval);
            get_neon_register(vm, mval);
            set_neon_register(vm, dval);
            set_neon_register(vd, mval);
4926 4927
          }
        } else if (instr->Bits(11, 7) == 0x18) {
4928 4929
          // vdup.<size> Dd, Dm[index].
          // vdup.<size> Qd, Dm[index].
4930
          int vm = instr->VFPMRegValue(kDoublePrecision);
4931 4932 4933 4934 4935
          int imm4 = instr->Bits(19, 16);
          int size = 0, index = 0, mask = 0;
          if ((imm4 & 0x1) != 0) {
            size = 8;
            index = imm4 >> 1;
4936
            mask = 0xFFu;
4937 4938 4939
          } else if ((imm4 & 0x2) != 0) {
            size = 16;
            index = imm4 >> 2;
4940
            mask = 0xFFFFu;
4941 4942 4943
          } else {
            size = 32;
            index = imm4 >> 3;
4944
            mask = 0xFFFFFFFFu;
4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961
          }
          uint64_t d_data;
          get_d_register(vm, &d_data);
          uint32_t scalar = (d_data >> (size * index)) & mask;
          uint32_t duped = scalar;
          for (int i = 1; i < 32 / size; i++) {
            scalar <<= size;
            duped |= scalar;
          }
          uint32_t result[4] = {duped, duped, duped, duped};
          if (instr->Bit(6) == 0) {
            int vd = instr->VFPDRegValue(kDoublePrecision);
            set_d_register(vd, result);
          } else {
            int vd = instr->VFPDRegValue(kSimd128Precision);
            set_neon_register(vd, result);
          }
4962 4963 4964 4965 4966
        } else if (instr->Bits(19, 16) == 0 && instr->Bits(11, 6) == 0x17) {
          // vmvn Qd, Qm.
          int vd = instr->VFPDRegValue(kSimd128Precision);
          int vm = instr->VFPMRegValue(kSimd128Precision);
          uint32_t q_data[4];
4967
          get_neon_register(vm, q_data);
4968
          for (int i = 0; i < 4; i++) q_data[i] = ~q_data[i];
4969
          set_neon_register(vd, q_data);
4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993
        } else if (instr->Bits(11, 10) == 0x2) {
          // vtb[l,x] Dd, <list>, Dm.
          int vd = instr->VFPDRegValue(kDoublePrecision);
          int vn = instr->VFPNRegValue(kDoublePrecision);
          int vm = instr->VFPMRegValue(kDoublePrecision);
          int table_len = (instr->Bits(9, 8) + 1) * kDoubleSize;
          bool vtbx = instr->Bit(6) != 0;  // vtbl / vtbx
          uint64_t destination = 0, indices = 0, result = 0;
          get_d_register(vd, &destination);
          get_d_register(vm, &indices);
          for (int i = 0; i < kDoubleSize; i++) {
            int shift = i * kBitsPerByte;
            int index = (indices >> shift) & 0xFF;
            if (index < table_len) {
              uint64_t table;
              get_d_register(vn + index / kDoubleSize, &table);
              result |=
                  ((table >> ((index % kDoubleSize) * kBitsPerByte)) & 0xFF)
                  << shift;
            } else if (vtbx) {
              result |= destination & (0xFFull << shift);
            }
          }
          set_d_register(vd, &result);
4994
        } else if (instr->Bits(17, 16) == 0x2 && instr->Bits(11, 8) == 0x1) {
4995
          NeonSize size = static_cast<NeonSize>(instr->Bits(19, 18));
4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013
          if (instr->Bit(6) == 0) {
            int Vd = instr->VFPDRegValue(kDoublePrecision);
            int Vm = instr->VFPMRegValue(kDoublePrecision);
            if (instr->Bit(7) == 1) {
              // vzip.<size> Dd, Dm.
              switch (size) {
                case Neon8:
                  Zip<uint8_t, kDoubleSize>(this, Vd, Vm);
                  break;
                case Neon16:
                  Zip<uint16_t, kDoubleSize>(this, Vd, Vm);
                  break;
                case Neon32:
                  UNIMPLEMENTED();
                  break;
                default:
                  UNREACHABLE();
                  break;
5014
              }
5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029
            } else {
              // vuzp.<size> Dd, Dm.
              switch (size) {
                case Neon8:
                  Unzip<uint8_t, kDoubleSize>(this, Vd, Vm);
                  break;
                case Neon16:
                  Unzip<uint16_t, kDoubleSize>(this, Vd, Vm);
                  break;
                case Neon32:
                  UNIMPLEMENTED();
                  break;
                default:
                  UNREACHABLE();
                  break;
5030
              }
5031
            }
5032
          } else {
5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049
            int Vd = instr->VFPDRegValue(kSimd128Precision);
            int Vm = instr->VFPMRegValue(kSimd128Precision);
            if (instr->Bit(7) == 1) {
              // vzip.<size> Qd, Qm.
              switch (size) {
                case Neon8:
                  Zip<uint8_t, kSimd128Size>(this, Vd, Vm);
                  break;
                case Neon16:
                  Zip<uint16_t, kSimd128Size>(this, Vd, Vm);
                  break;
                case Neon32:
                  Zip<uint32_t, kSimd128Size>(this, Vd, Vm);
                  break;
                default:
                  UNREACHABLE();
                  break;
5050
              }
5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065
            } else {
              // vuzp.<size> Qd, Qm.
              switch (size) {
                case Neon8:
                  Unzip<uint8_t, kSimd128Size>(this, Vd, Vm);
                  break;
                case Neon16:
                  Unzip<uint16_t, kSimd128Size>(this, Vd, Vm);
                  break;
                case Neon32:
                  Unzip<uint32_t, kSimd128Size>(this, Vd, Vm);
                  break;
                default:
                  UNREACHABLE();
                  break;
5066
              }
5067 5068 5069 5070 5071 5072
            }
          }
        } else if (instr->Bits(17, 16) == 0 && instr->Bits(11, 9) == 0) {
          // vrev<op>.size Qd, Qm
          int Vd = instr->VFPDRegValue(kSimd128Precision);
          int Vm = instr->VFPMRegValue(kSimd128Precision);
5073
          NeonSize size = static_cast<NeonSize>(instr->Bits(19, 18));
5074 5075
          NeonSize op = static_cast<NeonSize>(static_cast<int>(Neon64) -
                                              instr->Bits(8, 7));
5076
          switch (op) {
5077 5078
            case Neon16: {
              DCHECK_EQ(Neon8, size);
5079
              uint8_t src[16];
5080
              get_neon_register(Vm, src);
5081
              for (int i = 0; i < 16; i += 2) {
5082
                std::swap(src[i], src[i + 1]);
5083
              }
5084
              set_neon_register(Vd, src);
5085
              break;
5086 5087 5088
            }
            case Neon32: {
              switch (size) {
5089 5090
                case Neon16: {
                  uint16_t src[8];
5091
                  get_neon_register(Vm, src);
5092 5093
                  for (int i = 0; i < 8; i += 2) {
                    std::swap(src[i], src[i + 1]);
5094
                  }
5095
                  set_neon_register(Vd, src);
5096
                  break;
5097
                }
5098
                case Neon8: {
5099
                  uint8_t src[16];
5100
                  get_neon_register(Vm, src);
5101
                  for (int i = 0; i < 4; i++) {
5102 5103
                    std::swap(src[i * 4], src[i * 4 + 3]);
                    std::swap(src[i * 4 + 1], src[i * 4 + 2]);
5104
                  }
5105
                  set_neon_register(Vd, src);
5106 5107 5108 5109 5110 5111
                  break;
                }
                default:
                  UNREACHABLE();
                  break;
              }
5112
              break;
5113 5114 5115 5116
            }
            case Neon64: {
              switch (size) {
                case Neon32: {
5117
                  uint32_t src[4];
5118
                  get_neon_register(Vm, src);
5119 5120
                  std::swap(src[0], src[1]);
                  std::swap(src[2], src[3]);
5121
                  set_neon_register(Vd, src);
5122 5123 5124
                  break;
                }
                case Neon16: {
5125
                  uint16_t src[8];
5126
                  get_neon_register(Vm, src);
5127
                  for (int i = 0; i < 2; i++) {
5128 5129
                    std::swap(src[i * 4], src[i * 4 + 3]);
                    std::swap(src[i * 4 + 1], src[i * 4 + 2]);
5130
                  }
5131
                  set_neon_register(Vd, src);
5132 5133 5134
                  break;
                }
                case Neon8: {
5135
                  uint8_t src[16];
5136
                  get_neon_register(Vm, src);
5137
                  for (int i = 0; i < 4; i++) {
5138 5139
                    std::swap(src[i], src[7 - i]);
                    std::swap(src[i + 8], src[15 - i]);
5140
                  }
5141
                  set_neon_register(Vd, src);
5142 5143 5144 5145 5146 5147
                  break;
                }
                default:
                  UNREACHABLE();
                  break;
              }
5148
              break;
5149 5150 5151
            }
            default:
              UNREACHABLE();
5152 5153
              break;
          }
5154
        } else if (instr->Bits(17, 16) == 0x2 && instr->Bits(11, 7) == 0x1) {
5155
          NeonSize size = static_cast<NeonSize>(instr->Bits(19, 18));
5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172
          if (instr->Bit(6) == 0) {
            int Vd = instr->VFPDRegValue(kDoublePrecision);
            int Vm = instr->VFPMRegValue(kDoublePrecision);
            // vtrn.<size> Dd, Dm.
            switch (size) {
              case Neon8:
                Transpose<uint8_t, kDoubleSize>(this, Vd, Vm);
                break;
              case Neon16:
                Transpose<uint16_t, kDoubleSize>(this, Vd, Vm);
                break;
              case Neon32:
                Transpose<uint32_t, kDoubleSize>(this, Vd, Vm);
                break;
              default:
                UNREACHABLE();
                break;
5173
            }
5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190
          } else {
            int Vd = instr->VFPDRegValue(kSimd128Precision);
            int Vm = instr->VFPMRegValue(kSimd128Precision);
            // vtrn.<size> Qd, Qm.
            switch (size) {
              case Neon8:
                Transpose<uint8_t, kSimd128Size>(this, Vd, Vm);
                break;
              case Neon16:
                Transpose<uint16_t, kSimd128Size>(this, Vd, Vm);
                break;
              case Neon32:
                Transpose<uint32_t, kSimd128Size>(this, Vd, Vm);
                break;
              default:
                UNREACHABLE();
                break;
5191
            }
5192
          }
5193 5194 5195
        } else if (instr->Bits(17, 16) == 0x1 && instr->Bit(11) == 0) {
          int Vd = instr->VFPDRegValue(kSimd128Precision);
          int Vm = instr->VFPMRegValue(kSimd128Precision);
5196
          NeonSize size = static_cast<NeonSize>(instr->Bits(19, 18));
5197
          if (instr->Bits(9, 6) == 0xD) {
5198 5199 5200
            // vabs<type>.<size> Qd, Qm
            if (instr->Bit(10) != 0) {
              // floating point (clear sign bits)
5201
              uint32_t src[4];
5202
              get_neon_register(Vm, src);
5203 5204 5205
              for (int i = 0; i < 4; i++) {
                src[i] &= ~0x80000000;
              }
5206
              set_neon_register(Vd, src);
5207 5208 5209
            } else {
              // signed integer
              switch (size) {
5210 5211
                case Neon8:
                  Abs<int8_t, kSimd128Size>(this, Vd, Vm);
5212
                  break;
5213 5214
                case Neon16:
                  Abs<int16_t, kSimd128Size>(this, Vd, Vm);
5215
                  break;
5216 5217
                case Neon32:
                  Abs<int32_t, kSimd128Size>(this, Vd, Vm);
5218 5219 5220 5221 5222 5223
                  break;
                default:
                  UNIMPLEMENTED();
                  break;
              }
            }
5224
          } else if (instr->Bits(9, 6) == 0xF) {
5225 5226 5227
            // vneg<type>.<size> Qd, Qm (signed integer)
            if (instr->Bit(10) != 0) {
              // floating point (toggle sign bits)
5228
              uint32_t src[4];
5229
              get_neon_register(Vm, src);
5230 5231 5232
              for (int i = 0; i < 4; i++) {
                src[i] ^= 0x80000000;
              }
5233
              set_neon_register(Vd, src);
5234 5235 5236
            } else {
              // signed integer
              switch (size) {
5237 5238
                case Neon8:
                  Neg<int8_t, kSimd128Size>(this, Vd, Vm);
5239 5240
                  break;
                case Neon16:
5241
                  Neg<int16_t, kSimd128Size>(this, Vd, Vm);
5242
                  break;
5243 5244
                case Neon32:
                  Neg<int32_t, kSimd128Size>(this, Vd, Vm);
5245 5246 5247 5248 5249 5250 5251 5252
                  break;
                default:
                  UNIMPLEMENTED();
                  break;
              }
            }
          } else {
            UNIMPLEMENTED();
5253
          }
5254 5255 5256 5257 5258
        } else if (instr->Bits(19, 18) == 0x2 && instr->Bits(11, 8) == 0x5) {
          // vrecpe/vrsqrte.f32 Qd, Qm.
          int Vd = instr->VFPDRegValue(kSimd128Precision);
          int Vm = instr->VFPMRegValue(kSimd128Precision);
          uint32_t src[4];
5259
          get_neon_register(Vm, src);
5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270
          if (instr->Bit(7) == 0) {
            for (int i = 0; i < 4; i++) {
              float denom = bit_cast<float>(src[i]);
              div_zero_vfp_flag_ = (denom == 0);
              float result = 1.0f / denom;
              result = canonicalizeNaN(result);
              src[i] = bit_cast<uint32_t>(result);
            }
          } else {
            for (int i = 0; i < 4; i++) {
              float radicand = bit_cast<float>(src[i]);
5271
              float result = 1.0f / std::sqrt(radicand);
5272 5273 5274 5275
              result = canonicalizeNaN(result);
              src[i] = bit_cast<uint32_t>(result);
            }
          }
5276
          set_neon_register(Vd, src);
5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312
        } else if (instr->Bits(17, 16) == 0x2 && instr->Bits(11, 8) == 0x2 &&
                   instr->Bits(7, 6) != 0) {
          // vqmovn.<type><size> Dd, Qm.
          int Vd = instr->VFPDRegValue(kDoublePrecision);
          int Vm = instr->VFPMRegValue(kSimd128Precision);
          NeonSize size = static_cast<NeonSize>(instr->Bits(19, 18));
          bool is_unsigned = instr->Bit(6) != 0;
          switch (size) {
            case Neon8: {
              if (is_unsigned) {
                SaturatingNarrow<uint16_t, uint8_t>(this, Vd, Vm);
              } else {
                SaturatingNarrow<int16_t, int8_t>(this, Vd, Vm);
              }
              break;
            }
            case Neon16: {
              if (is_unsigned) {
                SaturatingNarrow<uint32_t, uint16_t>(this, Vd, Vm);
              } else {
                SaturatingNarrow<int32_t, int16_t>(this, Vd, Vm);
              }
              break;
            }
            case Neon32: {
              if (is_unsigned) {
                SaturatingNarrow<uint64_t, uint32_t>(this, Vd, Vm);
              } else {
                SaturatingNarrow<int64_t, int32_t>(this, Vd, Vm);
              }
              break;
            }
            default:
              UNIMPLEMENTED();
              break;
          }
5313 5314
        } else {
          UNIMPLEMENTED();
5315
        }
5316 5317 5318 5319 5320 5321 5322 5323
      } else if (instr->Bits(11, 7) == 0 && instr->Bit(4) == 1) {
        // vshr.u<size> Qd, Qm, shift
        int size = base::bits::RoundDownToPowerOfTwo32(instr->Bits(21, 16));
        int shift = 2 * size - instr->Bits(21, 16);
        int Vd = instr->VFPDRegValue(kSimd128Precision);
        int Vm = instr->VFPMRegValue(kSimd128Precision);
        NeonSize ns = static_cast<NeonSize>(size / 16);
        switch (ns) {
5324 5325
          case Neon8:
            ShiftRight<uint8_t, kSimd128Size>(this, Vd, Vm, shift);
5326
            break;
5327 5328
          case Neon16:
            ShiftRight<uint16_t, kSimd128Size>(this, Vd, Vm, shift);
5329
            break;
5330 5331
          case Neon32:
            ShiftRight<uint32_t, kSimd128Size>(this, Vd, Vm, shift);
5332 5333 5334 5335 5336
            break;
          default:
            UNREACHABLE();
            break;
        }
5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388
      } else if (instr->Bits(11, 8) == 0x5 && instr->Bit(6) == 0 &&
                 instr->Bit(4) == 1) {
        // vsli.<size> Dd, Dm, shift
        int imm7 = instr->Bits(21, 16);
        if (instr->Bit(7) != 0) imm7 += 64;
        int size = base::bits::RoundDownToPowerOfTwo32(imm7);
        int shift = imm7 - size;
        int Vd = instr->VFPDRegValue(kDoublePrecision);
        int Vm = instr->VFPMRegValue(kDoublePrecision);
        switch (size) {
          case 8:
            ShiftLeftAndInsert<uint8_t, kDoubleSize>(this, Vd, Vm, shift);
            break;
          case 16:
            ShiftLeftAndInsert<uint16_t, kDoubleSize>(this, Vd, Vm, shift);
            break;
          case 32:
            ShiftLeftAndInsert<uint32_t, kDoubleSize>(this, Vd, Vm, shift);
            break;
          case 64:
            ShiftLeftAndInsert<uint64_t, kDoubleSize>(this, Vd, Vm, shift);
            break;
          default:
            UNREACHABLE();
            break;
        }
      } else if (instr->Bits(11, 8) == 0x4 && instr->Bit(6) == 0 &&
                 instr->Bit(4) == 1) {
        // vsri.<size> Dd, Dm, shift
        int imm7 = instr->Bits(21, 16);
        if (instr->Bit(7) != 0) imm7 += 64;
        int size = base::bits::RoundDownToPowerOfTwo32(imm7);
        int shift = 2 * size - imm7;
        int Vd = instr->VFPDRegValue(kDoublePrecision);
        int Vm = instr->VFPMRegValue(kDoublePrecision);
        switch (size) {
          case 8:
            ShiftRightAndInsert<uint8_t, kDoubleSize>(this, Vd, Vm, shift);
            break;
          case 16:
            ShiftRightAndInsert<uint16_t, kDoubleSize>(this, Vd, Vm, shift);
            break;
          case 32:
            ShiftRightAndInsert<uint32_t, kDoubleSize>(this, Vd, Vm, shift);
            break;
          case 64:
            ShiftRightAndInsert<uint64_t, kDoubleSize>(this, Vd, Vm, shift);
            break;
          default:
            UNREACHABLE();
            break;
        }
5389 5390
      } else {
        UNIMPLEMENTED();
5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422
      }
      break;
    case 8:
      if (instr->Bits(21, 20) == 0) {
        // vst1
        int Vd = (instr->Bit(22) << 4) | instr->VdValue();
        int Rn = instr->VnValue();
        int type = instr->Bits(11, 8);
        int Rm = instr->VmValue();
        int32_t address = get_register(Rn);
        int regs = 0;
        switch (type) {
          case nlt_1:
            regs = 1;
            break;
          case nlt_2:
            regs = 2;
            break;
          case nlt_3:
            regs = 3;
            break;
          case nlt_4:
            regs = 4;
            break;
          default:
            UNIMPLEMENTED();
            break;
        }
        int r = 0;
        while (r < regs) {
          uint32_t data[2];
          get_d_register(Vd + r, data);
5423 5424
          WriteW(address, data[0]);
          WriteW(address + 4, data[1]);
5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462
          address += 8;
          r++;
        }
        if (Rm != 15) {
          if (Rm == 13) {
            set_register(Rn, address);
          } else {
            set_register(Rn, get_register(Rn) + get_register(Rm));
          }
        }
      } else if (instr->Bits(21, 20) == 2) {
        // vld1
        int Vd = (instr->Bit(22) << 4) | instr->VdValue();
        int Rn = instr->VnValue();
        int type = instr->Bits(11, 8);
        int Rm = instr->VmValue();
        int32_t address = get_register(Rn);
        int regs = 0;
        switch (type) {
          case nlt_1:
            regs = 1;
            break;
          case nlt_2:
            regs = 2;
            break;
          case nlt_3:
            regs = 3;
            break;
          case nlt_4:
            regs = 4;
            break;
          default:
            UNIMPLEMENTED();
            break;
        }
        int r = 0;
        while (r < regs) {
          uint32_t data[2];
5463 5464
          data[0] = ReadW(address);
          data[1] = ReadW(address + 4);
5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481
          set_d_register(Vd + r, data);
          address += 8;
          r++;
        }
        if (Rm != 15) {
          if (Rm == 13) {
            set_register(Rn, address);
          } else {
            set_register(Rn, get_register(Rn) + get_register(Rm));
          }
        }
      } else {
        UNIMPLEMENTED();
      }
      break;
    case 0xA:
    case 0xB:
5482
      if ((instr->Bits(22, 20) == 5) && (instr->Bits(15, 12) == 0xF)) {
5483
        // pld: ignore instruction.
5484 5485 5486
      } else if (instr->SpecialValue() == 0xA && instr->Bits(22, 20) == 7) {
        // dsb, dmb, isb: ignore instruction for now.
        // TODO(binji): implement
5487
        // Also refer to the ARMv6 CP15 equivalents in DecodeTypeCP15.
5488 5489 5490 5491
      } else {
        UNIMPLEMENTED();
      }
      break;
5492 5493
    case 0x1D:
      if (instr->Opc1Value() == 0x7 && instr->Opc3Value() == 0x1 &&
5494 5495 5496 5497
          instr->Bits(11, 9) == 0x5 && instr->Bits(19, 18) == 0x2) {
        if (instr->SzValue() == 0x1) {
          int vm = instr->VFPMRegValue(kDoublePrecision);
          int vd = instr->VFPDRegValue(kDoublePrecision);
5498
          double dm_value = get_double_from_d_register(vm).get_scalar();
5499 5500 5501 5502 5503 5504 5505
          double dd_value = 0.0;
          int rounding_mode = instr->Bits(17, 16);
          switch (rounding_mode) {
            case 0x0:  // vrinta - round with ties to away from zero
              dd_value = round(dm_value);
              break;
            case 0x1: {  // vrintn - round with ties to even
5506
              dd_value = nearbyint(dm_value);
5507
              break;
5508
            }
5509
            case 0x2:  // vrintp - ceil
5510
              dd_value = ceil(dm_value);
5511 5512
              break;
            case 0x3:  // vrintm - floor
5513
              dd_value = floor(dm_value);
5514 5515 5516 5517
              break;
            default:
              UNREACHABLE();  // Case analysis is exhaustive.
              break;
5518
          }
5519 5520 5521 5522 5523
          dd_value = canonicalizeNaN(dd_value);
          set_d_register_from_double(vd, dd_value);
        } else {
          int m = instr->VFPMRegValue(kSinglePrecision);
          int d = instr->VFPDRegValue(kSinglePrecision);
5524
          float sm_value = get_float_from_s_register(m).get_scalar();
5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546
          float sd_value = 0.0;
          int rounding_mode = instr->Bits(17, 16);
          switch (rounding_mode) {
            case 0x0:  // vrinta - round with ties to away from zero
              sd_value = roundf(sm_value);
              break;
            case 0x1: {  // vrintn - round with ties to even
              sd_value = nearbyintf(sm_value);
              break;
            }
            case 0x2:  // vrintp - ceil
              sd_value = ceilf(sm_value);
              break;
            case 0x3:  // vrintm - floor
              sd_value = floorf(sm_value);
              break;
            default:
              UNREACHABLE();  // Case analysis is exhaustive.
              break;
          }
          sd_value = canonicalizeNaN(sd_value);
          set_s_register_from_float(d, sd_value);
5547
        }
5548 5549 5550 5551 5552 5553
      } else if ((instr->Opc1Value() == 0x4) && (instr->Bits(11, 9) == 0x5) &&
                 (instr->Bit(4) == 0x0)) {
        if (instr->SzValue() == 0x1) {
          int m = instr->VFPMRegValue(kDoublePrecision);
          int n = instr->VFPNRegValue(kDoublePrecision);
          int d = instr->VFPDRegValue(kDoublePrecision);
5554 5555
          double dn_value = get_double_from_d_register(n).get_scalar();
          double dm_value = get_double_from_d_register(m).get_scalar();
5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583
          double dd_value;
          if (instr->Bit(6) == 0x1) {  // vminnm
            if ((dn_value < dm_value) || std::isnan(dm_value)) {
              dd_value = dn_value;
            } else if ((dm_value < dn_value) || std::isnan(dn_value)) {
              dd_value = dm_value;
            } else {
              DCHECK_EQ(dn_value, dm_value);
              // Make sure that we pick the most negative sign for +/-0.
              dd_value = std::signbit(dn_value) ? dn_value : dm_value;
            }
          } else {  // vmaxnm
            if ((dn_value > dm_value) || std::isnan(dm_value)) {
              dd_value = dn_value;
            } else if ((dm_value > dn_value) || std::isnan(dn_value)) {
              dd_value = dm_value;
            } else {
              DCHECK_EQ(dn_value, dm_value);
              // Make sure that we pick the most positive sign for +/-0.
              dd_value = std::signbit(dn_value) ? dm_value : dn_value;
            }
          }
          dd_value = canonicalizeNaN(dd_value);
          set_d_register_from_double(d, dd_value);
        } else {
          int m = instr->VFPMRegValue(kSinglePrecision);
          int n = instr->VFPNRegValue(kSinglePrecision);
          int d = instr->VFPDRegValue(kSinglePrecision);
5584 5585
          float sn_value = get_float_from_s_register(n).get_scalar();
          float sm_value = get_float_from_s_register(m).get_scalar();
5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610
          float sd_value;
          if (instr->Bit(6) == 0x1) {  // vminnm
            if ((sn_value < sm_value) || std::isnan(sm_value)) {
              sd_value = sn_value;
            } else if ((sm_value < sn_value) || std::isnan(sn_value)) {
              sd_value = sm_value;
            } else {
              DCHECK_EQ(sn_value, sm_value);
              // Make sure that we pick the most negative sign for +/-0.
              sd_value = std::signbit(sn_value) ? sn_value : sm_value;
            }
          } else {  // vmaxnm
            if ((sn_value > sm_value) || std::isnan(sm_value)) {
              sd_value = sn_value;
            } else if ((sm_value > sn_value) || std::isnan(sn_value)) {
              sd_value = sm_value;
            } else {
              DCHECK_EQ(sn_value, sm_value);
              // Make sure that we pick the most positive sign for +/-0.
              sd_value = std::signbit(sn_value) ? sm_value : sn_value;
            }
          }
          sd_value = canonicalizeNaN(sd_value);
          set_s_register_from_float(d, sd_value);
        }
5611 5612 5613 5614
      } else {
        UNIMPLEMENTED();
      }
      break;
5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640
    case 0x1C:
      if ((instr->Bits(11, 9) == 0x5) && (instr->Bit(6) == 0) &&
          (instr->Bit(4) == 0)) {
        // VSEL* (floating-point)
        bool condition_holds;
        switch (instr->Bits(21, 20)) {
          case 0x0:  // VSELEQ
            condition_holds = (z_flag_ == 1);
            break;
          case 0x1:  // VSELVS
            condition_holds = (v_flag_ == 1);
            break;
          case 0x2:  // VSELGE
            condition_holds = (n_flag_ == v_flag_);
            break;
          case 0x3:  // VSELGT
            condition_holds = ((z_flag_ == 0) && (n_flag_ == v_flag_));
            break;
          default:
            UNREACHABLE();  // Case analysis is exhaustive.
            break;
        }
        if (instr->SzValue() == 0x1) {
          int n = instr->VFPNRegValue(kDoublePrecision);
          int m = instr->VFPMRegValue(kDoublePrecision);
          int d = instr->VFPDRegValue(kDoublePrecision);
5641
          Float64 result = get_double_from_d_register(condition_holds ? n : m);
5642 5643 5644 5645 5646
          set_d_register_from_double(d, result);
        } else {
          int n = instr->VFPNRegValue(kSinglePrecision);
          int m = instr->VFPMRegValue(kSinglePrecision);
          int d = instr->VFPDRegValue(kSinglePrecision);
5647
          Float32 result = get_float_from_s_register(condition_holds ? n : m);
5648 5649 5650 5651 5652 5653
          set_s_register_from_float(d, result);
        }
      } else {
        UNIMPLEMENTED();
      }
      break;
5654 5655 5656 5657 5658 5659 5660
    default:
      UNIMPLEMENTED();
      break;
  }
}


5661
// Executes the current instruction.
5662
void Simulator::InstructionDecode(Instruction* instr) {
5663
  if (v8::internal::FLAG_check_icache) {
5664
    CheckICache(i_cache(), instr);
5665
  }
5666
  pc_modified_ = false;
5667
  if (::v8::internal::FLAG_trace_sim) {
5668 5669
    disasm::NameConverter converter;
    disasm::Disassembler dasm(converter);
5670 5671
    // use a reasonably large buffer
    v8::internal::EmbeddedVector<char, 256> buffer;
5672 5673
    dasm.InstructionDecode(buffer,
                           reinterpret_cast<byte*>(instr));
5674 5675
    PrintF("  0x%08" V8PRIxPTR "  %s\n", reinterpret_cast<intptr_t>(instr),
           buffer.start());
5676
  }
5677
  if (instr->ConditionField() == kSpecialCondition) {
5678
    DecodeSpecialCondition(instr);
lrn@chromium.org's avatar
lrn@chromium.org committed
5679
  } else if (ConditionallyExecute(instr)) {
5680
    switch (instr->TypeValue()) {
5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716
      case 0:
      case 1: {
        DecodeType01(instr);
        break;
      }
      case 2: {
        DecodeType2(instr);
        break;
      }
      case 3: {
        DecodeType3(instr);
        break;
      }
      case 4: {
        DecodeType4(instr);
        break;
      }
      case 5: {
        DecodeType5(instr);
        break;
      }
      case 6: {
        DecodeType6(instr);
        break;
      }
      case 7: {
        DecodeType7(instr);
        break;
      }
      default: {
        UNIMPLEMENTED();
        break;
      }
    }
  }
  if (!pc_modified_) {
5717
    set_register(pc, reinterpret_cast<int32_t>(instr) + kInstrSize);
5718 5719 5720
  }
}

5721
void Simulator::Execute() {
5722 5723 5724
  // Get the PC to simulate. Cannot use the accessor here as we need the
  // raw PC value and not the one used as input to arithmetic instructions.
  int program_counter = get_pc();
5725

5726
  if (::v8::internal::FLAG_stop_sim_at == 0) {
5727 5728 5729
    // Fast version of the dispatch loop without checking whether the simulator
    // should be stopping at a particular executed instruction.
    while (program_counter != end_sim_pc) {
5730
      Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
5731
      icount_++;
5732
      InstructionDecode(instr);
5733 5734 5735 5736
      program_counter = get_pc();
    }
  } else {
    // FLAG_stop_sim_at is at the non-default value. Stop in the debugger when
5737
    // we reach the particular instruction count.
5738
    while (program_counter != end_sim_pc) {
5739
      Instruction* instr = reinterpret_cast<Instruction*>(program_counter);
5740
      icount_++;
5741
      if (icount_ == ::v8::internal::FLAG_stop_sim_at) {
5742
        ArmDebugger dbg(this);
5743 5744 5745 5746 5747
        dbg.Debug();
      } else {
        InstructionDecode(instr);
      }
      program_counter = get_pc();
5748 5749 5750 5751
    }
  }
}

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

5756
  // Prepare to execute the code at entry
5757
  set_register(pc, static_cast<int32_t>(entry));
5758 5759 5760 5761 5762
  // Put down marker for end of simulation. The simulator will stop simulation
  // when the PC reaches this value. By saving the "end simulation" value into
  // the LR the simulation stops when returning to this call point.
  set_register(lr, end_sim_pc);

5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774
  // Remember the values of callee-saved registers.
  // The code below assumes that r9 is not used as sb (static base) in
  // simulator code and therefore is regarded as a callee-saved register.
  int32_t r4_val = get_register(r4);
  int32_t r5_val = get_register(r5);
  int32_t r6_val = get_register(r6);
  int32_t r7_val = get_register(r7);
  int32_t r8_val = get_register(r8);
  int32_t r9_val = get_register(r9);
  int32_t r10_val = get_register(r10);
  int32_t r11_val = get_register(r11);

5775
  // Set up the callee-saved registers with a known value. To be able to check
5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786
  // that they are preserved properly across JS execution.
  int32_t callee_saved_value = icount_;
  set_register(r4, callee_saved_value);
  set_register(r5, callee_saved_value);
  set_register(r6, callee_saved_value);
  set_register(r7, callee_saved_value);
  set_register(r8, callee_saved_value);
  set_register(r9, callee_saved_value);
  set_register(r10, callee_saved_value);
  set_register(r11, callee_saved_value);

5787
  // Start the simulation
5788
  Execute();
5789

5790
  // Check that the callee-saved registers have been preserved.
lrn@chromium.org's avatar
lrn@chromium.org committed
5791 5792 5793 5794 5795 5796 5797 5798
  CHECK_EQ(callee_saved_value, get_register(r4));
  CHECK_EQ(callee_saved_value, get_register(r5));
  CHECK_EQ(callee_saved_value, get_register(r6));
  CHECK_EQ(callee_saved_value, get_register(r7));
  CHECK_EQ(callee_saved_value, get_register(r8));
  CHECK_EQ(callee_saved_value, get_register(r9));
  CHECK_EQ(callee_saved_value, get_register(r10));
  CHECK_EQ(callee_saved_value, get_register(r11));
5799 5800 5801 5802 5803 5804 5805 5806 5807 5808

  // Restore callee-saved registers with the original value.
  set_register(r4, r4_val);
  set_register(r5, r5_val);
  set_register(r6, r6_val);
  set_register(r7, r7_val);
  set_register(r8, r8_val);
  set_register(r9, r9_val);
  set_register(r10, r10_val);
  set_register(r11, r11_val);
5809 5810
}

5811
intptr_t Simulator::CallImpl(Address entry, int argument_count,
5812
                             const intptr_t* arguments) {
5813 5814 5815
  // Set up arguments

  // First four arguments passed in registers.
5816 5817 5818 5819 5820
  int reg_arg_count = std::min(4, argument_count);
  if (reg_arg_count > 0) set_register(r0, arguments[0]);
  if (reg_arg_count > 1) set_register(r1, arguments[1]);
  if (reg_arg_count > 2) set_register(r2, arguments[2]);
  if (reg_arg_count > 3) set_register(r3, arguments[3]);
5821 5822 5823 5824 5825

  // Remaining arguments passed on stack.
  int original_stack = get_register(sp);
  // Compute position of stack on entry to generated code.
  int entry_stack = (original_stack - (argument_count - 4) * sizeof(int32_t));
5826 5827
  if (base::OS::ActivationFrameAlignment() != 0) {
    entry_stack &= -base::OS::ActivationFrameAlignment();
5828 5829
  }
  // Store remaining arguments on stack, from low to high memory.
5830 5831
  memcpy(reinterpret_cast<intptr_t*>(entry_stack), arguments + reg_arg_count,
         (argument_count - reg_arg_count) * sizeof(*arguments));
5832 5833 5834
  set_register(sp, entry_stack);

  CallInternal(entry);
5835

lrn@chromium.org's avatar
lrn@chromium.org committed
5836 5837 5838 5839
  // Pop stack passed arguments.
  CHECK_EQ(entry_stack, get_register(sp));
  set_register(sp, original_stack);

5840
  return get_register(r0);
5841 5842
}

5843
intptr_t Simulator::CallFPImpl(Address entry, double d0, double d1) {
5844 5845 5846 5847
  if (use_eabi_hardfloat()) {
    set_d_register_from_double(0, d0);
    set_d_register_from_double(1, d1);
  } else {
5848 5849
    set_register_pair_from_double(0, &d0);
    set_register_pair_from_double(2, &d1);
5850 5851
  }
  CallInternal(entry);
5852
  return get_register(r0);
5853 5854 5855
}


5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872
uintptr_t Simulator::PushAddress(uintptr_t address) {
  int new_sp = get_register(sp) - sizeof(uintptr_t);
  uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp);
  *stack_slot = address;
  set_register(sp, new_sp);
  return new_sp;
}


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

5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054
Simulator::LocalMonitor::LocalMonitor()
    : access_state_(MonitorAccess::Open),
      tagged_addr_(0),
      size_(TransactionSize::None) {}

void Simulator::LocalMonitor::Clear() {
  access_state_ = MonitorAccess::Open;
  tagged_addr_ = 0;
  size_ = TransactionSize::None;
}

void Simulator::LocalMonitor::NotifyLoad(int32_t addr) {
  if (access_state_ == MonitorAccess::Exclusive) {
    // A load could cause a cache eviction which will affect the monitor. As a
    // result, it's most strict to unconditionally clear the local monitor on
    // load.
    Clear();
  }
}

void Simulator::LocalMonitor::NotifyLoadExcl(int32_t addr,
                                             TransactionSize size) {
  access_state_ = MonitorAccess::Exclusive;
  tagged_addr_ = addr;
  size_ = size;
}

void Simulator::LocalMonitor::NotifyStore(int32_t addr) {
  if (access_state_ == MonitorAccess::Exclusive) {
    // It is implementation-defined whether a non-exclusive store to an address
    // covered by the local monitor during exclusive access transitions to open
    // or exclusive access. See ARM DDI 0406C.b, A3.4.1.
    //
    // However, a store could cause a cache eviction which will affect the
    // monitor. As a result, it's most strict to unconditionally clear the
    // local monitor on store.
    Clear();
  }
}

bool Simulator::LocalMonitor::NotifyStoreExcl(int32_t addr,
                                              TransactionSize size) {
  if (access_state_ == MonitorAccess::Exclusive) {
    // It is allowed for a processor to require that the address matches
    // exactly (A3.4.5), so this comparison does not mask addr.
    if (addr == tagged_addr_ && size_ == size) {
      Clear();
      return true;
    } else {
      // It is implementation-defined whether an exclusive store to a
      // non-tagged address will update memory. Behavior is unpredictable if
      // the transaction size of the exclusive store differs from that of the
      // exclusive load. See ARM DDI 0406C.b, A3.4.5.
      Clear();
      return false;
    }
  } else {
    DCHECK(access_state_ == MonitorAccess::Open);
    return false;
  }
}

Simulator::GlobalMonitor::Processor::Processor()
    : access_state_(MonitorAccess::Open),
      tagged_addr_(0),
      next_(nullptr),
      prev_(nullptr),
      failure_counter_(0) {}

void Simulator::GlobalMonitor::Processor::Clear_Locked() {
  access_state_ = MonitorAccess::Open;
  tagged_addr_ = 0;
}

void Simulator::GlobalMonitor::Processor::NotifyLoadExcl_Locked(int32_t addr) {
  access_state_ = MonitorAccess::Exclusive;
  tagged_addr_ = addr;
}

void Simulator::GlobalMonitor::Processor::NotifyStore_Locked(
    int32_t addr, bool is_requesting_processor) {
  if (access_state_ == MonitorAccess::Exclusive) {
    // It is implementation-defined whether a non-exclusive store by the
    // requesting processor to an address covered by the global monitor
    // during exclusive access transitions to open or exclusive access.
    //
    // For any other processor, the access state always transitions to open
    // access.
    //
    // See ARM DDI 0406C.b, A3.4.2.
    //
    // However, similar to the local monitor, it is possible that a store
    // caused a cache eviction, which can affect the montior, so
    // conservatively, we always clear the monitor.
    Clear_Locked();
  }
}

bool Simulator::GlobalMonitor::Processor::NotifyStoreExcl_Locked(
    int32_t addr, bool is_requesting_processor) {
  if (access_state_ == MonitorAccess::Exclusive) {
    if (is_requesting_processor) {
      // It is allowed for a processor to require that the address matches
      // exactly (A3.4.5), so this comparison does not mask addr.
      if (addr == tagged_addr_) {
        // The access state for the requesting processor after a successful
        // exclusive store is implementation-defined, but according to the ARM
        // DDI, this has no effect on the subsequent operation of the global
        // monitor.
        Clear_Locked();
        // Introduce occasional strex failures. This is to simulate the
        // behavior of hardware, which can randomly fail due to background
        // cache evictions.
        if (failure_counter_++ >= kMaxFailureCounter) {
          failure_counter_ = 0;
          return false;
        } else {
          return true;
        }
      }
    } else if ((addr & kExclusiveTaggedAddrMask) ==
               (tagged_addr_ & kExclusiveTaggedAddrMask)) {
      // Check the masked addresses when responding to a successful lock by
      // another processor so the implementation is more conservative (i.e. the
      // granularity of locking is as large as possible.)
      Clear_Locked();
      return false;
    }
  }
  return false;
}

void Simulator::GlobalMonitor::NotifyLoadExcl_Locked(int32_t addr,
                                                     Processor* processor) {
  processor->NotifyLoadExcl_Locked(addr);
  PrependProcessor_Locked(processor);
}

void Simulator::GlobalMonitor::NotifyStore_Locked(int32_t addr,
                                                  Processor* processor) {
  // Notify each processor of the store operation.
  for (Processor* iter = head_; iter; iter = iter->next_) {
    bool is_requesting_processor = iter == processor;
    iter->NotifyStore_Locked(addr, is_requesting_processor);
  }
}

bool Simulator::GlobalMonitor::NotifyStoreExcl_Locked(int32_t addr,
                                                      Processor* processor) {
  DCHECK(IsProcessorInLinkedList_Locked(processor));
  if (processor->NotifyStoreExcl_Locked(addr, true)) {
    // Notify the other processors that this StoreExcl succeeded.
    for (Processor* iter = head_; iter; iter = iter->next_) {
      if (iter != processor) {
        iter->NotifyStoreExcl_Locked(addr, false);
      }
    }
    return true;
  } else {
    return false;
  }
}

bool Simulator::GlobalMonitor::IsProcessorInLinkedList_Locked(
    Processor* processor) const {
  return head_ == processor || processor->next_ || processor->prev_;
}

void Simulator::GlobalMonitor::PrependProcessor_Locked(Processor* processor) {
  if (IsProcessorInLinkedList_Locked(processor)) {
    return;
  }

  if (head_) {
    head_->prev_ = processor;
  }
  processor->prev_ = nullptr;
  processor->next_ = head_;
  head_ = processor;
}

void Simulator::GlobalMonitor::RemoveProcessor(Processor* processor) {
6055
  base::MutexGuard lock_guard(&mutex);
6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071
  if (!IsProcessorInLinkedList_Locked(processor)) {
    return;
  }

  if (processor->prev_) {
    processor->prev_->next_ = processor->next_;
  } else {
    head_ = processor->next_;
  }
  if (processor->next_) {
    processor->next_->prev_ = processor->prev_;
  }
  processor->prev_ = nullptr;
  processor->next_ = nullptr;
}

6072 6073
}  // namespace internal
}  // namespace v8
6074

6075
#endif  // USE_SIMULATOR