Translator.cs 8.0 KB

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