Translator.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. using ARMeilleure.Common;
  2. using ARMeilleure.Decoders;
  3. using ARMeilleure.Diagnostics;
  4. using ARMeilleure.Instructions;
  5. using ARMeilleure.IntermediateRepresentation;
  6. using ARMeilleure.Memory;
  7. using ARMeilleure.Signal;
  8. using ARMeilleure.State;
  9. using ARMeilleure.Translation.Cache;
  10. using ARMeilleure.Translation.PTC;
  11. using Ryujinx.Common;
  12. using System;
  13. using System.Collections.Concurrent;
  14. using System.Collections.Generic;
  15. using System.Diagnostics;
  16. using System.Threading;
  17. using static ARMeilleure.IntermediateRepresentation.Operand.Factory;
  18. namespace ARMeilleure.Translation
  19. {
  20. public class Translator
  21. {
  22. private static readonly AddressTable<ulong>.Level[] Levels64Bit =
  23. new AddressTable<ulong>.Level[]
  24. {
  25. new(31, 17),
  26. new(23, 8),
  27. new(15, 8),
  28. new( 7, 8),
  29. new( 2, 5)
  30. };
  31. private static readonly AddressTable<ulong>.Level[] Levels32Bit =
  32. new AddressTable<ulong>.Level[]
  33. {
  34. new(31, 17),
  35. new(23, 8),
  36. new(15, 8),
  37. new( 7, 8),
  38. new( 1, 6)
  39. };
  40. private readonly IJitMemoryAllocator _allocator;
  41. private readonly ConcurrentQueue<KeyValuePair<ulong, TranslatedFunction>> _oldFuncs;
  42. private readonly ConcurrentDictionary<ulong, object> _backgroundSet;
  43. private readonly ConcurrentStack<RejitRequest> _backgroundStack;
  44. private readonly AutoResetEvent _backgroundTranslatorEvent;
  45. private readonly ReaderWriterLock _backgroundTranslatorLock;
  46. internal ConcurrentDictionary<ulong, TranslatedFunction> Functions { get; }
  47. internal AddressTable<ulong> FunctionTable { get; }
  48. internal EntryTable<uint> CountTable { get; }
  49. internal TranslatorStubs Stubs { get; }
  50. internal IMemoryManager Memory { get; }
  51. private volatile int _threadCount;
  52. // FIXME: Remove this once the init logic of the emulator will be redone.
  53. public static readonly ManualResetEvent IsReadyForTranslation = new(false);
  54. public Translator(IJitMemoryAllocator allocator, IMemoryManager memory, bool for64Bits)
  55. {
  56. _allocator = allocator;
  57. Memory = memory;
  58. _oldFuncs = new ConcurrentQueue<KeyValuePair<ulong, TranslatedFunction>>();
  59. _backgroundSet = new ConcurrentDictionary<ulong, object>();
  60. _backgroundStack = new ConcurrentStack<RejitRequest>();
  61. _backgroundTranslatorEvent = new AutoResetEvent(false);
  62. _backgroundTranslatorLock = new ReaderWriterLock();
  63. JitCache.Initialize(allocator);
  64. CountTable = new EntryTable<uint>();
  65. Functions = new ConcurrentDictionary<ulong, TranslatedFunction>();
  66. FunctionTable = new AddressTable<ulong>(for64Bits ? Levels64Bit : Levels32Bit);
  67. Stubs = new TranslatorStubs(this);
  68. FunctionTable.Fill = (ulong)Stubs.SlowDispatchStub;
  69. if (memory.Type.IsHostMapped())
  70. {
  71. NativeSignalHandler.InitializeSignalHandler();
  72. }
  73. }
  74. private void TranslateStackedSubs()
  75. {
  76. while (_threadCount != 0)
  77. {
  78. _backgroundTranslatorLock.AcquireReaderLock(Timeout.Infinite);
  79. if (_backgroundStack.TryPop(out RejitRequest request) &&
  80. _backgroundSet.TryRemove(request.Address, out _))
  81. {
  82. TranslatedFunction func = Translate(request.Address, request.Mode, highCq: true);
  83. Functions.AddOrUpdate(request.Address, func, (key, oldFunc) =>
  84. {
  85. EnqueueForDeletion(key, oldFunc);
  86. return func;
  87. });
  88. if (PtcProfiler.Enabled)
  89. {
  90. PtcProfiler.UpdateEntry(request.Address, request.Mode, highCq: true);
  91. }
  92. RegisterFunction(request.Address, func);
  93. _backgroundTranslatorLock.ReleaseReaderLock();
  94. }
  95. else
  96. {
  97. _backgroundTranslatorLock.ReleaseReaderLock();
  98. _backgroundTranslatorEvent.WaitOne();
  99. }
  100. }
  101. // Wake up any other background translator threads, to encourage them to exit.
  102. _backgroundTranslatorEvent.Set();
  103. }
  104. public void Execute(State.ExecutionContext context, ulong address)
  105. {
  106. if (Interlocked.Increment(ref _threadCount) == 1)
  107. {
  108. IsReadyForTranslation.WaitOne();
  109. if (Ptc.State == PtcState.Enabled)
  110. {
  111. Debug.Assert(Functions.Count == 0);
  112. Ptc.LoadTranslations(this);
  113. Ptc.MakeAndSaveTranslations(this);
  114. }
  115. PtcProfiler.Start();
  116. Ptc.Disable();
  117. // Simple heuristic, should be user configurable in future. (1 for 4 core/ht or less, 2 for 6 core + ht
  118. // etc). All threads are normal priority except from the last, which just fills as much of the last core
  119. // as the os lets it with a low priority. If we only have one rejit thread, it should be normal priority
  120. // as highCq code is performance critical.
  121. //
  122. // TODO: Use physical cores rather than logical. This only really makes sense for processors with
  123. // hyperthreading. Requires OS specific code.
  124. int unboundedThreadCount = Math.Max(1, (Environment.ProcessorCount - 6) / 3);
  125. int threadCount = Math.Min(4, unboundedThreadCount);
  126. for (int i = 0; i < threadCount; i++)
  127. {
  128. bool last = i != 0 && i == unboundedThreadCount - 1;
  129. Thread backgroundTranslatorThread = new Thread(TranslateStackedSubs)
  130. {
  131. Name = "CPU.BackgroundTranslatorThread." + i,
  132. Priority = last ? ThreadPriority.Lowest : ThreadPriority.Normal
  133. };
  134. backgroundTranslatorThread.Start();
  135. }
  136. }
  137. Statistics.InitializeTimer();
  138. NativeInterface.RegisterThread(context, Memory, this);
  139. if (Optimizations.UseUnmanagedDispatchLoop)
  140. {
  141. Stubs.DispatchLoop(context.NativeContextPtr, address);
  142. }
  143. else
  144. {
  145. do
  146. {
  147. address = ExecuteSingle(context, address);
  148. }
  149. while (context.Running && address != 0);
  150. }
  151. NativeInterface.UnregisterThread();
  152. if (Interlocked.Decrement(ref _threadCount) == 0)
  153. {
  154. _backgroundTranslatorEvent.Set();
  155. ClearJitCache();
  156. Stubs.Dispose();
  157. FunctionTable.Dispose();
  158. CountTable.Dispose();
  159. }
  160. }
  161. public ulong ExecuteSingle(State.ExecutionContext context, ulong address)
  162. {
  163. TranslatedFunction func = GetOrTranslate(address, context.ExecutionMode);
  164. Statistics.StartTimer();
  165. ulong nextAddr = func.Execute(context);
  166. Statistics.StopTimer(address);
  167. return nextAddr;
  168. }
  169. internal TranslatedFunction GetOrTranslate(ulong address, ExecutionMode mode)
  170. {
  171. if (!Functions.TryGetValue(address, out TranslatedFunction func))
  172. {
  173. func = Translate(address, mode, highCq: false);
  174. TranslatedFunction oldFunc = Functions.GetOrAdd(address, func);
  175. if (oldFunc != func)
  176. {
  177. JitCache.Unmap(func.FuncPtr);
  178. func = oldFunc;
  179. }
  180. if (PtcProfiler.Enabled)
  181. {
  182. PtcProfiler.AddEntry(address, mode, highCq: false);
  183. }
  184. RegisterFunction(address, func);
  185. }
  186. return func;
  187. }
  188. internal void RegisterFunction(ulong guestAddress, TranslatedFunction func)
  189. {
  190. if (FunctionTable.IsValid(guestAddress) && (Optimizations.AllowLcqInFunctionTable || func.HighCq))
  191. {
  192. Volatile.Write(ref FunctionTable.GetValue(guestAddress), (ulong)func.FuncPtr);
  193. }
  194. }
  195. internal TranslatedFunction Translate(ulong address, ExecutionMode mode, bool highCq)
  196. {
  197. var context = new ArmEmitterContext(
  198. Memory,
  199. CountTable,
  200. FunctionTable,
  201. Stubs,
  202. address,
  203. highCq,
  204. mode: Aarch32Mode.User);
  205. Logger.StartPass(PassName.Decoding);
  206. Block[] blocks = Decoder.Decode(Memory, address, mode, highCq, singleBlock: false);
  207. Logger.EndPass(PassName.Decoding);
  208. Logger.StartPass(PassName.Translation);
  209. EmitSynchronization(context);
  210. if (blocks[0].Address != address)
  211. {
  212. context.Branch(context.GetLabel(address));
  213. }
  214. ControlFlowGraph cfg = EmitAndGetCFG(context, blocks, out Range funcRange, out Counter<uint> counter);
  215. ulong funcSize = funcRange.End - funcRange.Start;
  216. Logger.EndPass(PassName.Translation, cfg);
  217. Logger.StartPass(PassName.RegisterUsage);
  218. RegisterUsage.RunPass(cfg, mode);
  219. Logger.EndPass(PassName.RegisterUsage);
  220. OperandType[] argTypes = new OperandType[] { OperandType.I64 };
  221. CompilerOptions options = highCq ? CompilerOptions.HighCq : CompilerOptions.None;
  222. GuestFunction func;
  223. if (!context.HasPtc)
  224. {
  225. func = Compiler.Compile<GuestFunction>(cfg, argTypes, OperandType.I64, options);
  226. }
  227. else
  228. {
  229. using PtcInfo ptcInfo = new PtcInfo();
  230. func = Compiler.Compile<GuestFunction>(cfg, argTypes, OperandType.I64, options, ptcInfo);
  231. Hash128 hash = Ptc.ComputeHash(Memory, address, funcSize);
  232. Ptc.WriteInfoCodeRelocUnwindInfo(address, funcSize, hash, highCq, ptcInfo);
  233. }
  234. var result = new TranslatedFunction(func, counter, funcSize, highCq);
  235. Allocators.ResetAll();
  236. return result;
  237. }
  238. private struct Range
  239. {
  240. public ulong Start { get; }
  241. public ulong End { get; }
  242. public Range(ulong start, ulong end)
  243. {
  244. Start = start;
  245. End = end;
  246. }
  247. }
  248. private static ControlFlowGraph EmitAndGetCFG(
  249. ArmEmitterContext context,
  250. Block[] blocks,
  251. out Range range,
  252. out Counter<uint> counter)
  253. {
  254. counter = null;
  255. ulong rangeStart = ulong.MaxValue;
  256. ulong rangeEnd = 0;
  257. for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
  258. {
  259. Block block = blocks[blkIndex];
  260. if (!block.Exit)
  261. {
  262. if (rangeStart > block.Address)
  263. {
  264. rangeStart = block.Address;
  265. }
  266. if (rangeEnd < block.EndAddress)
  267. {
  268. rangeEnd = block.EndAddress;
  269. }
  270. }
  271. if (block.Address == context.EntryAddress && !context.HighCq)
  272. {
  273. EmitRejitCheck(context, out counter);
  274. }
  275. context.CurrBlock = block;
  276. context.MarkLabel(context.GetLabel(block.Address));
  277. if (block.Exit)
  278. {
  279. // Left option here as it may be useful if we need to return to managed rather than tail call in
  280. // future. (eg. for debug)
  281. bool useReturns = false;
  282. InstEmitFlowHelper.EmitVirtualJump(context, Const(block.Address), isReturn: useReturns);
  283. }
  284. else
  285. {
  286. for (int opcIndex = 0; opcIndex < block.OpCodes.Count; opcIndex++)
  287. {
  288. OpCode opCode = block.OpCodes[opcIndex];
  289. context.CurrOp = opCode;
  290. bool isLastOp = opcIndex == block.OpCodes.Count - 1;
  291. if (isLastOp && block.Branch != null && !block.Branch.Exit && block.Branch.Address <= block.Address)
  292. {
  293. EmitSynchronization(context);
  294. }
  295. Operand lblPredicateSkip = default;
  296. if (opCode is OpCode32 op && op.Cond < Condition.Al)
  297. {
  298. lblPredicateSkip = Label();
  299. InstEmitFlowHelper.EmitCondBranch(context, lblPredicateSkip, op.Cond.Invert());
  300. }
  301. if (opCode.Instruction.Emitter != null)
  302. {
  303. opCode.Instruction.Emitter(context);
  304. }
  305. else
  306. {
  307. throw new InvalidOperationException($"Invalid instruction \"{opCode.Instruction.Name}\".");
  308. }
  309. if (lblPredicateSkip != default)
  310. {
  311. context.MarkLabel(lblPredicateSkip);
  312. }
  313. }
  314. }
  315. }
  316. range = new Range(rangeStart, rangeEnd);
  317. return context.GetControlFlowGraph();
  318. }
  319. internal static void EmitRejitCheck(ArmEmitterContext context, out Counter<uint> counter)
  320. {
  321. const int MinsCallForRejit = 100;
  322. counter = new Counter<uint>(context.CountTable);
  323. Operand lblEnd = Label();
  324. Operand address = !context.HasPtc ?
  325. Const(ref counter.Value) :
  326. Const(ref counter.Value, Ptc.CountTableSymbol);
  327. Operand curCount = context.Load(OperandType.I32, address);
  328. Operand count = context.Add(curCount, Const(1));
  329. context.Store(address, count);
  330. context.BranchIf(lblEnd, curCount, Const(MinsCallForRejit), Comparison.NotEqual, BasicBlockFrequency.Cold);
  331. context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.EnqueueForRejit)), Const(context.EntryAddress));
  332. context.MarkLabel(lblEnd);
  333. }
  334. internal static void EmitSynchronization(EmitterContext context)
  335. {
  336. long countOffs = NativeContext.GetCounterOffset();
  337. Operand lblNonZero = Label();
  338. Operand lblExit = Label();
  339. Operand countAddr = context.Add(context.LoadArgument(OperandType.I64, 0), Const(countOffs));
  340. Operand count = context.Load(OperandType.I32, countAddr);
  341. context.BranchIfTrue(lblNonZero, count, BasicBlockFrequency.Cold);
  342. Operand running = context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.CheckSynchronization)));
  343. context.BranchIfTrue(lblExit, running, BasicBlockFrequency.Cold);
  344. context.Return(Const(0L));
  345. context.MarkLabel(lblNonZero);
  346. count = context.Subtract(count, Const(1));
  347. context.Store(countAddr, count);
  348. context.MarkLabel(lblExit);
  349. }
  350. public void InvalidateJitCacheRegion(ulong address, ulong size)
  351. {
  352. // If rejit is running, stop it as it may be trying to rejit a function on the invalidated region.
  353. ClearRejitQueue(allowRequeue: true);
  354. // TODO: Completely remove functions overlapping the specified range from the cache.
  355. }
  356. internal void EnqueueForRejit(ulong guestAddress, ExecutionMode mode)
  357. {
  358. if (_backgroundSet.TryAdd(guestAddress, null))
  359. {
  360. _backgroundStack.Push(new RejitRequest(guestAddress, mode));
  361. _backgroundTranslatorEvent.Set();
  362. }
  363. }
  364. private void EnqueueForDeletion(ulong guestAddress, TranslatedFunction func)
  365. {
  366. _oldFuncs.Enqueue(new(guestAddress, func));
  367. }
  368. private void ClearJitCache()
  369. {
  370. // Ensure no attempt will be made to compile new functions due to rejit.
  371. ClearRejitQueue(allowRequeue: false);
  372. foreach (var func in Functions.Values)
  373. {
  374. JitCache.Unmap(func.FuncPtr);
  375. func.CallCounter?.Dispose();
  376. }
  377. Functions.Clear();
  378. while (_oldFuncs.TryDequeue(out var kv))
  379. {
  380. JitCache.Unmap(kv.Value.FuncPtr);
  381. kv.Value.CallCounter?.Dispose();
  382. }
  383. }
  384. private void ClearRejitQueue(bool allowRequeue)
  385. {
  386. _backgroundTranslatorLock.AcquireWriterLock(Timeout.Infinite);
  387. if (allowRequeue)
  388. {
  389. while (_backgroundStack.TryPop(out var request))
  390. {
  391. if (Functions.TryGetValue(request.Address, out var func) && func.CallCounter != null)
  392. {
  393. Volatile.Write(ref func.CallCounter.Value, 0);
  394. }
  395. _backgroundSet.TryRemove(request.Address, out _);
  396. }
  397. }
  398. else
  399. {
  400. _backgroundStack.Clear();
  401. }
  402. _backgroundTranslatorLock.ReleaseWriterLock();
  403. }
  404. }
  405. }