Skip to content
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

Improve the performance of ConditionalWeakTable.TryGetValue #80059

Merged
merged 17 commits into from
Jan 5, 2023
Merged
Show file tree
Hide file tree
Changes from 7 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 @@ -114,6 +114,17 @@ public static unsafe void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeH
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetHashCode(object? o);

/// <summary>
/// If a hash code has been assigned to the object, it is returned. Otherwise zero is
/// returned.
/// </summary>
/// <remarks>
/// The advantage of this over <see cref="GetHashCode" /> is that it avoids assigning a hash
/// code to the object if it does not already have one.
/// </remarks>
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int TryGetHashCode(object o);

[MethodImpl(MethodImplOptions.InternalCall)]
public static extern new bool Equals(object? o1, object? o2);

Expand Down
41 changes: 41 additions & 0 deletions src/coreclr/classlibnative/bcltype/objectnative.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,47 @@ FCIMPL1(INT32, ObjectNative::GetHashCode, Object* obj) {
}
FCIMPLEND

FCIMPL1(INT32, ObjectNative::TryGetHashCode, Object* obj) {

CONTRACTL
{
FCALL_CHECK;
}
CONTRACTL_END;

VALIDATEOBJECT(obj);

if (obj == 0)
return 0;

OBJECTREF objRef(obj);

{
DWORD bits = objRef->GetHeader()->GetBits();

if (bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX)
{
if (bits & BIT_SBLK_IS_HASHCODE)
{
// Common case: the object already has a hash code
return bits & MASK_HASHCODE;
}
else
{
// We have a sync block index. There may be a hash code stored within the sync block.
SyncBlock *psb = objRef->PassiveGetSyncBlock();
if (psb != NULL)
{
return psb->GetHashCode();
}
}
}
}

return 0;
}
FCIMPLEND

//
// Compare by ref for normal classes, by value for value types.
//
Expand Down
1 change: 1 addition & 0 deletions src/coreclr/classlibnative/bcltype/objectnative.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class ObjectNative
// If the Class object doesn't exist then you must call the GetClass() method.
static FCDECL1(Object*, GetObjectValue, Object* vThisRef);
static FCDECL1(INT32, GetHashCode, Object* vThisRef);
static FCDECL1(INT32, TryGetHashCode, Object* vThisRef);
static FCDECL2(FC_BOOL_RET, Equals, Object *pThisRef, Object *pCompareRef);
static FCDECL1(Object*, AllocateUninitializedClone, Object* pObjUNSAFE);
static FCDECL1(Object*, GetClass, Object* pThis);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,19 @@ public static unsafe int GetHashCode(object o)
return ObjectHeader.GetHashCode(o);
}

/// <summary>
/// If a hash code has been assigned to the object, it is returned. Otherwise zero is
/// returned.
/// </summary>
/// <remarks>
/// The advantage of this over <see cref="GetHashCode" /> is that it avoids assigning a hash
/// code to the object if it does not already have one.
/// </remarks>
internal static int TryGetHashCode(object o)
{
return ObjectHeader.TryGetHashCode(o);
}

[Obsolete("OffsetToStringData has been deprecated. Use string.GetPinnableReference() instead.")]
public static int OffsetToStringData
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,38 @@ public static unsafe int GetHashCode(object o)
}
}

/// <summary>
/// If a hash code has been assigned to the object, it is returned. Otherwise zero is
/// returned.
/// </summary>
public static unsafe int TryGetHashCode(object o)
{
if (o == null)
return 0;

fixed (MethodTable** ppMethodTable = &o.GetMethodTableRef())
{
int* pHeader = GetHeaderPtr(ppMethodTable);
int bits = *pHeader;
int hashOrIndex = bits & MASK_HASHCODE_INDEX;
if ((bits & BIT_SBLK_IS_HASHCODE) != 0)
{
// Found the hash code in the header
Debug.Assert(hashOrIndex != 0);
return hashOrIndex;
}

if ((bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) != 0)
{
// Look up the hash code in the SyncTable
return SyncTable.GetHashCode(hashOrIndex);
}

// The hash code has not yet been set.
return 0;
}
}

