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

Basic implementation of BoardMoveExecutor #9

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
164 changes: 164 additions & 0 deletions Backend/BoardMoveExecutor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Backend.Data;
using Backend.Data.Enum;
using Backend.Data.Struct;

namespace Backend;

public unsafe readonly struct BoardMoveExecutor
{
private readonly struct True { }

private static readonly delegate*<ref BitBoardMap, void>* FPs;

[ModuleInitializer]
internal static void RunCctor()
Copy link
Owner

Choose a reason for hiding this comment

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

No need to do this. It's already done by Util.cs.

Copy link
Author

Choose a reason for hiding this comment

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

Please don't tell me you're pre-running all cctors...

Copy link
Owner

@TheBlackPlague TheBlackPlague Jun 30, 2022

Choose a reason for hiding this comment

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

I am. See:

public static void RunStaticConstructor()

Copy link
Author

Choose a reason for hiding this comment

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

Does that even work? The ModuleInitializer attribute seems to be missing. Either way, RIP startup perf

Copy link
Owner

Choose a reason for hiding this comment

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

I believe it works? — Not 100% sure, but running it seems to be fine.

The start-up performance isn't actually hurt that much.

{
RuntimeHelpers.RunClassConstructor(typeof(BoardMoveExecutor).TypeHandle);
}

[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static MethodInfo GetMethodInfo(Delegate method)
{
return method.Method;
}

static BoardMoveExecutor()
{
//This should be above, for codegen accuracy
FPs = (delegate*<ref BitBoardMap, void>*) NativeMemory.Alloc(64, 64);

//This is necessary for InASM
if (Assembly.GetExecutingAssembly().GetName().Name!.Contains('@'))
{
return;
}

MethodInfo gMethod = GetMethodInfo(ExecuteMove<True, True, True, True, True, True>).GetGenericMethodDefinition();

const int gArgsCount = 6;

Type[] gArgs = new Type[gArgsCount];

ref Type firstArgOffsetByOne = ref Unsafe.Subtract(ref MemoryMarshal.GetArrayDataReference(gArgs), 1);

ref Type lastArg = ref Unsafe.Add(ref firstArgOffsetByOne, gArgsCount);

for (int I = 0; I < 64; I++)
{
const int extractionMask = 1, @true = 1; //LSB set

ref Type currentArg = ref lastArg;

int id = I;

for (; !Unsafe.AreSame(ref currentArg, ref firstArgOffsetByOne)
; currentArg = ref Unsafe.Subtract(ref currentArg, 1))
{
int extractedState = id & extractionMask;

if (extractedState == @true)
{
currentArg = typeof(True);
}

else
{
currentArg = typeof(int); //Any type that isn't True will be treated as false
}

id >>= 1;
}

MethodInfo specializedMethod = gMethod.MakeGenericMethod(gArgs);

RuntimeMethodHandle mh = specializedMethod.MethodHandle;

//JIT method before getting FP pointer, allowing FP to point to optimized code
RuntimeHelpers.PrepareMethod(mh);

FPs[I] = (delegate*<ref BitBoardMap, void>) mh.GetFunctionPointer();
}
}

//For testing purposes
public static MethodInfo PopulateGArgsArrayAndCreateSpecializedMethodInstantiation(int id)
{
Type[] gArgs = new Type[6];

MethodInfo gMethod = GetMethodInfo(ExecuteMove<True, True, True, True, True, True>).GetGenericMethodDefinition();

const int gArgsCount = 6;

ref Type firstArgOffsetByOne = ref Unsafe.Subtract(ref MemoryMarshal.GetArrayDataReference(gArgs), 1);

ref Type currentArg = ref Unsafe.Add(ref firstArgOffsetByOne, gArgsCount);

const int extractionMask = 1, @true = 1; //LSB set

for (; !Unsafe.AreSame(ref currentArg, ref firstArgOffsetByOne)
; currentArg = ref Unsafe.Subtract(ref currentArg, 1))
{
int extractedState = id & extractionMask;

if (extractedState == @true)
{
currentArg = typeof(True);
}

else
{
currentArg = typeof(int); //Any type that isn't True will be treated as false
}

id >>= 1;
}

MethodInfo specializedMethod = gMethod.MakeGenericMethod(gArgs);

return specializedMethod;
}

[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static void ExecuteMove(ref BitBoardMap map, nint id) //Do NOT reorder params! It will incur an additional reg to reg mov!
{
FPs[id](ref map);
}

[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void ExecuteMove<TIsWhiteTurn, TIsEnPassantSet, TIsWhiteKCastle, TIsWhiteQCastle, TIsBlackKCastle, TIsBlackQCastle>(ref BitBoardMap map)
{
if (typeof(TIsWhiteTurn) == typeof(True))
{
Console.WriteLine("IsWhiteTurn");
}

if (typeof(TIsEnPassantSet) == typeof(True))
{
Console.WriteLine("IsEnPassantSet");
}

if (typeof(TIsWhiteKCastle) == typeof(True))
{
Console.WriteLine("IsWhiteKCastle");
}

if (typeof(TIsWhiteQCastle) == typeof(True))
{
Console.WriteLine("IsWhiteQCastle");
}

if (typeof(TIsBlackKCastle) == typeof(True))
{
Console.WriteLine("IsBlackKCastle");
}

if (typeof(TIsBlackQCastle) == typeof(True))
{
Console.WriteLine("IsBlackQCastle");
}
}
}
13 changes: 13 additions & 0 deletions Test/BitBoardMap.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Runtime.CompilerServices;
using Backend.Data.Enum;
using Backend.Data.Struct;
using NUnit.Framework;
Expand Down Expand Up @@ -104,4 +105,16 @@ public void UndoEval()
Assert.IsTrue(evalChanged && evalReverted);
}

[Test]
public void DoesRuntimeCrash()
{
ref var NullRef = ref Unsafe.NullRef<Backend.Data.Struct.BitBoardMap>();

for (int I = 0; I < 64; I++)
{
Console.WriteLine($"\nCurrent ID: {I}\n");

Backend.BoardMoveExecutor.ExecuteMove(ref NullRef, I);
}
}
}