Translator.cs 20 KB

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