Decoder.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. using ChocolArm64.Instructions;
  2. using ChocolArm64.Memory;
  3. using ChocolArm64.State;
  4. using System;
  5. using System.Collections.Concurrent;
  6. using System.Collections.Generic;
  7. using System.Reflection.Emit;
  8. namespace ChocolArm64.Decoders
  9. {
  10. static class Decoder
  11. {
  12. private delegate object OpActivator(Inst inst, long position, int opCode);
  13. private static ConcurrentDictionary<Type, OpActivator> _opActivators;
  14. static Decoder()
  15. {
  16. _opActivators = new ConcurrentDictionary<Type, OpActivator>();
  17. }
  18. public static Block DecodeBasicBlock(MemoryManager memory, long start, ExecutionMode mode)
  19. {
  20. Block block = new Block(start);
  21. FillBlock(memory, mode, block);
  22. OpCode64 lastOp = block.GetLastOp();
  23. if (IsBranch(lastOp) && !IsCall(lastOp) && lastOp is IOpCodeBImm op)
  24. {
  25. //It's possible that the branch on this block lands on the middle of the block.
  26. //This is more common on tight loops. In this case, we can improve the codegen
  27. //a bit by changing the CFG and either making the branch point to the same block
  28. //(which indicates that the block is a loop that jumps back to the start), and the
  29. //other possible case is a jump somewhere on the middle of the block, which is
  30. //also a loop, but in this case we need to split the block in half.
  31. if (op.Imm == start)
  32. {
  33. block.Branch = block;
  34. }
  35. else if ((ulong)op.Imm > (ulong)start &&
  36. (ulong)op.Imm < (ulong)block.EndPosition)
  37. {
  38. Block botBlock = new Block(op.Imm);
  39. int botBlockIndex = 0;
  40. long currPosition = start;
  41. while ((ulong)currPosition < (ulong)op.Imm)
  42. {
  43. currPosition += block.OpCodes[botBlockIndex++].OpCodeSizeInBytes;
  44. }
  45. botBlock.OpCodes.AddRange(block.OpCodes);
  46. botBlock.OpCodes.RemoveRange(0, botBlockIndex);
  47. block.OpCodes.RemoveRange(botBlockIndex, block.OpCodes.Count - botBlockIndex);
  48. botBlock.EndPosition = block.EndPosition;
  49. block.EndPosition = op.Imm;
  50. botBlock.Branch = botBlock;
  51. block.Next = botBlock;
  52. }
  53. }
  54. return block;
  55. }
  56. public static Block DecodeSubroutine(MemoryManager memory, long start, ExecutionMode mode)
  57. {
  58. Dictionary<long, Block> visited = new Dictionary<long, Block>();
  59. Dictionary<long, Block> visitedEnd = new Dictionary<long, Block>();
  60. Queue<Block> blocks = new Queue<Block>();
  61. Block Enqueue(long position)
  62. {
  63. if (!visited.TryGetValue(position, out Block output))
  64. {
  65. output = new Block(position);
  66. blocks.Enqueue(output);
  67. visited.Add(position, output);
  68. }
  69. return output;
  70. }
  71. Block entry = Enqueue(start);
  72. while (blocks.Count > 0)
  73. {
  74. Block current = blocks.Dequeue();
  75. FillBlock(memory, mode, current);
  76. //Set child blocks. "Branch" is the block the branch instruction
  77. //points to (when taken), "Next" is the block at the next address,
  78. //executed when the branch is not taken. For Unconditional Branches
  79. //(except BL/BLR that are sub calls) or end of executable, Next is null.
  80. if (current.OpCodes.Count > 0)
  81. {
  82. OpCode64 lastOp = current.GetLastOp();
  83. bool isCall = IsCall(lastOp);
  84. if (lastOp is IOpCodeBImm op && !isCall)
  85. {
  86. current.Branch = Enqueue(op.Imm);
  87. }
  88. if (!IsUnconditionalBranch(lastOp) || isCall)
  89. {
  90. current.Next = Enqueue(current.EndPosition);
  91. }
  92. }
  93. //If we have on the graph two blocks with the same end position,
  94. //then we need to split the bigger block and have two small blocks,
  95. //the end position of the bigger "Current" block should then be == to
  96. //the position of the "Smaller" block.
  97. while (visitedEnd.TryGetValue(current.EndPosition, out Block smaller))
  98. {
  99. if (current.Position > smaller.Position)
  100. {
  101. Block temp = smaller;
  102. smaller = current;
  103. current = temp;
  104. }
  105. current.EndPosition = smaller.Position;
  106. current.Next = smaller;
  107. current.Branch = null;
  108. current.OpCodes.RemoveRange(
  109. current.OpCodes.Count - smaller.OpCodes.Count,
  110. smaller.OpCodes.Count);
  111. visitedEnd[smaller.EndPosition] = smaller;
  112. }
  113. visitedEnd.Add(current.EndPosition, current);
  114. }
  115. return entry;
  116. }
  117. private static void FillBlock(MemoryManager memory, ExecutionMode mode, Block block)
  118. {
  119. long position = block.Position;
  120. OpCode64 opCode;
  121. do
  122. {
  123. opCode = DecodeOpCode(memory, position, mode);
  124. block.OpCodes.Add(opCode);
  125. position += opCode.OpCodeSizeInBytes;
  126. }
  127. while (!(IsBranch(opCode) || IsException(opCode)));
  128. block.EndPosition = position;
  129. }
  130. private static bool IsBranch(OpCode64 opCode)
  131. {
  132. return opCode is OpCodeBImm64 ||
  133. opCode is OpCodeBReg64 || IsAarch32Branch(opCode);
  134. }
  135. private static bool IsUnconditionalBranch(OpCode64 opCode)
  136. {
  137. return opCode is OpCodeBImmAl64 ||
  138. opCode is OpCodeBReg64 || IsAarch32UnconditionalBranch(opCode);
  139. }
  140. private static bool IsAarch32UnconditionalBranch(OpCode64 opCode)
  141. {
  142. if (!(opCode is OpCode32 op))
  143. {
  144. return false;
  145. }
  146. //Note: On ARM32, most instructions have conditional execution,
  147. //so there's no "Always" (unconditional) branch like on ARM64.
  148. //We need to check if the condition is "Always" instead.
  149. return IsAarch32Branch(op) && op.Cond >= Condition.Al;
  150. }
  151. private static bool IsAarch32Branch(OpCode64 opCode)
  152. {
  153. //Note: On ARM32, most ALU operations can write to R15 (PC),
  154. //so we must consider such operations as a branch in potential aswell.
  155. if (opCode is IOpCode32Alu opAlu && opAlu.Rd == RegisterAlias.Aarch32Pc)
  156. {
  157. return true;
  158. }
  159. //Same thing for memory operations. We have the cases where PC is a target
  160. //register (Rt == 15 or (mask & (1 << 15)) != 0), and cases where there is
  161. //a write back to PC (wback == true && Rn == 15), however the later may
  162. //be "undefined" depending on the CPU, so compilers should not produce that.
  163. if (opCode is IOpCode32Mem || opCode is IOpCode32MemMult)
  164. {
  165. int rt, rn;
  166. bool wBack, isLoad;
  167. if (opCode is IOpCode32Mem opMem)
  168. {
  169. rt = opMem.Rt;
  170. rn = opMem.Rn;
  171. wBack = opMem.WBack;
  172. isLoad = opMem.IsLoad;
  173. //For the dual load, we also need to take into account the
  174. //case were Rt2 == 15 (PC).
  175. if (rt == 14 && opMem.Emitter == InstEmit32.Ldrd)
  176. {
  177. rt = RegisterAlias.Aarch32Pc;
  178. }
  179. }
  180. else if (opCode is IOpCode32MemMult opMemMult)
  181. {
  182. const int pcMask = 1 << RegisterAlias.Aarch32Pc;
  183. rt = (opMemMult.RegisterMask & pcMask) != 0 ? RegisterAlias.Aarch32Pc : 0;
  184. rn = opMemMult.Rn;
  185. wBack = opMemMult.PostOffset != 0;
  186. isLoad = opMemMult.IsLoad;
  187. }
  188. else
  189. {
  190. throw new NotImplementedException($"The type \"{opCode.GetType().Name}\" is not implemented on the decoder.");
  191. }
  192. if ((rt == RegisterAlias.Aarch32Pc && isLoad) ||
  193. (rn == RegisterAlias.Aarch32Pc && wBack))
  194. {
  195. return true;
  196. }
  197. }
  198. //Explicit branch instructions.
  199. return opCode is IOpCode32BImm ||
  200. opCode is IOpCode32BReg;
  201. }
  202. private static bool IsCall(OpCode64 opCode)
  203. {
  204. //TODO (CQ): ARM32 support.
  205. return opCode.Emitter == InstEmit.Bl ||
  206. opCode.Emitter == InstEmit.Blr;
  207. }
  208. private static bool IsException(OpCode64 opCode)
  209. {
  210. return opCode.Emitter == InstEmit.Brk ||
  211. opCode.Emitter == InstEmit.Svc ||
  212. opCode.Emitter == InstEmit.Und;
  213. }
  214. public static OpCode64 DecodeOpCode(MemoryManager memory, long position, ExecutionMode mode)
  215. {
  216. int opCode = memory.ReadInt32(position);
  217. Inst inst;
  218. if (mode == ExecutionMode.Aarch64)
  219. {
  220. inst = OpCodeTable.GetInstA64(opCode);
  221. }
  222. else
  223. {
  224. if (mode == ExecutionMode.Aarch32Arm)
  225. {
  226. inst = OpCodeTable.GetInstA32(opCode);
  227. }
  228. else /* if (mode == ExecutionMode.Aarch32Thumb) */
  229. {
  230. inst = OpCodeTable.GetInstT32(opCode);
  231. }
  232. }
  233. OpCode64 decodedOpCode = new OpCode64(Inst.Undefined, position, opCode);
  234. if (inst.Type != null)
  235. {
  236. decodedOpCode = MakeOpCode(inst.Type, inst, position, opCode);
  237. }
  238. return decodedOpCode;
  239. }
  240. private static OpCode64 MakeOpCode(Type type, Inst inst, long position, int opCode)
  241. {
  242. if (type == null)
  243. {
  244. throw new ArgumentNullException(nameof(type));
  245. }
  246. OpActivator createInstance = _opActivators.GetOrAdd(type, CacheOpActivator);
  247. return (OpCode64)createInstance(inst, position, opCode);
  248. }
  249. private static OpActivator CacheOpActivator(Type type)
  250. {
  251. Type[] argTypes = new Type[] { typeof(Inst), typeof(long), typeof(int) };
  252. DynamicMethod mthd = new DynamicMethod($"Make{type.Name}", type, argTypes);
  253. ILGenerator generator = mthd.GetILGenerator();
  254. generator.Emit(OpCodes.Ldarg_0);
  255. generator.Emit(OpCodes.Ldarg_1);
  256. generator.Emit(OpCodes.Ldarg_2);
  257. generator.Emit(OpCodes.Newobj, type.GetConstructor(argTypes));
  258. generator.Emit(OpCodes.Ret);
  259. return (OpActivator)mthd.CreateDelegate(typeof(OpActivator));
  260. }
  261. }
  262. }