Skip to content

Move GetMethodTable and IsReference to JIT #88860

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -188,15 +188,6 @@ public static object GetUninitializedObject(
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object AllocateUninitializedClone(object obj);

/// <returns>true if given type is reference type or value type that contains references</returns>
[Intrinsic]
public static bool IsReferenceOrContainsReferences<T>()
{
// The body of this function will be replaced by the EE with unsafe code!!!
// See getILIntrinsicImplementationForRuntimeHelpers for how this happens.
throw new InvalidOperationException();
}

/// <returns>true if given type is bitwise equatable (memcmp can be used for equality checking)</returns>
/// <remarks>
/// Only use the result of this for Equals() comparison, not for CompareTo() comparison.
Expand Down Expand Up @@ -297,18 +288,12 @@ internal static unsafe bool ObjectHasComponentSize(object obj)
// ... work with pMT ...
//
// GC.KeepAlive(o);
//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[Intrinsic]
internal static unsafe MethodTable* GetMethodTable(object obj)
{
// The body of this function will be replaced by the EE with unsafe code
// See getILIntrinsicImplementationForRuntimeHelpers for how this happens.

return (MethodTable *)Unsafe.Add(ref Unsafe.As<byte, IntPtr>(ref obj.GetRawData()), -1);
return GetMethodTable(obj);
}


[LibraryImport(QCall, EntryPoint = "MethodTable_AreTypesEquivalent")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static unsafe partial bool AreTypesEquivalent(MethodTable* pMTa, MethodTable* pMTb);
Expand Down
1 change: 1 addition & 0 deletions src/coreclr/jit/assertionprop.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4699,6 +4699,7 @@ GenTree* Compiler::optAssertionProp_Update(GenTree* newTree, GenTree* tree, Stat
if (parent != nullptr)
{
parent->ReplaceOperand(useEdge, newTree);
parent->gtFlags |= gtGetFlagsForOperand(parent->gtOper, newTree);
Comment on lines 4701 to +4702
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This flag updating call should be moved to this place in morph:

if (op1->IsIconHandle(GTF_ICON_OBJ_HDL))
{
tree->gtFlags |= (GTF_IND_INVARIANT | GTF_IND_NONFAULTING | GTF_IND_NONNULL);
}

}
else
{
Expand Down
2 changes: 2 additions & 0 deletions src/coreclr/jit/compiler.h
Original file line number Diff line number Diff line change
Expand Up @@ -3007,6 +3007,8 @@ class Compiler
// having to re-run the algorithm that looks for them (might also improve CQ).
bool gtMarkAddrMode(GenTree* addr, int* costEx, int* costSz, var_types type);

GenTreeFlags gtGetFlagsForOperand(genTreeOps oper, GenTree* op);

unsigned gtSetEvalOrder(GenTree* tree);

void gtSetStmtInfo(Statement* stmt);
Expand Down
37 changes: 4 additions & 33 deletions src/coreclr/jit/fgdiagnostic.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3135,39 +3135,10 @@ void Compiler::fgDebugCheckFlags(GenTree* tree)
break;

case GT_IND:
// Do we have a constant integer address as op1 that is also a handle?
if (op1->IsIconHandle())
{
if ((tree->gtFlags & GTF_IND_INVARIANT) != 0)
{
actualFlags |= GTF_IND_INVARIANT;
}
if ((tree->gtFlags & GTF_IND_NONFAULTING) != 0)
{
actualFlags |= GTF_IND_NONFAULTING;
}

GenTreeFlags handleKind = op1->GetIconHandleFlag();

// Some of these aren't handles to invariant data...
if ((handleKind == GTF_ICON_STATIC_HDL) || // Pointer to a mutable class Static variable
(handleKind == GTF_ICON_BBC_PTR) || // Pointer to a mutable basic block count value
(handleKind == GTF_ICON_GLOBAL_PTR)) // Pointer to mutable data from the VM state
{
// For statics, we expect the GTF_GLOB_REF to be set. However, we currently
// fail to set it in a number of situations, and so this check is disabled.
// TODO: enable checking of GTF_GLOB_REF.
// expectedFlags |= GTF_GLOB_REF;
}
else // All the other handle indirections are considered invariant
{
expectedFlags |= GTF_IND_INVARIANT;
}

// Currently we expect all indirections with constant addresses to be nonfaulting.
expectedFlags |= GTF_IND_NONFAULTING;
}

// For statics, we expect the GTF_GLOB_REF to be set. However, we currently
// fail to set it in a number of situations, and so this check is disabled.
// TODO: enable checking of GTF_GLOB_REF.
expectedFlags |= gtGetFlagsForOperand(GT_IND, op1);
assert(((tree->gtFlags & GTF_IND_TGT_NOT_HEAP) == 0) || ((tree->gtFlags & GTF_IND_TGT_HEAP) == 0));
break;

Expand Down
27 changes: 27 additions & 0 deletions src/coreclr/jit/gentree.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4889,6 +4889,32 @@ bool Compiler::gtMarkAddrMode(GenTree* addr, int* pCostEx, int* pCostSz, var_typ
return false;
}

//------------------------------------------------------------------------------
// gtGetFlagsForOperand : Get flags for an operation over the operant
//
// Arguments:
// oper - Performed operation
// op - Operand
//
// Return Value:
// Flags required by the operand
GenTreeFlags Compiler::gtGetFlagsForOperand(genTreeOps oper, GenTree* op)
{
GenTreeFlags flags = GTF_EMPTY;
if ((oper == GT_IND) && op->IsIconHandle())
{
flags |= GTF_IND_NONFAULTING;

GenTreeFlags handleKind = op->GetIconHandleFlag();
if ((handleKind != GTF_ICON_STATIC_HDL) && (handleKind != GTF_ICON_BBC_PTR) &&
(handleKind != GTF_ICON_GLOBAL_PTR))
{
flags |= GTF_IND_INVARIANT;
}
}
Comment on lines +4903 to +4914
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This invariantness setting is fragile; it does not check what type is being loaded.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I had the same concern - like why do we expect invariantess if we acess a byte location with long type

return flags;
}

/*****************************************************************************
*
* Given a tree, figure out the order in which its sub-operands should be
Expand Down Expand Up @@ -8214,6 +8240,7 @@ GenTreeBlk* Compiler::gtNewBlkIndir(ClassLayout* layout, GenTree* addr, GenTreeF
//
GenTreeIndir* Compiler::gtNewIndir(var_types typ, GenTree* addr, GenTreeFlags indirFlags)
{
indirFlags |= gtGetFlagsForOperand(GT_IND, addr);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this needed here? The caller is expected to pass the right indirFlags.

Copy link
Member

@EgorBo EgorBo Jul 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I bet it's not needed it's just how @MichalPetryka was trying to find the case where it's not set (turned out be assertprop)

GenTreeIndir* indir = new (this, GT_IND) GenTreeIndir(GT_IND, typ, addr, nullptr);
gtInitializeIndirNode(indir, indirFlags);

Expand Down
38 changes: 38 additions & 0 deletions src/coreclr/jit/importercalls.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2759,6 +2759,32 @@ GenTree* Compiler::impIntrinsic(GenTree* newobjThis,
break;
}

case NI_System_Runtime_CompilerServices_RuntimeHelpers_IsReference:
{
assert(sig->sigInst.methInstCount == 1);
CORINFO_CLASS_HANDLE hClass = sig->sigInst.methInst[0];

retNode = gtNewIconNode(eeIsValueClass(hClass) ? 0 : 1);
break;
}

case NI_System_Runtime_CompilerServices_RuntimeHelpers_IsReferenceOrContainsReferences:
{
assert(sig->sigInst.methInstCount == 1);
CORINFO_CLASS_HANDLE hClass = sig->sigInst.methInst[0];

uint32_t flags = info.compCompHnd->getClassAttribs(hClass) &
(CORINFO_FLG_VALUECLASS | CORINFO_FLG_CONTAINS_GC_PTR);
retNode = gtNewIconNode((flags == CORINFO_FLG_VALUECLASS) ? 0 : 1);
break;
}

case NI_System_Runtime_CompilerServices_RuntimeHelpers_GetMethodTable:
{
retNode = gtNewMethodTableLookup(impPopStack().val);
break;
}

case NI_System_Runtime_InteropService_MemoryMarshal_GetArrayDataReference:
{
assert(sig->numArgs == 1);
Expand Down Expand Up @@ -8948,6 +8974,18 @@ NamedIntrinsic Compiler::lookupNamedIntrinsic(CORINFO_METHOD_HANDLE method)
{
result = NI_System_Runtime_CompilerServices_RuntimeHelpers_IsKnownConstant;
}
else if (strcmp(methodName, "IsReference") == 0)
{
result = NI_System_Runtime_CompilerServices_RuntimeHelpers_IsReference;
}
else if (strcmp(methodName, "IsReferenceOrContainsReferences") == 0)
{
result = NI_System_Runtime_CompilerServices_RuntimeHelpers_IsReferenceOrContainsReferences;
}
else if (strcmp(methodName, "GetMethodTable") == 0)
{
result = NI_System_Runtime_CompilerServices_RuntimeHelpers_GetMethodTable;
}
}
else if (strcmp(className, "Unsafe") == 0)
{
Expand Down
3 changes: 3 additions & 0 deletions src/coreclr/jit/namedintrinsiclist.h
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ enum NamedIntrinsic : unsigned short
NI_System_Runtime_CompilerServices_RuntimeHelpers_CreateSpan,
NI_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray,
NI_System_Runtime_CompilerServices_RuntimeHelpers_IsKnownConstant,
NI_System_Runtime_CompilerServices_RuntimeHelpers_IsReference,
NI_System_Runtime_CompilerServices_RuntimeHelpers_IsReferenceOrContainsReferences,
NI_System_Runtime_CompilerServices_RuntimeHelpers_GetMethodTable,

NI_System_Runtime_InteropService_MemoryMarshal_GetArrayDataReference,

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,18 +186,10 @@ public static unsafe bool TryEnsureSufficientExecutionStack()
return (t_sufficientStackLimit = limit);
}

[Intrinsic]
public static bool IsReferenceOrContainsReferences<T>()
{
var pEEType = EETypePtr.EETypePtrOf<T>();
return !pEEType.IsValueType || pEEType.ContainsGCPointers;
}

[Intrinsic]
internal static bool IsReference<T>()
{
var pEEType = EETypePtr.EETypePtrOf<T>();
return !pEEType.IsValueType;
return IsReference<T>();
}

[Intrinsic]
Expand Down Expand Up @@ -231,8 +223,9 @@ internal static unsafe ushort GetElementSize(this Array array)
return array.GetMethodTable()->ComponentSize;
}

[Intrinsic]
internal static unsafe MethodTable* GetMethodTable(this object obj)
=> obj.m_pEEType;
=> GetMethodTable(obj);

internal static unsafe ref MethodTable* GetMethodTableRef(this object obj)
=> ref obj.m_pEEType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,6 @@ public static class RuntimeHelpersIntrinsics
public static MethodIL EmitIL(MethodDesc method)
{
Debug.Assert(((MetadataType)method.OwningType).Name == "RuntimeHelpers");
string methodName = method.Name;

if (methodName == "GetMethodTable")
{
ILEmitter emit = new ILEmitter();
ILCodeStream codeStream = emit.NewCodeStream();
codeStream.EmitLdArg(0);
codeStream.Emit(ILOpcode.ldflda, emit.NewToken(method.Context.SystemModule.GetKnownType("System.Runtime.CompilerServices", "RawData").GetField("Data")));
codeStream.EmitLdc(-method.Context.Target.PointerSize);
codeStream.Emit(ILOpcode.add);
codeStream.Emit(ILOpcode.ldind_i);
codeStream.Emit(ILOpcode.ret);
return emit.Link(method);
}

// All the methods handled below are per-instantiation generic methods
if (method.Instantiation.Length != 1 || method.IsTypicalMethodDefinition)
Expand All @@ -43,15 +29,7 @@ public static MethodIL EmitIL(MethodDesc method)
return null;

bool result;
if (methodName == "IsReferenceOrContainsReferences")
{
result = elementType.IsGCPointer || (elementType is DefType defType && defType.ContainsGCPointers);
}
else if (methodName == "IsReference")
{
result = elementType.IsGCPointer;
}
else if (methodName == "IsBitwiseEquatable")
if (method.Name == "IsBitwiseEquatable")
{
// Ideally we could detect automatically whether a type is trivially equatable
// (i.e., its operator == could be implemented via memcmp). But for now we'll
Expand Down
2 changes: 0 additions & 2 deletions src/coreclr/vm/corelib.h
Original file line number Diff line number Diff line change
Expand Up @@ -657,9 +657,7 @@ DEFINE_CLASS(RTFIELD, Reflection, RtFieldInfo)
DEFINE_METHOD(RTFIELD, GET_FIELDHANDLE, GetFieldHandle, IM_RetIntPtr)

DEFINE_CLASS(RUNTIME_HELPERS, CompilerServices, RuntimeHelpers)
DEFINE_METHOD(RUNTIME_HELPERS, IS_REFERENCE_OR_CONTAINS_REFERENCES, IsReferenceOrContainsReferences, NoSig)
DEFINE_METHOD(RUNTIME_HELPERS, IS_BITWISE_EQUATABLE, IsBitwiseEquatable, NoSig)
DEFINE_METHOD(RUNTIME_HELPERS, GET_METHOD_TABLE, GetMethodTable, NoSig)
DEFINE_METHOD(RUNTIME_HELPERS, GET_RAW_DATA, GetRawData, NoSig)
DEFINE_METHOD(RUNTIME_HELPERS, GET_UNINITIALIZED_OBJECT, GetUninitializedObject, SM_Type_RetObj)
DEFINE_METHOD(RUNTIME_HELPERS, ENUM_EQUALS, EnumEquals, NoSig)
Expand Down
65 changes: 0 additions & 65 deletions src/coreclr/vm/jitinterface.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7277,34 +7277,6 @@ bool getILIntrinsicImplementationForRuntimeHelpers(MethodDesc * ftn,

mdMethodDef tk = ftn->GetMemberDef();

if (tk == CoreLibBinder::GetMethod(METHOD__RUNTIME_HELPERS__IS_REFERENCE_OR_CONTAINS_REFERENCES)->GetMemberDef())
{
_ASSERTE(ftn->HasMethodInstantiation());
Instantiation inst = ftn->GetMethodInstantiation();

_ASSERTE(ftn->GetNumGenericMethodArgs() == 1);
TypeHandle typeHandle = inst[0];
MethodTable * methodTable = typeHandle.GetMethodTable();

static const BYTE returnTrue[] = { CEE_LDC_I4_1, CEE_RET };
static const BYTE returnFalse[] = { CEE_LDC_I4_0, CEE_RET };

if (!methodTable->IsValueType() || methodTable->ContainsPointers())
{
methInfo->ILCode = const_cast<BYTE*>(returnTrue);
}
else
{
methInfo->ILCode = const_cast<BYTE*>(returnFalse);
}

methInfo->ILCodeSize = sizeof(returnTrue);
methInfo->maxStack = 1;
methInfo->EHcount = 0;
methInfo->options = (CorInfoOptions)0;
return true;
}

if (tk == CoreLibBinder::GetMethod(METHOD__RUNTIME_HELPERS__IS_BITWISE_EQUATABLE)->GetMemberDef())
{
_ASSERTE(ftn->HasMethodInstantiation());
Expand Down Expand Up @@ -7354,43 +7326,6 @@ bool getILIntrinsicImplementationForRuntimeHelpers(MethodDesc * ftn,
return true;
}

if (tk == CoreLibBinder::GetMethod(METHOD__RUNTIME_HELPERS__GET_METHOD_TABLE)->GetMemberDef())
{
mdToken tokRawData = CoreLibBinder::GetField(FIELD__RAW_DATA__DATA)->GetMemberDef();

// In the CLR, an object is laid out as follows.
// [ object_header || MethodTable* (64-bit pointer) || instance_data ]
// ^ ^-- ref <theObj>.firstField points here
// `-- <theObj> reference (type O) points here
//
// So essentially what we want to do is to turn an object reference (type O) into a
// native int&, then dereference it to get the MethodTable*. (Essentially, an object
// reference is a MethodTable**.) Per ECMA-335, Sec. III.1.5, we can add
// (but not subtract) a & and an int32 to produce a &. So we'll get a reference to
// <theObj>.firstField (type &), then back up one pointer length to get a value of
// essentially type (MethodTable*)&. Both of these are legal GC-trackable references
// to <theObj>, regardless of <theObj>'s actual length.

static BYTE ilcode[] = { CEE_LDARG_0, // stack contains [ O ] = <theObj>
CEE_LDFLDA,0,0,0,0, // stack contains [ & ] = ref <theObj>.firstField
CEE_LDC_I4_S,(BYTE)(-TARGET_POINTER_SIZE), // stack contains [ &, int32 ] = -IntPtr.Size
CEE_ADD, // stack contains [ & ] = ref <theObj>.methodTablePtr
CEE_LDIND_I, // stack contains [ native int ] = <theObj>.methodTablePtr
CEE_RET };

ilcode[2] = (BYTE)(tokRawData);
ilcode[3] = (BYTE)(tokRawData >> 8);
ilcode[4] = (BYTE)(tokRawData >> 16);
ilcode[5] = (BYTE)(tokRawData >> 24);

methInfo->ILCode = const_cast<BYTE*>(ilcode);
methInfo->ILCodeSize = sizeof(ilcode);
methInfo->maxStack = 2;
methInfo->EHcount = 0;
methInfo->options = (CorInfoOptions)0;
return true;
}

if (tk == CoreLibBinder::GetMethod(METHOD__RUNTIME_HELPERS__ENUM_EQUALS)->GetMemberDef())
{
// Normally we would follow the above pattern and unconditionally replace the IL,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,9 @@ internal static bool IsPrimitiveType(this CorElementType et)
[Intrinsic]
public static unsafe ReadOnlySpan<T> CreateSpan<T>(RuntimeFieldHandle fldHandle) => new ReadOnlySpan<T>(GetSpanDataFrom(fldHandle, typeof(T).TypeHandle, out int length), length);

/// <returns>true if given type is reference type or value type that contains references</returns>
[Intrinsic]
public static bool IsReferenceOrContainsReferences<T>() => IsReferenceOrContainsReferences<T>();

// The following intrinsics return true if input is a compile-time constant
// Feel free to add more overloads on demand
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,6 @@ public static IntPtr AllocateTypeAssociatedMemory(Type type, int size)
[Intrinsic]
internal static ref byte GetRawData(this object obj) => ref obj.GetRawData();

[Intrinsic]
public static bool IsReferenceOrContainsReferences<T>() => IsReferenceOrContainsReferences<T>();

[Intrinsic]
internal static bool IsBitwiseEquatable<T>() => IsBitwiseEquatable<T>();

Expand Down