/// <summary>
/// Assigns a hash code to the object in a thread-safe way.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/coreclr/vm/ecalllist.h
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,7 @@ FCFuncStart(gRuntimeHelpers)
FCFuncElement("GetSpanDataFrom", ArrayNative::GetSpanDataFrom)
FCFuncElement("PrepareDelegate", ReflectionInvocation::PrepareDelegate)
FCFuncElement("GetHashCode", ObjectNative::GetHashCode)
FCFuncElement("TryGetHashCode", ObjectNative::TryGetHashCode)
FCFuncElement("Equals", ObjectNative::Equals)
FCFuncElement("AllocateUninitializedClone", ObjectNative::AllocateUninitializedClone)
FCFuncElement("EnsureSufficientExecutionStack", ReflectionInvocation::EnsureSufficientExecutionStack)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public ConditionalWeakTable()
/// </param>
/// <returns>Returns "true" if key was found, "false" otherwise.</returns>
/// <remarks>
/// The key may get garbaged collected during the TryGetValue operation. If so, TryGetValue
/// The key may get garbage collected during the TryGetValue operation. If so, TryGetValue
/// may at its discretion, return "false" and set "value" to the default (as if the key was not present.)
/// </remarks>
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
Expand Down Expand Up @@ -538,7 +538,23 @@ internal int FindEntry(TKey key, out object? value)
{
Debug.Assert(key != null); // Key already validated as non-null.

int hashCode = RuntimeHelpers.GetHashCode(key) & int.MaxValue;
int hashCode;

#if CORECLR || NATIVEAOT
hashCode = RuntimeHelpers.TryGetHashCode(key);

if (hashCode == 0)
AustinWise marked this conversation as resolved.
Show resolved Hide resolved
{
// No hash code has been assigned to the key, so therefore it has not been added
// to any ConditionalWeakTable.
value = null;
return -1;
}
#else
hashCode = RuntimeHelpers.GetHashCode(key);
#endif
AustinWise marked this conversation as resolved.
Show resolved Hide resolved

hashCode &= int.MaxValue;
int bucket = hashCode & (_buckets.Length - 1);
for (int entriesIndex = Volatile.Read(ref _buckets[bucket]); entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
{
Expand Down
8 changes: 8 additions & 0 deletions src/tests/Interop/ObjectiveC/ObjectiveCMarshalAPI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,14 @@ class Scenario
// Do not call this method from Main as it depends on a previous test for set up.
static void _Validate_ExceptionPropagation()
{
// Not yet implemented for NativeAOT.
AustinWise marked this conversation as resolved.
Show resolved Hide resolved
// https://github.com/dotnet/runtime/issues/77472
if (TestLibrary.Utilities.IsNativeAot)
{
Console.WriteLine($"Skipping {nameof(_Validate_ExceptionPropagation)}, NYI");
return;
}

Console.WriteLine($"Running {nameof(_Validate_ExceptionPropagation)}");

var delThrowInt = new ThrowExceptionDelegate(DEL_ThrowIntException);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestKind>BuildAndRun</CLRTestKind>
<CLRTestPriority>0</CLRTestPriority>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="RuntimeImportAttribute.cs" />
<Compile Include="RuntimeImports.cs" />
</ItemGroup>

</Project>
38 changes: 38 additions & 0 deletions src/tests/nativeaot/SmokeTests/GcRestrictedCallouts/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

static class Program
{
static readonly ConditionalWeakTable<object, object> s_weakTable = new();
static readonly object s_inTableObject = new();
static readonly object s_notInTableObject = new();

static volatile bool s_testPass;

static unsafe int Main()
{
s_weakTable.Add(s_inTableObject, new object());

Console.WriteLine("RhRegisterGcCallout");
RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.AfterMarkPhase,
(IntPtr)(delegate* unmanaged<uint, void>)&GcCallback);

Console.WriteLine("GC.Collect");
GC.Collect();

Console.WriteLine("Test passed: " + s_testPass);
return s_testPass ? 100 : 1;
}

[UnmanagedCallersOnly]
static void GcCallback(uint uiCondemnedGeneration)
{
s_testPass = s_weakTable.TryGetValue(s_inTableObject, out object _) &&
!s_weakTable.TryGetValue(s_notInTableObject, out object _);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace System.Runtime
{
// Exposed in Internal.CompilerServices only
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
public sealed class RuntimeImportAttribute : Attribute
{
public string DllName { get; }
public string EntryPoint { get; }

public RuntimeImportAttribute(string entry)
{
EntryPoint = entry;
}

public RuntimeImportAttribute(string dllName, string entry)
{
EntryPoint = entry;
DllName = dllName;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime;
using System.Runtime.CompilerServices;

namespace System.Runtime
{
// Copied from src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs
static class RuntimeImports
{
private const string RuntimeLibrary = "*";

internal enum GcRestrictedCalloutKind
{
StartCollection = 0, // Collection is about to begin
EndCollection = 1, // Collection has completed
AfterMarkPhase = 2, // All live objects are marked (not including ready for finalization objects),
// no handles have been cleared
}

[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhRegisterGcCallout")]
internal static extern bool RhRegisterGcCallout(GcRestrictedCalloutKind eKind, IntPtr pCalloutMethod);

[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhUnregisterGcCallout")]
internal static extern void RhUnregisterGcCallout(GcRestrictedCalloutKind eKind, IntPtr pCalloutMethod);
}
}