__ Bind(GetEntryLabel()); // The `src_curr_addr` and `dst_curr_addr` were initialized before entering the slow-path.
GenArrayAddress(assembler, src_stop_addr, src_curr_addr, length, type, /*data_offset=*/ 0u);
NearLabel loop;
__ Bind(&loop);
__ movl(value, Address(src_curr_addr, 0));
__ MaybeUnpoisonHeapReference(value); // TODO: Inline the mark bit check before calling the runtime? // value = ReadBarrier::Mark(value) // 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 ReadBarrierMarkSlowPathX86::EmitNativeCode for more // explanations.)
int32_t entry_point_offset = Thread::ReadBarrierMarkEntryPointsOffset<kX86PointerSize>(value); // This runtime call does not require a stack map.
x86_codegen->InvokeRuntimeWithoutRecordingPcInfo(entry_point_offset, instruction_, this);
__ MaybePoisonHeapReference(value);
__ movl(Address(dst_curr_addr, 0), value);
__ addl(src_curr_addr, Immediate(element_size));
__ addl(dst_curr_addr, Immediate(element_size));
__ cmpl(src_curr_addr, src_stop_addr);
__ j(kNotEqual, &loop);
__ jmp(GetExitLabel());
}
switch (size) { case DataType::Type::kInt16: // TODO: Can be done with an xchg of 8b registers. This is straight from Quick.
__ bswapl(out);
__ sarl(out, Immediate(16)); break; case DataType::Type::kInt32:
__ bswapl(out); break; default:
LOG(FATAL) << "Unexpected size for reverse-bytes: " << size;
UNREACHABLE();
}
}
void IntrinsicCodeGeneratorX86::VisitMathSqrt(HInvoke* invoke) {
LocationSummary* locations = invoke->GetLocations();
XmmRegister in = locations->InAt(0).AsFpuRegister<XmmRegister>();
XmmRegister out = locations->Out().AsFpuRegister<XmmRegister>();
GetAssembler()->sqrtsd(out, in);
}
staticvoid CreateSSE41FPToFPLocations(ArenaAllocator* allocator,
HInvoke* invoke, const CodeGeneratorX86* codegen) { // Do we have instruction support? if (!codegen->GetInstructionSetFeatures().HasSSE4_1()) { return;
}
CreateFPToFPLocations(allocator, invoke);
}
staticvoid GenSSE41FPToFPIntrinsic(HInvoke* invoke, X86Assembler* assembler, int round_mode) {
LocationSummary* locations = invoke->GetLocations();
DCHECK(!locations->WillCall());
XmmRegister in = locations->InAt(0).AsFpuRegister<XmmRegister>();
XmmRegister out = locations->Out().AsFpuRegister<XmmRegister>();
__ roundsd(out, in, Immediate(round_mode));
}
void IntrinsicLocationsBuilderX86::VisitMathRoundFloat(HInvoke* invoke) { // Do we have instruction support? if (!codegen_->GetInstructionSetFeatures().HasSSE4_1()) { return;
}
// Since no direct x86 rounding instruction matches the required semantics, // this intrinsic is implemented as follows: // result = floor(in); // if (in - result >= 0.5f) // result = result + 1.0f;
__ movss(t2, in);
__ roundss(t1, in, Immediate(1));
__ subss(t2, t1); if (locations->GetInputCount() == 2 && locations->InAt(1).IsValid()) { // Direct constant area available.
HX86ComputeBaseMethodAddress* method_address =
invoke->InputAt(1)->AsX86ComputeBaseMethodAddress(); Register constant_area = locations->InAt(1).AsCoreRegister<Register>();
__ comiss(t2, codegen_->LiteralInt32Address(bit_cast<int32_t, float>(0.5f),
method_address,
constant_area));
__ j(kBelow, &skip_incr);
__ addss(t1, codegen_->LiteralInt32Address(bit_cast<int32_t, float>(1.0f),
method_address,
constant_area));
__ Bind(&skip_incr);
} else { // No constant area: go through stack.
__ pushl(Immediate(bit_cast<int32_t, float>(0.5f)));
__ pushl(Immediate(bit_cast<int32_t, float>(1.0f)));
__ comiss(t2, Address(ESP, 4));
__ j(kBelow, &skip_incr);
__ addss(t1, Address(ESP, 0));
__ Bind(&skip_incr);
__ addl(ESP, Immediate(8));
}
// Final conversion to an integer. Unfortunately this also does not have a // direct x86 instruction, since NaN should map to 0 and large positive // values need to be clipped to the extreme value.
__ movl(out, Immediate(kPrimIntMax));
__ cvtsi2ss(t2, out);
__ comiss(t1, t2);
__ j(kAboveEqual, &done); // clipped to max (already in out), does not jump on unordered
__ movl(out, Immediate(0)); // does not change flags
__ j(kUnordered, &done); // NaN mapped to 0 (just moved in out)
__ cvttss2si(out, t1);
__ Bind(&done);
}
staticvoid CreateSystemArrayCopyLocations(HInvoke* invoke) { // We need at least two of the positions or length to be an integer constant, // or else we won't have enough free registers.
HIntConstant* src_pos = invoke->InputAt(1)->AsIntConstantOrNull();
HIntConstant* dest_pos = invoke->InputAt(3)->AsIntConstantOrNull();
HIntConstant* length = invoke->InputAt(4)->AsIntConstantOrNull();
if (num_constants < 2) { // Not enough free registers. return;
}
constexpr int32_t copy_threshold = -1; // negative value means "ignore threshold"
constexpr size_t kInitialNumTemps = 0u; // we need specific temporary registers (added below)
LocationSummary* locations = CodeGenerator::CreateSystemArrayCopyLocationSummary(
invoke, copy_threshold, kInitialNumTemps);
if (locations != nullptr) { // And we need some temporaries. We will use REP MOVS{B,W,L}, so we need fixed registers.
locations->AddTemp(Location::CoreRegister(ESI));
locations->AddTemp(Location::CoreRegister(EDI));
locations->AddTemp(Location::CoreRegister(ECX));
}
}
staticvoid CheckSystemArrayCopyPosition(X86Assembler* assembler, Register array,
Location pos,
Location length,
SlowPathCode* slow_path, 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 = pos.GetConstant()->AsIntConstant()->GetValue(); if (pos_const == 0) { if (!length_is_array_length) { // Check that length(array) >= length.
EmitCmplJLess(assembler, Address(array, length_offset), length, 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 JL below shall go to the slow path.
__ movl(temp, Address(array, length_offset));
__ subl(temp, Immediate(pos_const));
// Check that (length(array) - pos) >= length.
EmitCmplJLess(assembler, temp, length, slow_path->GetEntryLabel());
}
} elseif (length_is_array_length) { // The only way the copy can succeed is if pos is zero. Register pos_reg = pos.AsCoreRegister<Register>();
__ testl(pos_reg, pos_reg);
__ j(kNotEqual, slow_path->GetEntryLabel());
} else { // Check that pos >= 0. Register pos_reg = pos.AsCoreRegister<Register>(); if (!position_sign_checked) {
__ testl(pos_reg, pos_reg);
__ j(kLess, 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 JL below shall go to the slow path.
__ movl(temp, Address(array, length_offset));
__ subl(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 = src_pos.GetConstant()->AsIntConstant()->GetValue(); if (dest_pos.IsConstant()) {
int32_t dest_pos_constant = dest_pos.GetConstant()->AsIntConstant()->GetValue(); if (optimizations.GetDestinationIsSource()) { // Checked when building locations.
DCHECK_GE(src_pos_constant, dest_pos_constant);
} elseif (src_pos_constant < dest_pos_constant) {
__ cmpl(src, dest);
__ j(kEqual, slow_path->GetEntryLabel());
}
} else { if (!optimizations.GetDestinationIsSource()) {
__ cmpl(src, dest);
__ j(kNotEqual, &conditions_on_positions_validated);
}
__ cmpl(dest_pos.AsCoreRegister<Register>(), Immediate(src_pos_constant));
__ j(kGreater, slow_path->GetEntryLabel());
}
} else { if (!optimizations.GetDestinationIsSource()) {
__ cmpl(src, dest);
__ j(kNotEqual, &conditions_on_positions_validated);
} Register src_pos_reg = src_pos.AsCoreRegister<Register>();
EmitCmplJLess(assembler, src_pos_reg, dest_pos, slow_path->GetEntryLabel());
}
}
__ Bind(&conditions_on_positions_validated);
if (!optimizations.GetSourceIsNotNull()) { // Bail out if the source is null.
__ testl(src, src);
__ j(kEqual, slow_path->GetEntryLabel());
}
if (!optimizations.GetDestinationIsNotNull() && !optimizations.GetDestinationIsSource()) { // Bail out if the destination is null.
__ testl(dest, dest);
__ j(kEqual, slow_path->GetEntryLabel());
}
// If the length is negative, bail out. // We have already checked in the LocationsBuilder for the constant case. if (!length.IsConstant() &&
!optimizations.GetCountIsSourceLength() &&
!optimizations.GetCountIsDestinationLength()) {
__ testl(length.AsCoreRegister<Register>(), length.AsCoreRegister<Register>());
__ j(kLess, slow_path->GetEntryLabel());
}
}
// Temporaries that we need for MOVSB/W/L. Register src_base = locations->GetTemp(0).AsCoreRegister<Register>();
DCHECK_EQ(src_base, ESI); Register dest_base = locations->GetTemp(1).AsCoreRegister<Register>();
DCHECK_EQ(dest_base, EDI); Register count = locations->GetTemp(2).AsCoreRegister<Register>();
DCHECK_EQ(count, ECX);
SlowPathCode* slow_path = new (codegen->GetScopedAllocator()) IntrinsicSlowPathX86(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.
CheckSystemArrayCopyNullOrOverlap(
invoke, assembler, slow_path, src, dest, src_pos, dest_pos, length);
// We need the count in ECX. if (length.IsConstant()) {
__ movl(count, Immediate(length.GetConstant()->AsIntConstant()->GetValue()));
} else {
__ movl(count, length.AsCoreRegister<Register>());
}
// Check that source position is within bounds. Use src_base as a temporary register.
CheckSystemArrayCopyPosition(assembler,
src,
src_pos,
Location::CoreRegister(count),
slow_path,
src_base, /*length_is_array_length=*/ false, /*position_sign_checked=*/ false);
// Check that destination position is within bounds. Use src_base as a temporary register.
CheckSystemArrayCopyPosition(assembler,
dest,
dest_pos,
Location::CoreRegister(count),
slow_path,
src_base, /*length_is_array_length=*/ false, /*position_sign_checked=*/ false);
// Okay, everything checks out. Finally time to do the copy. // Check assumption that sizeof(Char) is 2 (used in scaling below). const size_t data_size = DataType::Size(type); const uint32_t data_offset = mirror::Array::DataOffset(data_size).Uint32Value();
// Do the move. switch (type) { case DataType::Type::kInt8:
__ rep_movsb(); break; case DataType::Type::kUint16:
__ rep_movsw(); break; case DataType::Type::kInt32:
__ rep_movsl(); break; default:
LOG(FATAL) << "Unexpected data type for intrinsic";
}
__ Bind(slow_path->GetExitLabel());
}
// Request temporary registers, ECX and EDI needed for repe_cmpsl instruction.
locations->AddTemp(Location::CoreRegister(ECX));
locations->AddTemp(Location::CoreRegister(EDI));
// Set output, ESI needed for repe_cmpsl instruction anyways.
locations->SetOut(Location::CoreRegister(ESI), Location::kOutputOverlap);
}
Register str = locations->InAt(0).AsCoreRegister<Register>(); Register arg = locations->InAt(1).AsCoreRegister<Register>(); Register ecx = locations->GetTemp(0).AsCoreRegister<Register>(); Register edi = locations->GetTemp(1).AsCoreRegister<Register>(); Register esi = locations->Out().AsCoreRegister<Register>();
NearLabel end, return_true, return_false;
// 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.
__ testl(arg, arg);
__ j(kEqual, &return_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(); // Also, because we use the loaded class references only to compare them, we // don't need to unpoison them. // /* HeapReference<Class> */ ecx = str->klass_
__ movl(ecx, Address(str, class_offset)); // if (ecx != /* HeapReference<Class> */ arg->klass_) return false
__ cmpl(ecx, Address(arg, class_offset));
__ j(kNotEqual, &return_false);
}
// Reference equality check, return true if same reference.
__ cmpl(str, arg);
__ j(kEqual, &return_true);
// Load length and compression flag of receiver string.
__ movl(ecx, Address(str, count_offset)); // Check if lengths and compression flags are equal, return false if they're not. // Two identical strings will always have same compression style since // compression style is decided on alloc.
__ cmpl(ecx, Address(arg, count_offset));
__ j(kNotEqual, &return_false); // Return true if 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");
__ jecxz(&return_true);
if (mirror::kUseStringCompression) {
NearLabel string_uncompressed; // Extract length and differentiate between both compressed or both uncompressed. // Different compression style is cut above.
__ shrl(ecx, Immediate(1));
__ j(kCarrySet, &string_uncompressed); // Divide string length by 2, rounding up, and continue as if uncompressed.
__ addl(ecx, Immediate(1));
__ shrl(ecx, Immediate(1));
__ Bind(&string_uncompressed);
} // Load starting addresses of string values into ESI/EDI as required for repe_cmpsl instruction.
__ leal(esi, Address(str, value_offset));
__ leal(edi, Address(arg, value_offset));
// Divide string length by 2 to compare characters 2 at a time and adjust for lengths not // divisible by 2.
__ addl(ecx, Immediate(1));
__ shrl(ecx, Immediate(1));
// Assertions that must hold in order to compare strings 2 characters (uncompressed) // or 4 characters (compressed) at a time.
DCHECK_ALIGNED(value_offset, 4);
static_assert(IsAligned<4>(kObjectAlignment), "String of odd length is not zero padded");
// Loop to compare strings two characters at a time starting at the beginning of the string.
__ repe_cmpsl(); // If strings are not equal, zero flag will be cleared.
__ j(kNotEqual, &return_false);
// Return true and exit the function. // If loop does not result in returning false, we return true.
__ Bind(&return_true);
__ movl(esi, Immediate(1));
__ jmp(&end);
// Return false and exit the function.
__ Bind(&return_false);
__ xorl(esi, esi);
__ Bind(&end);
}
staticvoid CreateStringIndexOfLocations(HInvoke* invoke,
ArenaAllocator* allocator, bool start_at_zero) {
LocationSummary* locations =
LocationSummary::Create(allocator, invoke, LocationSummary::kCallOnSlowPath, kIntrinsified); // The data needs to be in EDI for scasw. So request that the string is there, anyways.
locations->SetInAt(0, Location::CoreRegister(EDI)); // If we look for a constant char, we'll still have to copy it into EAX. So just request the // allocator to do that, anyways. We can still do the constant check by checking the parameter // of the instruction explicitly. // Note: This works as we don't clobber EAX anywhere.
locations->SetInAt(1, Location::CoreRegister(EAX)); if (!start_at_zero) {
locations->SetInAt(2, Location::RequiresCoreRegister()); // The starting index.
} // As we clobber EDI during execution anyways, also use it as the output.
locations->SetOut(Location::SameAsFirstInput());
// repne scasw uses ECX as the counter.
locations->AddTemp(Location::CoreRegister(ECX)); // Need another temporary to be able to compute the result.
locations->AddTemp(Location::RequiresCoreRegister()); if (mirror::kUseStringCompression) { // Need another temporary to be able to save unflagged string length.
locations->AddTemp(Location::RequiresCoreRegister());
}
}
// 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.
SlowPathCode* slow_path = nullptr;
HInstruction* code_point = invoke->InputAt(1); if (code_point->IsIntConstant()) { if (static_cast<uint32_t>(code_point->AsIntConstant()->GetValue()) >
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()) IntrinsicSlowPathX86(invoke);
codegen->AddSlowPath(slow_path);
__ jmp(slow_path->GetEntryLabel());
__ Bind(slow_path->GetExitLabel()); return;
}
} elseif (code_point->GetType() != DataType::Type::kUint16) {
__ cmpl(search_value, Immediate(std::numeric_limits<uint16_t>::max()));
slow_path = new (codegen->GetScopedAllocator()) IntrinsicSlowPathX86(invoke);
codegen->AddSlowPath(slow_path);
__ j(kAbove, slow_path->GetEntryLabel());
}
// From here down, we know that we are looking for a char that fits in 16 bits. // Location of reference to data array within the String object.
int32_t value_offset = mirror::String::ValueOffset().Int32Value(); // Location of count within the String object.
int32_t count_offset = mirror::String::CountOffset().Int32Value();
// Load the count field of the string containing the length and compression flag.
__ movl(string_length, Address(string_obj, count_offset));
// Do a zero-length check. Even with string compression `count == 0` means empty.
static_assert(static_cast<uint32_t>(mirror::StringCompressionFlag::kCompressed) == 0u, "Expecting 0=compressed, 1=uncompressed"); // TODO: Support jecxz.
NearLabel not_found_label;
__ testl(string_length, string_length);
__ j(kEqual, ¬_found_label);
if (mirror::kUseStringCompression) {
string_length_flagged = locations->GetTemp(2).AsCoreRegister<Register>();
__ movl(string_length_flagged, string_length); // Extract the length and shift out the least significant bit used as compression flag.
__ shrl(string_length, Immediate(1));
}
if (start_at_zero) { // Number of chars to scan is the same as the string length.
__ movl(counter, string_length);
// Move to the start of the string.
__ addl(string_obj, Immediate(value_offset));
} else { Register start_index = locations->InAt(2).AsCoreRegister<Register>();
// Do a start_index check.
__ cmpl(start_index, string_length);
__ j(kGreaterEqual, ¬_found_label);
// Ensure we have a start index >= 0;
__ xorl(counter, counter);
__ cmpl(start_index, Immediate(0));
__ cmovl(kGreater, counter, start_index);
if (mirror::kUseStringCompression) {
NearLabel modify_counter, offset_uncompressed_label;
__ testl(string_length_flagged, Immediate(1));
__ j(kNotZero, &offset_uncompressed_label); // Move to the start of the string: string_obj + value_offset + start_index.
__ leal(string_obj, Address(string_obj, counter, ScaleFactor::TIMES_1, value_offset));
__ jmp(&modify_counter);
// Move to the start of the string: string_obj + value_offset + 2 * start_index.
__ Bind(&offset_uncompressed_label);
__ leal(string_obj, Address(string_obj, counter, ScaleFactor::TIMES_2, value_offset));
// Now update ecx (the repne scasw work counter). We have string.length - start_index left to // compare.
__ Bind(&modify_counter);
} else {
__ leal(string_obj, Address(string_obj, counter, ScaleFactor::TIMES_2, value_offset));
}
__ negl(counter);
__ leal(counter, Address(string_length, counter, ScaleFactor::TIMES_1, 0));
}
// Check if EAX (search_value) is ASCII.
__ cmpl(search_value, Immediate(127));
__ j(kGreater, ¬_found_label); // Comparing byte-per-byte.
__ repne_scasb();
__ jmp(&comparison_done);
// Everything is set up for repne scasw: // * Comparison address in EDI. // * Counter in ECX.
__ Bind(&uncompressed_string_comparison);
__ repne_scasw();
__ Bind(&comparison_done);
} else {
__ repne_scasw();
} // Did we find a match?
__ j(kNotEqual, ¬_found_label);
// Yes, we matched. Compute the index of the result.
__ subl(string_length, counter);
__ leal(out, Address(string_length, -1));
void IntrinsicCodeGeneratorX86::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*>();
}
void IntrinsicLocationsBuilderX86::VisitStringGetCharsNoCheck(HInvoke* invoke) { // public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin);
LocationSummary* locations = LocationSummary::CreateNoCall(allocator_, invoke, kIntrinsified);
locations->SetInAt(0, Location::RequiresCoreRegister());
locations->SetInAt(1, Location::RegisterOrConstant(invoke->InputAt(1))); // Place srcEnd in ECX to save a move below.
locations->SetInAt(2, Location::CoreRegister(ECX));
locations->SetInAt(3, Location::RequiresCoreRegister());
locations->SetInAt(4, Location::RequiresCoreRegister());
// And we need some temporaries. We will use REP MOVSW, so we need fixed registers. // We don't have enough registers to also grab ECX, so handle below.
locations->AddTemp(Location::CoreRegister(ESI));
locations->AddTemp(Location::CoreRegister(EDI));
}
size_t char_component_size = DataType::Size(DataType::Type::kUint16); // Location of data in char array buffer. const uint32_t data_offset = mirror::Array::DataOffset(char_component_size).Uint32Value(); // Location of char array data in string. const uint32_t value_offset = mirror::String::ValueOffset().Uint32Value();
// public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin); Register obj = locations->InAt(0).AsCoreRegister<Register>();
Location srcBegin = locations->InAt(1); int srcBegin_value =
srcBegin.IsConstant() ? srcBegin.GetConstant()->AsIntConstant()->GetValue() : 0; Register srcEnd = locations->InAt(2).AsCoreRegister<Register>(); Register dst = locations->InAt(3).AsCoreRegister<Register>(); Register dstBegin = locations->InAt(4).AsCoreRegister<Register>();
// Check assumption that sizeof(Char) is 2 (used in scaling below). const size_t char_size = DataType::Size(DataType::Type::kUint16);
DCHECK_EQ(char_size, 2u);
// Compute the number of chars (words) to move. // Save ECX, since we don't know if it will be used later.
__ pushl(ECX); int stack_adjust = kX86WordSize;
__ cfi().AdjustCFAOffset(stack_adjust);
DCHECK_EQ(srcEnd, ECX); if (srcBegin.IsConstant()) {
__ subl(ECX, Immediate(srcBegin_value));
} else {
DCHECK(srcBegin.IsCoreRegister());
__ subl(ECX, srcBegin.AsCoreRegister<Register>());
}
NearLabel done; if (mirror::kUseStringCompression) { // Location of count in string const uint32_t count_offset = mirror::String::CountOffset().Uint32Value(); const size_t c_char_size = DataType::Size(DataType::Type::kInt8);
DCHECK_EQ(c_char_size, 1u);
__ pushl(EAX);
__ cfi().AdjustCFAOffset(stack_adjust);
// Do the copy for uncompressed string. // Compute the address of the destination buffer.
__ leal(EDI, Address(dst, dstBegin, ScaleFactor::TIMES_2, data_offset));
__ leal(ESI, CodeGeneratorX86::ArrayAddress(obj, srcBegin, TIMES_2, value_offset));
__ rep_movsw();
staticvoid GenPeek(LocationSummary* locations, DataType::Type size, X86Assembler* assembler) { Register address = locations->InAt(0).AsCoreRegisterPairLow<Register>();
Location out_loc = locations->Out(); // x86 allows unaligned access. We do not have to check the input or use specific instructions // to avoid a SIGBUS. switch (size) { case DataType::Type::kInt8:
__ movsxb(out_loc.AsCoreRegister<Register>(), Address(address, 0)); break; case DataType::Type::kInt16:
__ movsxw(out_loc.AsCoreRegister<Register>(), Address(address, 0)); break; case DataType::Type::kInt32:
__ movl(out_loc.AsCoreRegister<Register>(), Address(address, 0)); break; case DataType::Type::kInt64:
__ movl(out_loc.AsCoreRegisterPairLow<Register>(), Address(address, 0));
__ movl(out_loc.AsCoreRegisterPairHigh<Register>(), Address(address, 4)); break; default:
LOG(FATAL) << "Type not recognized for peek: " << size;
UNREACHABLE();
}
}
staticvoid CreateIntIntIntToVoidPlusTempsLocations(ArenaAllocator* allocator,
DataType::Type type,
HInvoke* invoke, bool is_volatile) {
LocationSummary* locations = LocationSummary::CreateNoCall(allocator, invoke, kIntrinsified);
locations->SetInAt(0, Location::NoLocation()); // Unused receiver.
locations->SetInAt(1, Location::RequiresCoreRegister()); if (type == DataType::Type::kInt8 || type == DataType::Type::kUint8) { // Ensure the value is in a byte register
locations->SetInAt(2, Location::ByteRegisterOrConstant(EAX, invoke->InputAt(3)));
} else {
locations->SetInAt(2, Location::RequiresCoreRegister());
} if (type == DataType::Type::kInt64 && is_volatile) {
locations->AddTemp(Location::RequiresFpuRegister());
locations->AddTemp(Location::RequiresFpuRegister());
}
}
staticvoid CreateIntIntIntIntToVoidPlusTempsLocations(ArenaAllocator* allocator,
DataType::Type type,
HInvoke* invoke, bool is_volatile) {
LocationSummary* locations = LocationSummary::CreateNoCall(allocator, invoke, kIntrinsified);
locations->SetInAt(0, Location::NoLocation()); // Unused receiver.
locations->SetInAt(1, Location::RequiresCoreRegister());
locations->SetInAt(2, Location::RequiresCoreRegister()); if (type == DataType::Type::kInt8 || type == DataType::Type::kUint8) { // Ensure the value is in a byte register
locations->SetInAt(3, Location::ByteRegisterOrConstant(EAX, invoke->InputAt(3)));
} else {
locations->SetInAt(3, Location::RequiresCoreRegister());
} if (type == DataType::Type::kReference) { // Need two temp registers for card-marking. One is also used for reference poisoning.
locations->AddTemp(Location::RequiresCoreRegister()); // Ensure the value is in a byte register.
locations->AddTemp(Location::CoreRegister(ECX));
} elseif (type == DataType::Type::kInt64 && is_volatile) {
locations->AddTemp(Location::RequiresFpuRegister());
locations->AddTemp(Location::RequiresFpuRegister());
}
}
// We don't care for ordered: it requires an AnyStore barrier, which is already given by the x86 // memory model. staticvoid GenUnsafePut(LocationSummary* locations,
DataType::Type type, bool is_volatile,
CodeGeneratorX86* codegen) {
X86Assembler* assembler = down_cast<X86Assembler*>(codegen->GetAssembler()); Register base = locations->InAt(1).AsCoreRegister<Register>(); Register offset = locations->InAt(2).AsCoreRegisterPairLow<Register>();
Location value_loc = locations->InAt(3);
if (type == DataType::Type::kReference) { bool value_can_be_null = true; // TODO: Worth finding out this information?
codegen->MaybeMarkGCCard(locations->GetTemp(0).AsCoreRegister<Register>(),
locations->GetTemp(1).AsCoreRegister<Register>(),
base,
value_loc.AsCoreRegister<Register>(),
value_can_be_null);
}
}
// We don't care for ordered: it requires an AnyStore barrier, which is already given by the x86 // memory model. staticvoid GenUnsafePutAbsolute(LocationSummary* locations,
DataType::Type type, bool is_volatile,
CodeGeneratorX86* codegen) {
X86Assembler* assembler = down_cast<X86Assembler*>(codegen->GetAssembler()); Register address = locations->InAt(1).AsCoreRegisterPairLow<Register>();
Address address_offset(address, 0);
Location value_loc = locations->InAt(2);
staticvoid CreateIntIntIntIntIntToInt(ArenaAllocator* allocator, const CodeGeneratorX86* codegen,
DataType::Type type,
HInvoke* invoke) { constbool can_call = codegen->EmitBakerReadBarrier() && IsUnsafeCASReference(invoke);
LocationSummary* locations = LocationSummary::Create(
allocator,
invoke,
can_call ? LocationSummary::kCallOnSlowPath : LocationSummary::kNoCall,
kIntrinsified);
locations->SetInAt(0, Location::NoLocation()); // Unused receiver.
locations->SetInAt(1, Location::RequiresCoreRegister()); // Offset is a long, but in 32 bit mode, we only need the low word. // Can we update the invoke here to remove a TypeConvert to Long?
locations->SetInAt(2, Location::RequiresCoreRegister()); // Expected value must be in EAX or EDX:EAX. // For long, new value must be in ECX:EBX. if (type == DataType::Type::kInt64) {
locations->SetInAt(3, Location::CoreRegisterPair(EAX, EDX));
locations->SetInAt(4, Location::CoreRegisterPair(EBX, ECX));
} else {
locations->SetInAt(3, Location::CoreRegister(EAX));
locations->SetInAt(4, Location::RequiresCoreRegister());
}
// Force a byte register for the output.
locations->SetOut(Location::CoreRegister(EAX)); if (type == DataType::Type::kReference) { // Need two temporary registers for card-marking, and possibly for // (Baker) read barrier. One is also used for reference poisoning.
locations->AddTemp(Location::RequiresCoreRegister()); // Need a byte register for marking.
locations->AddTemp(Location::CoreRegister(ECX));
}
}
void IntrinsicLocationsBuilderX86::VisitJdkUnsafeCompareAndSetReference(HInvoke* invoke) { // The only supported read barrier implementation is the Baker-style read barriers. if (codegen_->EmitNonBakerReadBarrier()) { return;
}
staticvoid GenPrimitiveLockedCmpxchg(DataType::Type type,
CodeGeneratorX86* codegen,
Location expected_value,
Location new_value, Register base, Register offset, // Only necessary for floating point Register temp = Register::kNoRegister) {
X86Assembler* assembler = down_cast<X86Assembler*>(codegen->GetAssembler());
if (DataType::Kind(type) == DataType::Type::kInt32) {
DCHECK_EQ(expected_value.AsCoreRegister<Register>(), EAX);
}
// The address of the field within the holding object.
Address field_addr(base, offset, TIMES_1, 0);
switch (type) { case DataType::Type::kBool: case DataType::Type::kInt8:
__ LockCmpxchgb(field_addr, new_value.AsCoreRegister<ByteRegister>()); break; case DataType::Type::kInt16: case DataType::Type::kUint16:
__ LockCmpxchgw(field_addr, new_value.AsCoreRegister<Register>()); break; case DataType::Type::kInt32:
__ LockCmpxchgl(field_addr, new_value.AsCoreRegister<Register>()); break; case DataType::Type::kFloat32: { // cmpxchg requires the expected value to be in EAX so the new value must be elsewhere.
DCHECK_NE(temp, EAX); // EAX is both an input and an output for cmpxchg
codegen->Move32(Location::CoreRegister(EAX), expected_value);
codegen->Move32(Location::CoreRegister(temp), new_value);
__ LockCmpxchgl(field_addr, temp); break;
} case DataType::Type::kInt64: // Ensure the expected value is in EAX:EDX and that the new // value is in EBX:ECX (required by the CMPXCHG8B instruction).
DCHECK_EQ(expected_value.AsCoreRegisterPairLow<Register>(), EAX);
DCHECK_EQ(expected_value.AsCoreRegisterPairHigh<Register>(), EDX);
DCHECK_EQ(new_value.AsCoreRegisterPairLow<Register>(), EBX);
DCHECK_EQ(new_value.AsCoreRegisterPairHigh<Register>(), ECX);
__ LockCmpxchg8b(field_addr); break; default:
LOG(FATAL) << "Unexpected CAS type " << type;
} // LOCK CMPXCHG/LOCK CMPXCHG8B have full barrier semantics, and we // don't need scheduling barriers at this time.
}
if (is_cmpxchg) { // Sign-extend, zero-extend or move the result if necessary switch (type) { case DataType::Type::kBool:
__ movzxb(out.AsCoreRegister<Register>(), out.AsCoreRegister<ByteRegister>()); break; case DataType::Type::kInt8:
__ movsxb(out.AsCoreRegister<Register>(), out.AsCoreRegister<ByteRegister>()); break; case DataType::Type::kInt16:
__ movsxw(out.AsCoreRegister<Register>(), out.AsCoreRegister<Register>()); break; case DataType::Type::kUint16:
__ movzxw(out.AsCoreRegister<Register>(), out.AsCoreRegister<Register>()); break; case DataType::Type::kFloat32:
__ movd(out.AsFpuRegister<XmmRegister>(), EAX); break; default: // Nothing to do break;
}
} else { // Convert ZF into the Boolean result.
__ setb(kZero, out.AsCoreRegister<Register>());
__ movzxb(out.AsCoreRegister<Register>(), out.AsCoreRegister<ByteRegister>());
}
}
if (codegen->EmitBakerReadBarrier()) { // Need to make sure the reference stored in the field is a to-space // one before attempting the CAS or the CAS could fail incorrectly.
codegen->GenerateReferenceLoadWithBakerReadBarrier(
invoke, // Unused, used only as a "temporary" within the read barrier.
Location::CoreRegister(temp),
base,
field_addr, /* needs_null_check= */ false, /* always_update_field= */ true,
&temp2);
} bool base_equals_value = (base == value); if (kPoisonHeapReferences) { if (base_equals_value) { // If `base` and `value` are the same register location, move // `value` to a temporary register. This way, poisoning // `value` won't invalidate `base`.
value = temp;
__ movl(value, base);
}
// Check that the register allocator did not assign the location // of `expected` (EAX) to `value` nor to `base`, so that heap // poisoning (when enabled) works as intended below. // - If `value` were equal to `expected`, both references would // be poisoned twice, meaning they would not be poisoned at // all, as heap poisoning uses address negation. // - If `base` were equal to `expected`, poisoning `expected` // would invalidate `base`.
DCHECK_NE(value, expected);
DCHECK_NE(base, expected);
__ PoisonHeapReference(expected);
__ PoisonHeapReference(value);
}
__ LockCmpxchgl(field_addr, value);
// LOCK CMPXCHG has full barrier semantics, and we don't need // scheduling barriers at this time.
if (is_cmpxchg) {
DCHECK_EQ(out.AsCoreRegister<Register>(), EAX);
__ MaybeUnpoisonHeapReference(out.AsCoreRegister<Register>());
} else { // Convert ZF into the Boolean result.
__ setb(kZero, out.AsCoreRegister<Register>());
__ movzxb(out.AsCoreRegister<Register>(), out.AsCoreRegister<ByteRegister>());
}
// Mark card for object if the new value is stored. bool value_can_be_null = true; // TODO: Worth finding out this information?
NearLabel skip_mark_gc_card;
__ j(kNotZero, &skip_mark_gc_card);
codegen->MaybeMarkGCCard(temp, temp2, base, value, value_can_be_null);
__ Bind(&skip_mark_gc_card);
// If heap poisoning is enabled, we need to unpoison the values // that were poisoned earlier. if (kPoisonHeapReferences) { if (base_equals_value) { // `value` has been moved to a temporary register, no need to // unpoison it.
} else { // Ensure `value` is different from `out`, so that unpoisoning // the former does not invalidate the latter.
DCHECK_NE(value, out.AsCoreRegister<Register>());
__ UnpoisonHeapReference(value);
}
} // Do not unpoison the reference contained in register // `expected`, as it is the same as register `out` (EAX).
}
if (type == DataType::Type::kReference) { // The only read barrier implementation supporting the // UnsafeCASObject intrinsic is the Baker-style read barriers.
DCHECK_IMPLIES(codegen->EmitReadBarrier(), kUseBakerReadBarrier);
void IntrinsicCodeGeneratorX86::VisitUnsafeCASObject(HInvoke* invoke) { // The only read barrier implementation supporting the // UnsafeCASObject intrinsic is the Baker-style read barriers.
DCHECK_IMPLIES(codegen_->EmitReadBarrier(), kUseBakerReadBarrier);
void IntrinsicCodeGeneratorX86::VisitJdkUnsafeCompareAndSetReference(HInvoke* invoke) { // The only supported read barrier implementation is the Baker-style read barriers.
DCHECK_IMPLIES(codegen_->EmitReadBarrier(), kUseBakerReadBarrier);
// Note: Unlike other architectures that use corresponding enums for the `VarHandle` // implementation, x86 is currently using it only for `Unsafe`. enumclass GetAndUpdateOp {
kSet,
kAdd,
};
void CreateUnsafeGetAndUpdateLocations(ArenaAllocator* allocator,
HInvoke* invoke, const CodeGeneratorX86* codegen,
DataType::Type type,
GetAndUpdateOp get_and_unsafe_op) { constbool can_call = codegen->EmitReadBarrier() && IsUnsafeGetAndSetReference(invoke);
LocationSummary* locations = LocationSummary::Create(
allocator,
invoke,
can_call ? LocationSummary::kCallOnSlowPath : LocationSummary::kNoCall,
kIntrinsified); if (can_call && kUseBakerReadBarrier) {
locations->SetCustomSlowPathCallerSaves(RegisterSet::Empty()); // No caller-save registers.
}
locations->SetInAt(0, Location::NoLocation()); // Unused receiver. constbool is_void = invoke->GetType() == DataType::Type::kVoid; if (type == DataType::Type::kInt64) { // Explicitly allocate all registers.
locations->SetInAt(1, Location::CoreRegister(EBP)); if (get_and_unsafe_op == GetAndUpdateOp::kAdd) {
locations->AddTemp(Location::CoreRegister(EBP)); // We shall clobber EBP.
locations->SetInAt(2, Location::Any()); // Offset is either on the stack or constant.
locations->SetInAt(3, Location::CoreRegisterPair(ESI, EDI));
locations->AddTemp(Location::CoreRegister(EBX));
locations->AddTemp(Location::CoreRegister(ECX));
} else {
locations->SetInAt(2, Location::CoreRegisterPair(ESI, EDI));
locations->SetInAt(3, Location::CoreRegisterPair(EBX, ECX));
} if (is_void) {
locations->AddTemp(Location::CoreRegister(EAX));
locations->AddTemp(Location::CoreRegister(EDX));
} else {
locations->SetOut(Location::CoreRegisterPair(EAX, EDX), Location::kOutputOverlap);
}
} else {
locations->SetInAt(1, Location::RequiresCoreRegister());
locations->SetInAt(2, Location::RequiresCoreRegister()); // Use the same register for both the output and the new value or addend // to take advantage of XCHG or XADD. Arbitrarily pick EAX.
locations->SetInAt(3, Location::CoreRegister(EAX)); // Only set the `out` register if it's needed. In the void case we can still use EAX in the // same manner as it is marked as a temp register. if (is_void) {
locations->AddTemp(Location::CoreRegister(EAX));
} else {
locations->SetOut(Location::CoreRegister(EAX));
}
}
}
void IntrinsicLocationsBuilderX86::VisitJdkUnsafeGetAndSetReference(HInvoke* invoke) { // The only supported read barrier implementation is the Baker-style read barriers. if (codegen_->EmitNonBakerReadBarrier()) { return;
}
constbool is_void = invoke->GetType() == DataType::Type::kVoid; // We use requested specific registers to use as temps for void methods, as we don't return the // value.
Location out_or_temp =
is_void ? (type == DataType::Type::kInt64 ? Location::CoreRegisterPair(EAX, EDX) :
Location::CoreRegister(EAX)) :
locations->Out(); Register base = locations->InAt(1).AsCoreRegister<Register>(); // Object pointer.
Location offset = locations->InAt(2); // Long offset.
Location arg = locations->InAt(3); // New value or addend.
if (type == DataType::Type::kInt32) {
DCHECK(out_or_temp.Equals(arg)); Register out_reg = out_or_temp.AsCoreRegister<Register>();
Address field_address(base, offset.AsCoreRegisterPairLow<Register>(), TIMES_1, 0); if (get_and_update_op == GetAndUpdateOp::kAdd) {
__ LockXaddl(field_address, out_reg);
} else {
DCHECK(get_and_update_op == GetAndUpdateOp::kSet);
__ xchgl(out_reg, field_address);
}
} elseif (type == DataType::Type::kInt64) { // Prepare the field address. Ignore the high 32 bits of the `offset`.
Address field_address_low(kNoRegister, 0), field_address_high(kNoRegister, 0); if (get_and_update_op == GetAndUpdateOp::kAdd) {
DCHECK(Location::CoreRegister(base).Equals(locations->GetTemp(0))); if (offset.IsDoubleStackSlot()) {
__ addl(base, Address(ESP, offset.GetStackIndex())); // Clobbers `base`.
field_address_low = Address(base, 0);
field_address_high = Address(base, 4);
} else {
DCHECK(offset.IsConstant());
int64_t offset_value = offset.GetConstant()->AsLongConstant()->GetValue();
field_address_low = Address(base, Low32Bits(offset_value));
field_address_high = Address(base, Low32Bits(offset_value) + 4u);
}
} else {
field_address_low = Address(base, offset.AsCoreRegisterPairLow<Register>(), TIMES_1, 0);
field_address_high = Address(base, offset.AsCoreRegisterPairLow<Register>(), TIMES_1, 4);
} // Load the old value to EDX:EAX and use LOCK CMPXCHG8B to set the new value.
NearLabel loop;
__ Bind(&loop);
__ movl(EAX, field_address_low);
__ movl(EDX, field_address_high); if (get_and_update_op == GetAndUpdateOp::kAdd) {
DCHECK(Location::CoreRegisterPair(ESI, EDI).Equals(arg));
__ movl(EBX, EAX);
__ movl(ECX, EDX);
__ addl(EBX, ESI);
__ adcl(ECX, EDI);
} else {
DCHECK(get_and_update_op == GetAndUpdateOp::kSet);
DCHECK(Location::CoreRegisterPair(EBX, ECX).Equals(arg));
}
__ LockCmpxchg8b(field_address_low);
__ j(kNotEqual, &loop); // Repeat on failure.
} else {
DCHECK_EQ(type, DataType::Type::kReference);
DCHECK(get_and_update_op == GetAndUpdateOp::kSet); Register out_reg = out_or_temp.AsCoreRegister<Register>();
Address field_address(base, offset.AsCoreRegisterPairLow<Register>(), TIMES_1, 0); Register temp1 = locations->GetTemp(0).AsCoreRegister<Register>(); Register temp2 = locations->GetTemp(1).AsCoreRegister<Register>();
if (codegen->EmitReadBarrier()) {
DCHECK(kUseBakerReadBarrier); // Ensure that the field contains a to-space reference.
codegen->GenerateReferenceLoadWithBakerReadBarrier(
invoke,
Location::CoreRegister(temp2),
base,
field_address, /*needs_null_check=*/ false, /*always_update_field=*/ true,
&temp1);
}
// Mark card for object as a new value shall be stored. bool new_value_can_be_null = true; // TODO: Worth finding out this information?
DCHECK_EQ(temp2, ECX); // Byte register for `MarkGCCard()`.
codegen->MaybeMarkGCCard(temp1, temp2, base, /*value=*/out_reg, new_value_can_be_null);
if (kPoisonHeapReferences) { // Use a temp to avoid poisoning base of the field address, which might happen if `out` // is the same as `base` (for code like `unsafe.getAndSet(obj, offset, obj)`).
__ movl(temp1, out_reg);
__ PoisonHeapReference(temp1);
__ xchgl(temp1, field_address); if (!is_void) {
__ UnpoisonHeapReference(temp1);
__ movl(out_reg, temp1);
}
} else {
__ xchgl(out_reg, field_address);
}
}
}
// We want to swap high/low, then bswap each one, and then do the same // as a 32 bit reverse. // Exchange high and low.
__ movl(temp, reg_low);
__ movl(reg_low, reg_high);
__ movl(reg_high, temp);
staticvoid CreateBitCountLocations(
ArenaAllocator* allocator, const CodeGeneratorX86* codegen, HInvoke* invoke, bool is_long) { if (!codegen->GetInstructionSetFeatures().HasPopCnt()) { // Do nothing if there is no popcnt support. This results in generating // a call for the intrinsic rather than direct code. return;
}
LocationSummary* locations = LocationSummary::CreateNoCall(allocator, invoke, kIntrinsified); if (is_long) {
locations->AddTemp(Location::RequiresCoreRegister());
}
locations->SetInAt(0, Location::Any());
locations->SetOut(Location::RequiresCoreRegister());
}
if (invoke->InputAt(0)->IsConstant()) { // Evaluate this at compile time.
int64_t value = Int64FromConstant(invoke->InputAt(0)->AsConstant());
int32_t result = is_long
? POPCOUNT(static_cast<uint64_t>(value))
: POPCOUNT(static_cast<uint32_t>(value));
codegen->Load32BitValue(out, result); return;
}
// Handle the non-constant cases. if (!is_long) { if (src.IsCoreRegister()) {
__ popcntl(out, src.AsCoreRegister<Register>());
} else {
DCHECK(src.IsStackSlot());
__ popcntl(out, Address(ESP, src.GetStackIndex()));
}
} else { // The 64-bit case needs to worry about two parts. Register temp = locations->GetTemp(0).AsCoreRegister<Register>(); if (src.IsCoreRegisterPair()) {
__ popcntl(temp, src.AsCoreRegisterPairLow<Register>());
__ popcntl(out, src.AsCoreRegisterPairHigh<Register>());
} else {
DCHECK(src.IsDoubleStackSlot());
__ popcntl(temp, Address(ESP, src.GetStackIndex()));
__ popcntl(out, Address(ESP, src.GetHighStackIndex(kX86WordSize)));
}
__ addl(out, temp);
}
}
if (invoke->InputAt(0)->IsConstant()) { // Evaluate this at compile time.
int64_t value = Int64FromConstant(invoke->InputAt(0)->AsConstant()); if (value == 0) {
value = is_long ? 64 : 32;
} else {
value = is_long ? CLZ(static_cast<uint64_t>(value)) : CLZ(static_cast<uint32_t>(value));
}
codegen->Load32BitValue(out, value); return;
}
// Handle the non-constant cases. if (!is_long) { if (src.IsCoreRegister()) {
__ bsrl(out, src.AsCoreRegister<Register>());
} else {
DCHECK(src.IsStackSlot());
__ bsrl(out, Address(ESP, src.GetStackIndex()));
}
// BSR sets ZF if the input was zero, and the output is undefined.
NearLabel all_zeroes, done;
__ j(kEqual, &all_zeroes);
// Correct the result from BSR to get the final CLZ result.
__ xorl(out, Immediate(31));
__ jmp(&done);
// Fix the zero case with the expected result.
__ Bind(&all_zeroes);
__ movl(out, Immediate(32));
__ Bind(&done); return;
}
// 64 bit case needs to worry about both parts of the register.
DCHECK(src.IsCoreRegisterPair()); Register src_lo = src.AsCoreRegisterPairLow<Register>(); Register src_hi = src.AsCoreRegisterPairHigh<Register>();
NearLabel handle_low, done, all_zeroes;
// Is the high word zero?
__ testl(src_hi, src_hi);
__ j(kEqual, &handle_low);
// High word is not zero. We know that the BSR result is defined in this case.
__ bsrl(out, src_hi);
// Correct the result from BSR to get the final CLZ result.
__ xorl(out, Immediate(31));
__ jmp(&done);
// High word was zero. We have to compute the low word count and add 32.
__ Bind(&handle_low);
__ bsrl(out, src_lo);
__ j(kEqual, &all_zeroes);
// We had a valid result. Use an XOR to both correct the result and add 32.
__ xorl(out, Immediate(63));
__ jmp(&done);
// All zero case.
__ Bind(&all_zeroes);
__ movl(out, Immediate(64));
if (invoke->InputAt(0)->IsConstant()) { // Evaluate this at compile time.
int64_t value = Int64FromConstant(invoke->InputAt(0)->AsConstant()); if (value == 0) {
value = is_long ? 64 : 32;
} else {
value = is_long ? CTZ(static_cast<uint64_t>(value)) : CTZ(static_cast<uint32_t>(value));
}
codegen->Load32BitValue(out, value); return;
}
// Handle the non-constant cases. if (!is_long) { if (src.IsCoreRegister()) {
__ bsfl(out, src.AsCoreRegister<Register>());
} else {
DCHECK(src.IsStackSlot());
__ bsfl(out, Address(ESP, src.GetStackIndex()));
}
// BSF sets ZF if the input was zero, and the output is undefined.
NearLabel done;
__ j(kNotEqual, &done);
// Fix the zero case with the expected result.
__ movl(out, Immediate(32));
__ Bind(&done); return;
}
// 64 bit case needs to worry about both parts of the register.
DCHECK(src.IsCoreRegisterPair()); Register src_lo = src.AsCoreRegisterPairLow<Register>(); Register src_hi = src.AsCoreRegisterPairHigh<Register>();
NearLabel done, all_zeroes;
// If the low word is zero, then ZF will be set. If not, we have the answer.
__ bsfl(out, src_lo);
__ j(kNotEqual, &done);
// Low word was zero. We have to compute the high word count and add 32.
__ bsfl(out, src_hi);
__ j(kEqual, &all_zeroes);
// We had a valid result. Add 32 to account for the low word being zero.
__ addl(out, Immediate(32));
__ jmp(&done);
// All zero case.
__ Bind(&all_zeroes);
__ movl(out, Immediate(64));
void IntrinsicLocationsBuilderX86::VisitSystemArrayCopy(HInvoke* invoke) { // The only read barrier implementation supporting the // SystemArrayCopy intrinsic is the Baker-style read barriers. if (codegen_->EmitNonBakerReadBarrier()) { return;
}
constexpr int32_t kLengthThreshold = -1; // No cut-off - handle large arrays in intrinsic code.
constexpr size_t kInitialNumTemps = 0u; // We shall allocate temps explicitly.
LocationSummary* locations = CodeGenerator::CreateSystemArrayCopyLocationSummary(
invoke, kLengthThreshold, kInitialNumTemps); if (locations != nullptr) { // Add temporaries. We will use REP MOVSL, so we need fixed registers.
DCHECK_EQ(locations->GetTempCount(), kInitialNumTemps);
locations->AddTemp(Location::CoreRegister(ESI));
locations->AddTemp(Location::CoreRegister(EDI));
locations->AddTemp(Location::CoreRegister(ECX)); // Byte reg also used for write barrier.
if (!locations->InAt(kLength).IsConstant()) { // We may not have enough registers for all inputs and temps, so put the // non-const length explicitly to the same register as one of the temps.
locations->SetInAt(kLength, Location::CoreRegister(ECX));
}
if (codegen_->EmitBakerReadBarrier()) { // We need an additional temp in the slow path for holding the reference. if (locations->InAt(kSrcPos).IsConstant() ||
locations->InAt(kDestPos).IsConstant() ||
IsSameInput(invoke, kSrc, kDest) ||
IsSameInput(invoke, kSrcPos, kDestPos)) { // We can allocate another temp register.
locations->AddTemp(Location::RequiresCoreRegister());
} else { // Use the same fixed register for the non-const `src_pos` and the additional temp. // The `src_pos` is no longer needed when we reach the slow path.
locations->SetInAt(kSrcPos, Location::CoreRegister(EDX));
locations->AddTemp(Location::CoreRegister(EDX));
}
}
}
}
void IntrinsicCodeGeneratorX86::VisitSystemArrayCopy(HInvoke* invoke) { // The only read barrier implementation supporting the // SystemArrayCopy intrinsic is the Baker-style read barriers.
DCHECK_IMPLIES(codegen_->EmitReadBarrier(), kUseBakerReadBarrier);
SlowPathCode* intrinsic_slow_path = new (codegen_->GetScopedAllocator()) IntrinsicSlowPathX86(invoke);
codegen_->AddSlowPath(intrinsic_slow_path);
NearLabel conditions_on_positions_validated;
// 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);
auto check_non_primitive_array_class = [&](Register klass, 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_
__ movl(temp, Address(klass, component_offset));
__ MaybeUnpoisonHeapReference(temp); // Check that the component type is not null.
__ testl(temp, temp);
__ j(kEqual, intrinsic_slow_path->GetEntryLabel()); // Check that the component type is not a primitive.
__ cmpw(Address(temp, primitive_offset), Immediate(Primitive::kPrimNot));
__ j(kNotEqual, 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, /* 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, /* needs_null_check= */ false);
} else { // /* HeapReference<Class> */ temp1 = dest->klass_
__ movl(temp1, Address(dest, class_offset));
__ MaybeUnpoisonHeapReference(temp1); // /* HeapReference<Class> */ temp2 = src->klass_
__ movl(temp2, Address(src, class_offset));
__ MaybeUnpoisonHeapReference(temp2);
}
__ cmpl(temp1, temp2); if (optimizations.GetDestinationIsTypedObjectArray()) {
DCHECK(optimizations.GetDestinationIsNonPrimitiveArray());
NearLabel do_copy; // For class match, we can skip the source type check regardless of the optimization flag.
__ j(kEqual, &do_copy); // No read barrier is needed for reading a chain of constant references // for comparing with null, see `ReadBarrierOption`. // /* HeapReference<Class> */ temp1 = temp1->component_type_
__ movl(temp1, Address(temp1, component_offset));
__ MaybeUnpoisonHeapReference(temp1); // No need to unpoison the following heap reference load, as // we're comparing against null.
__ cmpl(Address(temp1, super_offset), Immediate(0));
__ j(kNotEqual, 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.
__ j(kNotEqual, 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> */ temp1 = src->klass_
__ movl(temp1, Address(src, class_offset));
__ MaybeUnpoisonHeapReference(temp1);
check_non_primitive_array_class(temp1, temp1);
}
if (length.IsConstant() && length.GetConstant()->AsIntConstant()->GetValue() == 0) { // Null constant length: not need to emit the loop code at all.
} else { const DataType::Type type = DataType::Type::kReference; const size_t data_size = DataType::Size(type); const uint32_t data_offset = mirror::Array::DataOffset(data_size).Uint32Value();
// Don't enter copy loop if `length == 0`.
NearLabel skip_copy_and_write_barrier; if (!length.IsConstant()) {
__ testl(length.AsCoreRegister<Register>(), length.AsCoreRegister<Register>());
__ j(kEqual, &skip_copy_and_write_barrier);
}
// Compute the base source address in `temp1`.
GenArrayAddress(assembler, temp1, src, src_pos, type, data_offset); // Compute the base destination address in `temp2`.
GenArrayAddress(assembler, temp2, dest, dest_pos, type, data_offset);
SlowPathCode* read_barrier_slow_path = nullptr; if (codegen_->EmitBakerReadBarrier()) { // SystemArrayCopy implementation for Baker read barriers (see // also CodeGeneratorX86::GenerateReferenceLoadWithBakerReadBarrier): // // if (src_ptr != end_ptr) { // 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. // for (size_t i = 0; i != length; ++i) { // dest_array[dest_pos + i] = // MaybePoison(ReadBarrier::Mark(MaybeUnpoison(src_array[src_pos + i]))); // } // } else { // // Fast-path copy. // do { // *dest_ptr++ = *src_ptr++; // } while (src_ptr != end_ptr) // } // }
// Given the numeric representation, it's enough to check the low bit of the rb_state.
static_assert(ReadBarrier::NonGrayState() == 0, "Expecting non-gray to have value 0");
static_assert(ReadBarrier::GrayState() == 1, "Expecting gray to have value 1");
constexpr uint32_t gray_byte_position = LockWord::kReadBarrierStateShift / kBitsPerByte;
constexpr uint32_t gray_bit_position = LockWord::kReadBarrierStateShift % kBitsPerByte;
constexpr int32_t test_value = static_cast<int8_t>(1 << gray_bit_position);
// if (rb_state == ReadBarrier::GrayState()) // goto slow_path; // At this point, just do the "if" and make sure that flags are preserved until the branch.
__ testb(Address(src, monitor_offset + gray_byte_position), Immediate(test_value));
// Load fence to prevent load-load reordering. // Note that this is a no-op, thanks to the x86 memory model.
codegen_->GenerateMemoryBarrier(MemBarrierKind::kLoadAny);
// Slow path used to copy array when `src` is gray.
read_barrier_slow_path = new (codegen_->GetScopedAllocator()) ReadBarrierSystemArrayCopySlowPathX86(invoke);
codegen_->AddSlowPath(read_barrier_slow_path);
// We have done the "if" of the gray bit check above, now branch based on the flags.
__ j(kNotZero, read_barrier_slow_path->GetEntryLabel());
}
// Iterate over the arrays and do a raw copy of the objects. We don't need to poison/unpoison.
DCHECK_EQ(temp1, ESI);
DCHECK_EQ(temp2, EDI);
DCHECK_EQ(temp3, ECX);
__ rep_movsl();
if (read_barrier_slow_path != nullptr) {
DCHECK(codegen_->EmitBakerReadBarrier());
__ Bind(read_barrier_slow_path->GetExitLabel());
}
// We only need one card marking on the destination array.
codegen_->MarkGCCard(temp1, temp3, dest);
__ Bind(&skip_copy_and_write_barrier);
}
__ Bind(intrinsic_slow_path->GetExitLabel());
}
staticvoid RequestBaseMethodAddressInRegister(HInvoke* invoke) {
LocationSummary* locations = invoke->GetLocations(); if (locations != nullptr) {
HInvokeStaticOrDirect* invoke_static_or_direct = invoke->AsInvokeStaticOrDirect(); // Note: The base method address is not present yet when this is called from the // PCRelativeHandlerVisitor via IsIntrinsicCallFree() to determine whether to insert it. if (invoke_static_or_direct->HasSpecialInput()) {
DCHECK(invoke_static_or_direct->InputAt(invoke_static_or_direct->GetSpecialInputIndex())
->IsX86ComputeBaseMethodAddress());
locations->SetInAt(invoke_static_or_direct->GetSpecialInputIndex(),
Location::RequiresCoreRegister());
}
}
}
// Load the java.lang.ref.Reference class, use the output register as a temporary.
codegen_->LoadIntrinsicDeclaringClass(out.AsCoreRegister<Register>(),
invoke->AsInvokeStaticOrDirect());
// Load the value from the field.
uint32_t referent_offset = mirror::Reference::ReferentOffset().Uint32Value(); if (codegen_->EmitBakerReadBarrier()) {
codegen_->GenerateFieldLoadWithBakerReadBarrier(invoke,
out,
obj.AsCoreRegister<Register>(),
referent_offset, /*needs_null_check=*/ true); // Note that the fence is a no-op, thanks to the x86 memory model.
codegen_->GenerateMemoryBarrier(MemBarrierKind::kLoadAny); // `referent` is volatile.
} else {
__ movl(out.AsCoreRegister<Register>(),
Address(obj.AsCoreRegister<Register>(), referent_offset));
codegen_->MaybeRecordImplicitNullCheck(invoke); // Note that the fence is a no-op, thanks to the x86 memory model.
codegen_->GenerateMemoryBarrier(MemBarrierKind::kLoadAny); // `referent` is volatile.
codegen_->MaybeGenerateReadBarrierSlow(invoke, out, out, obj, referent_offset);
}
__ Bind(slow_path->GetExitLabel());
}
__ movl(out, Address(obj, referent_offset));
codegen_->MaybeRecordImplicitNullCheck(invoke);
__ MaybeUnpoisonHeapReference(out); // Note that the fence is a no-op, thanks to the x86 memory model.
codegen_->GenerateMemoryBarrier(MemBarrierKind::kLoadAny); // `referent` is volatile.
if (codegen_->EmitReadBarrier()) {
DCHECK(kUseBakerReadBarrier);
__ j(kEqual, &return_true);
// Check if the loaded reference is null.
__ testl(out, out);
__ j(kZero, &return_false);
// 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);
__ movl(out, Address(out, monitor_offset));
__ cmpl(out, Immediate(static_cast<int32_t>(0xc0000000)));
__ j(kBelow, &return_false);
// Extract the forwarding address and compare with `other`.
__ shll(out, Immediate(LockWord::kForwardingAddressShift));
__ cmpl(out, other);
}
__ j(kNotEqual, &return_false);
// Return true and exit the function.
__ Bind(&return_true);
__ movl(out, Immediate(1));
__ jmp(&end);
// Return false and exit the function.
__ Bind(&return_false);
__ xorl(out, out);
__ Bind(&end);
}
// Check if divisor is zero, bail to managed implementation to handle.
__ testl(second_reg, second_reg);
SlowPathCode* slow_path = new (codegen_->GetScopedAllocator()) IntrinsicSlowPathX86(invoke);
codegen_->AddSlowPath(slow_path);
__ j(kEqual, slow_path->GetEntryLabel());
size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke);
DCHECK_LE(expected_coordinates_count, 2u); // Filtered by the `DoNotIntrinsify` flag above. if (expected_coordinates_count > 1u) { // Only static and instance fields VarHandle are supported now. // TODO: add support for arrays and views. returnfalse;
}
// If the access mode is not supported, bail to runtime implementation to handle
__ testl(Address(varhandle_object, access_modes_bitmask_offset), Immediate(access_mode_bit));
__ j(kZero, slow_path->GetEntryLabel());
}
// 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.
__ cmpl(Address(varhandle_object, coordtype0_offset), Immediate(0));
__ j(kNotEqual, slow_path->GetEntryLabel());
}
// If the object is null, there is no need to check the type if (object_can_be_null) {
__ testl(object, object);
__ j(kZero, &type_matched);
}
// Do not unpoison for in-memory comparison. // We deliberately avoid the read barrier, letting the slow path handle the false negatives.
__ movl(temp, Address(object, class_offset));
__ Bind(&check_type_compatibility);
__ cmpl(temp, type_address);
__ j(kEqual, &type_matched); // Load the super class.
__ MaybeUnpoisonHeapReference(temp);
__ movl(temp, Address(temp, super_class_offset)); // If the super class is null, we reached the root of the hierarchy without a match. // We let the slow path handle uncovered cases (e.g. interfaces).
__ testl(temp, temp);
__ j(kEqual, slow_path->GetEntryLabel());
__ jmp(&check_type_compatibility);
__ Bind(&type_matched);
}
// Check that the VarHandle references an instance field by checking that // coordinateType1 == null. coordinateType0 should be not null, but this is handled by the // type compatibility check with the source object's type, which will fail for null.
__ cmpl(Address(varhandle_object, coordtype1_offset), Immediate(0));
__ j(kNotEqual, slow_path->GetEntryLabel());
// Check if the object is null if (!optimizations.GetSkipObjectNullCheck()) {
__ testl(object, object);
__ j(kZero, slow_path->GetEntryLabel());
}
// Check the object's class against coordinateType0.
GenerateSubTypeObjectCheck(object,
temp,
Address(varhandle_object, coordtype0_offset),
slow_path,
assembler, /* object_can_be_null= */ false);
}
// We do not need a read barrier when loading a reference only for loading a constant field // through the reference.
__ movl(temp, Address(varhandle_object, var_type_offset));
__ MaybeUnpoisonHeapReference(temp);
__ cmpw(Address(temp, primitive_type_offset), Immediate(primitive_type));
__ j(kNotEqual, slow_path->GetEntryLabel());
}
// Check the return type and varType parameters.
mirror::VarHandle::AccessModeTemplate access_mode_template =
mirror::VarHandle::GetAccessModeTemplate(access_mode);
DataType::Type type = invoke->GetType();
switch (access_mode_template) { case mirror::VarHandle::AccessModeTemplate::kGet: // Check the varType.primitiveType against the type we're trying to retrieve. Reference types // are also checked later by a HCheckCast node as an additional check.
GenerateVarTypePrimitiveTypeCheck(vh_object, temp, type, slow_path, assembler); break; case mirror::VarHandle::AccessModeTemplate::kSet: case mirror::VarHandle::AccessModeTemplate::kGetAndUpdate: {
uint32_t value_index = invoke->GetNumberOfArguments() - 1;
DataType::Type value_type = GetDataTypeFromShorty(invoke, value_index);
// Check the varType.primitiveType against the type of the value we're trying to set.
GenerateVarTypePrimitiveTypeCheck(vh_object, temp, value_type, slow_path, assembler); if (value_type == DataType::Type::kReference) { const uint32_t var_type_offset = mirror::VarHandle::VarTypeOffset().Uint32Value();
// If the value type is a reference, check it against the varType.
GenerateSubTypeObjectCheck(locations->InAt(value_index).AsCoreRegister<Register>(),
temp,
Address(vh_object, var_type_offset),
slow_path,
assembler);
} break;
} case mirror::VarHandle::AccessModeTemplate::kCompareAndSet: case mirror::VarHandle::AccessModeTemplate::kCompareAndExchange: {
uint32_t new_value_index = invoke->GetNumberOfArguments() - 1;
uint32_t expected_value_index = invoke->GetNumberOfArguments() - 2;
DataType::Type value_type = GetDataTypeFromShorty(invoke, new_value_index);
DCHECK_EQ(value_type, GetDataTypeFromShorty(invoke, expected_value_index));
// Check the varType.primitiveType against the type of the expected value.
GenerateVarTypePrimitiveTypeCheck(vh_object, temp, value_type, slow_path, assembler); if (value_type == DataType::Type::kReference) { const uint32_t var_type_offset = mirror::VarHandle::VarTypeOffset().Uint32Value();
// If the value type is a reference, check both the expected and the new value against // the varType.
GenerateSubTypeObjectCheck(locations->InAt(new_value_index).AsCoreRegister<Register>(),
temp,
Address(vh_object, var_type_offset),
slow_path,
assembler);
GenerateSubTypeObjectCheck(locations->InAt(expected_value_index).AsCoreRegister<Register>(),
temp,
Address(vh_object, var_type_offset),
slow_path,
assembler);
} break;
}
}
}
// This method loads the field's address referred by a field VarHandle (base + offset). // The return value is the register containing object's reference (in case of an instance field) // or the declaring class (in case of a static field). The declaring class is stored in temp // register. Field's offset is loaded to the `offset` register. staticRegister GenerateVarHandleFieldReference(HInvoke* invoke,
CodeGeneratorX86* codegen, Register temp, /*out*/ Register offset) {
X86Assembler* assembler = codegen->GetAssembler();
LocationSummary* locations = invoke->GetLocations(); const uint32_t artfield_offset = mirror::FieldVarHandle::ArtFieldOffset().Uint32Value(); const uint32_t offset_offset = ArtField::OffsetOffset().Uint32Value(); const uint32_t declaring_class_offset = ArtField::DeclaringClassOffset().Uint32Value(); Register varhandle_object = locations->InAt(0).AsCoreRegister<Register>();
// Load the ArtField* and the offset.
__ movl(temp, Address(varhandle_object, artfield_offset));
__ movl(offset, Address(temp, offset_offset));
size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke); if (expected_coordinates_count == 0) { // For static fields, load the declaring class
InstructionCodeGeneratorX86* instr_codegen =
down_cast<InstructionCodeGeneratorX86*>(codegen->GetInstructionVisitor());
instr_codegen->GenerateGcRootFieldLoad(invoke,
Location::CoreRegister(temp),
Address(temp, declaring_class_offset), /* fixup_label= */ nullptr,
codegen->GetCompilerReadBarrierOption()); return temp;
}
// For instance fields, return the register containing the object.
DCHECK_EQ(expected_coordinates_count, 1u);
staticvoid CreateVarHandleGetLocations(HInvoke* invoke, const CodeGeneratorX86* codegen) { // The only read barrier implementation supporting the // VarHandleGet intrinsic is the Baker-style read barriers. if (codegen->EmitNonBakerReadBarrier()) { return;
}
if (!HasVarHandleIntrinsicImplementation(invoke)) { return;
}
ArenaAllocator* allocator = codegen->GetGraph()->GetAllocator();
LocationSummary* locations =
LocationSummary::Create(allocator, invoke, LocationSummary::kCallOnSlowPath, kIntrinsified);
locations->SetInAt(0, Location::RequiresCoreRegister());
size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke); if (expected_coordinates_count == 1u) { // For instance fields, this is the source object.
locations->SetInAt(1, Location::RequiresCoreRegister());
}
locations->AddTemp(Location::RequiresCoreRegister());
DataType::Type type = invoke->GetType(); switch (DataType::Kind(type)) { case DataType::Type::kInt64:
locations->AddTemp(Location::RequiresCoreRegister()); if (invoke->GetIntrinsic() != Intrinsics::kVarHandleGet) { // We need an XmmRegister for Int64 to ensure an atomic load
locations->AddTemp(Location::RequiresFpuRegister());
}
FALLTHROUGH_INTENDED; case DataType::Type::kInt32: case DataType::Type::kReference:
locations->SetOut(Location::RequiresCoreRegister()); break; default:
DCHECK(DataType::IsFloatingPointType(type));
locations->AddTemp(Location::RequiresCoreRegister());
locations->SetOut(Location::RequiresFpuRegister());
}
}
staticvoid GenerateVarHandleGet(HInvoke* invoke, CodeGeneratorX86* codegen) { // The only read barrier implementation supporting the // VarHandleGet intrinsic is the Baker-style read barriers.
DCHECK_IMPLIES(codegen->EmitReadBarrier(), kUseBakerReadBarrier);
Location out = locations->Out(); // Use 'out' as a temporary register if it's a core register Register offset = out.IsCoreRegister()
? out.AsCoreRegister<Register>()
: locations->GetTemp(1).AsCoreRegister<Register>();
// Get the field referred by the VarHandle. The returned register contains the object reference // or the declaring class. The field offset will be placed in 'offset'. For static fields, the // declaring class will be placed in 'temp' register. Register ref = GenerateVarHandleFieldReference(invoke, codegen, temp, offset);
Address field_addr(ref, offset, TIMES_1, 0);
// Load the value from the field if (type == DataType::Type::kReference && codegen->EmitReadBarrier()) {
codegen->GenerateReferenceLoadWithBakerReadBarrier(
invoke, out, ref, field_addr, /* needs_null_check= */ false);
} elseif (type == DataType::Type::kInt64 &&
invoke->GetIntrinsic() != Intrinsics::kVarHandleGet) {
XmmRegister xmm_temp = locations->GetTemp(2).AsFpuRegister<XmmRegister>();
codegen->LoadFromMemoryNoBarrier(
type, out, field_addr, /* instr= */ nullptr, xmm_temp, /* is_atomic_load= */ true);
} else {
codegen->LoadFromMemoryNoBarrier(type, out, field_addr);
}
if (invoke->GetIntrinsic() == Intrinsics::kVarHandleGetVolatile ||
invoke->GetIntrinsic() == Intrinsics::kVarHandleGetAcquire) { // Load fence to prevent load-load reordering. // Note that this is a no-op, thanks to the x86 memory model.
codegen->GenerateMemoryBarrier(MemBarrierKind::kLoadAny);
}
staticvoid CreateVarHandleSetLocations(HInvoke* invoke, const CodeGeneratorX86* codegen) { // The only read barrier implementation supporting the // VarHandleGet intrinsic is the Baker-style read barriers. if (codegen->EmitNonBakerReadBarrier()) { return;
}
if (!HasVarHandleIntrinsicImplementation(invoke)) { return;
}
// The last argument should be the value we intend to set.
uint32_t value_index = invoke->GetNumberOfArguments() - 1;
HInstruction* value = invoke->InputAt(value_index);
DataType::Type value_type = GetDataTypeFromShorty(invoke, value_index); bool needs_atomicity = invoke->GetIntrinsic() != Intrinsics::kVarHandleSet; if (value_type == DataType::Type::kInt64 && (!value->IsConstant() || needs_atomicity)) { // We avoid the case of a non-constant (or volatile) Int64 value because we would need to // place it in a register pair. If the slow path is taken, the ParallelMove might fail to move // the pair according to the X86DexCallingConvention in case of an overlap (e.g., move the // int64 value from <EAX, EBX> to <EBX, ECX>). (Bug: b/168687887) return;
}
ArenaAllocator* allocator = codegen->GetGraph()->GetAllocator();
LocationSummary* locations =
LocationSummary::Create(allocator, invoke, LocationSummary::kCallOnSlowPath, kIntrinsified);
locations->SetInAt(0, Location::RequiresCoreRegister());
size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke); if (expected_coordinates_count == 1u) { // For instance fields, this is the source object
locations->SetInAt(1, Location::RequiresCoreRegister());
}
switch (value_type) { case DataType::Type::kBool: case DataType::Type::kInt8: case DataType::Type::kUint8: // Ensure the value is in a byte register
locations->SetInAt(value_index, Location::ByteRegisterOrConstant(EBX, value)); break; case DataType::Type::kInt16: case DataType::Type::kUint16: case DataType::Type::kInt32:
locations->SetInAt(value_index, Location::RegisterOrConstant(value)); break; case DataType::Type::kInt64: // We only handle constant non-atomic int64 values.
DCHECK(value->IsConstant());
locations->SetInAt(value_index, Location::ConstantLocation(value)); break; case DataType::Type::kReference:
locations->SetInAt(value_index, Location::RequiresCoreRegister()); break; default:
DCHECK(DataType::IsFloatingPointType(value_type)); if (needs_atomicity && value_type == DataType::Type::kFloat64) {
locations->SetInAt(value_index, Location::RequiresFpuRegister());
} else {
locations->SetInAt(value_index, Location::FpuRegisterOrConstant(value));
}
}
locations->AddTemp(Location::RequiresCoreRegister()); // This temporary register is also used for card for MarkGCCard. Make sure it's a byte register
locations->AddTemp(Location::CoreRegister(EAX)); if (expected_coordinates_count == 0 && value_type == DataType::Type::kReference) { // For static reference fields, we need another temporary for the declaring class. We set it // last because we want to make sure that the first 2 temps are reserved for HandleFieldSet.
locations->AddTemp(Location::RequiresCoreRegister());
}
}
staticvoid GenerateVarHandleSet(HInvoke* invoke, CodeGeneratorX86* codegen) { // The only read barrier implementation supporting the // VarHandleGet intrinsic is the Baker-style read barriers.
DCHECK_IMPLIES(codegen->EmitReadBarrier(), kUseBakerReadBarrier);
X86Assembler* assembler = codegen->GetAssembler();
LocationSummary* locations = invoke->GetLocations(); // The value we want to set is the last argument
uint32_t value_index = invoke->GetNumberOfArguments() - 1;
DataType::Type value_type = GetDataTypeFromShorty(invoke, value_index); Register temp = locations->GetTemp(0).AsCoreRegister<Register>(); Register temp2 = locations->GetTemp(1).AsCoreRegister<Register>();
SlowPathCode* slow_path = new (codegen->GetScopedAllocator()) IntrinsicSlowPathX86(invoke);
codegen->AddSlowPath(slow_path);
// For static reference fields, we need another temporary for the declaring class. But since // for instance fields the object is in a separate register, it is safe to use the first // temporary register for GenerateVarHandleFieldReference.
size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke); if (value_type == DataType::Type::kReference && expected_coordinates_count == 0) {
temp = locations->GetTemp(2).AsCoreRegister<Register>();
}
Register offset = temp2; // Get the field referred by the VarHandle. The returned register contains the object reference // or the declaring class. The field offset will be placed in 'offset'. For static fields, the // declaring class will be placed in 'temp' register. Register reference = GenerateVarHandleFieldReference(invoke, codegen, temp, offset);
bool is_volatile = false; switch (invoke->GetIntrinsic()) { case Intrinsics::kVarHandleSet: case Intrinsics::kVarHandleSetOpaque: // The only constraint for setOpaque is to ensure bitwise atomicity (atomically set 64 bit // values), but we don't treat Int64 values because we would need to place it in a register // pair. If the slow path is taken, the Parallel move might fail to move the register pair // in case of an overlap (e.g., move from <EAX, EBX> to <EBX, ECX>). (Bug: b/168687887) break; case Intrinsics::kVarHandleSetRelease: // setRelease needs to ensure atomicity too. See the above comment.
codegen->GenerateMemoryBarrier(MemBarrierKind::kAnyStore); break; case Intrinsics::kVarHandleSetVolatile:
is_volatile = true; break; default:
LOG(FATAL) << "GenerateVarHandleSet received non-set intrinsic " << invoke->GetIntrinsic();
}
InstructionCodeGeneratorX86* instr_codegen =
down_cast<InstructionCodeGeneratorX86*>(codegen->GetInstructionVisitor()); // Store the value to the field
instr_codegen->HandleFieldSet(
invoke,
value_index,
value_type,
Address(reference, offset, TIMES_1, 0),
reference,
is_volatile, /* value_can_be_null */ true, // Value can be null, and this write barrier is not being relied on for other sets.
value_type == DataType::Type::kReference ? WriteBarrierKind::kEmitNotBeingReliedOn :
WriteBarrierKind::kDontEmit);
staticvoid CreateVarHandleGetAndSetLocations(HInvoke* invoke, const CodeGeneratorX86* codegen) { // The only read barrier implementation supporting the // VarHandleGet intrinsic is the Baker-style read barriers. if (codegen->EmitNonBakerReadBarrier()) { return;
}
if (!HasVarHandleIntrinsicImplementation(invoke)) { return;
}
// Get the type from the shorty as the invokes may not return a value.
uint32_t number_of_arguments = invoke->GetNumberOfArguments();
uint32_t value_index = number_of_arguments - 1;
DataType::Type value_type = GetDataTypeFromShorty(invoke, value_index);
DataType::Type return_type = invoke->GetType(); constbool is_void = return_type == DataType::Type::kVoid;
DCHECK_IMPLIES(!is_void, return_type == value_type);
if (DataType::Is64BitType(value_type)) { // We avoid the case of an Int64/Float64 value because we would need to place it in a register // pair. If the slow path is taken, the ParallelMove might fail to move the pair according to // the X86DexCallingConvention in case of an overlap (e.g., move the 64 bit value from // <EAX, EBX> to <EBX, ECX>). return;
}
ArenaAllocator* allocator = codegen->GetGraph()->GetAllocator();
LocationSummary* locations =
LocationSummary::Create(allocator, invoke, LocationSummary::kCallOnSlowPath, kIntrinsified);
locations->AddRegisterTemps(2); // We use this temporary for the card, so we need a byte register
locations->AddTemp(Location::CoreRegister(EBX));
locations->SetInAt(0, Location::RequiresCoreRegister()); if (GetExpectedVarHandleCoordinatesCount(invoke) == 1u) { // For instance fields, this is the source object
locations->SetInAt(1, Location::RequiresCoreRegister());
} else { // For static fields, we need another temp because one will be busy with the declaring class.
locations->AddTemp(Location::RequiresCoreRegister());
} if (value_type == DataType::Type::kFloat32) {
locations->AddTemp(Location::CoreRegister(EAX));
locations->SetInAt(value_index, Location::FpuRegisterOrConstant(invoke->InputAt(value_index))); // Only set the `out` register if it's needed. In the void case, we will not use `out`. if (!is_void) {
locations->SetOut(Location::RequiresFpuRegister());
}
} else {
locations->SetInAt(value_index, Location::CoreRegister(EAX)); // Only set the `out` register if it's needed. In the void case we can still use EAX in the // same manner as it is marked as a temp register. if (is_void) {
locations->AddTemp(Location::CoreRegister(EAX));
} else {
locations->SetOut(Location::CoreRegister(EAX));
}
}
}
staticvoid GenerateVarHandleGetAndSet(HInvoke* invoke, CodeGeneratorX86* codegen) { // The only read barrier implementation supporting the // VarHandleGet intrinsic is the Baker-style read barriers.
DCHECK_IMPLIES(codegen->EmitReadBarrier(), kUseBakerReadBarrier);
X86Assembler* assembler = codegen->GetAssembler();
LocationSummary* locations = invoke->GetLocations(); // The value we want to set is the last argument
uint32_t value_index = invoke->GetNumberOfArguments() - 1;
Location value = locations->InAt(value_index); // Get the type from the shorty as the invokes may not return a value.
DataType::Type value_type = GetDataTypeFromShorty(invoke, value_index); Register temp = locations->GetTemp(1).AsCoreRegister<Register>(); Register temp2 = locations->GetTemp(2).AsCoreRegister<Register>();
SlowPathCode* slow_path = new (codegen->GetScopedAllocator()) IntrinsicSlowPathX86(invoke);
codegen->AddSlowPath(slow_path);
Register offset = locations->GetTemp(0).AsCoreRegister<Register>(); // Get the field referred by the VarHandle. The returned register contains the object reference // or the declaring class. The field offset will be placed in 'offset'. For static fields, the // declaring class will be placed in 'temp' register. Register reference = GenerateVarHandleFieldReference(invoke, codegen, temp, offset);
Address field_addr(reference, offset, TIMES_1, 0);
if (invoke->GetIntrinsic() == Intrinsics::kVarHandleGetAndSetRelease) {
codegen->GenerateMemoryBarrier(MemBarrierKind::kAnyStore);
}
size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke); // For static fields, we need another temporary for the declaring class. But since for instance // fields the object is in a separate register, it is safe to use the first temporary register.
temp = expected_coordinates_count == 1u ? temp : locations->GetTemp(3).AsCoreRegister<Register>(); // No need for a lock prefix. `xchg` has an implicit lock when it is used with an address.
DataType::Type return_type = invoke->GetType(); constbool is_void = return_type == DataType::Type::kVoid;
DCHECK_IMPLIES(!is_void, return_type == value_type); switch (value_type) { case DataType::Type::kBool:
__ xchgb(value.AsCoreRegister<ByteRegister>(), field_addr); if (!is_void) {
__ movzxb(locations->Out().AsCoreRegister<Register>(),
locations->Out().AsCoreRegister<ByteRegister>());
} break; case DataType::Type::kInt8:
__ xchgb(value.AsCoreRegister<ByteRegister>(), field_addr); if (!is_void) {
__ movsxb(locations->Out().AsCoreRegister<Register>(),
locations->Out().AsCoreRegister<ByteRegister>());
} break; case DataType::Type::kUint16:
__ xchgw(value.AsCoreRegister<Register>(), field_addr); if (!is_void) {
__ movzxw(locations->Out().AsCoreRegister<Register>(),
locations->Out().AsCoreRegister<Register>());
} break; case DataType::Type::kInt16:
__ xchgw(value.AsCoreRegister<Register>(), field_addr); if (!is_void) {
__ movsxw(locations->Out().AsCoreRegister<Register>(),
locations->Out().AsCoreRegister<Register>());
} break; case DataType::Type::kInt32:
__ xchgl(value.AsCoreRegister<Register>(), field_addr); break; case DataType::Type::kFloat32:
codegen->Move32(Location::CoreRegister(EAX), value);
__ xchgl(EAX, field_addr); if (!is_void) {
__ movd(locations->Out().AsFpuRegister<XmmRegister>(), EAX);
} break; case DataType::Type::kReference: { if (codegen->EmitBakerReadBarrier()) { // Need to make sure the reference stored in the field is a to-space // one before attempting the CAS or the CAS could fail incorrectly.
codegen->GenerateReferenceLoadWithBakerReadBarrier(
invoke, // Unused, used only as a "temporary" within the read barrier.
Location::CoreRegister(temp),
reference,
field_addr, /* needs_null_check= */ false, /* always_update_field= */ true,
&temp2);
}
codegen->MarkGCCard(temp, temp2, reference); if (kPoisonHeapReferences) {
__ movl(temp, value.AsCoreRegister<Register>());
__ PoisonHeapReference(temp);
__ xchgl(temp, field_addr); if (!is_void) {
__ UnpoisonHeapReference(temp);
__ movl(locations->Out().AsCoreRegister<Register>(), temp);
}
} else {
DCHECK_IMPLIES(!is_void, locations->Out().Equals(Location::CoreRegister(EAX)));
__ xchgl(Location::CoreRegister(EAX).AsCoreRegister<Register>(), field_addr);
} break;
} default:
LOG(FATAL) << "Unexpected type: " << value_type;
UNREACHABLE();
}
if (invoke->GetIntrinsic() == Intrinsics::kVarHandleGetAndSetAcquire) {
codegen->GenerateMemoryBarrier(MemBarrierKind::kLoadAny);
}
staticvoid CreateVarHandleCompareAndSetOrExchangeLocations(HInvoke* invoke, const CodeGeneratorX86* codegen) { // The only read barrier implementation supporting the // VarHandleGet intrinsic is the Baker-style read barriers. if (codegen->EmitNonBakerReadBarrier()) { return;
}
if (!HasVarHandleIntrinsicImplementation(invoke)) { return;
}
if (DataType::Is64BitType(value_type)) { // We avoid the case of an Int64/Float64 value because we would need to place it in a register // pair. If the slow path is taken, the ParallelMove might fail to move the pair according to // the X86DexCallingConvention in case of an overlap (e.g., move the 64 bit value from // <EAX, EBX> to <EBX, ECX>). return;
}
ArenaAllocator* allocator = codegen->GetGraph()->GetAllocator();
LocationSummary* locations =
LocationSummary::Create(allocator, invoke, LocationSummary::kCallOnSlowPath, kIntrinsified);
locations->AddRegisterTemps(2); // We use this temporary for the card, so we need a byte register
locations->AddTemp(Location::CoreRegister(EBX));
locations->SetInAt(0, Location::RequiresCoreRegister()); if (GetExpectedVarHandleCoordinatesCount(invoke) == 1u) { // For instance fields, this is the source object
locations->SetInAt(1, Location::RequiresCoreRegister());
} else { // For static fields, we need another temp because one will be busy with the declaring class.
locations->AddTemp(Location::RequiresCoreRegister());
} if (DataType::IsFloatingPointType(value_type)) { // We need EAX for placing the expected value
locations->AddTemp(Location::CoreRegister(EAX));
locations->SetInAt(new_value_index,
Location::FpuRegisterOrConstant(invoke->InputAt(new_value_index)));
locations->SetInAt(expected_value_index,
Location::FpuRegisterOrConstant(invoke->InputAt(expected_value_index)));
} else { // Ensure it's in a byte register
locations->SetInAt(new_value_index, Location::CoreRegister(ECX));
locations->SetInAt(expected_value_index, Location::CoreRegister(EAX));
}
staticvoid GenerateVarHandleCompareAndSetOrExchange(HInvoke* invoke, CodeGeneratorX86* codegen) { // The only read barrier implementation supporting the // VarHandleGet intrinsic is the Baker-style read barriers.
DCHECK_IMPLIES(codegen->EmitReadBarrier(), kUseBakerReadBarrier);
// Get the field referred by the VarHandle. The returned register contains the object reference // or the declaring class. The field offset will be placed in 'offset'. For static fields, the // declaring class will be placed in 'temp' register. Register reference = GenerateVarHandleFieldReference(invoke, codegen, temp, offset);
uint32_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke); // For generating the compare and exchange, we need 2 temporaries. In case of a static field, the // first temporary contains the declaring class so we need another temporary. In case of an // instance field, the object comes in a separate register so it's safe to use the first temp.
temp = (expected_coordinates_count == 1u) ? temp
: locations->GetTemp(3).AsCoreRegister<Register>();
DCHECK_NE(temp, reference);
// We are using `lock cmpxchg` in all cases because there is no CAS equivalent that has weak // failure semantics. `lock cmpxchg` has full barrier semantics, and we don't need scheduling // barriers at this time.
staticvoid CreateVarHandleGetAndAddLocations(HInvoke* invoke, const CodeGeneratorX86* codegen) { // The only read barrier implementation supporting the // VarHandleGet intrinsic is the Baker-style read barriers. if (codegen->EmitNonBakerReadBarrier()) { return;
}
if (!HasVarHandleIntrinsicImplementation(invoke)) { return;
}
// Get the type from the shorty as the invokes may not return a value. // The last argument should be the value we intend to set.
uint32_t value_index = invoke->GetNumberOfArguments() - 1;
DataType::Type value_type = GetDataTypeFromShorty(invoke, value_index); if (DataType::Is64BitType(value_type)) { // We avoid the case of an Int64/Float64 value because we would need to place it in a register // pair. If the slow path is taken, the ParallelMove might fail to move the pair according to // the X86DexCallingConvention in case of an overlap (e.g., move the 64 bit value from // <EAX, EBX> to <EBX, ECX>). (Bug: b/168687887) return;
}
ArenaAllocator* allocator = codegen->GetGraph()->GetAllocator();
LocationSummary* locations =
LocationSummary::Create(allocator, invoke, LocationSummary::kCallOnSlowPath, kIntrinsified);
locations->AddRegisterTemps(2);
locations->SetInAt(0, Location::RequiresCoreRegister());
size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke); if (expected_coordinates_count == 1u) { // For instance fields, this is the source object
locations->SetInAt(1, Location::RequiresCoreRegister());
} else { // For static fields, we need another temp because one will be busy with the declaring class.
locations->AddTemp(Location::RequiresCoreRegister());
}
if (DataType::IsFloatingPointType(value_type)) {
locations->AddTemp(Location::RequiresFpuRegister());
locations->AddTemp(Location::CoreRegister(EAX));
locations->SetInAt(value_index, Location::RequiresFpuRegister()); // Only set the `out` register if it's needed. In the void case, we do not use `out`. if (!is_void) {
locations->SetOut(Location::RequiresFpuRegister());
}
} else { // xadd updates the register argument with the old value. ByteRegister required for xaddb.
locations->SetInAt(value_index, Location::CoreRegister(EAX)); // Only set the `out` register if it's needed. In the void case we can still use EAX in the // same manner as it is marked as a temp register. if (is_void) {
locations->AddTemp(Location::CoreRegister(EAX));
} else {
locations->SetOut(Location::CoreRegister(EAX));
}
}
}
staticvoid GenerateVarHandleGetAndAdd(HInvoke* invoke, CodeGeneratorX86* codegen) { // The only read barrier implementation supporting the // VarHandleGet intrinsic is the Baker-style read barriers.
DCHECK_IMPLIES(codegen->EmitReadBarrier(), kUseBakerReadBarrier);
X86Assembler* assembler = codegen->GetAssembler();
LocationSummary* locations = invoke->GetLocations();
uint32_t number_of_arguments = invoke->GetNumberOfArguments();
uint32_t value_index = number_of_arguments - 1; // Get the type from the shorty as the invokes may not return a value.
DataType::Type type = GetDataTypeFromShorty(invoke, value_index);
DataType::Type return_type = invoke->GetType(); constbool is_void = return_type == DataType::Type::kVoid;
DCHECK_IMPLIES(!is_void, return_type == type);
Location value_loc = locations->InAt(value_index); Register temp = locations->GetTemp(0).AsCoreRegister<Register>();
SlowPathCode* slow_path = new (codegen->GetScopedAllocator()) IntrinsicSlowPathX86(invoke);
codegen->AddSlowPath(slow_path);
Register offset = locations->GetTemp(1).AsCoreRegister<Register>(); // Get the field referred by the VarHandle. The returned register contains the object reference // or the declaring class. The field offset will be placed in 'offset'. For static fields, the // declaring class will be placed in 'temp' register. Register reference = GenerateVarHandleFieldReference(invoke, codegen, temp, offset);
if (!is_void) { // The old value is present in EAX.
codegen->Move32(locations->Out(), eax);
} break;
} default:
LOG(FATAL) << "Unexpected type: " << type;
UNREACHABLE();
}
staticvoid CreateVarHandleGetAndBitwiseOpLocations(HInvoke* invoke, const CodeGeneratorX86* codegen) { // The only read barrier implementation supporting the // VarHandleGet intrinsic is the Baker-style read barriers. if (codegen->EmitNonBakerReadBarrier()) { return;
}
if (!HasVarHandleIntrinsicImplementation(invoke)) { return;
}
// Get the type from the shorty as the invokes may not return a value. // The last argument should be the value we intend to set.
uint32_t value_index = invoke->GetNumberOfArguments() - 1;
DataType::Type value_type = GetDataTypeFromShorty(invoke, value_index); if (DataType::Is64BitType(value_type)) { // We avoid the case of an Int64 value because we would need to place it in a register pair. // If the slow path is taken, the ParallelMove might fail to move the pair according to the // X86DexCallingConvention in case of an overlap (e.g., move the 64 bit value from // <EAX, EBX> to <EBX, ECX>). (Bug: b/168687887) return;
}
ArenaAllocator* allocator = codegen->GetGraph()->GetAllocator();
LocationSummary* locations =
LocationSummary::Create(allocator, invoke, LocationSummary::kCallOnSlowPath, kIntrinsified); // We need a byte register temp to store the result of the bitwise operation
locations->AddTemp(Location::CoreRegister(EBX));
locations->AddTemp(Location::RequiresCoreRegister());
locations->SetInAt(0, Location::RequiresCoreRegister());
size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke); if (expected_coordinates_count == 1u) { // For instance fields, this is the source object
locations->SetInAt(1, Location::RequiresCoreRegister());
} else { // For static fields, we need another temp because one will be busy with the declaring class.
locations->AddTemp(Location::RequiresCoreRegister());
}
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) { // Used as a temporary, even when we are not outputting it so reserve it. This has to be // requested before the other temporary since there's variable number of temp registers and the // other temp register is expected to be the last one.
locations->AddTemp(Location::CoreRegister(EAX));
} else {
locations->SetOut(Location::CoreRegister(EAX));
}
}
switch (invoke->GetIntrinsic()) { case Intrinsics::kVarHandleGetAndBitwiseOr: case Intrinsics::kVarHandleGetAndBitwiseOrAcquire: case Intrinsics::kVarHandleGetAndBitwiseOrRelease:
__ orl(left, right); break; case Intrinsics::kVarHandleGetAndBitwiseXor: case Intrinsics::kVarHandleGetAndBitwiseXorAcquire: case Intrinsics::kVarHandleGetAndBitwiseXorRelease:
__ xorl(left, right); break; case Intrinsics::kVarHandleGetAndBitwiseAnd: case Intrinsics::kVarHandleGetAndBitwiseAndAcquire: case Intrinsics::kVarHandleGetAndBitwiseAndRelease:
__ andl(left, right); break; default:
LOG(FATAL) << "Unexpected intrinsic: " << invoke->GetIntrinsic();
UNREACHABLE();
}
}
staticvoid GenerateVarHandleGetAndBitwiseOp(HInvoke* invoke, CodeGeneratorX86* codegen) { // The only read barrier implementation supporting the // VarHandleGet intrinsic is the Baker-style read barriers.
DCHECK_IMPLIES(codegen->EmitReadBarrier(), kUseBakerReadBarrier);
X86Assembler* assembler = codegen->GetAssembler();
LocationSummary* locations = invoke->GetLocations(); // Get the type from the shorty as the invokes may not return a value.
uint32_t value_index = invoke->GetNumberOfArguments() - 1;
DataType::Type type = GetDataTypeFromShorty(invoke, value_index);
DataType::Type return_type = invoke->GetType(); constbool is_void = return_type == DataType::Type::kVoid;
DCHECK_IMPLIES(!is_void, return_type == type); Register temp = locations->GetTemp(0).AsCoreRegister<Register>();
SlowPathCode* slow_path = new (codegen->GetScopedAllocator()) IntrinsicSlowPathX86(invoke);
codegen->AddSlowPath(slow_path);
Register offset = locations->GetTemp(1).AsCoreRegister<Register>();
size_t expected_coordinates_count = GetExpectedVarHandleCoordinatesCount(invoke); // For static field, we need another temporary because the first one contains the declaring class Register reference =
(expected_coordinates_count == 1u) ? temp : locations->GetTemp(2).AsCoreRegister<Register>(); // Get the field referred by the VarHandle. The returned register contains the object reference // or the declaring class. The field offset will be placed in 'offset'. For static fields, the // declaring class will be placed in 'reference' register.
reference = GenerateVarHandleFieldReference(invoke, codegen, reference, offset);
DCHECK_NE(temp, reference);
Address field_addr(reference, offset, TIMES_1, 0);
NearLabel try_again;
__ Bind(&try_again); // Place the expected value in EAX for cmpxchg
codegen->LoadFromMemoryNoBarrier(type, eax_loc, field_addr);
codegen->Move32(locations->GetTemp(0), locations->InAt(value_index));
GenerateBitwiseOp(invoke, codegen, temp, eax);
GenPrimitiveLockedCmpxchg(type,
codegen, /* expected_value= */ eax_loc, /* new_value= */ locations->GetTemp(0),
reference,
offset); // If the cmpxchg failed, another thread changed the value so try again.
__ j(kNotZero, &try_again);
¤ 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.102Bemerkung:
(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.