Translator.cs 11 KB

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