using helpers::DRegisterFrom; using helpers::HighRegisterFrom; using helpers::InputDRegisterAt; using helpers::InputRegisterAt; using helpers::InputSRegisterAt; using helpers::Int32ConstantFrom; using helpers::LocationFrom; using helpers::LowRegisterFrom; using helpers::LowSRegisterFrom; using helpers::HighSRegisterFrom; using helpers::OperandFrom; using helpers::OutputDRegister; using helpers::OutputRegister; using helpers::RegisterFrom; using helpers::SRegisterFrom;
__ Bind(GetEntryLabel()); // The source range and destination pointer were initialized before entering the slow-path.
vixl32::Label loop;
__ Bind(&loop);
__ Ldr(tmp, MemOperand(src_curr_addr, element_size, PostIndex));
assembler->MaybeUnpoisonHeapReference(tmp); // TODO: Inline the mark bit check before calling the runtime? // tmp = ReadBarrier::Mark(tmp); // No need to save live registers; it's taken care of by the // entrypoint. Also, there is no need to update the stack mask, // as this runtime call will not trigger a garbage collection. // (See ReadBarrierMarkSlowPathARM::EmitNativeCode for more // explanations.)
DCHECK(!tmp.IsSP());
DCHECK(!tmp.IsLR());
DCHECK(!tmp.IsPC()); // IP is used internally by the ReadBarrierMarkRegX entry point // as a temporary (and not preserved). It thus cannot be used by // any live register in this slow path.
DCHECK(!src_curr_addr.Is(ip));
DCHECK(!dst_curr_addr.Is(ip));
DCHECK(!src_stop_addr.Is(ip));
DCHECK(!tmp.Is(ip));
DCHECK(tmp.IsRegister()) << tmp; // TODO: Load the entrypoint once before the loop, instead of // loading it at every iteration.
int32_t entry_point_offset =
Thread::ReadBarrierMarkEntryPointsOffset<kArmPointerSize>(tmp.GetCode()); // This runtime call does not require a stack map.
arm_codegen->InvokeRuntimeWithoutRecordingPcInfo(entry_point_offset, instruction_, this);
assembler->MaybePoisonHeapReference(tmp);
__ Str(tmp, MemOperand(dst_curr_addr, element_size, PostIndex));
__ Cmp(src_curr_addr, src_stop_addr);
__ B(ne, &loop, /* is_far_target= */ false);
__ B(GetExitLabel());
}
// Round to nearest integer, ties away from zero.
__ Vcvta(S32, F32, temp1, in_reg);
__ Vmov(out_reg, temp1);
// For positive, zero or NaN inputs, rounding is done.
__ Cmp(out_reg, 0);
__ B(ge, final_label, /* is_far_target= */ false);
// Handle input < 0 cases. // If input is negative but not a tie, previous result (round to nearest) is valid. // If input is a negative tie, change rounding direction to positive infinity, out_reg += 1.
__ Vrinta(F32, temp1, in_reg);
__ Vmov(temp2, 0.5);
__ Vsub(F32, temp1, in_reg, temp1);
__ Vcmp(F32, temp1, temp2);
__ Vmrs(RegisterOrAPSR_nzcv(kPcCode), FPSCR);
{ // Use ExactAssemblyScope here because we are using IT.
ExactAssemblyScope it_scope(assembler->GetVIXLAssembler(), 2 * kMaxInstructionSizeInBytes,
CodeBufferCheckScope::kMaximumSize);
__ it(eq);
__ add(eq, out_reg, out_reg, 1);
}
void IntrinsicCodeGeneratorARMVIXL::VisitMemoryPokeLongNative(HInvoke* invoke) {
ArmVIXLAssembler* assembler = GetAssembler(); // Ignore upper 4B of long address.
vixl32::Register addr = LowRegisterFrom(invoke->GetLocations()->InAt(0)); // Worst case: Control register bit SCTLR.A = 0. Then unaligned accesses throw a processor // exception. So we can't use ldrd as addr may be unaligned.
__ Str(LowRegisterFrom(invoke->GetLocations()->InAt(1)), MemOperand(addr));
__ Str(HighRegisterFrom(invoke->GetLocations()->InAt(1)), MemOperand(addr, 4));
}
void IntrinsicLocationsBuilderARMVIXL::VisitStringCompareTo(HInvoke* invoke) { // The inputs plus one temp.
LocationSummary* locations = LocationSummary::Create(
allocator_,
invoke,
invoke->InputAt(1)->CanBeNull() ? LocationSummary::kCallOnSlowPath
: LocationSummary::kNoCall,
kIntrinsified);
locations->SetInAt(0, Location::RequiresCoreRegister());
locations->SetInAt(1, Location::RequiresCoreRegister());
locations->AddRegisterTemps(3); // Need temporary registers for String compression's feature. if (mirror::kUseStringCompression) {
locations->AddTemp(Location::RequiresCoreRegister());
}
locations->SetOut(Location::RequiresCoreRegister(), Location::kOutputOverlap);
}
// Forward declaration. // // ART build system imposes a size limit (deviceFrameSizeLimit) on the stack frames generated // by the compiler for every C++ function, and if this function gets inlined in // IntrinsicCodeGeneratorARMVIXL::VisitStringCompareTo, the limit will be exceeded, resulting in a // build failure. That is the reason why NO_INLINE attribute is used. staticvoid NO_INLINE GenerateStringCompareToLoop(ArmVIXLAssembler* assembler,
HInvoke* invoke,
vixl32::Label* end,
vixl32::Label* different_compression);
// Get offsets of count and value fields within a string object. const int32_t count_offset = mirror::String::CountOffset().Int32Value();
// Note that the null check must have been done earlier.
DCHECK(!invoke->CanDoImplicitNullCheckOn(invoke->InputAt(0)));
// Take slow path and throw if input can be and is null.
SlowPathCodeARMVIXL* slow_path = nullptr; constbool can_slow_path = invoke->InputAt(1)->CanBeNull(); if (can_slow_path) {
slow_path = new (codegen_->GetScopedAllocator()) IntrinsicSlowPathARMVIXL(invoke);
codegen_->AddSlowPath(slow_path);
__ CompareAndBranchIfZero(arg, slow_path->GetEntryLabel());
}
// Reference equality check, return 0 if same reference.
__ Subs(out, str, arg);
__ B(eq, &end);
if (mirror::kUseStringCompression) { // Load `count` fields of this and argument strings.
__ Ldr(temp3, MemOperand(str, count_offset));
__ Ldr(temp2, MemOperand(arg, count_offset)); // Extract lengths from the `count` fields.
__ Lsr(temp0, temp3, 1u);
__ Lsr(temp1, temp2, 1u);
} else { // Load lengths of this and argument strings.
__ Ldr(temp0, MemOperand(str, count_offset));
__ Ldr(temp1, MemOperand(arg, count_offset));
} // out = length diff.
__ Subs(out, temp0, temp1); // temp0 = min(len(str), len(arg)).
// Shorter string is empty? // Note that mirror::kUseStringCompression==true introduces lots of instructions, // which makes &end label far away from this branch and makes it not 'CBZ-encodable'.
__ CompareAndBranchIfZero(temp0, &end, mirror::kUseStringCompression);
if (mirror::kUseStringCompression) { // Check if both strings using same compression style to use this comparison loop.
__ Eors(temp2, temp2, temp3);
__ Lsrs(temp2, temp2, 1u);
__ B(cs, &different_compression); // For string compression, calculate the number of bytes to compare (not chars). // This could in theory exceed INT32_MAX, so treat temp0 as unsigned.
__ Lsls(temp3, temp3, 31u); // Extract purely the compression flag.
const int32_t value_offset = mirror::String::ValueOffset().Int32Value(); // Store offset of string value in preparation for comparison loop.
__ Mov(temp1, value_offset);
// Assertions that must hold in order to compare multiple characters at a time.
CHECK_ALIGNED(value_offset, 8);
static_assert(IsAligned<8>(kObjectAlignment), "String data must be 8-byte aligned for unrolled CompareTo loop.");
__ Bind(&find_char_diff_2nd_cmp); if (mirror::kUseStringCompression) {
__ Subs(temp0, temp0, 4); // 4 bytes previously compared.
__ B(ls, end, /* is_far_target= */ false); // Was the second comparison fully beyond the end?
} else { // Without string compression, we can start treating temp0 as signed // and rely on the signed comparison below.
__ Sub(temp0, temp0, 2);
}
// Find the single character difference.
__ Bind(&find_char_diff); // Get the bit position of the first character that differs.
__ Eor(temp1, temp2, temp_reg);
__ Rbit(temp1, temp1);
__ Clz(temp1, temp1);
// temp0 = number of characters remaining to compare. // (Without string compression, it could be < 1 if a difference is found by the second CMP // in the comparison loop, and after the end of the shorter string data).
// Without string compression (temp1 >> 4) = character where difference occurs between the last // two words compared, in the interval [0,1]. // (0 for low half-word different, 1 for high half-word different). // With string compression, (temp1 << 3) = byte where the difference occurs, // in the interval [0,3].
// If temp0 <= (temp1 >> (kUseStringCompression ? 3 : 4)), the difference occurs outside // the remaining string data, so just return length diff (out). // The comparison is unsigned for string compression, otherwise signed.
__ Cmp(temp0, Operand(temp1, vixl32::LSR, (mirror::kUseStringCompression ? 3 : 4)));
__ B((mirror::kUseStringCompression ? ls : le), end, /* is_far_target= */ false);
// Extract the characters and calculate the difference. if (mirror::kUseStringCompression) { // For compressed strings we need to clear 0x7 from temp1, for uncompressed we need to clear // 0xf. We also need to prepare the character extraction mask `uncompressed ? 0xffffu : 0xffu`. // The compression flag is now in the highest bit of temp3, so let's play some tricks.
__ Orr(temp3, temp3, 0xffu << 23); // uncompressed ? 0xff800000u : 0x7ff80000u
__ Bic(temp1, temp1, Operand(temp3, vixl32::LSR, 31 - 3)); // &= ~(uncompressed ? 0xfu : 0x7u)
__ Asr(temp3, temp3, 7u); // uncompressed ? 0xffff0000u : 0xff0000u.
__ Lsr(temp2, temp2, temp1); // Extract second character.
__ Lsr(temp3, temp3, 16u); // uncompressed ? 0xffffu : 0xffu
__ Lsr(out, temp_reg, temp1); // Extract first character.
__ And(temp2, temp2, temp3);
__ And(out, out, temp3);
} else {
__ Bic(temp1, temp1, 0xf);
__ Lsr(temp2, temp2, temp1);
__ Lsr(out, temp_reg, temp1);
__ Movt(temp2, 0);
__ Movt(out, 0);
}
__ Sub(out, out, temp2);
temps.Release(temp_reg);
if (mirror::kUseStringCompression) {
__ B(end);
__ Bind(different_compression);
// Comparison for different compression style. const size_t c_char_size = DataType::Size(DataType::Type::kInt8);
DCHECK_EQ(c_char_size, 1u);
// We want to free up the temp3, currently holding `str.count`, for comparison. // So, we move it to the bottom bit of the iteration count `temp0` which we tnen // need to treat as unsigned. Start by freeing the bit with an ADD and continue // further down by a LSRS+SBC which will flip the meaning of the flag but allow // `subs temp0, #2; bhi different_compression_loop` to serve as the loop condition.
__ Add(temp0, temp0, temp0); // Unlike LSL, this ADD is always 16-bit. // `temp1` will hold the compressed data pointer, `temp2` the uncompressed data pointer.
__ Mov(temp1, str);
__ Mov(temp2, arg);
__ Lsrs(temp3, temp3, 1u); // Continue the move of the compression flag.
{
ExactAssemblyScope aas(assembler->GetVIXLAssembler(), 3 * kMaxInstructionSizeInBytes,
CodeBufferCheckScope::kMaximumSize);
__ itt(cs); // Interleave with selection of temp1 and temp2.
__ mov(cs, temp1, arg); // Preserves flags.
__ mov(cs, temp2, str); // Preserves flags.
}
__ Sbc(temp0, temp0, 0); // Complete the move of the compression flag.
// Adjust temp1 and temp2 from string pointers to data pointers.
__ Add(temp1, temp1, value_offset);
__ Add(temp2, temp2, value_offset);
// The cut off for unrolling the loop in String.equals() intrinsic for const strings. // The normal loop plus the pre-header is 9 instructions (18-26 bytes) without string compression // and 12 instructions (24-32 bytes) with string compression. We can compare up to 4 bytes in 4 // instructions (LDR+LDR+CMP+BNE) and up to 8 bytes in 6 instructions (LDRD+LDRD+CMP+BNE+CMP+BNE). // Allow up to 12 instructions (32 bytes) for the unrolled loop.
constexpr size_t kShortConstStringEqualsCutoffInBytes = 16;
// Temporary registers to store lengths of strings and for calculations. // Using instruction cbz requires a low register, so explicitly set a temp to be R0.
locations->AddTemp(LocationFrom(r0));
// For the generic implementation and for long const strings we need an extra temporary. // We do not need it for short const strings, up to 4 bytes, see code generation below.
uint32_t const_string_length = 0u; constchar* const_string = GetConstString(invoke->InputAt(0), &const_string_length); if (const_string == nullptr) {
const_string = GetConstString(invoke->InputAt(1), &const_string_length);
} bool is_compressed =
mirror::kUseStringCompression &&
const_string != nullptr &&
mirror::String::DexFileStringAllASCII(const_string, const_string_length); if (const_string == nullptr || const_string_length > (is_compressed ? 4u : 2u)) {
locations->AddTemp(Location::RequiresCoreRegister());
}
// TODO: If the String.equals() is used only for an immediately following HIf, we can // mark it as emitted-at-use-site and emit branches directly to the appropriate blocks. // Then we shall need an extra temporary register instead of the output register.
locations->SetOut(Location::RequiresCoreRegister());
}
// Get offsets of count, value, and class fields within a string object. const uint32_t count_offset = mirror::String::CountOffset().Uint32Value(); const uint32_t value_offset = mirror::String::ValueOffset().Uint32Value(); const uint32_t class_offset = mirror::Object::ClassOffset().Uint32Value();
// Note that the null check must have been done earlier.
DCHECK(!invoke->CanDoImplicitNullCheckOn(invoke->InputAt(0)));
StringEqualsOptimizations optimizations(invoke); if (!optimizations.GetArgumentNotNull()) { // Check if input is null, return false if it is.
__ CompareAndBranchIfZero(arg, &return_false, /* is_far_target= */ false);
}
// Reference equality check, return true if same reference.
__ Cmp(str, arg);
__ B(eq, &return_true, /* is_far_target= */ false);
if (!optimizations.GetArgumentIsString()) { // Instanceof check for the argument by comparing class fields. // All string objects must have the same type since String cannot be subclassed. // Receiver must be a string object, so its class field is equal to all strings' class fields. // If the argument is a string object, its class field must be equal to receiver's class field. // // As the String class is expected to be non-movable, we can read the class // field from String.equals' arguments without read barriers.
AssertNonMovableStringClass(); // /* HeapReference<Class> */ temp = str->klass_
__ Ldr(temp, MemOperand(str, class_offset)); // /* HeapReference<Class> */ out = arg->klass_
__ Ldr(out, MemOperand(arg, class_offset)); // Also, because we use the previously loaded class references only in the // following comparison, we don't need to unpoison them.
__ Cmp(temp, out);
__ B(ne, &return_false, /* is_far_target= */ false);
}
// Check if one of the inputs is a const string. Do not special-case both strings // being const, such cases should be handled by constant folding if needed.
uint32_t const_string_length = 0u; constchar* const_string = GetConstString(invoke->InputAt(0), &const_string_length); if (const_string == nullptr) {
const_string = GetConstString(invoke->InputAt(1), &const_string_length); if (const_string != nullptr) {
std::swap(str, arg); // Make sure the const string is in `str`.
}
} bool is_compressed =
mirror::kUseStringCompression &&
const_string != nullptr &&
mirror::String::DexFileStringAllASCII(const_string, const_string_length);
if (const_string != nullptr) { // Load `count` field of the argument string and check if it matches the const string. // Also compares the compression style, if differs return false.
__ Ldr(temp, MemOperand(arg, count_offset));
__ Cmp(temp, Operand(mirror::String::GetFlaggedCount(const_string_length, is_compressed)));
__ B(ne, &return_false, /* is_far_target= */ false);
} else { // Load `count` fields of this and argument strings.
__ Ldr(temp, MemOperand(str, count_offset));
__ Ldr(out, MemOperand(arg, count_offset)); // Check if `count` fields are equal, return false if they're not. // Also compares the compression style, if differs return false.
__ Cmp(temp, out);
__ B(ne, &return_false, /* is_far_target= */ false);
}
// Assertions that must hold in order to compare strings 4 bytes at a time. // Ok to do this because strings are zero-padded to kObjectAlignment.
DCHECK_ALIGNED(value_offset, 4);
static_assert(IsAligned<4>(kObjectAlignment), "String data must be aligned for fast compare.");
if (const_string != nullptr &&
const_string_length <= (is_compressed ? kShortConstStringEqualsCutoffInBytes
: kShortConstStringEqualsCutoffInBytes / 2u)) { // Load and compare the contents. Though we know the contents of the short const string // at compile time, materializing constants may be more code than loading from memory.
int32_t offset = value_offset;
size_t remaining_bytes =
RoundUp(is_compressed ? const_string_length : const_string_length * 2u, 4u); while (remaining_bytes > sizeof(uint32_t)) {
vixl32::Register temp1 = RegisterFrom(locations->GetTemp(1));
UseScratchRegisterScope scratch_scope(assembler->GetVIXLAssembler());
vixl32::Register temp2 = scratch_scope.Acquire();
__ Ldrd(temp, temp1, MemOperand(str, offset));
__ Ldrd(temp2, out, MemOperand(arg, offset));
__ Cmp(temp, temp2);
__ B(ne, &return_false, /* is_far_target= */ false);
__ Cmp(temp1, out);
__ B(ne, &return_false, /* is_far_target= */ false);
offset += 2u * sizeof(uint32_t);
remaining_bytes -= 2u * sizeof(uint32_t);
} if (remaining_bytes != 0u) {
__ Ldr(temp, MemOperand(str, offset));
__ Ldr(out, MemOperand(arg, offset));
__ Cmp(temp, out);
__ B(ne, &return_false, /* is_far_target= */ false);
}
} else { // Return true if both strings are empty. Even with string compression `count == 0` means empty.
static_assert(static_cast<uint32_t>(mirror::StringCompressionFlag::kCompressed) == 0u, "Expecting 0=compressed, 1=uncompressed");
__ CompareAndBranchIfZero(temp, &return_true, /* is_far_target= */ false);
if (mirror::kUseStringCompression) { // For string compression, calculate the number of bytes to compare (not chars). // This could in theory exceed INT32_MAX, so treat temp as unsigned.
__ Lsrs(temp, temp, 1u); // Extract length and check compression flag.
ExactAssemblyScope aas(assembler->GetVIXLAssembler(), 2 * kMaxInstructionSizeInBytes,
CodeBufferCheckScope::kMaximumSize);
__ it(cs); // If uncompressed,
__ add(cs, temp, temp, temp); // double the byte count.
}
// Store offset of string value in preparation for comparison loop.
__ Mov(temp1, value_offset);
// Loop to compare strings 4 bytes at a time starting at the front of the string.
__ Bind(&loop);
__ Ldr(out, MemOperand(str, temp1));
__ Ldr(temp2, MemOperand(arg, temp1));
__ Add(temp1, temp1, Operand::From(sizeof(uint32_t)));
__ Cmp(out, temp2);
__ B(ne, &return_false, /* is_far_target= */ false); // With string compression, we have compared 4 bytes, otherwise 2 chars.
__ Subs(temp, temp, mirror::kUseStringCompression ? 4 : 2);
__ B(hi, &loop, /* is_far_target= */ false);
}
// Return true and exit the function. // If loop does not result in returning false, we return true.
__ Bind(&return_true);
__ Mov(out, 1);
__ B(final_label);
// Return false and exit the function.
__ Bind(&return_false);
__ Mov(out, 0);
// Note that the null check must have been done earlier.
DCHECK(!invoke->CanDoImplicitNullCheckOn(invoke->InputAt(0)));
// Check for code points > 0xFFFF. Either a slow-path check when we don't know statically, // or directly dispatch for a large constant, or omit slow-path for a small constant or a char.
SlowPathCodeARMVIXL* slow_path = nullptr;
HInstruction* code_point = invoke->InputAt(1); if (code_point->IsIntConstant()) { if (static_cast<uint32_t>(Int32ConstantFrom(code_point)) >
std::numeric_limits<uint16_t>::max()) { // Always needs the slow-path. We could directly dispatch to it, but this case should be // rare, so for simplicity just put the full slow-path down and branch unconditionally.
slow_path = new (codegen->GetScopedAllocator()) IntrinsicSlowPathARMVIXL(invoke);
codegen->AddSlowPath(slow_path);
__ B(slow_path->GetEntryLabel());
__ Bind(slow_path->GetExitLabel()); return;
}
} elseif (code_point->GetType() != DataType::Type::kUint16) {
vixl32::Register char_reg = InputRegisterAt(invoke, 1); // 0xffff is not modified immediate but 0x10000 is, so use `>= 0x10000` instead of `> 0xffff`.
__ Cmp(char_reg, static_cast<uint32_t>(std::numeric_limits<uint16_t>::max()) + 1);
slow_path = new (codegen->GetScopedAllocator()) IntrinsicSlowPathARMVIXL(invoke);
codegen->AddSlowPath(slow_path);
__ B(hs, slow_path->GetEntryLabel());
}
if (slow_path != nullptr) {
__ Bind(slow_path->GetExitLabel());
}
}
void IntrinsicLocationsBuilderARMVIXL::VisitStringIndexOf(HInvoke* invoke) {
LocationSummary* locations = LocationSummary::Create(
allocator_, invoke, LocationSummary::kCallOnMainAndSlowPath, kIntrinsified); // We have a hand-crafted assembly stub that follows the runtime calling convention. So it's // best to align the inputs accordingly.
InvokeRuntimeCallingConventionARMVIXL calling_convention;
locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0)));
locations->SetInAt(1, LocationFrom(calling_convention.GetRegisterAt(1)));
locations->SetOut(LocationFrom(r0));
// Need to send start-index=0.
locations->AddTemp(LocationFrom(calling_convention.GetRegisterAt(2)));
}
void IntrinsicLocationsBuilderARMVIXL::VisitStringIndexOfAfter(HInvoke* invoke) {
LocationSummary* locations = LocationSummary::Create(
allocator_, invoke, LocationSummary::kCallOnMainAndSlowPath, kIntrinsified); // We have a hand-crafted assembly stub that follows the runtime calling convention. So it's // best to align the inputs accordingly.
InvokeRuntimeCallingConventionARMVIXL calling_convention;
locations->SetInAt(0, LocationFrom(calling_convention.GetRegisterAt(0)));
locations->SetInAt(1, LocationFrom(calling_convention.GetRegisterAt(1)));
locations->SetInAt(2, LocationFrom(calling_convention.GetRegisterAt(2)));
locations->SetOut(LocationFrom(r0));
}
void IntrinsicCodeGeneratorARMVIXL::VisitStringNewStringFromChars(HInvoke* invoke) { // No need to emit code checking whether `locations->InAt(2)` is a null // pointer, as callers of the native method // // java.lang.StringFactory.newStringFromChars(int offset, int charCount, char[] data) // // all include a null check on `data` before calling that method.
codegen_->InvokeRuntime(kQuickAllocStringFromChars, invoke);
CheckEntrypointTypes<kQuickAllocStringFromChars, void*, int32_t, int32_t, void*>();
}
// This value is in bytes and greater than ARRAYCOPY_SHORT_XXX_ARRAY_THRESHOLD // in libcore, so if we choose to jump to the slow path we will end up // in the native implementation. static constexpr int32_t kSystemArrayCopyPrimThreshold = 384;
staticvoid CheckSystemArrayCopyPosition(ArmVIXLAssembler* assembler,
vixl32::Register array,
Location pos,
Location length,
SlowPathCodeARMVIXL* slow_path,
vixl32::Register temp, bool length_is_array_length, bool position_sign_checked) { // Where is the length in the Array? const uint32_t length_offset = mirror::Array::LengthOffset().Uint32Value();
if (pos.IsConstant()) {
int32_t pos_const = Int32ConstantFrom(pos); if (pos_const == 0) { if (!length_is_array_length) { // Check that length(array) >= length.
__ Ldr(temp, MemOperand(array, length_offset));
__ Cmp(temp, OperandFrom(length, DataType::Type::kInt32));
__ B(lt, slow_path->GetEntryLabel());
}
} else { // Calculate length(array) - pos. // Both operands are known to be non-negative `int32_t`, so the difference cannot underflow // as `int32_t`. If the result is negative, the BLT below shall go to the slow path.
__ Ldr(temp, MemOperand(array, length_offset));
__ Sub(temp, temp, pos_const);
// Check that (length(array) - pos) >= length.
__ Cmp(temp, OperandFrom(length, DataType::Type::kInt32));
__ B(lt, slow_path->GetEntryLabel());
}
} elseif (length_is_array_length) { // The only way the copy can succeed is if pos is zero.
vixl32::Register pos_reg = RegisterFrom(pos);
__ CompareAndBranchIfNonZero(pos_reg, slow_path->GetEntryLabel());
} else { // Check that pos >= 0.
vixl32::Register pos_reg = RegisterFrom(pos); if (!position_sign_checked) {
__ Cmp(pos_reg, 0);
__ B(lt, slow_path->GetEntryLabel());
}
// Calculate length(array) - pos. // Both operands are known to be non-negative `int32_t`, so the difference cannot underflow // as `int32_t`. If the result is negative, the BLT below shall go to the slow path.
__ Ldr(temp, MemOperand(array, length_offset));
__ Sub(temp, temp, pos_reg);
// If source and destination are the same, then the copied arrays may overlap. // For overlapping arrays we can only guarantee correctness if `src_pos >= dst_pos`, otherwise // copying the elements at the beginning of source array may clobber the elements at the end. if (!optimizations.GetSourcePositionIsDestinationPosition()) { if (src_pos.IsConstant()) {
int32_t src_pos_constant = Int32ConstantFrom(src_pos); if (dst_pos.IsConstant()) {
int32_t dst_pos_constant = Int32ConstantFrom(dst_pos); if (optimizations.GetDestinationIsSource()) { // Checked when building locations.
DCHECK_GE(src_pos_constant, dst_pos_constant);
} elseif (src_pos_constant < dst_pos_constant) {
__ Cmp(src, dst);
__ B(eq, slow_path->GetEntryLabel());
}
} else { if (!optimizations.GetDestinationIsSource()) {
__ Cmp(src, dst);
__ B(ne, &conditions_on_positions_validated, /* is_far_target= */ false);
}
__ Cmp(RegisterFrom(dst_pos), src_pos_constant);
__ B(gt, slow_path->GetEntryLabel());
}
} else { if (!optimizations.GetDestinationIsSource()) {
__ Cmp(src, dst);
__ B(ne, &conditions_on_positions_validated, /* is_far_target= */ false);
}
__ Cmp(RegisterFrom(src_pos), OperandFrom(dst_pos, DataType::Type::kInt32));
__ B(lt, slow_path->GetEntryLabel());
}
}
__ Bind(&conditions_on_positions_validated);
if (!optimizations.GetSourceIsNotNull()) { // Bail out if the source is null.
__ CompareAndBranchIfZero(src, slow_path->GetEntryLabel());
}
if (!optimizations.GetDestinationIsNotNull() && !optimizations.GetDestinationIsSource()) { // Bail out if the destination is null.
__ CompareAndBranchIfZero(dst, slow_path->GetEntryLabel());
}
// We have already checked in the LocationsBuilder for the constant case. if (!length.IsConstant()) { // Merge the following two comparisons into one: // If the length is negative, bail out (delegate to libcore's native implementation). // If the length > copy_threshold then (currently) prefer libcore's native implementation.
__ Cmp(RegisterFrom(length), copy_threshold);
__ B(hi, slow_path->GetEntryLabel());
} else { // We have already checked in the LocationsBuilder for the constant case.
DCHECK_GE(length.GetConstant()->AsIntConstant()->GetValue(), 0);
DCHECK_LE(length.GetConstant()->AsIntConstant()->GetValue(), copy_threshold);
}
}
SlowPathCodeARMVIXL* slow_path = new (codegen->GetScopedAllocator()) IntrinsicSlowPathARMVIXL(invoke);
codegen->AddSlowPath(slow_path);
// Check that source and position are different, or if they are the same check that copy // direction is backward. Also check for null pointers.
int32_t copy_threshold = kSystemArrayCopyPrimThreshold / DataType::Size(type);
CheckSystemArrayCopyNullOrOverlap(
invoke, assembler, slow_path, src, dst, src_pos, dst_pos, length, copy_threshold);
// Iterate over the arrays and do a raw copy of the chars. const int32_t element_size = DataType::Size(type);
UseScratchRegisterScope temps(assembler->GetVIXLAssembler());
// We split processing of the array in two parts: head and tail. // A first loop handles the head by copying a block of characters per // iteration (see: chars_per_block). // A second loop handles the tail by copying the remaining characters. // If the copy length is not constant, we copy them one-by-one. // If the copy length is constant, we optimize by always unrolling the tail // loop, and also unrolling the head loop when the copy length is small (see: // unroll_threshold). // // Both loops are inverted for better performance, meaning they are // implemented as conditional do-while loops. // Here, the loop condition is first checked to determine if there are // sufficient chars to run an iteration, then we enter the do-while: an // iteration is performed followed by a conditional branch only if another // iteration is necessary. As opposed to a standard while-loop, this inversion // can save some branching (e.g. we don't branch back to the initial condition // at the end of every iteration only to potentially immediately branch // again). // // A full block of chars is subtracted and added before and after the head // loop, respectively. This ensures that any remaining length after each // head loop iteration means there is a full block remaining, reducing the // number of conditional checks required on every iteration.
constexpr int32_t max_stride_in_bytes = 8;
constexpr int32_t unroll_threshold = 2 * max_stride_in_bytes;
DCHECK_EQ(max_stride_in_bytes % element_size, 0);
int32_t elements_per_block = max_stride_in_bytes / element_size;
vixl::aarch32::Label loop1, loop2, pre_loop2, done;
// We choose to use the native implementation for longer copy lengths. static constexpr int32_t kSystemArrayCopyThreshold = 128;
void IntrinsicLocationsBuilderARMVIXL::VisitSystemArrayCopy(HInvoke* invoke) { // The only read barrier implementation supporting the // SystemArrayCopy intrinsic is the Baker-style read barriers. if (codegen_->EmitNonBakerReadBarrier()) { return;
}
constexpr size_t kInitialNumTemps = 3u; // We need at least three temps.
LocationSummary* locations = CodeGenerator::CreateSystemArrayCopyLocationSummary(
invoke, kSystemArrayCopyThreshold, kInitialNumTemps); if (locations != nullptr) {
locations->SetInAt(1, LocationForSystemArrayCopyInput(assembler_, invoke->InputAt(1)));
locations->SetInAt(3, LocationForSystemArrayCopyInput(assembler_, invoke->InputAt(3)));
locations->SetInAt(4, LocationForSystemArrayCopyInput(assembler_, invoke->InputAt(4))); if (codegen_->EmitBakerReadBarrier()) { // Temporary register IP cannot be used in // ReadBarrierSystemArrayCopySlowPathARM (because that register // is clobbered by ReadBarrierMarkRegX entry points). Get an extra // temporary register from the register allocator.
locations->AddTemp(Location::RequiresCoreRegister());
}
}
}
void IntrinsicCodeGeneratorARMVIXL::VisitSystemArrayCopy(HInvoke* invoke) { // The only read barrier implementation supporting the // SystemArrayCopy intrinsic is the Baker-style read barriers.
DCHECK_IMPLIES(codegen_->EmitReadBarrier(), kUseBakerReadBarrier);
SlowPathCodeARMVIXL* intrinsic_slow_path = new (codegen_->GetScopedAllocator()) IntrinsicSlowPathARMVIXL(invoke);
codegen_->AddSlowPath(intrinsic_slow_path);
// Check that source and position are different, or if they are the same check that copy // direction is backward. Also check for null pointers.
CheckSystemArrayCopyNullOrOverlap(invoke,
assembler,
intrinsic_slow_path,
src,
dest,
src_pos,
dest_pos,
length,
kSystemArrayCopyThreshold);
// Check that source position is within bounds.
CheckSystemArrayCopyPosition(assembler,
src,
src_pos,
length,
intrinsic_slow_path,
temp1,
optimizations.GetCountIsSourceLength(), /*position_sign_checked=*/ false);
// Check that destination position is within bounds. bool dest_position_sign_checked = optimizations.GetSourcePositionIsDestinationPosition();
CheckSystemArrayCopyPosition(assembler,
dest,
dest_pos,
length,
intrinsic_slow_path,
temp1,
optimizations.GetCountIsDestinationLength(),
dest_position_sign_checked);
auto check_non_primitive_array_class = [&](vixl32::Register klass, vixl32::Register temp) { // No read barrier is needed for reading a chain of constant references for comparing // with null, or for reading a constant primitive value, see `ReadBarrierOption`. // /* HeapReference<Class> */ temp = klass->component_type_
__ Ldr(temp, MemOperand(klass, component_offset));
codegen_->GetAssembler()->MaybeUnpoisonHeapReference(temp); // Check that the component type is not null.
__ CompareAndBranchIfZero(temp, intrinsic_slow_path->GetEntryLabel()); // Check that the component type is not a primitive. // /* uint16_t */ temp = static_cast<uint16>(klass->primitive_type_);
__ Ldrh(temp, MemOperand(temp, primitive_offset));
static_assert(Primitive::kPrimNot == 0, "Expected 0 for kPrimNot");
__ CompareAndBranchIfNonZero(temp, intrinsic_slow_path->GetEntryLabel());
};
if (!optimizations.GetDoesNotNeedTypeCheck()) { // Check whether all elements of the source array are assignable to the component // type of the destination array. We do two checks: the classes are the same, // or the destination is Object[]. If none of these checks succeed, we go to the // slow path.
if (codegen_->EmitBakerReadBarrier()) { // /* HeapReference<Class> */ temp1 = dest->klass_
codegen_->GenerateFieldLoadWithBakerReadBarrier(
invoke, temp1_loc, dest, class_offset, temp2_loc, /* needs_null_check= */ false); // Register `temp1` is not trashed by the read barrier emitted // by GenerateFieldLoadWithBakerReadBarrier below, as that // method produces a call to a ReadBarrierMarkRegX entry point, // which saves all potentially live registers, including // temporaries such a `temp1`. // /* HeapReference<Class> */ temp2 = src->klass_
codegen_->GenerateFieldLoadWithBakerReadBarrier(
invoke, temp2_loc, src, class_offset, temp3_loc, /* needs_null_check= */ false);
} else { // /* HeapReference<Class> */ temp1 = dest->klass_
__ Ldr(temp1, MemOperand(dest, class_offset));
assembler->MaybeUnpoisonHeapReference(temp1); // /* HeapReference<Class> */ temp2 = src->klass_
__ Ldr(temp2, MemOperand(src, class_offset));
assembler->MaybeUnpoisonHeapReference(temp2);
}
__ Cmp(temp1, temp2); if (optimizations.GetDestinationIsTypedObjectArray()) {
DCHECK(optimizations.GetDestinationIsNonPrimitiveArray());
vixl32::Label do_copy; // For class match, we can skip the source type check regardless of the optimization flag.
__ B(eq, &do_copy, /* is_far_target= */ false); // No read barrier is needed for reading a chain of constant references // for comparing with null, see `ReadBarrierOption`. // /* HeapReference<Class> */ temp1 = temp1->component_type_
__ Ldr(temp1, MemOperand(temp1, component_offset));
assembler->MaybeUnpoisonHeapReference(temp1); // /* HeapReference<Class> */ temp1 = temp1->super_class_
__ Ldr(temp1, MemOperand(temp1, super_offset)); // No need to unpoison the result, we're comparing against null.
__ CompareAndBranchIfNonZero(temp1, intrinsic_slow_path->GetEntryLabel()); // Bail out if the source is not a non primitive array. if (!optimizations.GetSourceIsNonPrimitiveArray()) {
check_non_primitive_array_class(temp2, temp2);
}
__ Bind(&do_copy);
} else {
DCHECK(!optimizations.GetDestinationIsTypedObjectArray()); // For class match, we can skip the array type check completely if at least one of source // and destination is known to be a non primitive array, otherwise one check is enough.
__ B(ne, intrinsic_slow_path->GetEntryLabel()); if (!optimizations.GetDestinationIsNonPrimitiveArray() &&
!optimizations.GetSourceIsNonPrimitiveArray()) {
check_non_primitive_array_class(temp2, temp2);
}
}
} elseif (!optimizations.GetSourceIsNonPrimitiveArray()) {
DCHECK(optimizations.GetDestinationIsNonPrimitiveArray()); // Bail out if the source is not a non primitive array. // No read barrier is needed for reading a chain of constant references for comparing // with null, or for reading a constant primitive value, see `ReadBarrierOption`. // /* HeapReference<Class> */ temp2 = src->klass_
__ Ldr(temp2, MemOperand(src, class_offset));
assembler->MaybeUnpoisonHeapReference(temp2);
check_non_primitive_array_class(temp2, temp2);
}
if (length.IsConstant() && Int32ConstantFrom(length) == 0) { // Null constant length: not need to emit the loop code at all.
} else {
vixl32::Label skip_copy_and_write_barrier; if (length.IsCoreRegister()) { // Don't enter the copy loop if the length is null.
__ CompareAndBranchIfZero(
RegisterFrom(length), &skip_copy_and_write_barrier, /* is_far_target= */ false);
}
const DataType::Type type = DataType::Type::kReference; const int32_t element_size = DataType::Size(type);
SlowPathCodeARMVIXL* read_barrier_slow_path = nullptr;
vixl32::Register rb_tmp; bool emit_rb = codegen_->EmitBakerReadBarrier(); if (emit_rb) { // TODO: Also convert this intrinsic to the IsGcMarking strategy?
// SystemArrayCopy implementation for Baker read barriers (see // also CodeGeneratorARMVIXL::GenerateReferenceLoadWithBakerReadBarrier): // // uint32_t rb_state = Lockword(src->monitor_).ReadBarrierState(); // lfence; // Load fence or artificial data dependency to prevent load-load reordering // bool is_gray = (rb_state == ReadBarrier::GrayState()); // if (is_gray) { // // Slow-path copy. // do { // *dest_ptr++ = MaybePoison(ReadBarrier::Mark(MaybeUnpoison(*src_ptr++))); // } while (src_ptr != end_ptr) // } else { // // Fast-path copy. // do { // *dest_ptr++ = *src_ptr++; // } while (src_ptr != end_ptr) // }
// /* int32_t */ monitor = src->monitor_
rb_tmp = RegisterFrom(locations->GetTemp(3));
__ Ldr(rb_tmp, MemOperand(src, monitor_offset)); // /* LockWord */ lock_word = LockWord(monitor)
static_assert(sizeof(LockWord) == sizeof(int32_t), "art::LockWord and int32_t have different sizes.");
// Introduce a dependency on the lock_word including the rb_state, // which shall prevent load-load reordering without using // a memory barrier (which would be more expensive). // `src` is unchanged by this operation, but its value now depends // on `temp2`.
__ Add(src, src, Operand(rb_tmp, vixl32::LSR, 32));
// Slow path used to copy array when `src` is gray. // Note that the base destination address is computed in `temp2` // by the slow path code.
read_barrier_slow_path = new (codegen_->GetScopedAllocator()) ReadBarrierSystemArrayCopySlowPathARMVIXL(invoke);
codegen_->AddSlowPath(read_barrier_slow_path);
}
// Compute the base source address, base destination address and end source address in // `temp1`, `temp2` and `temp3` respectively. // Note that for read barrier, `temp1` (the base source address) is computed from `src` // (and `src_pos`) here, and thus honors the artificial dependency of `src` on `rb_tmp`.
GenSystemArrayCopyAddresses(assembler,
type,
src,
src_pos,
dest,
dest_pos,
length,
temp1,
temp2,
temp3);
if (emit_rb) { // Given the numeric representation, it's enough to check the low bit of the // rb_state. We do that by shifting the bit out of the lock word with LSRS // which can be a 16-bit instruction unlike the TST immediate.
static_assert(ReadBarrier::NonGrayState() == 0, "Expecting non-gray to have value 0");
static_assert(ReadBarrier::GrayState() == 1, "Expecting gray to have value 1");
DCHECK(rb_tmp.IsValid());
__ Lsrs(rb_tmp, rb_tmp, LockWord::kReadBarrierStateShift + 1); // Carry flag is the last bit shifted out by LSRS.
__ B(cs, read_barrier_slow_path->GetEntryLabel());
}
// Iterate over the arrays and do a raw copy of the objects. We don't need to // poison/unpoison.
vixl32::Label loop;
__ Bind(&loop);
{
UseScratchRegisterScope temps(assembler->GetVIXLAssembler()); const vixl32::Register temp_reg = temps.Acquire();
__ Ldr(temp_reg, MemOperand(temp1, element_size, PostIndex));
__ Str(temp_reg, MemOperand(temp2, element_size, PostIndex));
}
__ Cmp(temp1, temp3);
__ B(ne, &loop, /* is_far_target= */ false);
if (emit_rb) {
DCHECK(read_barrier_slow_path != nullptr);
__ Bind(read_barrier_slow_path->GetExitLabel());
}
// We only need one card marking on the destination array.
codegen_->MarkGCCard(temp1, temp2, dest);
__ Bind(&skip_copy_and_write_barrier);
}
__ Bind(intrinsic_slow_path->GetExitLabel());
}
staticvoid CreateFPToFPCallLocations(ArenaAllocator* allocator, HInvoke* invoke) { // If the graph is debuggable, all callee-saved floating-point registers are blocked by // the code generator. Furthermore, the register allocator creates fixed live intervals // for all caller-saved registers because we are doing a function call. As a result, if // the input and output locations are unallocated, the register allocator runs out of // registers and fails; however, a debuggable graph is not the common case. if (invoke->GetBlock()->GetGraph()->IsDebuggable()) { return;
}
locations->SetInAt(0, Location::RequiresFpuRegister());
locations->SetOut(Location::RequiresFpuRegister()); // Native code uses the soft float ABI.
locations->AddTemp(LocationFrom(calling_convention.GetRegisterAt(0)));
locations->AddTemp(LocationFrom(calling_convention.GetRegisterAt(1)));
}
staticvoid CreateFPFPToFPCallLocations(ArenaAllocator* allocator, HInvoke* invoke) { // If the graph is debuggable, all callee-saved floating-point registers are blocked by // the code generator. Furthermore, the register allocator creates fixed live intervals // for all caller-saved registers because we are doing a function call. As a result, if // the input and output locations are unallocated, the register allocator runs out of // registers and fails; however, a debuggable graph is not the common case. if (invoke->GetBlock()->GetGraph()->IsDebuggable()) { return;
}
// Move data from core register(s) to temp D-reg for bit count calculation, then move back. // According to Cortex A57 and A72 optimization guides, compared to transferring to full D-reg, // transferring data from core reg to upper or lower half of vfp D-reg requires extra latency, // That's why for integer bit count, we use 'vmov d0, r0, r0' instead of 'vmov d0[0], r0'.
__ Vmov(tmp_d, src_1, src_0); // Temp DReg |--src_1|--src_0|
__ Vcnt(Untyped8, tmp_d, tmp_d); // Temp DReg |c|c|c|c|c|c|c|c|
__ Vpaddl(U8, tmp_d, tmp_d); // Temp DReg |--c|--c|--c|--c|
__ Vpaddl(U16, tmp_d, tmp_d); // Temp DReg |------c|------c| if (is_long) {
__ Vpaddl(U32, tmp_d, tmp_d); // Temp DReg |--------------c|
}
__ Vmov(out_r, tmp_s);
}
// Discard result for lowest 32 bits if highest 32 bits are not zero. // Since IT blocks longer than a 16-bit instruction are deprecated by ARMv8, // we check that the output is in a low register, so that a 16-bit MOV // encoding can be used. If output is in a high register, then we generate // 4 more bytes of code to avoid a branch.
Operand mov_src(0); if (!out_reg_lo.IsLow()) {
__ Mov(LeaveFlags, temp, 0);
mov_src = Operand(temp);
}
ExactAssemblyScope it_scope(codegen->GetVIXLAssembler(), 2 * vixl32::k16BitT32InstructionSizeInBytes,
CodeBufferCheckScope::kExactSize);
__ it(ne);
__ mov(ne, out_reg_lo, mov_src);
} else {
vixl32::Register out = OutputRegister(invoke);
vixl32::Register in = InputRegisterAt(invoke, 0);
__ Rsb(out_reg_hi, in_reg_hi, 0);
__ Rsb(out_reg_lo, in_reg_lo, 0);
__ And(out_reg_hi, out_reg_hi, in_reg_hi); // The result of this operation is 0 iff in_reg_lo is 0
__ Ands(out_reg_lo, out_reg_lo, in_reg_lo);
// Discard result for highest 32 bits if lowest 32 bits are not zero. // Since IT blocks longer than a 16-bit instruction are deprecated by ARMv8, // we check that the output is in a low register, so that a 16-bit MOV // encoding can be used. If output is in a high register, then we generate // 4 more bytes of code to avoid a branch.
Operand mov_src(0); if (!out_reg_lo.IsLow()) {
__ Mov(LeaveFlags, temp, 0);
mov_src = Operand(temp);
}
ExactAssemblyScope it_scope(codegen->GetVIXLAssembler(), 2 * vixl32::k16BitT32InstructionSizeInBytes,
CodeBufferCheckScope::kExactSize);
__ it(ne);
__ mov(ne, out_reg_hi, mov_src);
} else {
vixl32::Register out = OutputRegister(invoke);
vixl32::Register in = InputRegisterAt(invoke, 0);
temp = temps.Acquire(); // Save repairing the value of num_chr on the < 4 character path.
__ Subs(temp, num_chr, 4);
__ B(lt, &remainder, /* is_far_target= */ false);
// Keep the result of the earlier subs, we are going to fetch at least 4 characters.
__ Mov(num_chr, temp);
// Main loop used for longer fetches loads and stores 4x16-bit characters at a time. // (LDRD/STRD fault on unaligned addresses and it's not worth inlining extra code // to rectify these everywhere this intrinsic applies.)
__ Bind(&loop);
__ Ldr(temp, MemOperand(src_ptr, char_size * 2));
__ Subs(num_chr, num_chr, 4);
__ Str(temp, MemOperand(dst_ptr, char_size * 2));
__ Ldr(temp, MemOperand(src_ptr, char_size * 4, PostIndex));
__ Str(temp, MemOperand(dst_ptr, char_size * 4, PostIndex));
temps.Release(temp);
__ B(ge, &loop, /* is_far_target= */ false);
// Main loop for < 4 character case and remainder handling. Loads and stores one // 16-bit Java character at a time.
__ Bind(&remainder);
temp = temps.Acquire();
__ Ldrh(temp, MemOperand(src_ptr, char_size, PostIndex));
__ Subs(num_chr, num_chr, 1);
__ Strh(temp, MemOperand(dst_ptr, char_size, PostIndex));
temps.Release(temp);
__ B(gt, &remainder, /* is_far_target= */ false);
if (mirror::kUseStringCompression) {
__ B(final_label);
void IntrinsicCodeGeneratorARMVIXL::VisitFloatIsInfinite(HInvoke* invoke) {
ArmVIXLAssembler* const assembler = GetAssembler(); const vixl32::Register out = OutputRegister(invoke); // Shifting left by 1 bit makes the value encodable as an immediate operand; // we don't care about the sign bit anyway.
constexpr uint32_t infinity = kPositiveInfinityFloat << 1U;
__ Vmov(out, InputSRegisterAt(invoke, 0)); // We don't care about the sign bit, so shift left.
__ Lsl(out, out, 1);
__ Eor(out, out, infinity);
codegen_->GenerateConditionWithZero(kCondEQ, out, out);
}
void IntrinsicCodeGeneratorARMVIXL::VisitDoubleIsInfinite(HInvoke* invoke) {
ArmVIXLAssembler* const assembler = GetAssembler(); const vixl32::Register out = OutputRegister(invoke);
UseScratchRegisterScope temps(assembler->GetVIXLAssembler()); const vixl32::Register temp = temps.Acquire(); // The highest 32 bits of double precision positive infinity separated into // two constants encodable as immediate operands.
constexpr uint32_t infinity_high = 0x7f000000U;
constexpr uint32_t infinity_high2 = 0x00f00000U;
static_assert((infinity_high | infinity_high2) == static_cast<uint32_t>(kPositiveInfinityDouble >> 32U), "The constants do not add up to the high 32 bits of double " "precision positive infinity.");
__ Vmov(temp, out, InputDRegisterAt(invoke, 0));
__ Eor(out, out, infinity_high);
__ Eor(out, out, infinity_high2); // We don't care about the sign bit, so shift left.
__ Orr(out, temp, Operand(out, vixl32::LSL, 1));
codegen_->GenerateConditionWithZero(kCondEQ, out, out);
}
vixl32::Register out = RegisterFrom(locations->Out());
UseScratchRegisterScope temps(assembler->GetVIXLAssembler());
vixl32::Register temp = temps.Acquire(); auto allocate_instance = [&]() {
DCHECK(out.Is(InvokeRuntimeCallingConventionARMVIXL().GetRegisterAt(0)));
codegen_->LoadIntrinsicDeclaringClass(out, invoke);
codegen_->InvokeRuntime(kQuickAllocObjectInitialized, invoke);
CheckEntrypointTypes<kQuickAllocObjectWithChecks, void*, mirror::Class*>();
}; if (invoke->InputAt(0)->IsIntConstant()) {
int32_t value = invoke->InputAt(0)->AsIntConstant()->GetValue(); if (static_cast<uint32_t>(value - info.low) < info.length) { // Just embed the object in the code.
DCHECK_NE(info.value_boot_image_reference, ValueOfInfo::kInvalidReference);
codegen_->LoadBootImageAddress(out, info.value_boot_image_reference);
} else {
DCHECK(locations->CanCall()); // Allocate and initialize a new object. // TODO: If we JIT, we could allocate the object now, and store it in the // JIT object table.
allocate_instance();
__ Mov(temp, value);
assembler->StoreToOffset(GetStoreOperandType(type), temp, out, info.value_offset); // Class pointer and `value` final field stores require a barrier before publication.
codegen_->GenerateMemoryBarrier(MemBarrierKind::kStoreStore);
}
} else {
DCHECK(locations->CanCall());
vixl32::Register in = RegisterFrom(locations->InAt(0)); // Check bounds of our cache.
__ Add(out, in, -info.low);
__ Cmp(out, info.length);
vixl32::Label allocate, done;
__ B(hs, &allocate, /* is_far_target= */ false); // If the value is within the bounds, load the object directly from the array.
codegen_->LoadBootImageAddress(temp, info.array_data_boot_image_reference);
codegen_->LoadFromShiftedRegOffset(DataType::Type::kReference, locations->Out(), temp, out);
assembler->MaybeUnpoisonHeapReference(out);
__ B(&done);
__ Bind(&allocate); // Otherwise allocate and initialize a new object.
allocate_instance();
assembler->StoreToOffset(GetStoreOperandType(type), in, out, info.value_offset); // Class pointer and `value` final field stores require a barrier before publication.
codegen_->GenerateMemoryBarrier(MemBarrierKind::kStoreStore);
__ Bind(&done);
}
}
{ // Ensure that between load and MaybeRecordImplicitNullCheck there are no pools emitted. // Loading scratch register always uses 32-bit encoding.
vixl::ExactAssemblyScope eas(assembler->GetVIXLAssembler(),
vixl32::k32BitT32InstructionSizeInBytes);
__ ldr(tmp, MemOperand(obj, referent_offset));
codegen_->MaybeRecordImplicitNullCheck(invoke);
}
assembler->MaybeUnpoisonHeapReference(tmp);
codegen_->GenerateMemoryBarrier(MemBarrierKind::kLoadAny); // `referent` is volatile.
if (codegen_->EmitReadBarrier()) {
DCHECK(kUseBakerReadBarrier);
vixl32::Label calculate_result;
__ Subs(out, tmp, other);
__ B(eq, &calculate_result); // `out` is 0 if taken.
// Check if the loaded reference is null.
__ Cmp(tmp, 0);
__ B(eq, &calculate_result); // `out` is not 0 if taken.
// For correct memory visibility, we need a barrier before loading the lock word // but we already have the barrier emitted for volatile load above which is sufficient.
// Load the lockword and check if it is a forwarding address.
static_assert(LockWord::kStateShift == 30u);
static_assert(LockWord::kStateForwardingAddress == 3u);
__ Ldr(tmp, MemOperand(tmp, monitor_offset));
__ Cmp(tmp, Operand(0xc0000000));
__ B(lo, &calculate_result); // `out` is not 0 if taken.
// Extract the forwarding address and subtract from `other`.
__ Sub(out, other, Operand(tmp, LSL, LockWord::kForwardingAddressShift));
// Convert 0 to 1 and non-zero to 0 for the Boolean result (`out = (out == 0)`).
__ Clz(out, out);
__ Lsr(out, out, WhichPowerOf2(out.GetSizeInBits()));
}
// Check if divisor is zero, bail to managed implementation to handle.
SlowPathCodeARMVIXL* slow_path = new (codegen_->GetScopedAllocator()) IntrinsicSlowPathARMVIXL(invoke);
codegen_->AddSlowPath(slow_path);
__ CompareAndBranchIfZero(divisor, slow_path->GetEntryLabel());
ArmVIXLAssembler* assembler = codegen->GetAssembler();
MemOperand address(base); if (offset.IsValid()) { // If offset is valid then this is a get from a relative address.
address = MemOperand(base, offset);
}
switch (type) { case DataType::Type::kBool:
__ Ldrb(RegisterFrom(out), address); break; case DataType::Type::kInt8:
__ Ldrsb(RegisterFrom(out), address); break; case DataType::Type::kUint16:
__ Ldrh(RegisterFrom(out), address); break; case DataType::Type::kInt16:
__ Ldrsh(RegisterFrom(out), address); break; case DataType::Type::kInt32:
__ Ldr(RegisterFrom(out), address); break; case DataType::Type::kInt64: { if (Use64BitExclusiveLoadStore(atomic, codegen)) {
UseScratchRegisterScope temps(assembler->GetVIXLAssembler()); if (offset.IsValid()) {
vixl32::Register temp_reg = temps.Acquire();
__ Add(temp_reg, base, offset);
address = MemOperand(temp_reg);
}
staticvoid EmitLoadExclusive(CodeGeneratorARMVIXL* codegen,
DataType::Type type,
vixl32::Register ptr,
Location old_value) {
ArmVIXLAssembler* assembler = codegen->GetAssembler(); switch (type) { case DataType::Type::kBool: case DataType::Type::kInt8:
__ Ldrexb(RegisterFrom(old_value), MemOperand(ptr)); break; case DataType::Type::kUint16: case DataType::Type::kInt16:
__ Ldrexh(RegisterFrom(old_value), MemOperand(ptr)); break; case DataType::Type::kInt32: case DataType::Type::kReference:
__ Ldrex(RegisterFrom(old_value), MemOperand(ptr)); break; case DataType::Type::kInt64:
__ Ldrexd(LowRegisterFrom(old_value), HighRegisterFrom(old_value), MemOperand(ptr)); break; default:
LOG(FATAL) << "Unexpected type: " << type;
UNREACHABLE();
} switch (type) { case DataType::Type::kInt8:
__ Sxtb(RegisterFrom(old_value), RegisterFrom(old_value)); break; case DataType::Type::kInt16:
__ Sxth(RegisterFrom(old_value), RegisterFrom(old_value)); break; case DataType::Type::kReference:
assembler->MaybeUnpoisonHeapReference(RegisterFrom(old_value)); break; default: break;
}
}
staticvoid EmitStoreExclusive(CodeGeneratorARMVIXL* codegen,
DataType::Type type,
vixl32::Register ptr,
vixl32::Register store_result,
Location new_value) {
ArmVIXLAssembler* assembler = codegen->GetAssembler(); if (type == DataType::Type::kReference) {
assembler->MaybePoisonHeapReference(RegisterFrom(new_value));
} switch (type) { case DataType::Type::kBool: case DataType::Type::kInt8:
__ Strexb(store_result, RegisterFrom(new_value), MemOperand(ptr)); break; case DataType::Type::kUint16: case DataType::Type::kInt16:
__ Strexh(store_result, RegisterFrom(new_value), MemOperand(ptr)); break; case DataType::Type::kInt32: case DataType::Type::kReference:
__ Strex(store_result, RegisterFrom(new_value), MemOperand(ptr)); break; case DataType::Type::kInt64:
__ Strexd(
store_result, LowRegisterFrom(new_value), HighRegisterFrom(new_value), MemOperand(ptr)); break; default:
LOG(FATAL) << "Unexpected type: " << type;
UNREACHABLE();
} if (type == DataType::Type::kReference) {
assembler->MaybeUnpoisonHeapReference(RegisterFrom(new_value));
}
}
staticvoid GenerateCompareAndSet(CodeGeneratorARMVIXL* codegen,
DataType::Type type, bool strong,
vixl32::Label* cmp_failure, bool cmp_failure_is_far_target,
vixl32::Register ptr,
Location expected,
Location new_value,
Location old_value,
vixl32::Register store_result,
vixl32::Register success) { // For kReference, the `expected` shall be a register pair when called from a read barrier // slow path, specifying both the original `expected` as well as the unmarked old value from // the main path attempt to emit CAS when it matched `expected` after marking. // Otherwise the type of `expected` shall match the type of `new_value` and `old_value`. if (type == DataType::Type::kInt64) {
DCHECK(expected.IsCoreRegisterPair());
DCHECK(new_value.IsCoreRegisterPair());
DCHECK(old_value.IsCoreRegisterPair());
} else {
DCHECK(expected.IsCoreRegister() ||
(type == DataType::Type::kReference && expected.IsCoreRegisterPair()));
DCHECK(new_value.IsCoreRegister());
DCHECK(old_value.IsCoreRegister()); // Make sure the unmarked old value for reference CAS slow path is not clobbered by STREX.
DCHECK(!expected.Contains(LocationFrom(store_result)));
}
// do { // old_value = [ptr]; // Load exclusive. // if (old_value != expected) goto cmp_failure; // store_result = failed([ptr] <- new_value); // Store exclusive. // } while (strong && store_result); // // If `success` is a valid register, there are additional instructions in the above code // to report success with value 1 and failure with value 0 in that register.
vixl32::Label loop_head; if (strong) {
__ Bind(&loop_head);
}
EmitLoadExclusive(codegen, type, ptr, old_value); // We do not need to initialize the failure code for comparison failure if the // branch goes to the read barrier slow path that clobbers `success` anyway. bool init_failure_for_cmp =
success.IsValid() &&
!(type == DataType::Type::kReference &&
codegen->EmitReadBarrier() &&
expected.IsCoreRegister()); // Instruction scheduling: Loading a constant between LDREX* and using the loaded value // is essentially free, so prepare the failure value here if we can. bool init_failure_for_cmp_early =
init_failure_for_cmp && !old_value.Contains(LocationFrom(success)); if (init_failure_for_cmp_early) {
__ Mov(success, 0); // Indicate failure if the comparison fails.
} if (type == DataType::Type::kInt64) {
__ Cmp(LowRegisterFrom(old_value), LowRegisterFrom(expected));
ExactAssemblyScope aas(assembler->GetVIXLAssembler(), 2 * k16BitT32InstructionSizeInBytes);
__ it(eq);
__ cmp(eq, HighRegisterFrom(old_value), HighRegisterFrom(expected));
} elseif (expected.IsCoreRegisterPair()) {
DCHECK_EQ(type, DataType::Type::kReference);
DCHECK(!expected.Contains(old_value)); // Check if the loaded value matches any of the two registers in `expected`.
__ Cmp(RegisterFrom(old_value), LowRegisterFrom(expected));
ExactAssemblyScope aas(assembler->GetVIXLAssembler(), 2 * k16BitT32InstructionSizeInBytes);
__ it(ne);
__ cmp(ne, RegisterFrom(old_value), HighRegisterFrom(expected));
} else {
__ Cmp(RegisterFrom(old_value), RegisterFrom(expected));
} if (init_failure_for_cmp && !init_failure_for_cmp_early) {
__ Mov(LeaveFlags, success, 0); // Indicate failure if the comparison fails.
}
__ B(ne, cmp_failure, /*is_far_target=*/ cmp_failure_is_far_target);
EmitStoreExclusive(codegen, type, ptr, store_result, new_value); if (strong) { // Instruction scheduling: Loading a constant between STREX* and using its result // is essentially free, so prepare the success value here if needed and possible. if (success.IsValid() && !success.Is(store_result)) {
__ Mov(success, 1); // Indicate success if the store succeeds.
}
__ Cmp(store_result, 0); if (success.IsValid() && success.Is(store_result)) {
__ Mov(LeaveFlags, success, 1); // Indicate success if the store succeeds.
}
__ B(ne, &loop_head, /*is_far_target=*/ false);
} else { // Weak CAS (VarHandle.CompareAndExchange variants) always indicates success.
DCHECK(success.IsValid()); // Flip the `store_result` to indicate success by 1 and failure by 0.
__ Eor(success, store_result, 1);
}
}
class ReadBarrierCasSlowPathARMVIXL : public SlowPathCodeARMVIXL { public: explicit ReadBarrierCasSlowPathARMVIXL(HInvoke* invoke, bool strong,
vixl32::Register base,
vixl32::Register offset,
vixl32::Register expected,
vixl32::Register new_value,
vixl32::Register old_value,
vixl32::Register old_value_temp,
vixl32::Register store_result,
vixl32::Register success,
CodeGeneratorARMVIXL* arm_codegen)
: SlowPathCodeARMVIXL(invoke),
strong_(strong),
base_(base),
offset_(offset),
expected_(expected),
new_value_(new_value),
old_value_(old_value),
old_value_temp_(old_value_temp),
store_result_(store_result),
success_(success),
mark_old_value_slow_path_(nullptr),
update_old_value_slow_path_(nullptr) { if (!kUseBakerReadBarrier) { // We need to add the slow path now, it is too late when emitting slow path code.
mark_old_value_slow_path_ = arm_codegen->AddReadBarrierSlowPath(
invoke,
Location::CoreRegister(old_value_temp.GetCode()),
Location::CoreRegister(old_value.GetCode()),
Location::CoreRegister(base.GetCode()), /*offset=*/ 0u, /*index=*/ Location::CoreRegister(offset.GetCode())); if (!success.IsValid()) {
update_old_value_slow_path_ = arm_codegen->AddReadBarrierSlowPath(
invoke,
Location::CoreRegister(old_value.GetCode()),
Location::CoreRegister(old_value_temp.GetCode()),
Location::CoreRegister(base.GetCode()), /*offset=*/ 0u, /*index=*/ Location::CoreRegister(offset.GetCode()));
}
}
}
// Mark the `old_value_` from the main path and compare with `expected_`. if (kUseBakerReadBarrier) {
DCHECK(mark_old_value_slow_path_ == nullptr);
arm_codegen->GenerateIntrinsicMoveWithBakerReadBarrier(old_value_temp_, old_value_);
} else {
DCHECK(mark_old_value_slow_path_ != nullptr);
__ B(mark_old_value_slow_path_->GetEntryLabel());
__ Bind(mark_old_value_slow_path_->GetExitLabel());
}
__ Cmp(old_value_temp_, expected_); if (success_.IsValid()) {
__ Mov(LeaveFlags, success_, 0); // Indicate failure if we take the branch out.
} else { // In case of failure, update the `old_value_` with the marked reference.
ExactAssemblyScope aas(assembler->GetVIXLAssembler(), 2 * k16BitT32InstructionSizeInBytes);
__ it(ne);
__ mov(ne, old_value_, old_value_temp_);
}
__ B(ne, GetExitLabel());
// The old value we have read did not match `expected` (which is always a to-space // reference) but after the read barrier the marked to-space value matched, so the // old value must be a from-space reference to the same object. Do the same CAS loop // as the main path but check for both `expected` and the unmarked old value // representing the to-space and from-space references for the same object.
// Recalculate the `tmp_ptr` clobbered above.
__ Add(tmp_ptr, base_, offset_);
vixl32::Label mark_old_value;
GenerateCompareAndSet(arm_codegen,
DataType::Type::kReference,
strong_, /*cmp_failure=*/ success_.IsValid() ? GetExitLabel() : &mark_old_value, /*cmp_failure_is_far_target=*/ success_.IsValid(),
tmp_ptr, /*expected=*/ LocationFrom(expected_, old_value_), /*new_value=*/ LocationFrom(new_value_), /*old_value=*/ LocationFrom(old_value_temp_),
store_result_,
success_); if (!success_.IsValid()) { // To reach this point, the `old_value_temp_` must be either a from-space or a to-space // reference of the `expected_` object. Update the `old_value_` to the to-space reference.
__ Mov(old_value_, expected_);
}
__ B(GetExitLabel());
if (!success_.IsValid()) {
__ Bind(&mark_old_value); if (kUseBakerReadBarrier) {
DCHECK(update_old_value_slow_path_ == nullptr);
arm_codegen->GenerateIntrinsicMoveWithBakerReadBarrier(old_value_, old_value_temp_);
} else { // Note: We could redirect the `failure` above directly to the entry label and bind // the exit label in the main path, but the main path would need to access the // `update_old_value_slow_path_`. To keep the code simple, keep the extra jumps.
DCHECK(update_old_value_slow_path_ != nullptr);
__ B(update_old_value_slow_path_->GetEntryLabel());
__ Bind(update_old_value_slow_path_->GetExitLabel());
}
__ B(GetExitLabel());
}
}
// Temporary register used in CAS. In the object case (UnsafeCASObject intrinsic), // this is also used for card-marking, and possibly for read barrier.
locations->AddTemp(Location::RequiresCoreRegister());
}
if (type == DataType::Type::kReference) { // Mark card for object assuming new value is stored. Worst case we will mark an unchanged // object and scan the receiver at the next GC for nothing. bool value_can_be_null = true; // TODO: Worth finding out this information?
codegen->MaybeMarkGCCard(tmp_ptr, tmp, base, new_value, value_can_be_null);
}
if (type == DataType::Type::kReference && codegen->EmitReadBarrier()) { // If marking, check if the stored reference is a from-space reference to the same // object as the to-space reference `expected`. If so, perform a custom CAS loop.
ReadBarrierCasSlowPathARMVIXL* slow_path = new (codegen->GetScopedAllocator()) ReadBarrierCasSlowPathARMVIXL(
invoke, /*strong=*/ true,
base,
offset,
expected,
new_value, /*old_value=*/ tmp, /*old_value_temp=*/ out, /*store_result=*/ out, /*success=*/ out,
codegen);
codegen->AddSlowPath(slow_path);
exit_loop = slow_path->GetExitLabel();
cmp_failure = slow_path->GetEntryLabel();
}
Location loaded_value;
Location new_value; switch (get_and_update_op) { case GetAndUpdateOp::kSet:
loaded_value = old_value;
new_value = arg; break; case GetAndUpdateOp::kAddWithByteSwap: if (old_value.IsCoreRegisterPair()) { // To avoid register overlap when reversing bytes, load into temps.
DCHECK(maybe_temp.IsCoreRegisterPair());
loaded_value = maybe_temp;
new_value = loaded_value; // Use the same temporaries for the new value. break;
}
FALLTHROUGH_INTENDED; case GetAndUpdateOp::kAdd: if (old_value.IsFpuRegisterPair()) {
DCHECK(maybe_temp.IsCoreRegisterPair());
loaded_value = maybe_temp;
new_value = loaded_value; // Use the same temporaries for the new value. break;
} if (old_value.IsFpuRegister()) {
DCHECK(maybe_temp.IsCoreRegister());
loaded_value = maybe_temp;
new_value = loaded_value; // Use the same temporary for the new value. break;
}
FALLTHROUGH_INTENDED; case GetAndUpdateOp::kAnd: case GetAndUpdateOp::kOr: case GetAndUpdateOp::kXor:
loaded_value = old_value;
new_value = maybe_temp; break;
}
vixl32::Label loop_label;
__ Bind(&loop_label);
EmitLoadExclusive(codegen, load_store_type, ptr, loaded_value); switch (get_and_update_op) { case GetAndUpdateOp::kSet: break; case GetAndUpdateOp::kAddWithByteSwap: if (arg.IsFpuRegisterPair()) {
GenerateReverseBytes(assembler, DataType::Type::kFloat64, loaded_value, old_value);
vixl32::DRegister sum = DRegisterFrom(maybe_vreg_temp);
__ Vadd(sum, DRegisterFrom(old_value), DRegisterFrom(arg));
__ Vmov(HighRegisterFrom(new_value), LowRegisterFrom(new_value), sum); // Swap low/high.
} elseif (arg.IsFpuRegister()) {
GenerateReverseBytes(assembler, DataType::Type::kFloat32, loaded_value, old_value);
vixl32::SRegister sum = LowSRegisterFrom(maybe_vreg_temp); // The temporary is a pair.
__ Vadd(sum, SRegisterFrom(old_value), SRegisterFrom(arg));
__ Vmov(RegisterFrom(new_value), sum);
} elseif (load_store_type == DataType::Type::kInt64) {
GenerateReverseBytes(assembler, DataType::Type::kInt64, loaded_value, old_value); // Swap low/high registers for the addition results.
__ Adds(HighRegisterFrom(new_value), LowRegisterFrom(old_value), LowRegisterFrom(arg));
__ Adc(LowRegisterFrom(new_value), HighRegisterFrom(old_value), HighRegisterFrom(arg));
} else {
GenerateReverseBytes(assembler, DataType::Type::kInt32, loaded_value, old_value);
__ Add(RegisterFrom(new_value), RegisterFrom(old_value), RegisterFrom(arg));
} if (load_store_type == DataType::Type::kInt64) { // The `new_value` already has the high and low word swapped. Reverse bytes in each.
GenerateReverseBytesInPlaceForEachWord(assembler, new_value);
} else {
GenerateReverseBytes(assembler, load_store_type, new_value, new_value);
} break; case GetAndUpdateOp::kAdd: if (arg.IsFpuRegisterPair()) {
vixl32::DRegister old_value_vreg = DRegisterFrom(old_value);
vixl32::DRegister sum = DRegisterFrom(maybe_vreg_temp);
__ Vmov(old_value_vreg, LowRegisterFrom(loaded_value), HighRegisterFrom(loaded_value));
__ Vadd(sum, old_value_vreg, DRegisterFrom(arg));
__ Vmov(LowRegisterFrom(new_value), HighRegisterFrom(new_value), sum);
} elseif (arg.IsFpuRegister()) {
vixl32::SRegister old_value_vreg = SRegisterFrom(old_value);
vixl32::SRegister sum = LowSRegisterFrom(maybe_vreg_temp); // The temporary is a pair.
__ Vmov(old_value_vreg, RegisterFrom(loaded_value));
__ Vadd(sum, old_value_vreg, SRegisterFrom(arg));
__ Vmov(RegisterFrom(new_value), sum);
} elseif (load_store_type == DataType::Type::kInt64) {
__ Adds(LowRegisterFrom(new_value), LowRegisterFrom(loaded_value), LowRegisterFrom(arg));
__ Adc(HighRegisterFrom(new_value), HighRegisterFrom(loaded_value), HighRegisterFrom(arg));
} else {
__ Add(RegisterFrom(new_value), RegisterFrom(loaded_value), RegisterFrom(arg));
} break; case GetAndUpdateOp::kAnd: if (load_store_type == DataType::Type::kInt64) {
__ And(LowRegisterFrom(new_value), LowRegisterFrom(loaded_value), LowRegisterFrom(arg));
__ And(HighRegisterFrom(new_value), HighRegisterFrom(loaded_value), HighRegisterFrom(arg));
} else {
__ And(RegisterFrom(new_value), RegisterFrom(loaded_value), RegisterFrom(arg));
} break; case GetAndUpdateOp::kOr: if (load_store_type == DataType::Type::kInt64) {
__ Orr(LowRegisterFrom(new_value), LowRegisterFrom(loaded_value), LowRegisterFrom(arg));
__ Orr(HighRegisterFrom(new_value), HighRegisterFrom(loaded_value), HighRegisterFrom(arg));
} else {
__ Orr(RegisterFrom(new_value), RegisterFrom(loaded_value), RegisterFrom(arg));
} break; case GetAndUpdateOp::kXor: if (load_store_type == DataType::Type::kInt64) {
__ Eor(LowRegisterFrom(new_value), LowRegisterFrom(loaded_value), LowRegisterFrom(arg));
__ Eor(HighRegisterFrom(new_value), HighRegisterFrom(loaded_value), HighRegisterFrom(arg));
} else {
__ Eor(RegisterFrom(new_value), RegisterFrom(loaded_value), RegisterFrom(arg));
} break;
}
EmitStoreExclusive(codegen, load_store_type, ptr, store_result, new_value);
__ Cmp(store_result, 0);
__ B(ne, &loop_label);
}
// Request another temporary register for methods that don't return a value.
size_t num_temps = 1u; // We always need `tmp_ptr`. constbool is_void = invoke->GetType() == DataType::Type::kVoid; if (is_void) {
num_temps++;
} else {
locations->SetOut(Location::RequiresCoreRegister(), Location::kOutputOverlap);
}
if (get_and_update_op == GetAndUpdateOp::kAdd) { // Add `maybe_temp` used for the new value in `GenerateGetAndUpdate()`.
num_temps += (type == DataType::Type::kInt64) ? 2u : 1u; if (type == DataType::Type::kInt64) { // There are enough available registers but the register allocator can fail to allocate // them correctly because it can block register pairs by single-register inputs and temps. // To work around this limitation, use a fixed register pair for both the output as well // as the offset which is not needed anymore after the address calculation. // (Alternatively, we could set up distinct fixed locations for `offset`, `arg` and `out`.)
locations->SetInAt(2, LocationFrom(r0, r1));
locations->UpdateOut(LocationFrom(r0, r1));
}
}
locations->AddRegisterTemps(num_temps);
}
staticvoid GenUnsafeGetAndUpdate(HInvoke* invoke,
CodeGeneratorARMVIXL* codegen,
DataType::Type type,
GetAndUpdateOp get_and_update_op) { // Currently only used for these GetAndUpdateOp. Might be fine for other ops but double check // before using.
DCHECK(get_and_update_op == GetAndUpdateOp::kAdd || get_and_update_op == GetAndUpdateOp::kSet);
if (type == DataType::Type::kReference) {
DCHECK(get_and_update_op == GetAndUpdateOp::kSet); // Mark card for object as a new value shall be stored. bool new_value_can_be_null = true; // TODO: Worth finding out this information?
vixl32::Register card = tmp_ptr; // Use the `tmp_ptr` also as the `card` temporary.
codegen->MaybeMarkGCCard(temp, card, base, /*value=*/ RegisterFrom(arg), new_value_can_be_null);
}
// Note: UnsafeGetAndUpdate operations are sequentially consistent, requiring // a barrier before and after the raw load/store-exclusive operation.
vixl32::Label byte_array_view_check_label_;
vixl32::Label native_byte_order_label_; // Shared parameter for all VarHandle intrinsics.
std::memory_order order_; // Extra argument for GenerateVarHandleGet() and GenerateVarHandleSet(). bool atomic_; // Extra arguments for GenerateVarHandleCompareAndSetOrExchange(). bool return_success_; bool strong_; // Extra argument for GenerateVarHandleGetAndUpdate().
GetAndUpdateOp get_and_update_op_;
};
// Check access mode and the primitive type from VarHandle.varType. // Check reference arguments against the VarHandle.varType; for references this is a subclass // check without read barrier, so it can have false negatives which we handle in the slow path. staticvoid GenerateVarHandleAccessModeAndVarTypeChecks(HInvoke* invoke,
CodeGeneratorARMVIXL* codegen,
SlowPathCodeARMVIXL* slow_path,
DataType::Type type) {
mirror::VarHandle::AccessMode access_mode =
mirror::VarHandle::GetAccessModeByIntrinsic(invoke->GetIntrinsic());
Primitive::Type primitive_type = DataTypeToPrimitive(type);
// Use the temporary register reserved for offset. It is not used yet at this point.
size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke);
vixl32::Register var_type_no_rb =
RegisterFrom(invoke->GetLocations()->GetTemp(expected_coordinates_count == 0u ? 1u : 0u));
// Check that the operation is permitted and the primitive type of varhandle.varType. // We do not need a read barrier when loading a reference only for loading constant // primitive field through the reference. Use LDRD to load the fields together.
{
UseScratchRegisterScope temps(assembler->GetVIXLAssembler());
vixl32::Register temp2 = temps.Acquire();
DCHECK_EQ(var_type_offset.Int32Value() + 4, access_mode_bit_mask_offset.Int32Value());
__ Ldrd(var_type_no_rb, temp2, MemOperand(varhandle, var_type_offset.Int32Value()));
assembler->MaybeUnpoisonHeapReference(var_type_no_rb);
__ Tst(temp2, 1u << static_cast<uint32_t>(access_mode));
__ B(eq, slow_path->GetEntryLabel());
__ Ldrh(temp2, MemOperand(var_type_no_rb, primitive_type_offset.Int32Value()));
__ Cmp(temp2, static_cast<uint16_t>(primitive_type));
__ B(ne, slow_path->GetEntryLabel());
}
if (type == DataType::Type::kReference) { // Check reference arguments against the varType. // False negatives due to varType being an interface or array type // or due to the missing read barrier are handled by the slow path.
uint32_t arguments_start = /* VarHandle object */ 1u + expected_coordinates_count;
uint32_t number_of_arguments = invoke->GetNumberOfArguments(); for (size_t arg_index = arguments_start; arg_index != number_of_arguments; ++arg_index) {
HInstruction* arg = invoke->InputAt(arg_index);
DCHECK_EQ(arg->GetType(), DataType::Type::kReference); if (!arg->IsNullConstant()) {
vixl32::Register arg_reg = RegisterFrom(invoke->GetLocations()->InAt(arg_index));
GenerateSubTypeObjectCheckNoReadBarrier(codegen, slow_path, arg_reg, var_type_no_rb);
}
}
}
}
// Check that the VarHandle references a static field by checking that coordinateType0 == null. // Do not emit read barrier (or unpoison the reference) for comparing to null.
__ Ldr(temp, MemOperand(varhandle, coordinate_type0_offset.Int32Value()));
__ Cmp(temp, 0);
__ B(ne, slow_path->GetEntryLabel());
}
// Null-check the object. if (!optimizations.GetSkipObjectNullCheck()) {
__ Cmp(object, 0);
__ B(eq, slow_path->GetEntryLabel());
}
if (!optimizations.GetUseKnownImageVarHandle()) { // Use the first temporary register, whether it's for the declaring class or the offset. // It is not used yet at this point.
vixl32::Register temp = RegisterFrom(invoke->GetLocations()->GetTemp(0u));
// Check that the VarHandle references an instance field by checking that // coordinateType1 == null. coordinateType0 should not be null, but this is handled by the // type compatibility check with the source object's type, which will fail for null.
{
UseScratchRegisterScope temps(assembler->GetVIXLAssembler());
vixl32::Register temp2 = temps.Acquire();
DCHECK_EQ(coordinate_type0_offset.Int32Value() + 4, coordinate_type1_offset.Int32Value());
__ Ldrd(temp, temp2, MemOperand(varhandle, coordinate_type0_offset.Int32Value()));
assembler->MaybeUnpoisonHeapReference(temp); // No need for read barrier or unpoisoning of coordinateType1 for comparison with null.
__ Cmp(temp2, 0);
__ B(ne, slow_path->GetEntryLabel());
}
// Check that the object has the correct type. // We deliberately avoid the read barrier, letting the slow path handle the false negatives.
GenerateSubTypeObjectCheckNoReadBarrier(
codegen, slow_path, object, temp, /*object_can_be_null=*/ false);
}
}
// Check that the VarHandle references an array, byte array view or ByteBuffer by checking // that coordinateType1 != null. If that's true, coordinateType1 shall be int.class and // coordinateType0 shall not be null but we do not explicitly verify that.
DCHECK_EQ(coordinate_type0_offset.Int32Value() + 4, coordinate_type1_offset.Int32Value());
__ Ldrd(temp, temp2, MemOperand(varhandle, coordinate_type0_offset.Int32Value()));
codegen->GetAssembler()->MaybeUnpoisonHeapReference(temp); // No need for read barrier or unpoisoning of coordinateType1 for comparison with null.
__ Cmp(temp2, 0);
__ B(eq, slow_path->GetEntryLabel());
// Check object class against componentType0. // // This is an exact check and we defer other cases to the runtime. This includes // conversion to array of superclass references, which is valid but subsequently // requires all update operations to check that the value can indeed be stored. // We do not want to perform such extra checks in the intrinsified code. // // We do this check without read barrier, so there can be false negatives which we // defer to the slow path. There shall be no false negatives for array classes in the // boot image (including Object[] and primitive arrays) because they are non-movable.
__ Ldr(temp2, MemOperand(object, class_offset.Int32Value()));
codegen->GetAssembler()->MaybeUnpoisonHeapReference(temp2);
__ Cmp(temp, temp2);
__ B(ne, slow_path->GetEntryLabel());
// Check that the coordinateType0 is an array type. We do not need a read barrier // for loading constant reference fields (or chains of them) for comparison with null, // nor for finally loading a constant primitive field (primitive type) below.
__ Ldr(temp2, MemOperand(temp, component_type_offset.Int32Value()));
codegen->GetAssembler()->MaybeUnpoisonHeapReference(temp2);
__ Cmp(temp2, 0);
__ B(eq, slow_path->GetEntryLabel());
// Check that the array component type matches the primitive type. // With the exception of `kPrimNot`, `kPrimByte` and `kPrimBoolean`, // we shall check for a byte array view in the slow path. // The check requires the ByteArrayViewVarHandle.class to be in the boot image, // so we cannot emit that if we're JITting without boot image. bool boot_image_available =
codegen->GetCompilerOptions().IsBootImage() ||
!Runtime::Current()->GetHeap()->GetBootImageSpaces().empty(); bool can_be_view =
((value_type != DataType::Type::kReference) && (DataType::Size(value_type) != 1u)) &&
boot_image_available;
vixl32::Label* slow_path_label =
can_be_view ? slow_path->GetByteArrayViewCheckLabel() : slow_path->GetEntryLabel();
__ Ldrh(temp2, MemOperand(temp2, primitive_type_offset.Int32Value()));
__ Cmp(temp2, static_cast<uint16_t>(primitive_type));
__ B(ne, slow_path_label);
// Check for array index out of bounds.
__ Ldr(temp, MemOperand(object, array_length_offset.Int32Value()));
__ Cmp(index, temp);
__ B(hs, slow_path->GetEntryLabel());
}
struct VarHandleTarget {
vixl32::Register object; // The object holding the value to operate on.
vixl32::Register offset; // The offset of the value to operate on.
};
VarHandleTarget target; // The temporary allocated for loading the offset.
target.offset = RegisterFrom(locations->GetTemp(0u)); // The reference to the object that holds the value to operate on.
target.object = (expected_coordinates_count == 0u)
? RegisterFrom(locations->GetTemp(1u))
: InputRegisterAt(invoke, 1); return target;
}
if (expected_coordinates_count <= 1u) { if (VarHandleOptimizations(invoke).GetUseKnownImageVarHandle()) {
ScopedObjectAccess soa(Thread::Current());
ArtField* target_field = GetImageVarHandleField(invoke); if (expected_coordinates_count == 0u) {
ObjPtr<mirror::Class> declaring_class = target_field->GetDeclaringClass(); if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(declaring_class)) {
uint32_t boot_image_offset = CodeGenerator::GetBootImageOffset(declaring_class);
codegen->LoadBootImageRelRoEntry(target.object, boot_image_offset);
} else {
codegen->LoadTypeForBootImageIntrinsic(
target.object,
TypeReference(&declaring_class->GetDexFile(), declaring_class->GetDexTypeIndex()));
}
}
__ Mov(target.offset, target_field->GetOffset().Uint32Value());
} else { // For static fields, we need to fill the `target.object` with the declaring class, // so we can use `target.object` as temporary for the `ArtField*`. For instance fields, // we do not need the declaring class, so we can forget the `ArtField*` when // we load the `target.offset`, so use the `target.offset` to hold the `ArtField*`.
vixl32::Register field = (expected_coordinates_count == 0) ? target.object : target.offset;
ArenaAllocator* allocator = codegen->GetGraph()->GetAllocator();
LocationSummary* locations =
LocationSummary::Create(allocator, invoke, LocationSummary::kCallOnSlowPath, kIntrinsified);
locations->SetInAt(0, Location::RequiresCoreRegister()); // Require coordinates in registers. These are the object holding the value // to operate on (except for static fields) and index (for arrays and views). for (size_t i = 0; i != expected_coordinates_count; ++i) {
locations->SetInAt(/* VarHandle object */ 1u + i, Location::RequiresCoreRegister());
} if (return_type != DataType::Type::kVoid) { if (DataType::IsFloatingPointType(return_type)) {
locations->SetOut(Location::RequiresFpuRegister());
} else {
locations->SetOut(Location::RequiresCoreRegister());
}
}
uint32_t arguments_start = /* VarHandle object */ 1u + expected_coordinates_count;
uint32_t number_of_arguments = invoke->GetNumberOfArguments(); for (size_t arg_index = arguments_start; arg_index != number_of_arguments; ++arg_index) {
HInstruction* arg = invoke->InputAt(arg_index); if (DataType::IsFloatingPointType(arg->GetType())) {
locations->SetInAt(arg_index, Location::RequiresFpuRegister());
} else {
locations->SetInAt(arg_index, Location::RequiresCoreRegister());
}
}
// Add a temporary for offset. if (codegen->EmitNonBakerReadBarrier() &&
GetExpectedVarHandleCoordinatesCount(invoke) == 0u) { // For static fields. // To preserve the offset value across the non-Baker read barrier slow path // for loading the declaring class, use a fixed callee-save register.
constexpr int first_callee_save = CTZ(kArmCalleeSaveRefSpills);
locations->AddTemp(Location::CoreRegister(first_callee_save));
} else {
locations->AddTemp(Location::RequiresCoreRegister());
} if (expected_coordinates_count == 0u) { // Add a temporary to hold the declaring class.
locations->AddTemp(Location::RequiresCoreRegister());
}
if (codegen->EmitNonBakerReadBarrier() &&
invoke->GetType() == DataType::Type::kReference &&
invoke->GetIntrinsic() != Intrinsics::kVarHandleGet &&
invoke->GetIntrinsic() != Intrinsics::kVarHandleGetOpaque) { // Unsupported for non-Baker read barrier because the artReadBarrierSlow() ignores // the passed reference and reloads it from the field. This gets the memory visibility // wrong for Acquire/Volatile operations. b/173104084 return;
}
DataType::Type type = invoke->GetType(); if (type == DataType::Type::kFloat64 && Use64BitExclusiveLoadStore(atomic, codegen)) { // We need 3 temporaries for GenerateIntrinsicGet() but we can reuse the // declaring class (if present) and offset temporary.
DCHECK_EQ(locations->GetTempCount(),
(GetExpectedVarHandleCoordinatesCount(invoke) == 0) ? 2u : 1u);
locations->AddRegisterTemps(3u - locations->GetTempCount());
}
}
Location maybe_temp = Location::NoLocation();
Location maybe_temp2 = Location::NoLocation();
Location maybe_temp3 = Location::NoLocation(); if (type == DataType::Type::kReference && codegen->EmitBakerReadBarrier()) { // Reuse the offset temporary.
maybe_temp = LocationFrom(target.offset);
} elseif (DataType::Is64BitType(type) && Use64BitExclusiveLoadStore(atomic, codegen)) { // Reuse the offset temporary and declaring class (if present). // The address shall be constructed in the scratch register before they are clobbered.
maybe_temp = LocationFrom(target.offset);
DCHECK(maybe_temp.Equals(locations->GetTemp(0))); if (type == DataType::Type::kFloat64) {
maybe_temp2 = locations->GetTemp(1);
maybe_temp3 = locations->GetTemp(2);
}
}
UseScratchRegisterScope temps(assembler->GetVIXLAssembler());
Location loaded_value = out;
DataType::Type load_type = type; if (byte_swap) { if (type == DataType::Type::kFloat64) { if (Use64BitExclusiveLoadStore(atomic, codegen)) { // Change load type to Int64 and promote `maybe_temp2` and `maybe_temp3` to `loaded_value`.
loaded_value = LocationFrom(RegisterFrom(maybe_temp2), RegisterFrom(maybe_temp3));
maybe_temp2 = Location::NoLocation();
maybe_temp3 = Location::NoLocation();
} else { // Use the offset temporary and the scratch register.
loaded_value = LocationFrom(target.offset, temps.Acquire());
}
load_type = DataType::Type::kInt64;
} elseif (type == DataType::Type::kFloat32) { // Reuse the offset temporary.
loaded_value = LocationFrom(target.offset);
load_type = DataType::Type::kInt32;
} elseif (type == DataType::Type::kInt64) { // Swap the high and low registers and reverse the bytes in each after the load.
loaded_value = LocationFrom(HighRegisterFrom(out), LowRegisterFrom(out));
}
}
// Get the type from the shorty as the invokes may not return a value.
uint32_t number_of_arguments = invoke->GetNumberOfArguments();
DataType::Type value_type = GetDataTypeFromShorty(invoke, number_of_arguments - 1u); if (DataType::Is64BitType(value_type)) {
size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke);
DCHECK_EQ(locations->GetTempCount(), (expected_coordinates_count == 0) ? 2u : 1u);
HInstruction* arg = invoke->InputAt(number_of_arguments - 1u); bool has_reverse_bytes_slow_path =
(expected_coordinates_count == 2u) &&
!IsZeroBitPattern(arg); if (Use64BitExclusiveLoadStore(atomic, codegen)) { // We need 4 temporaries in the byte array view slow path. Otherwise, we need // 2 or 3 temporaries for GenerateIntrinsicSet() depending on the value type. // We can reuse the offset temporary and declaring class (if present).
size_t temps_needed = has_reverse_bytes_slow_path
? 4u
: ((value_type == DataType::Type::kFloat64) ? 3u : 2u);
locations->AddRegisterTemps(temps_needed - locations->GetTempCount());
} elseif (has_reverse_bytes_slow_path) { // We need 2 temps for the value with reversed bytes in the byte array view slow path. // We can reuse the offset temporary.
DCHECK_EQ(locations->GetTempCount(), 1u);
locations->AddTemp(Location::RequiresCoreRegister());
}
}
}
Location maybe_temp = Location::NoLocation();
Location maybe_temp2 = Location::NoLocation();
Location maybe_temp3 = Location::NoLocation(); if (DataType::Is64BitType(value_type) && Use64BitExclusiveLoadStore(atomic, codegen)) { // Reuse the offset temporary and declaring class (if present). // The address shall be constructed in the scratch register before they are clobbered.
maybe_temp = locations->GetTemp(0);
maybe_temp2 = locations->GetTemp(1); if (value_type == DataType::Type::kFloat64) {
maybe_temp3 = locations->GetTemp(2);
}
}
UseScratchRegisterScope temps(assembler->GetVIXLAssembler()); if (byte_swap) { if (DataType::Is64BitType(value_type) || value_type == DataType::Type::kFloat32) { // Calculate the address in scratch register, so that we can use the offset temporary.
vixl32::Register base = temps.Acquire();
__ Add(base, target.object, target.offset);
target.object = base;
target.offset = vixl32::Register();
}
Location original_value = value; if (DataType::Is64BitType(value_type)) {
size_t temp_start = 0u; if (Use64BitExclusiveLoadStore(atomic, codegen)) { // Clear `maybe_temp3` which was initialized above for Float64.
DCHECK_IMPLIES(value_type == DataType::Type::kFloat64,
maybe_temp3.Equals(locations->GetTemp(2)));
maybe_temp3 = Location::NoLocation();
temp_start = 2u;
}
value = LocationFrom(RegisterFrom(locations->GetTemp(temp_start)),
RegisterFrom(locations->GetTemp(temp_start + 1u))); if (value_type == DataType::Type::kFloat64) {
__ Vmov(HighRegisterFrom(value), LowRegisterFrom(value), DRegisterFrom(original_value));
GenerateReverseBytesInPlaceForEachWord(assembler, value);
value_type = DataType::Type::kInt64;
} else {
GenerateReverseBytes(assembler, value_type, original_value, value);
}
} elseif (value_type == DataType::Type::kFloat32) {
value = locations->GetTemp(0); // Use the offset temporary which was freed above.
__ Vmov(RegisterFrom(value), SRegisterFrom(original_value));
GenerateReverseBytes(assembler, DataType::Type::kInt32, value, value);
value_type = DataType::Type::kInt32;
} else {
value = LocationFrom(temps.Acquire());
GenerateReverseBytes(assembler, value_type, original_value, value);
}
}
uint32_t number_of_arguments = invoke->GetNumberOfArguments();
DataType::Type value_type = GetDataTypeFromShorty(invoke, number_of_arguments - 1u); if (value_type == DataType::Type::kReference && codegen->EmitNonBakerReadBarrier()) { // Unsupported for non-Baker read barrier because the artReadBarrierSlow() ignores // the passed reference and reloads it from the field. This breaks the read barriers // in slow path in different ways. The marked old value may not actually be a to-space // reference to the same object as `old_value`, breaking slow path assumptions. And // for CompareAndExchange, marking the old value after comparison failure may actually // return the reference to `expected`, erroneously indicating success even though we // did not set the new value. (And it also gets the memory visibility wrong.) b/173104084 return;
}
if (codegen->EmitNonBakerReadBarrier()) { // We need callee-save registers for both the class object and offset instead of // the temporaries reserved in CreateVarHandleCommonLocations().
static_assert(POPCOUNT(kArmCalleeSaveRefSpills) >= 2u);
constexpr int first_callee_save = CTZ(kArmCalleeSaveRefSpills);
constexpr int second_callee_save = CTZ(kArmCalleeSaveRefSpills ^ (1u << first_callee_save)); if (GetExpectedVarHandleCoordinatesCount(invoke) == 0u) { // For static fields.
DCHECK_EQ(locations->GetTempCount(), 2u);
DCHECK(locations->GetTemp(0u).Equals(Location::RequiresCoreRegister()));
DCHECK(locations->GetTemp(1u).Equals(Location::CoreRegister(first_callee_save)));
locations->SetTempAt(0u, Location::CoreRegister(second_callee_save));
} else {
DCHECK_EQ(locations->GetTempCount(), 1u);
DCHECK(locations->GetTemp(0u).Equals(Location::RequiresCoreRegister()));
locations->SetTempAt(0u, Location::CoreRegister(first_callee_save));
}
}
if (DataType::IsFloatingPointType(value_type)) { // We can reuse the declaring class (if present) and offset temporary.
DCHECK_EQ(locations->GetTempCount(),
(GetExpectedVarHandleCoordinatesCount(invoke) == 0) ? 2u : 1u);
size_t temps_needed = (value_type == DataType::Type::kFloat64)
? (return_success ? 5u : 7u)
: (return_success ? 3u : 4u);
locations->AddRegisterTemps(temps_needed - locations->GetTempCount());
} elseif (GetExpectedVarHandleCoordinatesCount(invoke) == 2u) { // Add temps for the byte-reversed `expected` and `new_value` in the byte array view slow path.
DCHECK_EQ(locations->GetTempCount(), 1u); if (value_type == DataType::Type::kInt64) { // We would ideally add 4 temps for Int64 but that would simply run out of registers, // so we instead need to reverse bytes in actual arguments and undo it at the end.
} else {
locations->AddRegisterTemps(2u);
}
} if (value_type == DataType::Type::kReference && codegen->EmitReadBarrier()) { // Add a temporary for store result, also used for the `old_value_temp` in slow path.
locations->AddTemp(Location::RequiresCoreRegister());
}
}
if (release_barrier) {
codegen->GenerateMemoryBarrier(
seq_cst_barrier ? MemBarrierKind::kAnyAny : MemBarrierKind::kAnyStore);
}
// Calculate the pointer to the value.
UseScratchRegisterScope temps(assembler->GetVIXLAssembler());
vixl32::Register tmp_ptr = temps.Acquire();
__ Add(tmp_ptr, target.object, target.offset);
// Move floating point values to temporaries and prepare output registers. // Note that float/double CAS uses bitwise comparison, rather than the operator==. // Reuse the declaring class (if present) and offset temporary for non-reference types, // the address has already been constructed in the scratch register. We are more careful // for references due to read and write barrier, see below.
Location old_value;
vixl32::Register store_result;
vixl32::Register success = return_success ? RegisterFrom(out) : vixl32::Register();
DataType::Type cas_type = value_type; if (value_type == DataType::Type::kFloat64) {
vixl32::DRegister expected_vreg = DRegisterFrom(expected);
vixl32::DRegister new_value_vreg = DRegisterFrom(new_value);
expected =
LocationFrom(RegisterFrom(locations->GetTemp(0)), RegisterFrom(locations->GetTemp(1)));
new_value =
LocationFrom(RegisterFrom(locations->GetTemp(2)), RegisterFrom(locations->GetTemp(3)));
store_result = RegisterFrom(locations->GetTemp(4));
old_value = return_success
? LocationFrom(success, store_result)
: LocationFrom(RegisterFrom(locations->GetTemp(5)), RegisterFrom(locations->GetTemp(6))); if (byte_swap) {
__ Vmov(HighRegisterFrom(expected), LowRegisterFrom(expected), expected_vreg);
__ Vmov(HighRegisterFrom(new_value), LowRegisterFrom(new_value), new_value_vreg);
GenerateReverseBytesInPlaceForEachWord(assembler, expected);
GenerateReverseBytesInPlaceForEachWord(assembler, new_value);
} else {
__ Vmov(LowRegisterFrom(expected), HighRegisterFrom(expected), expected_vreg);
__ Vmov(LowRegisterFrom(new_value), HighRegisterFrom(new_value), new_value_vreg);
}
cas_type = DataType::Type::kInt64;
} elseif (value_type == DataType::Type::kFloat32) {
vixl32::SRegister expected_vreg = SRegisterFrom(expected);
vixl32::SRegister new_value_vreg = SRegisterFrom(new_value);
expected = locations->GetTemp(0);
new_value = locations->GetTemp(1);
store_result = RegisterFrom(locations->GetTemp(2));
old_value = return_success ? LocationFrom(store_result) : locations->GetTemp(3);
__ Vmov(RegisterFrom(expected), expected_vreg);
__ Vmov(RegisterFrom(new_value), new_value_vreg); if (byte_swap) {
GenerateReverseBytes(assembler, DataType::Type::kInt32, expected, expected);
GenerateReverseBytes(assembler, DataType::Type::kInt32, new_value, new_value);
}
cas_type = DataType::Type::kInt32;
} elseif (value_type == DataType::Type::kInt64) {
store_result = RegisterFrom(locations->GetTemp(0));
old_value = return_success
? LocationFrom(success, store_result) // If swapping bytes, swap the high/low regs and reverse the bytes in each after the load.
: byte_swap ? LocationFrom(HighRegisterFrom(out), LowRegisterFrom(out)) : out; if (byte_swap) { // Due to lack of registers, reverse bytes in `expected` and `new_value` and undo that later.
GenerateReverseBytesInPlaceForEachWord(assembler, expected);
expected = LocationFrom(HighRegisterFrom(expected), LowRegisterFrom(expected));
GenerateReverseBytesInPlaceForEachWord(assembler, new_value);
new_value = LocationFrom(HighRegisterFrom(new_value), LowRegisterFrom(new_value));
}
} else { // Use the last temp. For references with read barriers, this is an extra temporary // allocated to avoid overwriting the temporaries for declaring class (if present) // and offset as they are needed in the slow path. Otherwise, this is the offset // temporary which also works for references without read barriers that need the // object register preserved for the write barrier.
store_result = RegisterFrom(locations->GetTemp(locations->GetTempCount() - 1u));
old_value = return_success ? LocationFrom(store_result) : out; if (byte_swap) {
DCHECK_EQ(locations->GetTempCount(), 3u);
Location original_expected = expected;
Location original_new_value = new_value;
expected = locations->GetTemp(0);
new_value = locations->GetTemp(1);
GenerateReverseBytes(assembler, value_type, original_expected, expected);
GenerateReverseBytes(assembler, value_type, original_new_value, new_value);
}
}
if (value_type == DataType::Type::kReference && codegen->EmitReadBarrier()) { // The `old_value_temp` is used first for the marked `old_value` and then for the unmarked // reloaded old value for subsequent CAS in the slow path. This must not clobber `old_value`.
vixl32::Register old_value_temp = return_success ? RegisterFrom(out) : store_result; // The slow path store result must not clobber `old_value`.
vixl32::Register slow_path_store_result = old_value_temp;
ReadBarrierCasSlowPathARMVIXL* rb_slow_path = new (codegen->GetScopedAllocator()) ReadBarrierCasSlowPathARMVIXL(
invoke,
strong,
target.object,
target.offset,
RegisterFrom(expected),
RegisterFrom(new_value),
RegisterFrom(old_value),
old_value_temp,
slow_path_store_result,
success,
codegen);
codegen->AddSlowPath(rb_slow_path);
exit_loop = rb_slow_path->GetExitLabel();
cmp_failure = rb_slow_path->GetEntryLabel();
}
if (acquire_barrier) {
codegen->GenerateMemoryBarrier(
seq_cst_barrier ? MemBarrierKind::kAnyAny : MemBarrierKind::kLoadAny);
}
if (byte_swap && value_type == DataType::Type::kInt64) { // Undo byte swapping in `expected` and `new_value`. We do not have the // information whether the value in these registers shall be needed later.
GenerateReverseBytesInPlaceForEachWord(assembler, expected);
GenerateReverseBytesInPlaceForEachWord(assembler, new_value);
} if (!return_success) { if (byte_swap) { if (value_type == DataType::Type::kInt64) {
GenerateReverseBytesInPlaceForEachWord(assembler, old_value);
} else {
GenerateReverseBytes(assembler, value_type, old_value, out);
}
} elseif (value_type == DataType::Type::kFloat64) {
__ Vmov(DRegisterFrom(out), LowRegisterFrom(old_value), HighRegisterFrom(old_value));
} elseif (value_type == DataType::Type::kFloat32) {
__ Vmov(SRegisterFrom(out), RegisterFrom(old_value));
}
}
if (CodeGenerator::StoreNeedsWriteBarrier(value_type, invoke->InputAt(new_value_index))) { // Reuse the offset temporary and scratch register for MarkGCCard.
vixl32::Register temp = target.offset;
vixl32::Register card = tmp_ptr; // Mark card for object assuming new value is stored. bool new_value_can_be_null = true; // TODO: Worth finding out this information?
codegen->MaybeMarkGCCard(
temp, card, target.object, RegisterFrom(new_value), new_value_can_be_null);
}
if (slow_path != nullptr) {
DCHECK(!byte_swap);
__ Bind(slow_path->GetExitLabel());
}
}
// Get the type from the shorty as the invokes may not return a value.
uint32_t arg_index = invoke->GetNumberOfArguments() - 1;
DataType::Type value_type = GetDataTypeFromShorty(invoke, arg_index); if (value_type == DataType::Type::kReference && codegen->EmitNonBakerReadBarrier()) { // Unsupported for non-Baker read barrier because the artReadBarrierSlow() ignores // the passed reference and reloads it from the field, thus seeing the new value // that we have just stored. (And it also gets the memory visibility wrong.) b/173104084 return;
}
// We can reuse the declaring class (if present) and offset temporary, except for // non-Baker read barriers that need them for the slow path.
DCHECK_EQ(locations->GetTempCount(),
(GetExpectedVarHandleCoordinatesCount(invoke) == 0) ? 2u : 1u);
if (get_and_update_op == GetAndUpdateOp::kSet) { if (DataType::IsFloatingPointType(value_type)) { // Add temps needed to do the GenerateGetAndUpdate() with core registers.
size_t temps_needed = (value_type == DataType::Type::kFloat64) ? 5u : 3u;
locations->AddRegisterTemps(temps_needed - locations->GetTempCount());
} elseif (value_type == DataType::Type::kReference && codegen->EmitNonBakerReadBarrier()) { // We need to preserve the declaring class (if present) and offset for read barrier // slow paths, so we must use a separate temporary for the exclusive store result.
locations->AddTemp(Location::RequiresCoreRegister());
} elseif (GetExpectedVarHandleCoordinatesCount(invoke) == 2u) { // Add temps for the byte-reversed `arg` in the byte array view slow path.
DCHECK_EQ(locations->GetTempCount(), 1u);
locations->AddRegisterTemps((value_type == DataType::Type::kInt64) ? 2u : 1u);
}
} else { // We need temporaries for the new value and exclusive store result.
size_t temps_needed = DataType::Is64BitType(value_type) ? 3u : 2u; if (get_and_update_op != GetAndUpdateOp::kAdd &&
GetExpectedVarHandleCoordinatesCount(invoke) == 2u) { // Add temps for the byte-reversed `arg` in the byte array view slow path. if (value_type == DataType::Type::kInt64) { // We would ideally add 2 temps for Int64 but that would simply run out of registers, // so we instead need to reverse bytes in the actual argument and undo it at the end.
} else {
temps_needed += 1u;
}
}
locations->AddRegisterTemps(temps_needed - locations->GetTempCount()); if (DataType::IsFloatingPointType(value_type)) { // Note: This shall allocate a D register. There is no way to request an S register.
locations->AddTemp(Location::RequiresFpuRegister());
}
}
// For the non-void case, we already set `out` in `CreateVarHandleCommonLocations`.
DataType::Type return_type = invoke->GetType(); constbool is_void = return_type == DataType::Type::kVoid;
DCHECK_IMPLIES(!is_void, return_type == value_type); if (is_void) { if (DataType::IsFloatingPointType(value_type)) { // Note: This shall allocate a D register. There is no way to request an S register.
locations->AddTemp(Location::RequiresFpuRegister());
} elseif (DataType::Is64BitType(value_type)) { // We need two for non-fpu 64 bit types.
locations->AddTemp(Location::RequiresCoreRegister());
locations->AddTemp(Location::RequiresCoreRegister());
} else {
locations->AddTemp(Location::RequiresCoreRegister());
}
}
}
staticvoid GenerateVarHandleGetAndUpdate(HInvoke* invoke,
CodeGeneratorARMVIXL* codegen,
GetAndUpdateOp get_and_update_op,
std::memory_order order, bool byte_swap = false) { // Get the type from the shorty as the invokes may not return a value.
uint32_t arg_index = invoke->GetNumberOfArguments() - 1;
DataType::Type value_type = GetDataTypeFromShorty(invoke, arg_index);
if (release_barrier) {
codegen->GenerateMemoryBarrier(
seq_cst_barrier ? MemBarrierKind::kAnyAny : MemBarrierKind::kAnyStore);
}
// Use the scratch register for the pointer to the target location.
UseScratchRegisterScope temps(assembler->GetVIXLAssembler());
vixl32::Register tmp_ptr = temps.Acquire();
__ Add(tmp_ptr, target.object, target.offset);
// Use the offset temporary for the exclusive store result.
vixl32::Register store_result = target.offset;
// The load/store type is never floating point.
DataType::Type load_store_type = DataType::IsFloatingPointType(value_type)
? ((value_type == DataType::Type::kFloat32) ? DataType::Type::kInt32 : DataType::Type::kInt64)
: value_type;
// Prepare register for old value and temporaries if any.
Location old_value = result;
Location maybe_temp = Location::NoLocation();
Location maybe_vreg_temp = Location::NoLocation(); if (get_and_update_op == GetAndUpdateOp::kSet) { // For floating point GetAndSet, do the GenerateGetAndUpdate() with core registers, // rather than moving between core and FP registers in the loop. if (value_type == DataType::Type::kFloat64) {
vixl32::DRegister arg_vreg = DRegisterFrom(arg); // `store_result` and the four here, plus maybe an extra one for the temp that mimics the // "out" register.
DCHECK_EQ(temp_count, 5u + temps_that_mimic_out);
old_value =
LocationFrom(RegisterFrom(locations->GetTemp(1)), RegisterFrom(locations->GetTemp(2)));
arg = LocationFrom(RegisterFrom(locations->GetTemp(3)), RegisterFrom(locations->GetTemp(4))); if (byte_swap) {
__ Vmov(HighRegisterFrom(arg), LowRegisterFrom(arg), arg_vreg);
GenerateReverseBytesInPlaceForEachWord(assembler, arg);
} else {
__ Vmov(LowRegisterFrom(arg), HighRegisterFrom(arg), arg_vreg);
}
} elseif (value_type == DataType::Type::kFloat32) {
vixl32::SRegister arg_vreg = SRegisterFrom(arg); // `store_result` and the two here, plus maybe an extra one for the temp that mimics the // "out" register.
DCHECK_EQ(temp_count, 3u + temps_that_mimic_out);
old_value = locations->GetTemp(1);
arg = locations->GetTemp(2);
__ Vmov(RegisterFrom(arg), arg_vreg); if (byte_swap) {
GenerateReverseBytes(assembler, DataType::Type::kInt32, arg, arg);
}
} elseif (value_type == DataType::Type::kReference && codegen->EmitReadBarrier()) { if (kUseBakerReadBarrier) { // Load the old value initially to a temporary register. // We shall move it to `out` later with a read barrier.
old_value = LocationFrom(store_result);
store_result = RegisterFrom(result); // Use `result` for the exclusive store result.
} else { // The store_result is a separate temporary.
DCHECK(!store_result.Is(target.object));
DCHECK(!store_result.Is(target.offset));
}
} elseif (byte_swap) {
Location original_arg = arg;
arg = locations->GetTemp(1); if (value_type == DataType::Type::kInt64) {
arg = LocationFrom(RegisterFrom(arg), RegisterFrom(locations->GetTemp(2))); // Swap the high/low regs and reverse the bytes in each after the load.
old_value = LocationFrom(HighRegisterFrom(result), LowRegisterFrom(result));
}
GenerateReverseBytes(assembler, value_type, original_arg, arg);
}
} else {
maybe_temp = DataType::Is64BitType(value_type)
? LocationFrom(RegisterFrom(locations->GetTemp(1)), RegisterFrom(locations->GetTemp(2)))
: locations->GetTemp(1);
DCHECK(!maybe_temp.Contains(LocationFrom(store_result))); if (DataType::IsFloatingPointType(value_type)) {
maybe_vreg_temp = locations->GetTemp(temp_count - 1u - temps_that_mimic_out);
DCHECK(maybe_vreg_temp.IsFpuRegisterPair());
} if (byte_swap) { if (get_and_update_op == GetAndUpdateOp::kAdd) { // We need to do the byte swapping in the CAS loop for GetAndAdd.
get_and_update_op = GetAndUpdateOp::kAddWithByteSwap;
} elseif (value_type == DataType::Type::kInt64) { // Swap the high/low regs and reverse the bytes in each after the load.
old_value = LocationFrom(HighRegisterFrom(result), LowRegisterFrom(result)); // Due to lack of registers, reverse bytes in `arg` and undo that later.
GenerateReverseBytesInPlaceForEachWord(assembler, arg);
arg = LocationFrom(HighRegisterFrom(arg), LowRegisterFrom(arg));
} else {
DCHECK(!DataType::IsFloatingPointType(value_type));
Location original_arg = arg;
arg = locations->GetTemp(2);
DCHECK(!arg.Contains(LocationFrom(store_result)));
GenerateReverseBytes(assembler, value_type, original_arg, arg);
}
}
}
if (acquire_barrier) {
codegen->GenerateMemoryBarrier(
seq_cst_barrier ? MemBarrierKind::kAnyAny : MemBarrierKind::kLoadAny);
}
if (!is_void) { if (byte_swap && get_and_update_op != GetAndUpdateOp::kAddWithByteSwap) { if (value_type == DataType::Type::kInt64) {
GenerateReverseBytesInPlaceForEachWord(assembler, old_value); if (get_and_update_op != GetAndUpdateOp::kSet) { // Undo byte swapping in `arg`. We do not have the information // whether the value in these registers shall be needed later.
GenerateReverseBytesInPlaceForEachWord(assembler, arg);
}
} else {
GenerateReverseBytes(assembler, value_type, old_value, result);
}
} elseif (get_and_update_op == GetAndUpdateOp::kSet &&
DataType::IsFloatingPointType(value_type)) { if (value_type == DataType::Type::kFloat64) {
__ Vmov(DRegisterFrom(result), LowRegisterFrom(old_value), HighRegisterFrom(old_value));
} else {
__ Vmov(SRegisterFrom(result), RegisterFrom(old_value));
}
} elseif (value_type == DataType::Type::kReference && codegen->EmitReadBarrier()) { if (kUseBakerReadBarrier) {
codegen->GenerateIntrinsicMoveWithBakerReadBarrier(RegisterFrom(result),
RegisterFrom(old_value));
} else {
codegen->GenerateReadBarrierSlow(
invoke,
Location::CoreRegister(RegisterFrom(result).GetCode()),
Location::CoreRegister(RegisterFrom(old_value).GetCode()),
Location::CoreRegister(target.object.GetCode()), /*offset=*/ 0u, /*index=*/ Location::CoreRegister(target.offset.GetCode()));
}
}
}
if (CodeGenerator::StoreNeedsWriteBarrier(value_type, invoke->InputAt(arg_index))) { // Reuse the offset temporary and scratch register for MarkGCCard.
vixl32::Register temp = target.offset;
vixl32::Register card = tmp_ptr; // Mark card for object assuming new value is stored. bool new_value_can_be_null = true; // TODO: Worth finding out this information?
codegen->MaybeMarkGCCard(temp, card, target.object, RegisterFrom(arg), new_value_can_be_null);
}
if (slow_path != nullptr) {
DCHECK(!byte_swap);
__ Bind(slow_path->GetExitLabel());
}
}
VarHandleTarget target = GetVarHandleTarget(invoke);
{ // Use the offset temporary register. It is not used yet at this point.
vixl32::Register temp = RegisterFrom(invoke->GetLocations()->GetTemp(0u));
// The main path checked that the coordinateType0 is an array class that matches // the class of the actual coordinate argument but it does not match the value type. // Check if the `varhandle` references a ByteArrayViewVarHandle instance.
__ Ldr(temp, MemOperand(varhandle, class_offset.Int32Value()));
codegen->GetAssembler()->MaybeUnpoisonHeapReference(temp);
codegen->LoadClassRootForIntrinsic(temp2, ClassRoot::kJavaLangInvokeByteArrayViewVarHandle);
__ Cmp(temp, temp2);
__ B(ne, GetEntryLabel());
// Check for array index out of bounds.
__ Ldr(temp, MemOperand(object, array_length_offset.Int32Value())); if (!temp.IsLow()) { // Avoid using the 32-bit `cmp temp, #imm` in IT block by loading `size` into `temp2`.
__ Mov(temp2, size_operand);
}
__ Subs(temp, temp, index);
{ // Use ExactAssemblyScope here because we are using IT.
ExactAssemblyScope it_scope(assembler->GetVIXLAssembler(), 2 * k16BitT32InstructionSizeInBytes);
__ it(hs); if (temp.IsLow()) {
__ cmp(hs, temp, size_operand);
} else {
__ cmp(hs, temp, temp2);
}
}
__ B(lo, GetEntryLabel());
// Construct the target.
__ Add(target.offset, index, data_offset.Int32Value()); // Note: `temp` cannot be used below.
// Alignment check. For unaligned access, go to the runtime.
DCHECK(IsPowerOfTwo(size));
__ Tst(target.offset, dchecked_integral_cast<int32_t>(size - 1u));
__ B(ne, GetEntryLabel());
// Byte order check. For native byte order return to the main path. if (access_mode_template == mirror::VarHandle::AccessModeTemplate::kSet) {
HInstruction* arg = invoke->InputAt(invoke->GetNumberOfArguments() - 1u); if (IsZeroBitPattern(arg)) { // There is no reason to differentiate between native byte order and byte-swap // for setting a zero bit pattern. Just return to the main path.
__ B(GetNativeByteOrderLabel()); return;
}
}
__ Ldrb(temp2, MemOperand(varhandle, native_byte_order_offset.Int32Value()));
__ Cmp(temp2, 0);
__ B(ne, GetNativeByteOrderLabel());
}
switch (access_mode_template) { case mirror::VarHandle::AccessModeTemplate::kGet:
GenerateVarHandleGet(invoke, codegen, order_, atomic_, /*byte_swap=*/ true); break; case mirror::VarHandle::AccessModeTemplate::kSet:
GenerateVarHandleSet(invoke, codegen, order_, atomic_, /*byte_swap=*/ true); break; case mirror::VarHandle::AccessModeTemplate::kCompareAndSet: case mirror::VarHandle::AccessModeTemplate::kCompareAndExchange:
GenerateVarHandleCompareAndSetOrExchange(
invoke, codegen, order_, return_success_, strong_, /*byte_swap=*/ true); break; case mirror::VarHandle::AccessModeTemplate::kGetAndUpdate:
GenerateVarHandleGetAndUpdate(
invoke, codegen, get_and_update_op_, order_, /*byte_swap=*/ true); break;
}
__ B(GetExitLabel());
}
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.182Bemerkung:
(vorverarbeitet am 2026-06-29)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.