forked from Mirror/Ryujinx
22b2cb39af
* Turn `MemoryOperand` into a struct * Remove `IntrinsicOperation` * Remove `PhiNode` * Remove `Node` * Turn `Operand` into a struct * Turn `Operation` into a struct * Clean up pool management methods * Add `Arena` allocator * Move `OperationHelper` to `Operation.Factory` * Move `OperandHelper` to `Operand.Factory` * Optimize `Operation` a bit * Fix `Arena` initialization * Rename `NativeList<T>` to `ArenaList<T>` * Reduce `Operand` size from 88 to 56 bytes * Reduce `Operation` size from 56 to 40 bytes * Add optimistic interning of Register & Constant operands * Optimize `RegisterUsage` pass a bit * Optimize `RemoveUnusedNodes` pass a bit Iterating in reverse-order allows killing dependency chains in a single pass. * Fix PPTC symbols * Optimize `BasicBlock` a bit Reduce allocations from `_successor` & `DominanceFrontiers` * Fix `Operation` resize * Make `Arena` expandable Change the arena allocator to be expandable by allocating in pages, with some of them being pooled. Currently 32 pages are pooled. An LRU removal mechanism should probably be added to it. Apparently MHR can allocate bitmaps large enough to exceed the 16MB limit for the type. * Move `Arena` & `ArenaList` to `Common` * Remove `ThreadStaticPool` & co * Add `PhiOperation` * Reduce `Operand` size from 56 from 48 bytes * Add linear-probing to `Operand` intern table * Optimize `HybridAllocator` a bit * Add `Allocators` class * Tune `ArenaAllocator` sizes * Add page removal mechanism to `ArenaAllocator` Remove pages which have not been used for more than 5s after each reset. I am on fence if this would be better using a Gen2 callback object like the one in System.Buffers.ArrayPool<T>, to trim the pool. Because right now if a large translation happens, the pages will be freed only after a reset. This reset may not happen for a while because no new translation is hit, but the arena base sizes are rather small. * Fix `OOM` when allocating larger than page size in `ArenaAllocator` Tweak resizing mechanism for Operand.Uses and Assignemnts. * Optimize `Optimizer` a bit * Optimize `Operand.Add<T>/Remove<T>` a bit * Clean up `PreAllocator` * Fix phi insertion order Reduce codegen diffs. * Fix code alignment * Use new heuristics for degree of parallelism * Suppress warnings * Address gdkchan's feedback Renamed `GetValue()` to `GetValueUnsafe()` to make it more clear that `Operand.Value` should usually not be modified directly. * Add fast path to `ArenaAllocator` * Assembly for `ArenaAllocator.Allocate(ulong)`: .L0: mov rax, [rcx+0x18] lea r8, [rax+rdx] cmp r8, [rcx+0x10] ja short .L2 .L1: mov rdx, [rcx+8] add rax, [rdx+8] mov [rcx+0x18], r8 ret .L2: jmp ArenaAllocator.AllocateSlow(UInt64) A few variable/field had to be changed to ulong so that RyuJIT avoids emitting zero-extends. * Implement a new heuristic to free pooled pages. If an arena is used often, it is more likely that its pages will be needed, so the pages are kept for longer (e.g: during PPTC rebuild or burst sof compilations). If is not used often, then it is more likely that its pages will not be needed (e.g: after PPTC rebuild or bursts of compilations). * Address riperiperi's feedback * Use `EqualityComparer<T>` in `IntrusiveList<T>` Avoids a potential GC hole in `Equals(T, T)`.
248 lines
9.4 KiB
C#
248 lines
9.4 KiB
C#
using ARMeilleure.Instructions;
|
|
using ARMeilleure.IntermediateRepresentation;
|
|
using ARMeilleure.State;
|
|
using ARMeilleure.Translation.Cache;
|
|
using System;
|
|
using System.Reflection;
|
|
using System.Runtime.InteropServices;
|
|
using static ARMeilleure.IntermediateRepresentation.Operand.Factory;
|
|
|
|
namespace ARMeilleure.Translation
|
|
{
|
|
/// <summary>
|
|
/// Represents a stub manager.
|
|
/// </summary>
|
|
class TranslatorStubs : IDisposable
|
|
{
|
|
private static readonly Lazy<IntPtr> _slowDispatchStub = new(GenerateSlowDispatchStub, isThreadSafe: true);
|
|
|
|
private bool _disposed;
|
|
|
|
private readonly Translator _translator;
|
|
private readonly Lazy<IntPtr> _dispatchStub;
|
|
private readonly Lazy<DispatcherFunction> _dispatchLoop;
|
|
|
|
/// <summary>
|
|
/// Gets the dispatch stub.
|
|
/// </summary>
|
|
/// <exception cref="ObjectDisposedException"><see cref="TranslatorStubs"/> instance was disposed</exception>
|
|
public IntPtr DispatchStub
|
|
{
|
|
get
|
|
{
|
|
if (_disposed)
|
|
{
|
|
throw new ObjectDisposedException(null);
|
|
}
|
|
|
|
return _dispatchStub.Value;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the slow dispatch stub.
|
|
/// </summary>
|
|
/// <exception cref="ObjectDisposedException"><see cref="TranslatorStubs"/> instance was disposed</exception>
|
|
public IntPtr SlowDispatchStub
|
|
{
|
|
get
|
|
{
|
|
if (_disposed)
|
|
{
|
|
throw new ObjectDisposedException(null);
|
|
}
|
|
|
|
return _slowDispatchStub.Value;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the dispatch loop function.
|
|
/// </summary>
|
|
/// <exception cref="ObjectDisposedException"><see cref="TranslatorStubs"/> instance was disposed</exception>
|
|
public DispatcherFunction DispatchLoop
|
|
{
|
|
get
|
|
{
|
|
if (_disposed)
|
|
{
|
|
throw new ObjectDisposedException(null);
|
|
}
|
|
|
|
return _dispatchLoop.Value;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="TranslatorStubs"/> class with the specified
|
|
/// <see cref="Translator"/> instance.
|
|
/// </summary>
|
|
/// <param name="translator"><see cref="Translator"/> instance to use</param>
|
|
/// <exception cref="ArgumentNullException"><paramref name="translator"/> is null</exception>
|
|
public TranslatorStubs(Translator translator)
|
|
{
|
|
_translator = translator ?? throw new ArgumentNullException(nameof(translator));
|
|
_dispatchStub = new(GenerateDispatchStub, isThreadSafe: true);
|
|
_dispatchLoop = new(GenerateDispatchLoop, isThreadSafe: true);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Releases all resources used by the <see cref="TranslatorStubs"/> instance.
|
|
/// </summary>
|
|
public void Dispose()
|
|
{
|
|
Dispose(true);
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Releases all unmanaged and optionally managed resources used by the <see cref="TranslatorStubs"/> instance.
|
|
/// </summary>
|
|
/// <param name="disposing"><see langword="true"/> to dispose managed resources also; otherwise just unmanaged resouces</param>
|
|
protected virtual void Dispose(bool disposing)
|
|
{
|
|
if (!_disposed)
|
|
{
|
|
if (_dispatchStub.IsValueCreated)
|
|
{
|
|
JitCache.Unmap(_dispatchStub.Value);
|
|
}
|
|
|
|
if (_dispatchLoop.IsValueCreated)
|
|
{
|
|
JitCache.Unmap(Marshal.GetFunctionPointerForDelegate(_dispatchLoop.Value));
|
|
}
|
|
|
|
_disposed = true;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Frees resources used by the <see cref="TranslatorStubs"/> instance.
|
|
/// </summary>
|
|
~TranslatorStubs()
|
|
{
|
|
Dispose(false);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Generates a <see cref="DispatchStub"/>.
|
|
/// </summary>
|
|
/// <returns>Generated <see cref="DispatchStub"/></returns>
|
|
private IntPtr GenerateDispatchStub()
|
|
{
|
|
var context = new EmitterContext();
|
|
|
|
Operand lblFallback = Label();
|
|
Operand lblEnd = Label();
|
|
|
|
// Load the target guest address from the native context.
|
|
Operand nativeContext = context.LoadArgument(OperandType.I64, 0);
|
|
Operand guestAddress = context.Load(OperandType.I64,
|
|
context.Add(nativeContext, Const((ulong)NativeContext.GetDispatchAddressOffset())));
|
|
|
|
// Check if guest address is within range of the AddressTable.
|
|
Operand masked = context.BitwiseAnd(guestAddress, Const(~_translator.FunctionTable.Mask));
|
|
context.BranchIfTrue(lblFallback, masked);
|
|
|
|
Operand index = default;
|
|
Operand page = Const((long)_translator.FunctionTable.Base);
|
|
|
|
for (int i = 0; i < _translator.FunctionTable.Levels.Length; i++)
|
|
{
|
|
ref var level = ref _translator.FunctionTable.Levels[i];
|
|
|
|
// level.Mask is not used directly because it is more often bigger than 32-bits, so it will not
|
|
// be encoded as an immediate on x86's bitwise and operation.
|
|
Operand mask = Const(level.Mask >> level.Index);
|
|
|
|
index = context.BitwiseAnd(context.ShiftRightUI(guestAddress, Const(level.Index)), mask);
|
|
|
|
if (i < _translator.FunctionTable.Levels.Length - 1)
|
|
{
|
|
page = context.Load(OperandType.I64, context.Add(page, context.ShiftLeft(index, Const(3))));
|
|
context.BranchIfFalse(lblFallback, page);
|
|
}
|
|
}
|
|
|
|
Operand hostAddress;
|
|
Operand hostAddressAddr = context.Add(page, context.ShiftLeft(index, Const(3)));
|
|
hostAddress = context.Load(OperandType.I64, hostAddressAddr);
|
|
context.Tailcall(hostAddress, nativeContext);
|
|
|
|
context.MarkLabel(lblFallback);
|
|
hostAddress = context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetFunctionAddress)), guestAddress);
|
|
context.Tailcall(hostAddress, nativeContext);
|
|
|
|
var cfg = context.GetControlFlowGraph();
|
|
var retType = OperandType.I64;
|
|
var argTypes = new[] { OperandType.I64 };
|
|
|
|
var func = Compiler.Compile<GuestFunction>(cfg, argTypes, retType, CompilerOptions.HighCq);
|
|
|
|
return Marshal.GetFunctionPointerForDelegate(func);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Generates a <see cref="SlowDispatchStub"/>.
|
|
/// </summary>
|
|
/// <returns>Generated <see cref="SlowDispatchStub"/></returns>
|
|
private static IntPtr GenerateSlowDispatchStub()
|
|
{
|
|
var context = new EmitterContext();
|
|
|
|
// Load the target guest address from the native context.
|
|
Operand nativeContext = context.LoadArgument(OperandType.I64, 0);
|
|
Operand guestAddress = context.Load(OperandType.I64,
|
|
context.Add(nativeContext, Const((ulong)NativeContext.GetDispatchAddressOffset())));
|
|
|
|
MethodInfo getFuncAddress = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetFunctionAddress));
|
|
Operand hostAddress = context.Call(getFuncAddress, guestAddress);
|
|
context.Tailcall(hostAddress, nativeContext);
|
|
|
|
var cfg = context.GetControlFlowGraph();
|
|
var retType = OperandType.I64;
|
|
var argTypes = new[] { OperandType.I64 };
|
|
|
|
var func = Compiler.Compile<GuestFunction>(cfg, argTypes, retType, CompilerOptions.HighCq);
|
|
|
|
return Marshal.GetFunctionPointerForDelegate(func);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Generates a <see cref="DispatchLoop"/> function.
|
|
/// </summary>
|
|
/// <returns><see cref="DispatchLoop"/> function</returns>
|
|
private DispatcherFunction GenerateDispatchLoop()
|
|
{
|
|
var context = new EmitterContext();
|
|
|
|
Operand beginLbl = Label();
|
|
Operand endLbl = Label();
|
|
|
|
Operand nativeContext = context.LoadArgument(OperandType.I64, 0);
|
|
Operand guestAddress = context.Copy(
|
|
context.AllocateLocal(OperandType.I64),
|
|
context.LoadArgument(OperandType.I64, 1));
|
|
|
|
Operand runningAddress = context.Add(nativeContext, Const((ulong)NativeContext.GetRunningOffset()));
|
|
Operand dispatchAddress = context.Add(nativeContext, Const((ulong)NativeContext.GetDispatchAddressOffset()));
|
|
|
|
context.MarkLabel(beginLbl);
|
|
context.Store(dispatchAddress, guestAddress);
|
|
context.Copy(guestAddress, context.Call(Const((ulong)DispatchStub), OperandType.I64, nativeContext));
|
|
context.BranchIfFalse(endLbl, guestAddress);
|
|
context.BranchIfFalse(endLbl, context.Load(OperandType.I32, runningAddress));
|
|
context.Branch(beginLbl);
|
|
|
|
context.MarkLabel(endLbl);
|
|
context.Return();
|
|
|
|
var cfg = context.GetControlFlowGraph();
|
|
var retType = OperandType.None;
|
|
var argTypes = new[] { OperandType.I64, OperandType.I64 };
|
|
|
|
return Compiler.Compile<DispatcherFunction>(cfg, argTypes, retType, CompilerOptions.HighCq);
|
|
}
|
|
}
|
|
}
|