Translator.cs 15 KB

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