Translator.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. Debug.Assert(_funcs.Count == 0);
  85. Ptc.LoadTranslations(_funcs, _memory, _jumpTable);
  86. Ptc.MakeAndSaveTranslations(_funcs, _memory, _jumpTable);
  87. }
  88. PtcProfiler.Start();
  89. Ptc.Disable();
  90. // Simple heuristic, should be user configurable in future. (1 for 4 core/ht or less, 2 for 6 core+ht etc).
  91. // 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.
  92. // If we only have one rejit thread, it should be normal priority as highCq code is performance critical.
  93. // TODO: Use physical cores rather than logical. This only really makes sense for processors with hyperthreading. Requires OS specific code.
  94. int unboundedThreadCount = Math.Max(1, (Environment.ProcessorCount - 6) / 3);
  95. int threadCount = Math.Min(4, unboundedThreadCount);
  96. for (int i = 0; i < threadCount; i++)
  97. {
  98. bool last = i != 0 && i == unboundedThreadCount - 1;
  99. Thread backgroundTranslatorThread = new Thread(TranslateStackedSubs)
  100. {
  101. Name = "CPU.BackgroundTranslatorThread." + i,
  102. Priority = last ? ThreadPriority.Lowest : ThreadPriority.Normal
  103. };
  104. backgroundTranslatorThread.Start();
  105. }
  106. }
  107. Statistics.InitializeTimer();
  108. NativeInterface.RegisterThread(context, _memory, this);
  109. do
  110. {
  111. address = ExecuteSingle(context, address);
  112. }
  113. while (context.Running && address != 0);
  114. NativeInterface.UnregisterThread();
  115. if (Interlocked.Decrement(ref _threadCount) == 0)
  116. {
  117. _backgroundTranslatorEvent.Set();
  118. ClearJitCache();
  119. DisposePools();
  120. _jumpTable.Dispose();
  121. _jumpTable = null;
  122. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
  123. }
  124. }
  125. public ulong ExecuteSingle(State.ExecutionContext context, ulong address)
  126. {
  127. TranslatedFunction func = GetOrTranslate(address, context.ExecutionMode);
  128. Statistics.StartTimer();
  129. ulong nextAddr = func.Execute(context);
  130. Statistics.StopTimer(address);
  131. return nextAddr;
  132. }
  133. internal TranslatedFunction GetOrTranslate(ulong address, ExecutionMode mode, bool hintRejit = false)
  134. {
  135. if (!_funcs.TryGetValue(address, out TranslatedFunction func))
  136. {
  137. func = Translate(_memory, _jumpTable, address, mode, highCq: false);
  138. TranslatedFunction getFunc = _funcs.GetOrAdd(address, func);
  139. if (getFunc != func)
  140. {
  141. JitCache.Unmap(func.FuncPtr);
  142. func = getFunc;
  143. }
  144. if (PtcProfiler.Enabled)
  145. {
  146. PtcProfiler.AddEntry(address, mode, highCq: false);
  147. }
  148. }
  149. if (hintRejit && func.ShouldRejit())
  150. {
  151. _backgroundStack.Push(new RejitRequest(address, mode));
  152. _backgroundTranslatorEvent.Set();
  153. }
  154. return func;
  155. }
  156. internal static TranslatedFunction Translate(IMemoryManager memory, JumpTable jumpTable, ulong address, ExecutionMode mode, bool highCq)
  157. {
  158. ArmEmitterContext context = new ArmEmitterContext(memory, jumpTable, address, highCq, Aarch32Mode.User);
  159. Logger.StartPass(PassName.Decoding);
  160. Block[] blocks = Decoder.Decode(memory, address, mode, highCq, singleBlock: false);
  161. Logger.EndPass(PassName.Decoding);
  162. PreparePool(highCq ? 1 : 0);
  163. Logger.StartPass(PassName.Translation);
  164. EmitSynchronization(context);
  165. if (blocks[0].Address != address)
  166. {
  167. context.Branch(context.GetLabel(address));
  168. }
  169. ControlFlowGraph cfg = EmitAndGetCFG(context, blocks, out Range funcRange);
  170. ulong funcSize = funcRange.End - funcRange.Start;
  171. Logger.EndPass(PassName.Translation);
  172. Logger.StartPass(PassName.RegisterUsage);
  173. RegisterUsage.RunPass(cfg, mode);
  174. Logger.EndPass(PassName.RegisterUsage);
  175. OperandType[] argTypes = new OperandType[] { OperandType.I64 };
  176. CompilerOptions options = highCq ? CompilerOptions.HighCq : CompilerOptions.None;
  177. GuestFunction func;
  178. if (Ptc.State == PtcState.Disabled)
  179. {
  180. func = Compiler.Compile<GuestFunction>(cfg, argTypes, OperandType.I64, options);
  181. ResetPool(highCq ? 1 : 0);
  182. }
  183. else
  184. {
  185. using PtcInfo ptcInfo = new PtcInfo();
  186. func = Compiler.Compile<GuestFunction>(cfg, argTypes, OperandType.I64, options, ptcInfo);
  187. ResetPool(highCq ? 1 : 0);
  188. Ptc.WriteInfoCodeRelocUnwindInfo(address, funcSize, highCq, ptcInfo);
  189. }
  190. return new TranslatedFunction(func, funcSize, highCq);
  191. }
  192. internal static void PreparePool(int groupId = 0)
  193. {
  194. PrepareOperandPool(groupId);
  195. PrepareOperationPool(groupId);
  196. }
  197. internal static void ResetPool(int groupId = 0)
  198. {
  199. ResetOperationPool(groupId);
  200. ResetOperandPool(groupId);
  201. }
  202. internal static void DisposePools()
  203. {
  204. DisposeOperandPools();
  205. DisposeOperationPools();
  206. DisposeBitMapPools();
  207. }
  208. private struct Range
  209. {
  210. public ulong Start { get; }
  211. public ulong End { get; }
  212. public Range(ulong start, ulong end)
  213. {
  214. Start = start;
  215. End = end;
  216. }
  217. }
  218. private static ControlFlowGraph EmitAndGetCFG(ArmEmitterContext context, Block[] blocks, out Range range)
  219. {
  220. ulong rangeStart = ulong.MaxValue;
  221. ulong rangeEnd = 0;
  222. for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
  223. {
  224. Block block = blocks[blkIndex];
  225. if (!block.Exit)
  226. {
  227. if (rangeStart > block.Address)
  228. {
  229. rangeStart = block.Address;
  230. }
  231. if (rangeEnd < block.EndAddress)
  232. {
  233. rangeEnd = block.EndAddress;
  234. }
  235. }
  236. context.CurrBlock = block;
  237. context.MarkLabel(context.GetLabel(block.Address));
  238. if (block.Exit)
  239. {
  240. InstEmitFlowHelper.EmitTailContinue(context, Const(block.Address), block.TailCall);
  241. }
  242. else
  243. {
  244. for (int opcIndex = 0; opcIndex < block.OpCodes.Count; opcIndex++)
  245. {
  246. OpCode opCode = block.OpCodes[opcIndex];
  247. context.CurrOp = opCode;
  248. bool isLastOp = opcIndex == block.OpCodes.Count - 1;
  249. if (isLastOp && block.Branch != null && !block.Branch.Exit && block.Branch.Address <= block.Address)
  250. {
  251. EmitSynchronization(context);
  252. }
  253. Operand lblPredicateSkip = null;
  254. if (opCode is OpCode32 op && op.Cond < Condition.Al)
  255. {
  256. lblPredicateSkip = Label();
  257. InstEmitFlowHelper.EmitCondBranch(context, lblPredicateSkip, op.Cond.Invert());
  258. }
  259. if (opCode.Instruction.Emitter != null)
  260. {
  261. opCode.Instruction.Emitter(context);
  262. }
  263. else
  264. {
  265. throw new InvalidOperationException($"Invalid instruction \"{opCode.Instruction.Name}\".");
  266. }
  267. if (lblPredicateSkip != null)
  268. {
  269. context.MarkLabel(lblPredicateSkip);
  270. }
  271. }
  272. }
  273. }
  274. range = new Range(rangeStart, rangeEnd);
  275. return context.GetControlFlowGraph();
  276. }
  277. internal static void EmitSynchronization(EmitterContext context)
  278. {
  279. long countOffs = NativeContext.GetCounterOffset();
  280. Operand countAddr = context.Add(context.LoadArgument(OperandType.I64, 0), Const(countOffs));
  281. Operand count = context.Load(OperandType.I32, countAddr);
  282. Operand lblNonZero = Label();
  283. Operand lblExit = Label();
  284. context.BranchIfTrue(lblNonZero, count, BasicBlockFrequency.Cold);
  285. Operand running = context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.CheckSynchronization)));
  286. context.BranchIfTrue(lblExit, running, BasicBlockFrequency.Cold);
  287. context.Return(Const(0L));
  288. context.MarkLabel(lblNonZero);
  289. count = context.Subtract(count, Const(1));
  290. context.Store(countAddr, count);
  291. context.MarkLabel(lblExit);
  292. }
  293. public void InvalidateJitCacheRegion(ulong address, ulong size)
  294. {
  295. // If rejit is running, stop it as it may be trying to rejit a function on the invalidated region.
  296. ClearRejitQueue(allowRequeue: true);
  297. // TODO: Completely remove functions overlapping the specified range from the cache.
  298. }
  299. private void EnqueueForDeletion(ulong guestAddress, TranslatedFunction func)
  300. {
  301. _oldFuncs.Enqueue(new KeyValuePair<ulong, IntPtr>(guestAddress, func.FuncPtr));
  302. }
  303. private void ClearJitCache()
  304. {
  305. // Ensure no attempt will be made to compile new functions due to rejit.
  306. ClearRejitQueue(allowRequeue: false);
  307. foreach (var kv in _funcs)
  308. {
  309. JitCache.Unmap(kv.Value.FuncPtr);
  310. }
  311. _funcs.Clear();
  312. while (_oldFuncs.TryDequeue(out var kv))
  313. {
  314. JitCache.Unmap(kv.Value);
  315. }
  316. }
  317. private void ClearRejitQueue(bool allowRequeue)
  318. {
  319. _backgroundTranslatorLock.AcquireWriterLock(Timeout.Infinite);
  320. if (allowRequeue)
  321. {
  322. while (_backgroundStack.TryPop(out var request))
  323. {
  324. if (_funcs.TryGetValue(request.Address, out var func))
  325. {
  326. func.ResetCallCount();
  327. }
  328. }
  329. }
  330. else
  331. {
  332. _backgroundStack.Clear();
  333. }
  334. _backgroundTranslatorLock.ReleaseWriterLock();
  335. }
  336. }
  337. }