Translator.cs 15 KB

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