Translator.cs 19 KB

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