Source code

Revision control

Copy as Markdown

Other Tools

// Copyright 2015, VIXL authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of ARM Limited nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "jstypes.h"
#ifdef JS_SIMULATOR_ARM64
#include "jit/arm64/vixl/Simulator-vixl.h"
#include <cmath>
#include <string.h>
#include "jit/AtomicOperations.h"
namespace vixl {
const Instruction* Simulator::kEndOfSimAddress = NULL;
void SimSystemRegister::SetBits(int msb, int lsb, uint32_t bits) {
int width = msb - lsb + 1;
VIXL_ASSERT(IsUintN(width, bits) || IsIntN(width, bits));
bits <<= lsb;
uint32_t mask = ((1 << width) - 1) << lsb;
VIXL_ASSERT((mask & write_ignore_mask_) == 0);
value_ = (value_ & ~mask) | (bits & mask);
}
SimSystemRegister SimSystemRegister::DefaultValueFor(SystemRegister id) {
switch (id) {
case NZCV:
return SimSystemRegister(0x00000000, NZCVWriteIgnoreMask);
case FPCR:
return SimSystemRegister(0x00000000, FPCRWriteIgnoreMask);
default:
VIXL_UNREACHABLE();
return SimSystemRegister();
}
}
void Simulator::Run() {
pc_modified_ = false;
while (pc_ != kEndOfSimAddress) {
ExecuteInstruction();
LogAllWrittenRegisters();
}
}
void Simulator::RunFrom(const Instruction* first) {
set_pc(first);
Run();
}
const char* Simulator::xreg_names[] = {
"x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7",
"x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15",
"x16", "x17", "x18", "x19", "x20", "x21", "x22", "x23",
"x24", "x25", "x26", "x27", "x28", "x29", "lr", "xzr", "sp"};
const char* Simulator::wreg_names[] = {
"w0", "w1", "w2", "w3", "w4", "w5", "w6", "w7",
"w8", "w9", "w10", "w11", "w12", "w13", "w14", "w15",
"w16", "w17", "w18", "w19", "w20", "w21", "w22", "w23",
"w24", "w25", "w26", "w27", "w28", "w29", "w30", "wzr", "wsp"};
const char* Simulator::sreg_names[] = {
"s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
"s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15",
"s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23",
"s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31"};
const char* Simulator::dreg_names[] = {
"d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
"d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15",
"d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23",
"d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31"};
const char* Simulator::vreg_names[] = {
"v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7",
"v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
"v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23",
"v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"};
const char* Simulator::WRegNameForCode(unsigned code, Reg31Mode mode) {
VIXL_ASSERT(code < kNumberOfRegisters);
// If the code represents the stack pointer, index the name after zr.
if ((code == kZeroRegCode) && (mode == Reg31IsStackPointer)) {
code = kZeroRegCode + 1;
}
return wreg_names[code];
}
const char* Simulator::XRegNameForCode(unsigned code, Reg31Mode mode) {
VIXL_ASSERT(code < kNumberOfRegisters);
// If the code represents the stack pointer, index the name after zr.
if ((code == kZeroRegCode) && (mode == Reg31IsStackPointer)) {
code = kZeroRegCode + 1;
}
return xreg_names[code];
}
const char* Simulator::SRegNameForCode(unsigned code) {
VIXL_ASSERT(code < kNumberOfFPRegisters);
return sreg_names[code];
}
const char* Simulator::DRegNameForCode(unsigned code) {
VIXL_ASSERT(code < kNumberOfFPRegisters);
return dreg_names[code];
}
const char* Simulator::VRegNameForCode(unsigned code) {
VIXL_ASSERT(code < kNumberOfVRegisters);
return vreg_names[code];
}
#define COLOUR(colour_code) "\033[0;" colour_code "m"
#define COLOUR_BOLD(colour_code) "\033[1;" colour_code "m"
#define NORMAL ""
#define GREY "30"
#define RED "31"
#define GREEN "32"
#define YELLOW "33"
#define BLUE "34"
#define MAGENTA "35"
#define CYAN "36"
#define WHITE "37"
void Simulator::set_coloured_trace(bool value) {
coloured_trace_ = value;
clr_normal = value ? COLOUR(NORMAL) : "";
clr_flag_name = value ? COLOUR_BOLD(WHITE) : "";
clr_flag_value = value ? COLOUR(NORMAL) : "";
clr_reg_name = value ? COLOUR_BOLD(CYAN) : "";
clr_reg_value = value ? COLOUR(CYAN) : "";
clr_vreg_name = value ? COLOUR_BOLD(MAGENTA) : "";
clr_vreg_value = value ? COLOUR(MAGENTA) : "";
clr_memory_address = value ? COLOUR_BOLD(BLUE) : "";
clr_warning = value ? COLOUR_BOLD(YELLOW) : "";
clr_warning_message = value ? COLOUR(YELLOW) : "";
clr_printf = value ? COLOUR(GREEN) : "";
}
#undef COLOUR
#undef COLOUR_BOLD
#undef NORMAL
#undef GREY
#undef RED
#undef GREEN
#undef YELLOW
#undef BLUE
#undef MAGENTA
#undef CYAN
#undef WHITE
void Simulator::set_trace_parameters(int parameters) {
bool disasm_before = trace_parameters_ & LOG_DISASM;
trace_parameters_ = parameters;
bool disasm_after = trace_parameters_ & LOG_DISASM;
if (disasm_before != disasm_after) {
if (disasm_after) {
decoder_->InsertVisitorBefore(print_disasm_, this);
} else {
decoder_->RemoveVisitor(print_disasm_);
}
}
}
void Simulator::set_instruction_stats(bool value) {
if (instrumentation_ == nullptr) {
return;
}
if (value != instruction_stats_) {
if (value) {
decoder_->AppendVisitor(instrumentation_);
} else {
decoder_->RemoveVisitor(instrumentation_);
}
instruction_stats_ = value;
}
}
// Helpers ---------------------------------------------------------------------
uint64_t Simulator::AddWithCarry(unsigned reg_size,
bool set_flags,
uint64_t left,
uint64_t right,
int carry_in) {
VIXL_ASSERT((carry_in == 0) || (carry_in == 1));
VIXL_ASSERT((reg_size == kXRegSize) || (reg_size == kWRegSize));
uint64_t max_uint = (reg_size == kWRegSize) ? kWMaxUInt : kXMaxUInt;
uint64_t reg_mask = (reg_size == kWRegSize) ? kWRegMask : kXRegMask;
uint64_t sign_mask = (reg_size == kWRegSize) ? kWSignMask : kXSignMask;
left &= reg_mask;
right &= reg_mask;
uint64_t result = (left + right + carry_in) & reg_mask;
if (set_flags) {
nzcv().SetN(CalcNFlag(result, reg_size));
nzcv().SetZ(CalcZFlag(result));
// Compute the C flag by comparing the result to the max unsigned integer.
uint64_t max_uint_2op = max_uint - carry_in;
bool C = (left > max_uint_2op) || ((max_uint_2op - left) < right);
nzcv().SetC(C ? 1 : 0);
// Overflow iff the sign bit is the same for the two inputs and different
// for the result.
uint64_t left_sign = left & sign_mask;
uint64_t right_sign = right & sign_mask;
uint64_t result_sign = result & sign_mask;
bool V = (left_sign == right_sign) && (left_sign != result_sign);
nzcv().SetV(V ? 1 : 0);
LogSystemRegister(NZCV);
}
return result;
}
int64_t Simulator::ShiftOperand(unsigned reg_size,
int64_t value,
Shift shift_type,
unsigned amount) {
if (amount == 0) {
return value;
}
int64_t mask = reg_size == kXRegSize ? kXRegMask : kWRegMask;
switch (shift_type) {
case LSL:
return (value << amount) & mask;
case LSR:
return static_cast<uint64_t>(value) >> amount;
case ASR: {
// Shift used to restore the sign.
unsigned s_shift = kXRegSize - reg_size;
// Value with its sign restored.
int64_t s_value = (value << s_shift) >> s_shift;
return (s_value >> amount) & mask;
}
case ROR: {
if (reg_size == kWRegSize) {
value &= kWRegMask;
}
return (static_cast<uint64_t>(value) >> amount) |
((value & ((INT64_C(1) << amount) - 1)) <<
(reg_size - amount));
}
default:
VIXL_UNIMPLEMENTED();
return 0;
}
}
int64_t Simulator::ExtendValue(unsigned reg_size,
int64_t value,
Extend extend_type,
unsigned left_shift) {
switch (extend_type) {
case UXTB:
value &= kByteMask;
break;
case UXTH:
value &= kHalfWordMask;
break;
case UXTW:
value &= kWordMask;
break;
case SXTB:
value = (value << 56) >> 56;
break;
case SXTH:
value = (value << 48) >> 48;
break;
case SXTW:
value = (value << 32) >> 32;
break;
case UXTX:
case SXTX:
break;
default:
VIXL_UNREACHABLE();
}
int64_t mask = (reg_size == kXRegSize) ? kXRegMask : kWRegMask;
return (value << left_shift) & mask;
}
void Simulator::FPCompare(double val0, double val1, FPTrapFlags trap) {
AssertSupportedFPCR();
// TODO: This assumes that the C++ implementation handles comparisons in the
// way that we expect (as per AssertSupportedFPCR()).
bool process_exception = false;
if ((std::isnan(val0) != 0) || (std::isnan(val1) != 0)) {
nzcv().SetRawValue(FPUnorderedFlag);
if (IsSignallingNaN(val0) || IsSignallingNaN(val1) ||
(trap == EnableTrap)) {
process_exception = true;
}
} else if (val0 < val1) {
nzcv().SetRawValue(FPLessThanFlag);
} else if (val0 > val1) {
nzcv().SetRawValue(FPGreaterThanFlag);
} else if (val0 == val1) {
nzcv().SetRawValue(FPEqualFlag);
} else {
VIXL_UNREACHABLE();
}
LogSystemRegister(NZCV);
if (process_exception) FPProcessException();
}
Simulator::PrintRegisterFormat Simulator::GetPrintRegisterFormatForSize(
unsigned reg_size, unsigned lane_size) {
VIXL_ASSERT(reg_size >= lane_size);
uint32_t format = 0;
if (reg_size != lane_size) {
switch (reg_size) {
default: VIXL_UNREACHABLE(); break;
case kQRegSizeInBytes: format = kPrintRegAsQVector; break;
case kDRegSizeInBytes: format = kPrintRegAsDVector; break;
}
}
switch (lane_size) {
default: VIXL_UNREACHABLE(); break;
case kQRegSizeInBytes: format |= kPrintReg1Q; break;
case kDRegSizeInBytes: format |= kPrintReg1D; break;
case kSRegSizeInBytes: format |= kPrintReg1S; break;
case kHRegSizeInBytes: format |= kPrintReg1H; break;
case kBRegSizeInBytes: format |= kPrintReg1B; break;
}
// These sizes would be duplicate case labels.
VIXL_STATIC_ASSERT(kXRegSizeInBytes == kDRegSizeInBytes);
VIXL_STATIC_ASSERT(kWRegSizeInBytes == kSRegSizeInBytes);
VIXL_STATIC_ASSERT(kPrintXReg == kPrintReg1D);
VIXL_STATIC_ASSERT(kPrintWReg == kPrintReg1S);
return static_cast<PrintRegisterFormat>(format);
}
Simulator::PrintRegisterFormat Simulator::GetPrintRegisterFormat(
VectorFormat vform) {
switch (vform) {
default: VIXL_UNREACHABLE(); return kPrintReg16B;
case kFormat16B: return kPrintReg16B;
case kFormat8B: return kPrintReg8B;
case kFormat8H: return kPrintReg8H;
case kFormat4H: return kPrintReg4H;
case kFormat4S: return kPrintReg4S;
case kFormat2S: return kPrintReg2S;
case kFormat2D: return kPrintReg2D;
case kFormat1D: return kPrintReg1D;
}
}
void Simulator::PrintWrittenRegisters() {
for (unsigned i = 0; i < kNumberOfRegisters; i++) {
if (registers_[i].WrittenSinceLastLog()) PrintRegister(i);
}
}
void Simulator::PrintWrittenVRegisters() {
for (unsigned i = 0; i < kNumberOfVRegisters; i++) {
// At this point there is no type information, so print as a raw 1Q.
if (vregisters_[i].WrittenSinceLastLog()) PrintVRegister(i, kPrintReg1Q);
}
}
void Simulator::PrintSystemRegisters() {
PrintSystemRegister(NZCV);
PrintSystemRegister(FPCR);
}
void Simulator::PrintRegisters() {
for (unsigned i = 0; i < kNumberOfRegisters; i++) {
PrintRegister(i);
}
}
void Simulator::PrintVRegisters() {
for (unsigned i = 0; i < kNumberOfVRegisters; i++) {
// At this point there is no type information, so print as a raw 1Q.
PrintVRegister(i, kPrintReg1Q);
}
}
// Print a register's name and raw value.
//
// Only the least-significant `size_in_bytes` bytes of the register are printed,
// but the value is aligned as if the whole register had been printed.
//
// For typical register updates, size_in_bytes should be set to kXRegSizeInBytes
// -- the default -- so that the whole register is printed. Other values of
// size_in_bytes are intended for use when the register hasn't actually been
// updated (such as in PrintWrite).
//
// No newline is printed. This allows the caller to print more details (such as
// a memory access annotation).
void Simulator::PrintRegisterRawHelper(unsigned code, Reg31Mode r31mode,
int size_in_bytes) {
// The template for all supported sizes.
// "# x{code}: 0xffeeddccbbaa9988"
// "# w{code}: 0xbbaa9988"
// "# w{code}<15:0>: 0x9988"
// "# w{code}<7:0>: 0x88"
unsigned padding_chars = (kXRegSizeInBytes - size_in_bytes) * 2;
const char * name = "";
const char * suffix = "";
switch (size_in_bytes) {
case kXRegSizeInBytes: name = XRegNameForCode(code, r31mode); break;
case kWRegSizeInBytes: name = WRegNameForCode(code, r31mode); break;
case 2:
name = WRegNameForCode(code, r31mode);
suffix = "<15:0>";
padding_chars -= strlen(suffix);
break;
case 1:
name = WRegNameForCode(code, r31mode);
suffix = "<7:0>";
padding_chars -= strlen(suffix);
break;
default:
VIXL_UNREACHABLE();
}
fprintf(stream_, "# %s%5s%s: ", clr_reg_name, name, suffix);
// Print leading padding spaces.
VIXL_ASSERT(padding_chars < (kXRegSizeInBytes * 2));
for (unsigned i = 0; i < padding_chars; i++) {
putc(' ', stream_);
}
// Print the specified bits in hexadecimal format.
uint64_t bits = reg<uint64_t>(code, r31mode);
bits &= kXRegMask >> ((kXRegSizeInBytes - size_in_bytes) * 8);
VIXL_STATIC_ASSERT(sizeof(bits) == kXRegSizeInBytes);
int chars = size_in_bytes * 2;
fprintf(stream_, "%s0x%0*" PRIx64 "%s",
clr_reg_value, chars, bits, clr_normal);
}
void Simulator::PrintRegister(unsigned code, Reg31Mode r31mode) {
registers_[code].NotifyRegisterLogged();
// Don't print writes into xzr.
if ((code == kZeroRegCode) && (r31mode == Reg31IsZeroRegister)) {
return;
}
// The template for all x and w registers:
// "# x{code}: 0x{value}"
// "# w{code}: 0x{value}"
PrintRegisterRawHelper(code, r31mode);
fprintf(stream_, "\n");
}
// Print a register's name and raw value.
//
// The `bytes` and `lsb` arguments can be used to limit the bytes that are
// printed. These arguments are intended for use in cases where register hasn't
// actually been updated (such as in PrintVWrite).
//
// No newline is printed. This allows the caller to print more details (such as
// a floating-point interpretation or a memory access annotation).
void Simulator::PrintVRegisterRawHelper(unsigned code, int bytes, int lsb) {
// The template for vector types:
// "# v{code}: 0xffeeddccbbaa99887766554433221100".
// An example with bytes=4 and lsb=8:
// "# v{code}: 0xbbaa9988 ".
fprintf(stream_, "# %s%5s: %s",
clr_vreg_name, VRegNameForCode(code), clr_vreg_value);
int msb = lsb + bytes - 1;
int byte = kQRegSizeInBytes - 1;
// Print leading padding spaces. (Two spaces per byte.)
while (byte > msb) {
fprintf(stream_, " ");
byte--;
}
// Print the specified part of the value, byte by byte.
qreg_t rawbits = qreg(code);
fprintf(stream_, "0x");
while (byte >= lsb) {
fprintf(stream_, "%02x", rawbits.val[byte]);
byte--;
}
// Print trailing padding spaces.
while (byte >= 0) {
fprintf(stream_, " ");
byte--;
}
fprintf(stream_, "%s", clr_normal);
}
// Print each of the specified lanes of a register as a float or double value.
//
// The `lane_count` and `lslane` arguments can be used to limit the lanes that
// are printed. These arguments are intended for use in cases where register
// hasn't actually been updated (such as in PrintVWrite).
//
// No newline is printed. This allows the caller to print more details (such as
// a memory access annotation).
void Simulator::PrintVRegisterFPHelper(unsigned code,
unsigned lane_size_in_bytes,
int lane_count,
int rightmost_lane) {
VIXL_ASSERT((lane_size_in_bytes == kSRegSizeInBytes) ||
(lane_size_in_bytes == kDRegSizeInBytes));
unsigned msb = ((lane_count + rightmost_lane) * lane_size_in_bytes);
VIXL_ASSERT(msb <= kQRegSizeInBytes);
// For scalar types ((lane_count == 1) && (rightmost_lane == 0)), a register
// name is used:
// " (s{code}: {value})"
// " (d{code}: {value})"
// For vector types, "..." is used to represent one or more omitted lanes.
// " (..., {value}, {value}, ...)"
if ((lane_count == 1) && (rightmost_lane == 0)) {
const char * name =
(lane_size_in_bytes == kSRegSizeInBytes) ? SRegNameForCode(code)
: DRegNameForCode(code);
fprintf(stream_, " (%s%s: ", clr_vreg_name, name);
} else {
if (msb < (kQRegSizeInBytes - 1)) {
fprintf(stream_, " (..., ");
} else {
fprintf(stream_, " (");
}
}
// Print the list of values.
const char * separator = "";
int leftmost_lane = rightmost_lane + lane_count - 1;
for (int lane = leftmost_lane; lane >= rightmost_lane; lane--) {
double value =
(lane_size_in_bytes == kSRegSizeInBytes) ? vreg(code).Get<float>(lane)
: vreg(code).Get<double>(lane);
fprintf(stream_, "%s%s%#g%s", separator, clr_vreg_value, value, clr_normal);
separator = ", ";
}
if (rightmost_lane > 0) {
fprintf(stream_, ", ...");
}
fprintf(stream_, ")");
}
void Simulator::PrintVRegister(unsigned code, PrintRegisterFormat format) {
vregisters_[code].NotifyRegisterLogged();
int lane_size_log2 = format & kPrintRegLaneSizeMask;
int reg_size_log2;
if (format & kPrintRegAsQVector) {
reg_size_log2 = kQRegSizeInBytesLog2;
} else if (format & kPrintRegAsDVector) {
reg_size_log2 = kDRegSizeInBytesLog2;
} else {
// Scalar types.
reg_size_log2 = lane_size_log2;
}
int lane_count = 1 << (reg_size_log2 - lane_size_log2);
int lane_size = 1 << lane_size_log2;
// The template for vector types:
// "# v{code}: 0x{rawbits} (..., {value}, ...)".
// The template for scalar types:
// "# v{code}: 0x{rawbits} ({reg}:{value})".
// The values in parentheses after the bit representations are floating-point
// interpretations. They are displayed only if the kPrintVRegAsFP bit is set.
PrintVRegisterRawHelper(code);
if (format & kPrintRegAsFP) {
PrintVRegisterFPHelper(code, lane_size, lane_count);
}
fprintf(stream_, "\n");
}
void Simulator::PrintSystemRegister(SystemRegister id) {
switch (id) {
case NZCV:
fprintf(stream_, "# %sNZCV: %sN:%d Z:%d C:%d V:%d%s\n",
clr_flag_name, clr_flag_value,
nzcv().N(), nzcv().Z(), nzcv().C(), nzcv().V(),
clr_normal);
break;
case FPCR: {
static const char * rmode[] = {
"0b00 (Round to Nearest)",
"0b01 (Round towards Plus Infinity)",
"0b10 (Round towards Minus Infinity)",
"0b11 (Round towards Zero)"
};
VIXL_ASSERT(fpcr().RMode() < (sizeof(rmode) / sizeof(rmode[0])));
fprintf(stream_,
"# %sFPCR: %sAHP:%d DN:%d FZ:%d RMode:%s%s\n",
clr_flag_name, clr_flag_value,
fpcr().AHP(), fpcr().DN(), fpcr().FZ(), rmode[fpcr().RMode()],
clr_normal);
break;
}
default:
VIXL_UNREACHABLE();
}
}
void Simulator::PrintRead(uintptr_t address,
unsigned reg_code,
PrintRegisterFormat format) {
registers_[reg_code].NotifyRegisterLogged();
USE(format);
// The template is "# {reg}: 0x{value} <- {address}".
PrintRegisterRawHelper(reg_code, Reg31IsZeroRegister);
fprintf(stream_, " <- %s0x%016" PRIxPTR "%s\n",
clr_memory_address, address, clr_normal);
}
void Simulator::PrintVRead(uintptr_t address,
unsigned reg_code,
PrintRegisterFormat format,
unsigned lane) {
vregisters_[reg_code].NotifyRegisterLogged();
// The template is "# v{code}: 0x{rawbits} <- address".
PrintVRegisterRawHelper(reg_code);
if (format & kPrintRegAsFP) {
PrintVRegisterFPHelper(reg_code, GetPrintRegLaneSizeInBytes(format),
GetPrintRegLaneCount(format), lane);
}
fprintf(stream_, " <- %s0x%016" PRIxPTR "%s\n",
clr_memory_address, address, clr_normal);
}
void Simulator::PrintWrite(uintptr_t address,
unsigned reg_code,
PrintRegisterFormat format) {
VIXL_ASSERT(GetPrintRegLaneCount(format) == 1);
// The template is "# v{code}: 0x{value} -> {address}". To keep the trace tidy
// and readable, the value is aligned with the values in the register trace.
PrintRegisterRawHelper(reg_code, Reg31IsZeroRegister,
GetPrintRegSizeInBytes(format));
fprintf(stream_, " -> %s0x%016" PRIxPTR "%s\n",
clr_memory_address, address, clr_normal);
}
void Simulator::PrintVWrite(uintptr_t address,
unsigned reg_code,
PrintRegisterFormat format,
unsigned lane) {
// The templates:
// "# v{code}: 0x{rawbits} -> {address}"
// "# v{code}: 0x{rawbits} (..., {value}, ...) -> {address}".
// "# v{code}: 0x{rawbits} ({reg}:{value}) -> {address}"
// Because this trace doesn't represent a change to the source register's
// value, only the relevant part of the value is printed. To keep the trace
// tidy and readable, the raw value is aligned with the other values in the
// register trace.
int lane_count = GetPrintRegLaneCount(format);
int lane_size = GetPrintRegLaneSizeInBytes(format);
int reg_size = GetPrintRegSizeInBytes(format);
PrintVRegisterRawHelper(reg_code, reg_size, lane_size * lane);
if (format & kPrintRegAsFP) {
PrintVRegisterFPHelper(reg_code, lane_size, lane_count, lane);
}
fprintf(stream_, " -> %s0x%016" PRIxPTR "%s\n",
clr_memory_address, address, clr_normal);
}
// Visitors---------------------------------------------------------------------
void Simulator::VisitUnimplemented(const Instruction* instr) {
printf("Unimplemented instruction at %p: 0x%08" PRIx32 "\n",
reinterpret_cast<const void*>(instr), instr->InstructionBits());
VIXL_UNIMPLEMENTED();
}
void Simulator::VisitUnallocated(const Instruction* instr) {
printf("Unallocated instruction at %p: 0x%08" PRIx32 "\n",
reinterpret_cast<const void*>(instr), instr->InstructionBits());
VIXL_UNIMPLEMENTED();
}
void Simulator::VisitPCRelAddressing(const Instruction* instr) {
VIXL_ASSERT((instr->Mask(PCRelAddressingMask) == ADR) ||
(instr->Mask(PCRelAddressingMask) == ADRP));
set_reg(instr->Rd(), instr->ImmPCOffsetTarget());
}
void Simulator::VisitUnconditionalBranch(const Instruction* instr) {
switch (instr->Mask(UnconditionalBranchMask)) {
case BL:
set_lr(instr->NextInstruction());
VIXL_FALLTHROUGH();
case B:
set_pc(instr->ImmPCOffsetTarget());
break;
default: VIXL_UNREACHABLE();
}
}
void Simulator::VisitConditionalBranch(const Instruction* instr) {
VIXL_ASSERT(instr->Mask(ConditionalBranchMask) == B_cond);
if (ConditionPassed(instr->ConditionBranch())) {
set_pc(instr->ImmPCOffsetTarget());
}
}
void Simulator::VisitUnconditionalBranchToRegister(const Instruction* instr) {
const Instruction* target = Instruction::Cast(xreg(instr->Rn()));
switch (instr->Mask(UnconditionalBranchToRegisterMask)) {
case BLR:
set_lr(instr->NextInstruction());
VIXL_FALLTHROUGH();
case BR:
case RET: set_pc(target); break;
default: VIXL_UNREACHABLE();
}
}
void Simulator::VisitTestBranch(const Instruction* instr) {
unsigned bit_pos = (instr->ImmTestBranchBit5() << 5) |
instr->ImmTestBranchBit40();
bool bit_zero = ((xreg(instr->Rt()) >> bit_pos) & 1) == 0;
bool take_branch = false;
switch (instr->Mask(TestBranchMask)) {
case TBZ: take_branch = bit_zero; break;
case TBNZ: take_branch = !bit_zero; break;
default: VIXL_UNIMPLEMENTED();
}
if (take_branch) {
set_pc(instr->ImmPCOffsetTarget());
}
}
void Simulator::VisitCompareBranch(const Instruction* instr) {
unsigned rt = instr->Rt();
bool take_branch = false;
switch (instr->Mask(CompareBranchMask)) {
case CBZ_w: take_branch = (wreg(rt) == 0); break;
case CBZ_x: take_branch = (xreg(rt) == 0); break;
case CBNZ_w: take_branch = (wreg(rt) != 0); break;
case CBNZ_x: take_branch = (xreg(rt) != 0); break;
default: VIXL_UNIMPLEMENTED();
}
if (take_branch) {
set_pc(instr->ImmPCOffsetTarget());
}
}
void Simulator::AddSubHelper(const Instruction* instr, int64_t op2) {
unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize;
bool set_flags = instr->FlagsUpdate();
int64_t new_val = 0;
Instr operation = instr->Mask(AddSubOpMask);
switch (operation) {
case ADD:
case ADDS: {
new_val = AddWithCarry(reg_size,
set_flags,
reg(reg_size, instr->Rn(), instr->RnMode()),
op2);
break;
}
case SUB:
case SUBS: {
new_val = AddWithCarry(reg_size,
set_flags,
reg(reg_size, instr->Rn(), instr->RnMode()),
~op2,
1);
break;
}
default: VIXL_UNREACHABLE();
}
set_reg(reg_size, instr->Rd(), new_val, LogRegWrites, instr->RdMode());
}
void Simulator::VisitAddSubShifted(const Instruction* instr) {
unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize;
int64_t op2 = ShiftOperand(reg_size,
reg(reg_size, instr->Rm()),
static_cast<Shift>(instr->ShiftDP()),
instr->ImmDPShift());
AddSubHelper(instr, op2);
}
void Simulator::VisitAddSubImmediate(const Instruction* instr) {
int64_t op2 = instr->ImmAddSub() << ((instr->ShiftAddSub() == 1) ? 12 : 0);
AddSubHelper(instr, op2);
}
void Simulator::VisitAddSubExtended(const Instruction* instr) {
unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize;
int64_t op2 = ExtendValue(reg_size,
reg(reg_size, instr->Rm()),
static_cast<Extend>(instr->ExtendMode()),
instr->ImmExtendShift());
AddSubHelper(instr, op2);
}
void Simulator::VisitAddSubWithCarry(const Instruction* instr) {
unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize;
int64_t op2 = reg(reg_size, instr->Rm());
int64_t new_val;
if ((instr->Mask(AddSubOpMask) == SUB) || instr->Mask(AddSubOpMask) == SUBS) {
op2 = ~op2;
}
new_val = AddWithCarry(reg_size,
instr->FlagsUpdate(),
reg(reg_size, instr->Rn()),
op2,
C());
set_reg(reg_size, instr->Rd(), new_val);
}
void Simulator::VisitLogicalShifted(const Instruction* instr) {
unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize;
Shift shift_type = static_cast<Shift>(instr->ShiftDP());
unsigned shift_amount = instr->ImmDPShift();
int64_t op2 = ShiftOperand(reg_size, reg(reg_size, instr->Rm()), shift_type,
shift_amount);
if (instr->Mask(NOT) == NOT) {
op2 = ~op2;
}
LogicalHelper(instr, op2);
}
void Simulator::VisitLogicalImmediate(const Instruction* instr) {
LogicalHelper(instr, instr->ImmLogical());
}
void Simulator::LogicalHelper(const Instruction* instr, int64_t op2) {
unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize;
int64_t op1 = reg(reg_size, instr->Rn());
int64_t result = 0;
bool update_flags = false;
// Switch on the logical operation, stripping out the NOT bit, as it has a
// different meaning for logical immediate instructions.
switch (instr->Mask(LogicalOpMask & ~NOT)) {
case ANDS: update_flags = true; VIXL_FALLTHROUGH();
case AND: result = op1 & op2; break;
case ORR: result = op1 | op2; break;
case EOR: result = op1 ^ op2; break;
default:
VIXL_UNIMPLEMENTED();
}
if (update_flags) {
nzcv().SetN(CalcNFlag(result, reg_size));
nzcv().SetZ(CalcZFlag(result));
nzcv().SetC(0);
nzcv().SetV(0);
LogSystemRegister(NZCV);
}
set_reg(reg_size, instr->Rd(), result, LogRegWrites, instr->RdMode());
}
void Simulator::VisitConditionalCompareRegister(const Instruction* instr) {
unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize;
ConditionalCompareHelper(instr, reg(reg_size, instr->Rm()));
}
void Simulator::VisitConditionalCompareImmediate(const Instruction* instr) {
ConditionalCompareHelper(instr, instr->ImmCondCmp());
}
void Simulator::ConditionalCompareHelper(const Instruction* instr,
int64_t op2) {
unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize;
int64_t op1 = reg(reg_size, instr->Rn());
if (ConditionPassed(instr->Condition())) {
// If the condition passes, set the status flags to the result of comparing
// the operands.
if (instr->Mask(ConditionalCompareMask) == CCMP) {
AddWithCarry(reg_size, true, op1, ~op2, 1);
} else {
VIXL_ASSERT(instr->Mask(ConditionalCompareMask) == CCMN);
AddWithCarry(reg_size, true, op1, op2, 0);
}
} else {
// If the condition fails, set the status flags to the nzcv immediate.
nzcv().SetFlags(instr->Nzcv());
LogSystemRegister(NZCV);
}
}
void Simulator::VisitLoadStoreUnsignedOffset(const Instruction* instr) {
int offset = instr->ImmLSUnsigned() << instr->SizeLS();
LoadStoreHelper(instr, offset, Offset);
}
void Simulator::VisitLoadStoreUnscaledOffset(const Instruction* instr) {
LoadStoreHelper(instr, instr->ImmLS(), Offset);
}
void Simulator::VisitLoadStorePreIndex(const Instruction* instr) {
LoadStoreHelper(instr, instr->ImmLS(), PreIndex);
}
void Simulator::VisitLoadStorePostIndex(const Instruction* instr) {
LoadStoreHelper(instr, instr->ImmLS(), PostIndex);
}
void Simulator::VisitLoadStoreRegisterOffset(const Instruction* instr) {
Extend ext = static_cast<Extend>(instr->ExtendMode());
VIXL_ASSERT((ext == UXTW) || (ext == UXTX) || (ext == SXTW) || (ext == SXTX));
unsigned shift_amount = instr->ImmShiftLS() * instr->SizeLS();
int64_t offset = ExtendValue(kXRegSize, xreg(instr->Rm()), ext,
shift_amount);
LoadStoreHelper(instr, offset, Offset);
}
template<typename T>
static T Faulted() {
return ~0;
}
template<>
Simulator::qreg_t Faulted() {
static_assert(kQRegSizeInBytes == 16, "Known constraint");
static Simulator::qreg_t dummy = { {
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255
} };
return dummy;
}
template<typename T> T
Simulator::Read(uintptr_t address)
{
address = Memory::AddressUntag(address);
if (handle_wasm_seg_fault(address, sizeof(T)))
return Faulted<T>();
return Memory::Read<T>(address);
}
template <typename T> void
Simulator::Write(uintptr_t address, T value)
{
address = Memory::AddressUntag(address);
if (handle_wasm_seg_fault(address, sizeof(T)))
return;
Memory::Write<T>(address, value);
}
void Simulator::LoadStoreHelper(const Instruction* instr,
int64_t offset,
AddrMode addrmode) {
unsigned srcdst = instr->Rt();
uintptr_t address = AddressModeHelper(instr->Rn(), offset, addrmode);
LoadStoreOp op = static_cast<LoadStoreOp>(instr->Mask(LoadStoreMask));
switch (op) {
case LDRB_w:
set_wreg(srcdst, Read<uint8_t>(address), NoRegLog); break;
case LDRH_w:
set_wreg(srcdst, Read<uint16_t>(address), NoRegLog); break;
case LDR_w:
set_wreg(srcdst, Read<uint32_t>(address), NoRegLog); break;
case LDR_x:
set_xreg(srcdst, Read<uint64_t>(address), NoRegLog); break;
case LDRSB_w:
set_wreg(srcdst, Read<int8_t>(address), NoRegLog); break;
case LDRSH_w:
set_wreg(srcdst, Read<int16_t>(address), NoRegLog); break;
case LDRSB_x:
set_xreg(srcdst, Read<int8_t>(address), NoRegLog); break;
case LDRSH_x:
set_xreg(srcdst, Read<int16_t>(address), NoRegLog); break;
case LDRSW_x:
set_xreg(srcdst, Read<int32_t>(address), NoRegLog); break;
case LDR_b:
set_breg(srcdst, Read<uint8_t>(address), NoRegLog); break;
case LDR_h:
set_hreg(srcdst, Read<uint16_t>(address), NoRegLog); break;
case LDR_s:
set_sreg(srcdst, Read<float>(address), NoRegLog); break;
case LDR_d:
set_dreg(srcdst, Read<double>(address), NoRegLog); break;
case LDR_q:
set_qreg(srcdst, Read<qreg_t>(address), NoRegLog); break;
case STRB_w: Write<uint8_t>(address, wreg(srcdst)); break;
case STRH_w: Write<uint16_t>(address, wreg(srcdst)); break;
case STR_w: Write<uint32_t>(address, wreg(srcdst)); break;
case STR_x: Write<uint64_t>(address, xreg(srcdst)); break;
case STR_b: Write<uint8_t>(address, breg(srcdst)); break;
case STR_h: Write<uint16_t>(address, hreg(srcdst)); break;
case STR_s: Write<float>(address, sreg(srcdst)); break;
case STR_d: Write<double>(address, dreg(srcdst)); break;
case STR_q: Write<qreg_t>(address, qreg(srcdst)); break;
// Ignore prfm hint instructions.
case PRFM: break;
default: VIXL_UNIMPLEMENTED();
}
unsigned access_size = 1 << instr->SizeLS();
if (instr->IsLoad()) {
if ((op == LDR_s) || (op == LDR_d)) {
LogVRead(address, srcdst, GetPrintRegisterFormatForSizeFP(access_size));
} else if ((op == LDR_b) || (op == LDR_h) || (op == LDR_q)) {
LogVRead(address, srcdst, GetPrintRegisterFormatForSize(access_size));
} else {
LogRead(address, srcdst, GetPrintRegisterFormatForSize(access_size));
}
} else {
if ((op == STR_s) || (op == STR_d)) {
LogVWrite(address, srcdst, GetPrintRegisterFormatForSizeFP(access_size));
} else if ((op == STR_b) || (op == STR_h) || (op == STR_q)) {
LogVWrite(address, srcdst, GetPrintRegisterFormatForSize(access_size));
} else {
LogWrite(address, srcdst, GetPrintRegisterFormatForSize(access_size));
}
}
local_monitor_.MaybeClear();
}
void Simulator::VisitLoadStorePairOffset(const Instruction* instr) {
LoadStorePairHelper(instr, Offset);
}
void Simulator::VisitLoadStorePairPreIndex(const Instruction* instr) {
LoadStorePairHelper(instr, PreIndex);
}
void Simulator::VisitLoadStorePairPostIndex(const Instruction* instr) {
LoadStorePairHelper(instr, PostIndex);
}
void Simulator::VisitLoadStorePairNonTemporal(const Instruction* instr) {
LoadStorePairHelper(instr, Offset);
}
void Simulator::LoadStorePairHelper(const Instruction* instr,
AddrMode addrmode) {
unsigned rt = instr->Rt();
unsigned rt2 = instr->Rt2();
int element_size = 1 << instr->SizeLSPair();
int64_t offset = instr->ImmLSPair() * element_size;
uintptr_t address = AddressModeHelper(instr->Rn(), offset, addrmode);
uintptr_t address2 = address + element_size;
LoadStorePairOp op =
static_cast<LoadStorePairOp>(instr->Mask(LoadStorePairMask));
// 'rt' and 'rt2' can only be aliased for stores.
VIXL_ASSERT(((op & LoadStorePairLBit) == 0) || (rt != rt2));
switch (op) {
// Use NoRegLog to suppress the register trace (LOG_REGS, LOG_FP_REGS). We
// will print a more detailed log.
case LDP_w: {
set_wreg(rt, Read<uint32_t>(address), NoRegLog);
set_wreg(rt2, Read<uint32_t>(address2), NoRegLog);
break;
}
case LDP_s: {
set_sreg(rt, Read<float>(address), NoRegLog);
set_sreg(rt2, Read<float>(address2), NoRegLog);
break;
}
case LDP_x: {
set_xreg(rt, Read<uint64_t>(address), NoRegLog);
set_xreg(rt2, Read<uint64_t>(address2), NoRegLog);
break;
}
case LDP_d: {
set_dreg(rt, Read<double>(address), NoRegLog);
set_dreg(rt2, Read<double>(address2), NoRegLog);
break;
}
case LDP_q: {
set_qreg(rt, Read<qreg_t>(address), NoRegLog);
set_qreg(rt2, Read<qreg_t>(address2), NoRegLog);
break;
}
case LDPSW_x: {
set_xreg(rt, Read<int32_t>(address), NoRegLog);
set_xreg(rt2, Read<int32_t>(address2), NoRegLog);
break;
}
case STP_w: {
Write<uint32_t>(address, wreg(rt));
Write<uint32_t>(address2, wreg(rt2));
break;
}
case STP_s: {
Write<float>(address, sreg(rt));
Write<float>(address2, sreg(rt2));
break;
}
case STP_x: {
Write<uint64_t>(address, xreg(rt));
Write<uint64_t>(address2, xreg(rt2));
break;
}
case STP_d: {
Write<double>(address, dreg(rt));
Write<double>(address2, dreg(rt2));
break;
}
case STP_q: {
Write<qreg_t>(address, qreg(rt));
Write<qreg_t>(address2, qreg(rt2));
break;
}
default: VIXL_UNREACHABLE();
}
// Print a detailed trace (including the memory address) instead of the basic
// register:value trace generated by set_*reg().
if (instr->IsLoad()) {
if ((op == LDP_s) || (op == LDP_d)) {
LogVRead(address, rt, GetPrintRegisterFormatForSizeFP(element_size));
LogVRead(address2, rt2, GetPrintRegisterFormatForSizeFP(element_size));
} else if (op == LDP_q) {
LogVRead(address, rt, GetPrintRegisterFormatForSize(element_size));
LogVRead(address2, rt2, GetPrintRegisterFormatForSize(element_size));
} else {
LogRead(address, rt, GetPrintRegisterFormatForSize(element_size));
LogRead(address2, rt2, GetPrintRegisterFormatForSize(element_size));
}
} else {
if ((op == STP_s) || (op == STP_d)) {
LogVWrite(address, rt, GetPrintRegisterFormatForSizeFP(element_size));
LogVWrite(address2, rt2, GetPrintRegisterFormatForSizeFP(element_size));
} else if (op == STP_q) {
LogVWrite(address, rt, GetPrintRegisterFormatForSize(element_size));
LogVWrite(address2, rt2, GetPrintRegisterFormatForSize(element_size));
} else {
LogWrite(address, rt, GetPrintRegisterFormatForSize(element_size));
LogWrite(address2, rt2, GetPrintRegisterFormatForSize(element_size));
}
}
local_monitor_.MaybeClear();
}
void Simulator::PrintExclusiveAccessWarning() {
if (print_exclusive_access_warning_) {
fprintf(
stderr,
"%sWARNING:%s VIXL simulator support for load-/store-/clear-exclusive "
"instructions is limited. Refer to the README for details.%s\n",
clr_warning, clr_warning_message, clr_normal);
print_exclusive_access_warning_ = false;
}
}
template <typename T>
void Simulator::CompareAndSwapHelper(const Instruction* instr) {
unsigned rs = instr->Rs();
unsigned rt = instr->Rt();
unsigned rn = instr->Rn();
unsigned element_size = sizeof(T);
uint64_t address = reg<uint64_t>(rn, Reg31IsStackPointer);
// Verify that the address is available to the host.
VIXL_ASSERT(address == static_cast<uintptr_t>(address));
address = Memory::AddressUntag(address);
if (handle_wasm_seg_fault(address, element_size))
return;
bool is_acquire = instr->Bit(22) == 1;
bool is_release = instr->Bit(15) == 1;
T comparevalue = reg<T>(rs);
T newvalue = reg<T>(rt);
// The architecture permits that the data read clears any exclusive monitors
// associated with that location, even if the compare subsequently fails.
local_monitor_.Clear();
T data = Memory::Read<T>(address);
if (is_acquire) {
// Approximate load-acquire by issuing a full barrier after the load.
__sync_synchronize();
}
if (data == comparevalue) {
if (is_release) {
// Approximate store-release by issuing a full barrier before the store.
__sync_synchronize();
}
Memory::Write<T>(address, newvalue);
LogWrite(address, rt, GetPrintRegisterFormatForSize(element_size));
}
set_reg<T>(rs, data);
LogRead(address, rs, GetPrintRegisterFormatForSize(element_size));
}
template <typename T>
void Simulator::CompareAndSwapPairHelper(const Instruction* instr) {
VIXL_ASSERT((sizeof(T) == 4) || (sizeof(T) == 8));
unsigned rs = instr->Rs();
unsigned rt = instr->Rt();
unsigned rn = instr->Rn();
VIXL_ASSERT((rs % 2 == 0) && (rs % 2 == 0));
unsigned element_size = sizeof(T);
uint64_t address = reg<uint64_t>(rn, Reg31IsStackPointer);
// Verify that the address is available to the host.
VIXL_ASSERT(address == static_cast<uintptr_t>(address));
address = Memory::AddressUntag(address);
if (handle_wasm_seg_fault(address, element_size))
return;
uint64_t address2 = address + element_size;
bool is_acquire = instr->Bit(22) == 1;
bool is_release = instr->Bit(15) == 1;
T comparevalue_high = reg<T>(rs + 1);
T comparevalue_low = reg<T>(rs);
T newvalue_high = reg<T>(rt + 1);
T newvalue_low = reg<T>(rt);
// The architecture permits that the data read clears any exclusive monitors
// associated with that location, even if the compare subsequently fails.
local_monitor_.Clear();
T data_high = Memory::Read<T>(address);
T data_low = Memory::Read<T>(address2);
if (is_acquire) {
// Approximate load-acquire by issuing a full barrier after the load.
__sync_synchronize();
}
bool same =
(data_high == comparevalue_high) && (data_low == comparevalue_low);
if (same) {
if (is_release) {
// Approximate store-release by issuing a full barrier before the store.
__sync_synchronize();
}
Memory::Write<T>(address, newvalue_high);
Memory::Write<T>(address2, newvalue_low);
}
set_reg<T>(rs + 1, data_high);
set_reg<T>(rs, data_low);
LogRead(address, rs + 1, GetPrintRegisterFormatForSize(element_size));
LogRead(address2, rs, GetPrintRegisterFormatForSize(element_size));
if (same) {
LogWrite(address, rt + 1, GetPrintRegisterFormatForSize(element_size));
LogWrite(address2, rt, GetPrintRegisterFormatForSize(element_size));
}
}
void Simulator::VisitLoadStoreExclusive(const Instruction* instr) {
LoadStoreExclusive op =
static_cast<LoadStoreExclusive>(instr->Mask(LoadStoreExclusiveMask));
switch (op) {
case CAS_w:
case CASA_w:
case CASL_w:
case CASAL_w:
CompareAndSwapHelper<uint32_t>(instr);
break;
case CAS_x:
case CASA_x:
case CASL_x:
case CASAL_x:
CompareAndSwapHelper<uint64_t>(instr);
break;
case CASB:
case CASAB:
case CASLB:
case CASALB:
CompareAndSwapHelper<uint8_t>(instr);
break;
case CASH:
case CASAH:
case CASLH:
case CASALH:
CompareAndSwapHelper<uint16_t>(instr);
break;
case CASP_w:
case CASPA_w:
case CASPL_w:
case CASPAL_w:
CompareAndSwapPairHelper<uint32_t>(instr);
break;
case CASP_x:
case CASPA_x:
case CASPL_x:
case CASPAL_x:
CompareAndSwapPairHelper<uint64_t>(instr);
break;
default:
PrintExclusiveAccessWarning();
unsigned rs = instr->Rs();
unsigned rt = instr->Rt();
unsigned rt2 = instr->Rt2();
unsigned rn = instr->Rn();
bool is_exclusive = !instr->LdStXNotExclusive();
bool is_acquire_release = !is_exclusive || instr->LdStXAcquireRelease();
bool is_load = instr->LdStXLoad();
bool is_pair = instr->LdStXPair();
unsigned element_size = 1 << instr->LdStXSizeLog2();
unsigned access_size = is_pair ? element_size * 2 : element_size;
uint64_t address = reg<uint64_t>(rn, Reg31IsStackPointer);
// Verify that the address is available to the host.
VIXL_ASSERT(address == static_cast<uintptr_t>(address));
// Check the alignment of `address`.
if (AlignDown(address, access_size) != address) {
VIXL_ALIGNMENT_EXCEPTION();
}
// The sp must be aligned to 16 bytes when it is accessed.
if ((rn == 31) && (AlignDown(address, 16) != address)) {
VIXL_ALIGNMENT_EXCEPTION();
}
if (is_load) {
if (is_exclusive) {
local_monitor_.MarkExclusive(address, access_size);
} else {
// Any non-exclusive load can clear the local monitor as a side
// effect. We don't need to do this, but it is useful to stress the
// simulated code.
local_monitor_.Clear();
}
// Use NoRegLog to suppress the register trace (LOG_REGS, LOG_FP_REGS).
// We will print a more detailed log.
switch (op) {
case LDXRB_w:
case LDAXRB_w:
case LDARB_w:
set_wreg(rt, Read<uint8_t>(address), NoRegLog);
break;
case LDXRH_w:
case LDAXRH_w:
case LDARH_w:
set_wreg(rt, Read<uint16_t>(address), NoRegLog);
break;
case LDXR_w:
case LDAXR_w:
case LDAR_w:
set_wreg(rt, Read<uint32_t>(address), NoRegLog);
break;
case LDXR_x:
case LDAXR_x:
case LDAR_x:
set_xreg(rt, Read<uint64_t>(address), NoRegLog);
break;
case LDXP_w:
case LDAXP_w:
set_wreg(rt, Read<uint32_t>(address), NoRegLog);
set_wreg(rt2, Read<uint32_t>(address + element_size), NoRegLog);
break;
case LDXP_x:
case LDAXP_x:
set_xreg(rt, Read<uint64_t>(address), NoRegLog);
set_xreg(rt2, Read<uint64_t>(address + element_size), NoRegLog);
break;
default:
VIXL_UNREACHABLE();
}
if (is_acquire_release) {
// Approximate load-acquire by issuing a full barrier after the load.
js::jit::AtomicOperations::fenceSeqCst();
}
LogRead(address, rt, GetPrintRegisterFormatForSize(element_size));
if (is_pair) {
LogRead(address + element_size, rt2,
GetPrintRegisterFormatForSize(element_size));
}
} else {
if (is_acquire_release) {
// Approximate store-release by issuing a full barrier before the
// store.
js::jit::AtomicOperations::fenceSeqCst();
}
bool do_store = true;
if (is_exclusive) {
do_store = local_monitor_.IsExclusive(address, access_size) &&
global_monitor_.IsExclusive(address, access_size);
set_wreg(rs, do_store ? 0 : 1);
// - All exclusive stores explicitly clear the local monitor.
local_monitor_.Clear();
} else {
// - Any other store can clear the local monitor as a side effect.
local_monitor_.MaybeClear();
}
if (do_store) {
switch (op) {
case STXRB_w:
case STLXRB_w:
case STLRB_w:
Write<uint8_t>(address, wreg(rt));
break;
case STXRH_w:
case STLXRH_w:
case STLRH_w:
Write<uint16_t>(address, wreg(rt));
break;
case STXR_w:
case STLXR_w:
case STLR_w:
Write<uint32_t>(address, wreg(rt));
break;
case STXR_x:
case STLXR_x:
case STLR_x:
Write<uint64_t>(address, xreg(rt));
break;
case STXP_w:
case STLXP_w:
Write<uint32_t>(address, wreg(rt));
Write<uint32_t>(address + element_size, wreg(rt2));
break;
case STXP_x:
case STLXP_x:
Write<uint64_t>(address, xreg(rt));
Write<uint64_t>(address + element_size, xreg(rt2));
break;
default:
VIXL_UNREACHABLE();
}
LogWrite(address, rt, GetPrintRegisterFormatForSize(element_size));
if (is_pair) {
LogWrite(address + element_size, rt2,
GetPrintRegisterFormatForSize(element_size));
}
}
}
}
}
template <typename T>
void Simulator::AtomicMemorySimpleHelper(const Instruction* instr) {
unsigned rs = instr->Rs();
unsigned rt = instr->Rt();
unsigned rn = instr->Rn();
bool is_acquire = (instr->Bit(23) == 1) && (rt != kZeroRegCode);
bool is_release = instr->Bit(22) == 1;
unsigned element_size = sizeof(T);
uint64_t address = reg<uint64_t>(rn, Reg31IsStackPointer);
// Verify that the address is available to the host.
VIXL_ASSERT(address == static_cast<uintptr_t>(address));
address = Memory::AddressUntag(address);
if (handle_wasm_seg_fault(address, sizeof(T)))
return;
T value = reg<T>(rs);
T data = Memory::Read<T>(address);
if (is_acquire) {
// Approximate load-acquire by issuing a full barrier after the load.
__sync_synchronize();
}
T result = 0;
switch (instr->Mask(AtomicMemorySimpleOpMask)) {
case LDADDOp:
result = data + value;
break;
case LDCLROp:
VIXL_ASSERT(!std::numeric_limits<T>::is_signed);
result = data & ~value;
break;
case LDEOROp:
VIXL_ASSERT(!std::numeric_limits<T>::is_signed);
result = data ^ value;
break;
case LDSETOp:
VIXL_ASSERT(!std::numeric_limits<T>::is_signed);
result = data | value;
break;
// Signed/Unsigned difference is done via the templated type T.
case LDSMAXOp:
case LDUMAXOp:
result = (data > value) ? data : value;
break;
case LDSMINOp:
case LDUMINOp:
result = (data > value) ? value : data;
break;
}
if (is_release) {
// Approximate store-release by issuing a full barrier before the store.
__sync_synchronize();
}
Memory::Write<T>(address, result);
set_reg<T>(rt, data, NoRegLog);
LogRead(address, rt, GetPrintRegisterFormatForSize(element_size));
LogWrite(address, rs, GetPrintRegisterFormatForSize(element_size));
}
template <typename T>
void Simulator::AtomicMemorySwapHelper(const Instruction* instr) {
unsigned rs = instr->Rs();
unsigned rt = instr->Rt();
unsigned rn = instr->Rn();
bool is_acquire = (instr->Bit(23) == 1) && (rt != kZeroRegCode);
bool is_release = instr->Bit(22) == 1;
unsigned element_size = sizeof(T);
uint64_t address = reg<uint64_t>(rn, Reg31IsStackPointer);
// Verify that the address is available to the host.
VIXL_ASSERT(address == static_cast<uintptr_t>(address));
address = Memory::AddressUntag(address);
if (handle_wasm_seg_fault(address, sizeof(T)))
return;
T data = Memory::Read<T>(address);
if (is_acquire) {
// Approximate load-acquire by issuing a full barrier after the load.
__sync_synchronize();
}
if (is_release) {
// Approximate store-release by issuing a full barrier before the store.
__sync_synchronize();
}
Memory::Write<T>(address, reg<T>(rs));
set_reg<T>(rt, data);
LogRead(address, rt, GetPrintRegisterFormat(element_size));
LogWrite(address, rs, GetPrintRegisterFormat(element_size));
}
template <typename T>
void Simulator::LoadAcquireRCpcHelper(const Instruction* instr) {
unsigned rt = instr->Rt();
unsigned rn = instr->Rn();
unsigned element_size = sizeof(T);
uint64_t address = reg<uint64_t>(rn, Reg31IsStackPointer);
// Verify that the address is available to the host.
VIXL_ASSERT(address == static_cast<uintptr_t>(address));
address = Memory::AddressUntag(address);
if (handle_wasm_seg_fault(address, sizeof(T)))
return;
set_reg<T>(rt, Memory::Read<T>(address));
// Approximate load-acquire by issuing a full barrier after the load.
__sync_synchronize();
LogRead(address, rt, GetPrintRegisterFormat(element_size));
}
#define ATOMIC_MEMORY_SIMPLE_UINT_LIST(V) \
V(LDADD) \
V(LDCLR) \
V(LDEOR) \
V(LDSET) \
V(LDUMAX) \
V(LDUMIN)
#define ATOMIC_MEMORY_SIMPLE_INT_LIST(V) \
V(LDSMAX) \
V(LDSMIN)
void Simulator::VisitAtomicMemory(const Instruction* instr) {
switch (instr->Mask(AtomicMemoryMask)) {
// clang-format off
#define SIM_FUNC_B(A) \
case A##B: \
case A##AB: \
case A##LB: \
case A##ALB:
#define SIM_FUNC_H(A) \
case A##H: \
case A##AH: \
case A##LH: \
case A##ALH:
#define SIM_FUNC_w(A) \
case A##_w: \
case A##A_w: \
case A##L_w: \
case A##AL_w:
#define SIM_FUNC_x(A) \
case A##_x: \
case A##A_x: \
case A##L_x: \
case A##AL_x:
ATOMIC_MEMORY_SIMPLE_UINT_LIST(SIM_FUNC_B)
AtomicMemorySimpleHelper<uint8_t>(instr);
break;
ATOMIC_MEMORY_SIMPLE_INT_LIST(SIM_FUNC_B)
AtomicMemorySimpleHelper<int8_t>(instr);
break;
ATOMIC_MEMORY_SIMPLE_UINT_LIST(SIM_FUNC_H)
AtomicMemorySimpleHelper<uint16_t>(instr);
break;
ATOMIC_MEMORY_SIMPLE_INT_LIST(SIM_FUNC_H)
AtomicMemorySimpleHelper<int16_t>(instr);
break;
ATOMIC_MEMORY_SIMPLE_UINT_LIST(SIM_FUNC_w)
AtomicMemorySimpleHelper<uint32_t>(instr);
break;
ATOMIC_MEMORY_SIMPLE_INT_LIST(SIM_FUNC_w)
AtomicMemorySimpleHelper<int32_t>(instr);
break;
ATOMIC_MEMORY_SIMPLE_UINT_LIST(SIM_FUNC_x)
AtomicMemorySimpleHelper<uint64_t>(instr);
break;
ATOMIC_MEMORY_SIMPLE_INT_LIST(SIM_FUNC_x)
AtomicMemorySimpleHelper<int64_t>(instr);
break;
// clang-format on
case SWPB:
case SWPAB:
case SWPLB:
case SWPALB:
AtomicMemorySwapHelper<uint8_t>(instr);
break;
case SWPH:
case SWPAH:
case SWPLH:
case SWPALH:
AtomicMemorySwapHelper<uint16_t>(instr);
break;
case SWP_w:
case SWPA_w:
case SWPL_w:
case SWPAL_w:
AtomicMemorySwapHelper<uint32_t>(instr);
break;
case SWP_x:
case SWPA_x:
case SWPL_x:
case SWPAL_x:
AtomicMemorySwapHelper<uint64_t>(instr);
break;
case LDAPRB:
LoadAcquireRCpcHelper<uint8_t>(instr);
break;
case LDAPRH:
LoadAcquireRCpcHelper<uint16_t>(instr);
break;
case LDAPR_w:
LoadAcquireRCpcHelper<uint32_t>(instr);
break;
case LDAPR_x:
LoadAcquireRCpcHelper<uint64_t>(instr);
break;
}
}
void Simulator::VisitLoadLiteral(const Instruction* instr) {
unsigned rt = instr->Rt();
uint64_t address = instr->LiteralAddress<uint64_t>();
// Verify that the calculated address is available to the host.
VIXL_ASSERT(address == static_cast<uintptr_t>(address));
switch (instr->Mask(LoadLiteralMask)) {
// Use NoRegLog to suppress the register trace (LOG_REGS, LOG_VREGS), then
// print a more detailed log.
case LDR_w_lit:
set_wreg(rt, Read<uint32_t>(address), NoRegLog);
LogRead(address, rt, kPrintWReg);
break;
case LDR_x_lit:
set_xreg(rt, Read<uint64_t>(address), NoRegLog);
LogRead(address, rt, kPrintXReg);
break;
case LDR_s_lit:
set_sreg(rt, Read<float>(address), NoRegLog);
LogVRead(address, rt, kPrintSReg);
break;
case LDR_d_lit:
set_dreg(rt, Read<double>(address), NoRegLog);
LogVRead(address, rt, kPrintDReg);
break;
case LDR_q_lit:
set_qreg(rt, Read<qreg_t>(address), NoRegLog);
LogVRead(address, rt, kPrintReg1Q);
break;
case LDRSW_x_lit:
set_xreg(rt, Read<int32_t>(address), NoRegLog);
LogRead(address, rt, kPrintWReg);
break;
// Ignore prfm hint instructions.
case PRFM_lit: break;
default: VIXL_UNREACHABLE();
}
local_monitor_.MaybeClear();
}
uintptr_t Simulator::AddressModeHelper(unsigned addr_reg,
int64_t offset,
AddrMode addrmode) {
uint64_t address = xreg(addr_reg, Reg31IsStackPointer);
if ((addr_reg == 31) && ((address % 16) != 0)) {
// When the base register is SP the stack pointer is required to be
// quadword aligned prior to the address calculation and write-backs.
// Misalignment will cause a stack alignment fault.
VIXL_ALIGNMENT_EXCEPTION();
}
if ((addrmode == PreIndex) || (addrmode == PostIndex)) {
VIXL_ASSERT(offset != 0);
// Only preindex should log the register update here. For Postindex, the
// update will be printed automatically by LogWrittenRegisters _after_ the
// memory access itself is logged.
RegLogMode log_mode = (addrmode == PreIndex) ? LogRegWrites : NoRegLog;
set_xreg(addr_reg, address + offset, log_mode, Reg31IsStackPointer);
}
if ((addrmode == Offset) || (addrmode == PreIndex)) {
address += offset;
}
// Verify that the calculated address is available to the host.
VIXL_ASSERT(address == static_cast<uintptr_t>(address));
return static_cast<uintptr_t>(address);
}
void Simulator::VisitMoveWideImmediate(const Instruction* instr) {
MoveWideImmediateOp mov_op =
static_cast<MoveWideImmediateOp>(instr->Mask(MoveWideImmediateMask));
int64_t new_xn_val = 0;
bool is_64_bits = instr->SixtyFourBits() == 1;
// Shift is limited for W operations.
VIXL_ASSERT(is_64_bits || (instr->ShiftMoveWide() < 2));
// Get the shifted immediate.
int64_t shift = instr->ShiftMoveWide() * 16;
int64_t shifted_imm16 = static_cast<int64_t>(instr->ImmMoveWide()) << shift;
// Compute the new value.
switch (mov_op) {
case MOVN_w:
case MOVN_x: {
new_xn_val = ~shifted_imm16;
if (!is_64_bits) new_xn_val &= kWRegMask;
break;
}
case MOVK_w:
case MOVK_x: {
unsigned reg_code = instr->Rd();
int64_t prev_xn_val = is_64_bits ? xreg(reg_code)
: wreg(reg_code);
new_xn_val =
(prev_xn_val & ~(INT64_C(0xffff) << shift)) | shifted_imm16;
break;
}
case MOVZ_w:
case MOVZ_x: {
new_xn_val = shifted_imm16;
break;
}
default:
VIXL_UNREACHABLE();
}
// Update the destination register.
set_xreg(instr->Rd(), new_xn_val);
}
void Simulator::VisitConditionalSelect(const Instruction* instr) {
uint64_t new_val = xreg(instr->Rn());
if (ConditionFailed(static_cast<Condition>(instr->Condition()))) {
new_val = xreg(instr->Rm());
switch (instr->Mask(ConditionalSelectMask)) {
case CSEL_w:
case CSEL_x: break;
case CSINC_w:
case CSINC_x: new_val++; break;
case CSINV_w:
case CSINV_x: new_val = ~new_val; break;
case CSNEG_w:
case CSNEG_x: new_val = -new_val; break;
default: VIXL_UNIMPLEMENTED();
}
}
unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize;
set_reg(reg_size, instr->Rd(), new_val);
}
void Simulator::VisitDataProcessing1Source(const Instruction* instr) {
unsigned dst = instr->Rd();
unsigned src = instr->Rn();
switch (instr->Mask(DataProcessing1SourceMask)) {
case RBIT_w: set_wreg(dst, ReverseBits(wreg(src))); break;
case RBIT_x: set_xreg(dst, ReverseBits(xreg(src))); break;
case REV16_w: set_wreg(dst, ReverseBytes(wreg(src), 1)); break;
case REV16_x: set_xreg(dst, ReverseBytes(xreg(src), 1)); break;
case REV_w: set_wreg(dst, ReverseBytes(wreg(src), 2)); break;
case REV32_x: set_xreg(dst, ReverseBytes(xreg(src), 2)); break;
case REV_x: set_xreg(dst, ReverseBytes(xreg(src), 3)); break;
case CLZ_w: set_wreg(dst, CountLeadingZeros(wreg(src))); break;
case CLZ_x: set_xreg(dst, CountLeadingZeros(xreg(src))); break;
case CLS_w: {
set_wreg(dst, CountLeadingSignBits(wreg(src)));
break;
}
case CLS_x: {
set_xreg(dst, CountLeadingSignBits(xreg(src)));
break;
}
default: VIXL_UNIMPLEMENTED();
}
}
uint32_t Simulator::Poly32Mod2(unsigned n, uint64_t data, uint32_t poly) {
VIXL_ASSERT((n > 32) && (n <= 64));
for (unsigned i = (n - 1); i >= 32; i--) {
if (((data >> i) & 1) != 0) {
uint64_t polysh32 = (uint64_t)poly << (i - 32);
uint64_t mask = (UINT64_C(1) << i) - 1;
data = ((data & mask) ^ polysh32);
}
}
return data & 0xffffffff;
}
template <typename T>
uint32_t Simulator::Crc32Checksum(uint32_t acc, T val, uint32_t poly) {
unsigned size = sizeof(val) * 8; // Number of bits in type T.
VIXL_ASSERT((size == 8) || (size == 16) || (size == 32));
uint64_t tempacc = static_cast<uint64_t>(ReverseBits(acc)) << size;
uint64_t tempval = static_cast<uint64_t>(ReverseBits(val)) << 32;
return ReverseBits(Poly32Mod2(32 + size, tempacc ^ tempval, poly));
}
uint32_t Simulator::Crc32Checksum(uint32_t acc, uint64_t val, uint32_t poly) {
// Poly32Mod2 cannot handle inputs with more than 32 bits, so compute
// the CRC of each 32-bit word sequentially.
acc = Crc32Checksum(acc, (uint32_t)(val & 0xffffffff), poly);
return Crc32Checksum(acc, (uint32_t)(val >> 32), poly);
}
void Simulator::VisitDataProcessing2Source(const Instruction* instr) {
Shift shift_op = NO_SHIFT;
int64_t result = 0;
unsigned reg_size = instr->SixtyFourBits() ? kXRegSize : kWRegSize;
switch (instr->Mask(DataProcessing2SourceMask)) {
case SDIV_w: {
int32_t rn = wreg(instr->Rn());
int32_t rm = wreg(instr->Rm());
if ((rn == kWMinInt) && (rm == -1)) {
result = kWMinInt;
} else if (rm == 0) {
// Division by zero can be trapped, but not on A-class processors.
result = 0;
} else {
result = rn / rm;
}
break;
}
case SDIV_x: {
int64_t rn = xreg(instr->Rn());
int64_t rm = xreg(instr->Rm());
if ((rn == kXMinInt) && (rm == -1)) {
result = kXMinInt;
} else if (rm == 0) {
// Division by zero can be trapped, but not on A-class processors.
result = 0;
} else {
result = rn / rm;
}
break;
}
case UDIV_w: {
uint32_t rn = static_cast<uint32_t>(wreg(instr->Rn()));
uint32_t rm = static_cast<uint32_t>(wreg(instr->Rm()));
if (rm == 0) {
// Division by zero can be trapped, but not on A-class processors.
result = 0;
} else {
result = rn / rm;
}
break;
}
case UDIV_x: {
uint64_t rn = static_cast<uint64_t>(xreg(instr->Rn()));
uint64_t rm = static_cast<uint64_t>(xreg(instr->Rm()));
if (rm == 0) {
// Division by zero can be trapped, but not on A-class processors.
result = 0;
} else {
result = rn / rm;
}
break;
}
case LSLV_w:
case LSLV_x: shift_op = LSL; break;
case LSRV_w:
case LSRV_x: shift_op = LSR; break;
case ASRV_w:
case ASRV_x: shift_op = ASR; break;
case RORV_w:
case RORV_x: shift_op = ROR; break;
case CRC32B: {
uint32_t acc = reg<uint32_t>(instr->Rn());
uint8_t val = reg<uint8_t>(instr->Rm());
result = Crc32Checksum(acc, val, CRC32_POLY);
break;
}
case CRC32H: {
uint32_t acc = reg<uint32_t>(instr->Rn());
uint16_t val = reg<uint16_t>(instr->Rm());
result = Crc32Checksum(acc, val, CRC32_POLY);
break;
}
case CRC32W: {
uint32_t acc = reg<uint32_t>(instr->Rn());
uint32_t val = reg<uint32_t>(instr->Rm());
result = Crc32Checksum(acc, val, CRC32_POLY);
break;
}
case CRC32X: {
uint32_t acc = reg<uint32_t>(instr->Rn());
uint64_t val = reg<uint64_t>(instr->Rm());
result = Crc32Checksum(acc, val, CRC32_POLY);
reg_size = kWRegSize;
break;
}
case CRC32CB: {
uint32_t acc = reg<uint32_t>(instr->Rn());
uint8_t val = reg<uint8_t>(instr->Rm());
result = Crc32Checksum(acc, val, CRC32C_POLY);
break;
}
case CRC32CH: {
uint32_t acc = reg<uint32_t>(instr->Rn());
uint16_t val = reg<uint16_t>(instr->Rm());
result = Crc32Checksum(acc, val, CRC32C_POLY);
break;
}
case CRC32CW: {
uint32_t acc = reg<uint32_t>(instr->Rn());
uint32_t val = reg<uint32_t>(instr->Rm());
result = Crc32Checksum(acc, val, CRC32C_POLY);
break;
}
case CRC32CX: {
uint32_t acc = reg<uint32_t>(instr->Rn());
uint64_t val = reg<uint64_t>(instr->Rm());
result = Crc32Checksum(acc, val, CRC32C_POLY);
reg_size = kWRegSize;
break;
}
default: VIXL_UNIMPLEMENTED();
}
if (shift_op != NO_SHIFT) {
// Shift distance encoded in the least-significant five/six bits of the