Translator.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 System;
  8. using System.Collections.Concurrent;
  9. using System.Threading;
  10. using static ARMeilleure.IntermediateRepresentation.OperandHelper;
  11. using static ARMeilleure.IntermediateRepresentation.OperationHelper;
  12. namespace ARMeilleure.Translation
  13. {
  14. using PTC;
  15. public class Translator
  16. {
  17. private const ulong CallFlag = InstEmitFlowHelper.CallFlag;
  18. private readonly IMemoryManager _memory;
  19. private readonly ConcurrentDictionary<ulong, TranslatedFunction> _funcs;
  20. private readonly ConcurrentStack<RejitRequest> _backgroundStack;
  21. private readonly AutoResetEvent _backgroundTranslatorEvent;
  22. private readonly JumpTable _jumpTable;
  23. private volatile int _threadCount;
  24. // FIXME: Remove this once the init logic of the emulator will be redone
  25. public static ManualResetEvent IsReadyForTranslation = new ManualResetEvent(false);
  26. public Translator(IJitMemoryAllocator allocator, IMemoryManager memory)
  27. {
  28. _memory = memory;
  29. _funcs = new ConcurrentDictionary<ulong, TranslatedFunction>();
  30. _backgroundStack = new ConcurrentStack<RejitRequest>();
  31. _backgroundTranslatorEvent = new AutoResetEvent(false);
  32. _jumpTable = new JumpTable(allocator);
  33. JitCache.Initialize(allocator);
  34. DirectCallStubs.InitializeStubs();
  35. if (Ptc.State == PtcState.Enabled)
  36. {
  37. Ptc.LoadTranslations(_funcs, memory.PageTablePointer, _jumpTable);
  38. }
  39. }
  40. private void TranslateStackedSubs()
  41. {
  42. while (_threadCount != 0)
  43. {
  44. if (_backgroundStack.TryPop(out RejitRequest request))
  45. {
  46. TranslatedFunction func = Translate(_memory, _jumpTable, request.Address, request.Mode, highCq: true);
  47. _funcs.AddOrUpdate(request.Address, func, (key, oldFunc) => func);
  48. _jumpTable.RegisterFunction(request.Address, func);
  49. if (PtcProfiler.Enabled)
  50. {
  51. PtcProfiler.UpdateEntry(request.Address, request.Mode, highCq: true);
  52. }
  53. }
  54. else
  55. {
  56. _backgroundTranslatorEvent.WaitOne();
  57. }
  58. }
  59. _backgroundTranslatorEvent.Set(); // Wake up any other background translator threads, to encourage them to exit.
  60. }
  61. public void Execute(State.ExecutionContext context, ulong address)
  62. {
  63. if (Interlocked.Increment(ref _threadCount) == 1)
  64. {
  65. IsReadyForTranslation.WaitOne();
  66. if (Ptc.State == PtcState.Enabled)
  67. {
  68. Ptc.MakeAndSaveTranslations(_funcs, _memory, _jumpTable);
  69. }
  70. PtcProfiler.Start();
  71. Ptc.Disable();
  72. // Simple heuristic, should be user configurable in future. (1 for 4 core/ht or less, 2 for 6 core+ht etc).
  73. // 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.
  74. // If we only have one rejit thread, it should be normal priority as highCq code is performance critical.
  75. // TODO: Use physical cores rather than logical. This only really makes sense for processors with hyperthreading. Requires OS specific code.
  76. int unboundedThreadCount = Math.Max(1, (Environment.ProcessorCount - 6) / 3);
  77. int threadCount = Math.Min(4, unboundedThreadCount);
  78. for (int i = 0; i < threadCount; i++)
  79. {
  80. bool last = i != 0 && i == unboundedThreadCount - 1;
  81. Thread backgroundTranslatorThread = new Thread(TranslateStackedSubs)
  82. {
  83. Name = "CPU.BackgroundTranslatorThread." + i,
  84. Priority = last ? ThreadPriority.Lowest : ThreadPriority.Normal
  85. };
  86. backgroundTranslatorThread.Start();
  87. }
  88. }
  89. Statistics.InitializeTimer();
  90. NativeInterface.RegisterThread(context, _memory, this);
  91. do
  92. {
  93. address = ExecuteSingle(context, address);
  94. }
  95. while (context.Running && (address & ~1UL) != 0);
  96. NativeInterface.UnregisterThread();
  97. if (Interlocked.Decrement(ref _threadCount) == 0)
  98. {
  99. _backgroundTranslatorEvent.Set();
  100. }
  101. }
  102. public ulong ExecuteSingle(State.ExecutionContext context, ulong address)
  103. {
  104. TranslatedFunction func = GetOrTranslate(address, context.ExecutionMode);
  105. Statistics.StartTimer();
  106. ulong nextAddr = func.Execute(context);
  107. Statistics.StopTimer(address);
  108. return nextAddr;
  109. }
  110. internal TranslatedFunction GetOrTranslate(ulong address, ExecutionMode mode)
  111. {
  112. // TODO: Investigate how we should handle code at unaligned addresses.
  113. // Currently, those low bits are used to store special flags.
  114. bool isCallTarget = (address & CallFlag) != 0;
  115. address &= ~CallFlag;
  116. if (!_funcs.TryGetValue(address, out TranslatedFunction func))
  117. {
  118. func = Translate(_memory, _jumpTable, address, mode, highCq: false);
  119. _funcs.TryAdd(address, func);
  120. if (PtcProfiler.Enabled)
  121. {
  122. PtcProfiler.AddEntry(address, mode, highCq: false);
  123. }
  124. }
  125. if (isCallTarget && func.ShouldRejit())
  126. {
  127. _backgroundStack.Push(new RejitRequest(address, mode));
  128. _backgroundTranslatorEvent.Set();
  129. }
  130. return func;
  131. }
  132. internal static TranslatedFunction Translate(IMemoryManager memory, JumpTable jumpTable, ulong address, ExecutionMode mode, bool highCq)
  133. {
  134. ArmEmitterContext context = new ArmEmitterContext(memory, jumpTable, (long)address, highCq, Aarch32Mode.User);
  135. PrepareOperandPool(highCq);
  136. PrepareOperationPool(highCq);
  137. Logger.StartPass(PassName.Decoding);
  138. Block[] blocks = Decoder.Decode(memory, address, mode, highCq, singleBlock: false);
  139. Logger.EndPass(PassName.Decoding);
  140. Logger.StartPass(PassName.Translation);
  141. EmitSynchronization(context);
  142. if (blocks[0].Address != address)
  143. {
  144. context.Branch(context.GetLabel(address));
  145. }
  146. ControlFlowGraph cfg = EmitAndGetCFG(context, blocks);
  147. Logger.EndPass(PassName.Translation);
  148. Logger.StartPass(PassName.RegisterUsage);
  149. RegisterUsage.RunPass(cfg, mode);
  150. Logger.EndPass(PassName.RegisterUsage);
  151. OperandType[] argTypes = new OperandType[] { OperandType.I64 };
  152. CompilerOptions options = highCq ? CompilerOptions.HighCq : CompilerOptions.None;
  153. GuestFunction func;
  154. if (Ptc.State == PtcState.Disabled)
  155. {
  156. func = Compiler.Compile<GuestFunction>(cfg, argTypes, OperandType.I64, options);
  157. }
  158. else
  159. {
  160. using (PtcInfo ptcInfo = new PtcInfo())
  161. {
  162. func = Compiler.Compile<GuestFunction>(cfg, argTypes, OperandType.I64, options, ptcInfo);
  163. Ptc.WriteInfoCodeReloc((long)address, highCq, ptcInfo);
  164. }
  165. }
  166. ResetOperandPool(highCq);
  167. ResetOperationPool(highCq);
  168. return new TranslatedFunction(func, highCq);
  169. }
  170. private static ControlFlowGraph EmitAndGetCFG(ArmEmitterContext context, Block[] blocks)
  171. {
  172. for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
  173. {
  174. Block block = blocks[blkIndex];
  175. context.CurrBlock = block;
  176. context.MarkLabel(context.GetLabel(block.Address));
  177. if (block.Exit)
  178. {
  179. InstEmitFlowHelper.EmitTailContinue(context, Const(block.Address), block.TailCall);
  180. }
  181. else
  182. {
  183. for (int opcIndex = 0; opcIndex < block.OpCodes.Count; opcIndex++)
  184. {
  185. OpCode opCode = block.OpCodes[opcIndex];
  186. context.CurrOp = opCode;
  187. bool isLastOp = opcIndex == block.OpCodes.Count - 1;
  188. if (isLastOp && block.Branch != null && !block.Branch.Exit && block.Branch.Address <= block.Address)
  189. {
  190. EmitSynchronization(context);
  191. }
  192. Operand lblPredicateSkip = null;
  193. if (opCode is OpCode32 op && op.Cond < Condition.Al)
  194. {
  195. lblPredicateSkip = Label();
  196. InstEmitFlowHelper.EmitCondBranch(context, lblPredicateSkip, op.Cond.Invert());
  197. }
  198. if (opCode.Instruction.Emitter != null)
  199. {
  200. opCode.Instruction.Emitter(context);
  201. }
  202. else
  203. {
  204. throw new InvalidOperationException($"Invalid instruction \"{opCode.Instruction.Name}\".");
  205. }
  206. if (lblPredicateSkip != null)
  207. {
  208. context.MarkLabel(lblPredicateSkip);
  209. }
  210. }
  211. }
  212. }
  213. return context.GetControlFlowGraph();
  214. }
  215. internal static void EmitSynchronization(EmitterContext context)
  216. {
  217. long countOffs = NativeContext.GetCounterOffset();
  218. Operand countAddr = context.Add(context.LoadArgument(OperandType.I64, 0), Const(countOffs));
  219. Operand count = context.Load(OperandType.I32, countAddr);
  220. Operand lblNonZero = Label();
  221. Operand lblExit = Label();
  222. context.BranchIfTrue(lblNonZero, count, BasicBlockFrequency.Cold);
  223. Operand running = context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.CheckSynchronization)));
  224. context.BranchIfTrue(lblExit, running, BasicBlockFrequency.Cold);
  225. context.Return(Const(0L));
  226. context.MarkLabel(lblNonZero);
  227. count = context.Subtract(count, Const(1));
  228. context.Store(countAddr, count);
  229. context.MarkLabel(lblExit);
  230. }
  231. }
  232. }