Translator.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. namespace ARMeilleure.Translation
  12. {
  13. public class Translator : ITranslator
  14. {
  15. private const ulong CallFlag = InstEmitFlowHelper.CallFlag;
  16. private MemoryManager _memory;
  17. private ConcurrentDictionary<ulong, TranslatedFunction> _funcs;
  18. private PriorityQueue<ulong> _backgroundQueue;
  19. private AutoResetEvent _backgroundTranslatorEvent;
  20. private volatile int _threadCount;
  21. public Translator(MemoryManager memory)
  22. {
  23. _memory = memory;
  24. _funcs = new ConcurrentDictionary<ulong, TranslatedFunction>();
  25. _backgroundQueue = new PriorityQueue<ulong>(2);
  26. _backgroundTranslatorEvent = new AutoResetEvent(false);
  27. }
  28. private void TranslateQueuedSubs()
  29. {
  30. while (_threadCount != 0)
  31. {
  32. if (_backgroundQueue.TryDequeue(out ulong address))
  33. {
  34. TranslatedFunction func = Translate(address, ExecutionMode.Aarch64, highCq: true);
  35. _funcs.AddOrUpdate(address, func, (key, oldFunc) => func);
  36. }
  37. else
  38. {
  39. _backgroundTranslatorEvent.WaitOne();
  40. }
  41. }
  42. }
  43. public void Execute(IExecutionContext ctx, ulong address)
  44. {
  45. State.ExecutionContext context = (State.ExecutionContext)ctx;
  46. if (Interlocked.Increment(ref _threadCount) == 1)
  47. {
  48. Thread backgroundTranslatorThread = new Thread(TranslateQueuedSubs);
  49. backgroundTranslatorThread.Priority = ThreadPriority.Lowest;
  50. backgroundTranslatorThread.Start();
  51. }
  52. Statistics.InitializeTimer();
  53. NativeInterface.RegisterThread(context, _memory);
  54. do
  55. {
  56. address = ExecuteSingle(context, address);
  57. }
  58. while (context.Running && (address & ~1UL) != 0);
  59. NativeInterface.UnregisterThread();
  60. if (Interlocked.Decrement(ref _threadCount) == 0)
  61. {
  62. _backgroundTranslatorEvent.Set();
  63. }
  64. }
  65. public ulong ExecuteSingle(State.ExecutionContext context, ulong address)
  66. {
  67. TranslatedFunction func = GetOrTranslate(address, context.ExecutionMode);
  68. Statistics.StartTimer();
  69. ulong nextAddr = func.Execute(context);
  70. Statistics.StopTimer(address);
  71. return nextAddr;
  72. }
  73. private TranslatedFunction GetOrTranslate(ulong address, ExecutionMode mode)
  74. {
  75. // TODO: Investigate how we should handle code at unaligned addresses.
  76. // Currently, those low bits are used to store special flags.
  77. bool isCallTarget = (address & CallFlag) != 0;
  78. address &= ~CallFlag;
  79. if (!_funcs.TryGetValue(address, out TranslatedFunction func))
  80. {
  81. func = Translate(address, mode, highCq: false);
  82. _funcs.TryAdd(address, func);
  83. }
  84. else if (isCallTarget && func.ShouldRejit())
  85. {
  86. _backgroundQueue.Enqueue(0, address);
  87. _backgroundTranslatorEvent.Set();
  88. }
  89. return func;
  90. }
  91. private TranslatedFunction Translate(ulong address, ExecutionMode mode, bool highCq)
  92. {
  93. ArmEmitterContext context = new ArmEmitterContext(_memory, Aarch32Mode.User);
  94. Logger.StartPass(PassName.Decoding);
  95. Block[] blocks = highCq
  96. ? Decoder.DecodeFunction (_memory, address, mode)
  97. : Decoder.DecodeBasicBlock(_memory, address, mode);
  98. Logger.EndPass(PassName.Decoding);
  99. Logger.StartPass(PassName.Translation);
  100. EmitSynchronization(context);
  101. if (blocks[0].Address != address)
  102. {
  103. context.Branch(context.GetLabel(address));
  104. }
  105. ControlFlowGraph cfg = EmitAndGetCFG(context, blocks);
  106. Logger.EndPass(PassName.Translation);
  107. Logger.StartPass(PassName.RegisterUsage);
  108. RegisterUsage.RunPass(cfg, isCompleteFunction: false);
  109. Logger.EndPass(PassName.RegisterUsage);
  110. OperandType[] argTypes = new OperandType[] { OperandType.I64 };
  111. CompilerOptions options = highCq
  112. ? CompilerOptions.HighCq
  113. : CompilerOptions.None;
  114. GuestFunction func = Compiler.Compile<GuestFunction>(cfg, argTypes, OperandType.I64, options);
  115. return new TranslatedFunction(func, rejit: !highCq);
  116. }
  117. private static ControlFlowGraph EmitAndGetCFG(ArmEmitterContext context, Block[] blocks)
  118. {
  119. for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
  120. {
  121. Block block = blocks[blkIndex];
  122. context.CurrBlock = block;
  123. context.MarkLabel(context.GetLabel(block.Address));
  124. for (int opcIndex = 0; opcIndex < block.OpCodes.Count; opcIndex++)
  125. {
  126. OpCode opCode = block.OpCodes[opcIndex];
  127. context.CurrOp = opCode;
  128. bool isLastOp = opcIndex == block.OpCodes.Count - 1;
  129. if (isLastOp && block.Branch != null && block.Branch.Address <= block.Address)
  130. {
  131. EmitSynchronization(context);
  132. }
  133. Operand lblPredicateSkip = null;
  134. if (opCode is OpCode32 op && op.Cond < Condition.Al)
  135. {
  136. lblPredicateSkip = Label();
  137. InstEmitFlowHelper.EmitCondBranch(context, lblPredicateSkip, op.Cond.Invert());
  138. }
  139. if (opCode.Instruction.Emitter != null)
  140. {
  141. opCode.Instruction.Emitter(context);
  142. }
  143. else
  144. {
  145. throw new InvalidOperationException($"Invalid instruction \"{opCode.Instruction.Name}\".");
  146. }
  147. if (lblPredicateSkip != null)
  148. {
  149. context.MarkLabel(lblPredicateSkip);
  150. // If this is the last op on the block, and there's no "next" block
  151. // after this one, then we have to return right now, with the address
  152. // of the next instruction to be executed (in the case that the condition
  153. // is false, and the branch was not taken, as all basic blocks should end
  154. // with some kind of branch).
  155. if (isLastOp && block.Next == null)
  156. {
  157. context.Return(Const(opCode.Address + (ulong)opCode.OpCodeSizeInBytes));
  158. }
  159. }
  160. }
  161. }
  162. return context.GetControlFlowGraph();
  163. }
  164. private static void EmitSynchronization(EmitterContext context)
  165. {
  166. long countOffs = NativeContext.GetCounterOffset();
  167. Operand countAddr = context.Add(context.LoadArgument(OperandType.I64, 0), Const(countOffs));
  168. Operand count = context.Load(OperandType.I32, countAddr);
  169. Operand lblNonZero = Label();
  170. Operand lblExit = Label();
  171. context.BranchIfTrue(lblNonZero, count);
  172. context.Call(new _Void(NativeInterface.CheckSynchronization));
  173. context.Branch(lblExit);
  174. context.MarkLabel(lblNonZero);
  175. count = context.Subtract(count, Const(1));
  176. context.Store(countAddr, count);
  177. context.MarkLabel(lblExit);
  178. }
  179. }
  180. }